diff --git a/components/audio/audio_device/bouffalo.mk b/components/audio/audio_device/bouffalo.mk index c4a4ade4..36eae80b 100644 --- a/components/audio/audio_device/bouffalo.mk +++ b/components/audio/audio_device/bouffalo.mk @@ -6,18 +6,18 @@ COMPONENT_ADD_INCLUDEDIRS += audio_device/include ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := audio_device/include -## This component's src +## This component's src ifeq ($(CONFIG_CHIP_NAME),BL602) COMPONENT_SRCS := bl602_dac/bl602_dac_device.c COMPONENT_SRCDIRS := bl602_dac endif ifeq ($(CONFIG_CHIP_NAME),BL60X) -COMPONENT_SRCS := bl60x_i2s/bl60x_i2s_device.c +COMPONENT_SRCS := bl60x_i2s/bl60x_i2s_device.c COMPONENT_SRCDIRS := bl60x_i2s endif COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/audio/audio_framework/bouffalo.mk b/components/audio/audio_framework/bouffalo.mk index 7bdd0ed7..4b4d97d8 100644 --- a/components/audio/audio_framework/bouffalo.mk +++ b/components/audio/audio_framework/bouffalo.mk @@ -6,7 +6,7 @@ COMPONENT_ADD_INCLUDEDIRS += audio_framework/include ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := audio_framework/include -## This component's src +## This component's src COMPONENT_SRCS := audio_framework/audio_framework.c COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) @@ -15,4 +15,4 @@ COMPONENT_SRCDIRS := audio_framework ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/bl602/bl602/evb/evb.mk b/components/bl602/bl602/evb/evb.mk index 72c587ba..9abdeeb4 100755 --- a/components/bl602/bl602/evb/evb.mk +++ b/components/bl602/bl602/evb/evb.mk @@ -3,12 +3,12 @@ toolchains := gcc # Component Makefile # ## These include paths would be exported to project level -COMPONENT_ADD_INCLUDEDIRS += - -## not be exported to project level -COMPONENT_PRIV_INCLUDEDIRS := +COMPONENT_ADD_INCLUDEDIRS += -## This component's src +## not be exported to project level +COMPONENT_PRIV_INCLUDEDIRS := + +## This component's src COMPONENT_SRCS1 := evb/src/boot/$(toolchains)/entry.S \ evb/src/boot/$(toolchains)/start.S \ evb/src/debug.c \ @@ -39,7 +39,7 @@ endif ## COMPONENT_ADD_LDFLAGS += -L $(COMPONENT_PATH)/evb/ld \ $(addprefix -T ,$(LINKER_SCRIPTS)) -## +## COMPONENT_ADD_LINKER_DEPS := $(addprefix evb/ld/,$(LINKER_SCRIPTS)) endif diff --git a/components/bl602/bl602/evb/ld/flash.ld b/components/bl602/bl602/evb/ld/flash.ld index 2e4965ed..a84b17fd 100644 --- a/components/bl602/bl602/evb/ld/flash.ld +++ b/components/bl602/bl602/evb/ld/flash.ld @@ -123,7 +123,7 @@ SECTIONS *(.srodata.cst4) *(.srodata.cst2) *(.srodata .srodata.*) - + . = ALIGN(8); *(._k_queue.static.*) *(._k_sem.static.*) @@ -196,7 +196,7 @@ SECTIONS /*BOOT2 sections*/ PROVIDE ( __boot2_pt_addr_src = BOOT2_PT_ADDR ); - PROVIDE ( __boot2_flashCfg_src = BOOT2_FLASHCFG_ADDR ); + PROVIDE ( __boot2_flashCfg_src = BOOT2_FLASHCFG_ADDR ); PROVIDE(__LD_CONFIG_EM_SEL = __EM_SIZE); } diff --git a/components/bl602/bl602/evb/ld/flash_rom.ld b/components/bl602/bl602/evb/ld/flash_rom.ld index 542b7c10..bfa3bd06 100644 --- a/components/bl602/bl602/evb/ld/flash_rom.ld +++ b/components/bl602/bl602/evb/ld/flash_rom.ld @@ -72,7 +72,7 @@ SECTIONS _bl_static_blogpri_code_end = .; *(.gnu.linkonce.r.*) - + /*Framework table section, use ALIGN here to avoid fill section*/ . = ALIGN(4); _rom_framework_audio_device_start = .; @@ -136,7 +136,7 @@ SECTIONS *(.srodata.cst4) *(.srodata.cst2) *(.srodata .srodata.*) - + . = ALIGN(8); *(._k_queue.static.*) *(._k_sem.static.*) @@ -213,7 +213,7 @@ SECTIONS /*BOOT2 sections*/ PROVIDE ( __boot2_pt_addr_src = BOOT2_PT_ADDR ); - PROVIDE ( __boot2_flashCfg_src = BOOT2_FLASHCFG_ADDR ); + PROVIDE ( __boot2_flashCfg_src = BOOT2_FLASHCFG_ADDR ); PROVIDE(xTaskGetTickCount = 0x0000000021017694); PROVIDE(xTaskGetTickCountFromISR = 0x00000000210176aa); @@ -269,7 +269,7 @@ SECTIONS PROVIDE(vTaskStartScheduler = 0x0000000021017610); PROVIDE(vPortDefineHeapRegions = 0x00000000210197da); PROVIDE(__LD_CONFIG_EM_SEL = __EM_SIZE); - + PROVIDE( _ld_symbol_rom_framework_audio_device_start = _rom_framework_audio_device_start); PROVIDE( _ld_symbol_rom_framework_audio_device_end = _rom_framework_audio_device_end); diff --git a/components/bl602/bl602/evb/ld/ram.ld b/components/bl602/bl602/evb/ld/ram.ld index 6f0c6b27..34530641 100644 --- a/components/bl602/bl602/evb/ld/ram.ld +++ b/components/bl602/bl602/evb/ld/ram.ld @@ -93,5 +93,5 @@ SECTIONS PROVIDE( _ld_ram_addr1 = 0); PROVIDE( _ld_ram_size2 = 0); PROVIDE( _ld_ram_addr2 = 0); - + } diff --git a/components/bl602/bl602/evb/src/compat_attribute.h b/components/bl602/bl602/evb/src/compat_attribute.h old mode 100755 new mode 100644 diff --git a/components/bl602/bl602/evb/src/debug.c b/components/bl602/bl602/evb/src/debug.c old mode 100755 new mode 100644 index 32bf7366..9e70d549 --- a/components/bl602/bl602/evb/src/debug.c +++ b/components/bl602/bl602/evb/src/debug.c @@ -34,171 +34,171 @@ #include #include -//#define CHAR_BIT 8 +//#define CHAR_BIT 8 //FIXME no ugly declare extern int bl_uart_data_send(uint8_t id, uint8_t data); enum flag { - FL_ZERO = 0x01, /* Zero modifier */ - FL_MINUS = 0x02, /* Minus modifier */ - FL_PLUS = 0x04, /* Plus modifier */ - FL_TICK = 0x08, /* ' modifier */ - FL_SPACE = 0x10, /* Space modifier */ - FL_HASH = 0x20, /* # modifier */ - FL_SIGNED = 0x40, /* Number is signed */ - FL_UPPER = 0x80 /* Upper case digits */ + FL_ZERO = 0x01, /* Zero modifier */ + FL_MINUS = 0x02, /* Minus modifier */ + FL_PLUS = 0x04, /* Plus modifier */ + FL_TICK = 0x08, /* ' modifier */ + FL_SPACE = 0x10, /* Space modifier */ + FL_HASH = 0x20, /* # modifier */ + FL_SIGNED = 0x40, /* Number is signed */ + FL_UPPER = 0x80 /* Upper case digits */ }; /* These may have to be adjusted on certain implementations */ enum ranks { - rank_char = -2, - rank_short = -1, - rank_int = 0, - rank_long = 1, - rank_longlong = 2 + rank_char = -2, + rank_short = -1, + rank_int = 0, + rank_long = 1, + rank_longlong = 2 }; -#define MIN_RANK rank_char -#define MAX_RANK rank_longlong +#define MIN_RANK rank_char +#define MAX_RANK rank_longlong -#define INTMAX_RANK rank_longlong -#define SIZE_T_RANK rank_long -#define PTRDIFF_T_RANK rank_long +#define INTMAX_RANK rank_longlong +#define SIZE_T_RANK rank_long +#define PTRDIFF_T_RANK rank_long #define EMIT(x) { if (o < n) { *q++ = (x); } o++; } static size_t format_int(char *q, size_t n, uintmax_t val, unsigned int flags, - int base, int width, int prec) + int base, int width, int prec) { - char *qq; - size_t o = 0, oo; - static const char lcdigits[] = "0123456789abcdef"; - static const char ucdigits[] = "0123456789ABCDEF"; - const char *digits; - uintmax_t tmpval; - int minus = 0; - int ndigits = 0, nchars; - int tickskip, b4tick; + char *qq; + size_t o = 0, oo; + static const char lcdigits[] = "0123456789abcdef"; + static const char ucdigits[] = "0123456789ABCDEF"; + const char *digits; + uintmax_t tmpval; + int minus = 0; + int ndigits = 0, nchars; + int tickskip, b4tick; - /* Select type of digits */ - digits = (flags & FL_UPPER) ? ucdigits : lcdigits; + /* Select type of digits */ + digits = (flags & FL_UPPER) ? ucdigits : lcdigits; - /* If signed, separate out the minus */ - if (flags & FL_SIGNED && (intmax_t) val < 0) { - minus = 1; - val = (uintmax_t) (-(intmax_t) val); - } + /* If signed, separate out the minus */ + if (flags & FL_SIGNED && (intmax_t) val < 0) { + minus = 1; + val = (uintmax_t) (-(intmax_t) val); + } - /* Count the number of digits needed. This returns zero for 0. */ - tmpval = val; - while (tmpval) { - tmpval /= base; - ndigits++; - } + /* Count the number of digits needed. This returns zero for 0. */ + tmpval = val; + while (tmpval) { + tmpval /= base; + ndigits++; + } - /* Adjust ndigits for size of output */ + /* Adjust ndigits for size of output */ - if (flags & FL_HASH && base == 8) { - if (prec < ndigits + 1) - prec = ndigits + 1; - } + if (flags & FL_HASH && base == 8) { + if (prec < ndigits + 1) + prec = ndigits + 1; + } - if (ndigits < prec) { - ndigits = prec; /* Mandatory number padding */ - } else if (val == 0) { - ndigits = 1; /* Zero still requires space */ - } + if (ndigits < prec) { + ndigits = prec; /* Mandatory number padding */ + } else if (val == 0) { + ndigits = 1; /* Zero still requires space */ + } - /* For ', figure out what the skip should be */ - if (flags & FL_TICK) { - tickskip = (base == 16) ? 4 : 3; - } else { - tickskip = ndigits; /* No tick marks */ - } + /* For ', figure out what the skip should be */ + if (flags & FL_TICK) { + tickskip = (base == 16) ? 4 : 3; + } else { + tickskip = ndigits; /* No tick marks */ + } - /* Tick marks aren't digits, but generated by the number converter */ - ndigits += (ndigits - 1) / tickskip; + /* Tick marks aren't digits, but generated by the number converter */ + ndigits += (ndigits - 1) / tickskip; - /* Now compute the number of nondigits */ - nchars = ndigits; + /* Now compute the number of nondigits */ + nchars = ndigits; - if (minus || (flags & (FL_PLUS | FL_SPACE))) - nchars++; /* Need space for sign */ - if ((flags & FL_HASH) && base == 16) { - nchars += 2; /* Add 0x for hex */ - } + if (minus || (flags & (FL_PLUS | FL_SPACE))) + nchars++; /* Need space for sign */ + if ((flags & FL_HASH) && base == 16) { + nchars += 2; /* Add 0x for hex */ + } - /* Emit early space padding */ - if (!(flags & (FL_MINUS | FL_ZERO)) && width > nchars) { - while (width > nchars) { - EMIT(' '); - width--; - } - } + /* Emit early space padding */ + if (!(flags & (FL_MINUS | FL_ZERO)) && width > nchars) { + while (width > nchars) { + EMIT(' '); + width--; + } + } - /* Emit nondigits */ - if (minus) { - EMIT('-'); - } else if (flags & FL_PLUS) { - EMIT('+'); - } else if (flags & FL_SPACE) { - EMIT(' '); - } + /* Emit nondigits */ + if (minus) { + EMIT('-'); + } else if (flags & FL_PLUS) { + EMIT('+'); + } else if (flags & FL_SPACE) { + EMIT(' '); + } - if ((flags & FL_HASH) && base == 16) { - EMIT('0'); - EMIT((flags & FL_UPPER) ? 'X' : 'x'); - } + if ((flags & FL_HASH) && base == 16) { + EMIT('0'); + EMIT((flags & FL_UPPER) ? 'X' : 'x'); + } - /* Emit zero padding */ - if ((flags & (FL_MINUS | FL_ZERO)) == FL_ZERO && width > ndigits) { - while (width > nchars) { - EMIT('0'); - width--; - } - } + /* Emit zero padding */ + if ((flags & (FL_MINUS | FL_ZERO)) == FL_ZERO && width > ndigits) { + while (width > nchars) { + EMIT('0'); + width--; + } + } - /* Generate the number. This is done from right to left. */ - q += ndigits; /* Advance the pointer to end of number */ - o += ndigits; - qq = q; - oo = o; /* Temporary values */ + /* Generate the number. This is done from right to left. */ + q += ndigits; /* Advance the pointer to end of number */ + o += ndigits; + qq = q; + oo = o; /* Temporary values */ - b4tick = tickskip; - while (ndigits > 0) { - if (!b4tick--) { - qq--; - oo--; - ndigits--; - if (oo < n) - *qq = '_'; - b4tick = tickskip - 1; - } - qq--; - oo--; - ndigits--; - if (oo < n) - *qq = digits[val % base]; - val /= base; - } + b4tick = tickskip; + while (ndigits > 0) { + if (!b4tick--) { + qq--; + oo--; + ndigits--; + if (oo < n) + *qq = '_'; + b4tick = tickskip - 1; + } + qq--; + oo--; + ndigits--; + if (oo < n) + *qq = digits[val % base]; + val /= base; + } - /* Emit late space padding */ - while ((flags & FL_MINUS) && width > nchars) { - EMIT(' '); - width--; - } + /* Emit late space padding */ + while ((flags & FL_MINUS) && width > nchars) { + EMIT(' '); + width--; + } - return o; + return o; } -#define ZEROPAD (1<<0) /* Pad with zero */ -#define SIGN (1<<1) /* Unsigned/signed long */ -#define PLUS (1<<2) /* Show plus */ -#define SPACE (1<<3) /* Spacer */ -#define LEFT (1<<4) /* Left justified */ -#define HEX_PREP (1<<5) /* 0x */ -#define UPPERCASE (1<<6) /* 'ABCDEF' */ +#define ZEROPAD (1<<0) /* Pad with zero */ +#define SIGN (1<<1) /* Unsigned/signed long */ +#define PLUS (1<<2) /* Show plus */ +#define SPACE (1<<3) /* Spacer */ +#define LEFT (1<<4) /* Left justified */ +#define HEX_PREP (1<<5) /* 0x */ +#define UPPERCASE (1<<6) /* 'ABCDEF' */ #include #define CVTBUFSIZE 80 @@ -295,9 +295,9 @@ char *fcvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf) static void ee_bufcpy(char *d, char *s, int count); void ee_bufcpy(char *pd, char *ps, int count) { - char *pe=ps+count; - while (ps!=pe) - *pd++=*ps++; + char *pe=ps+count; + while (ps!=pe) + *pd++=*ps++; } static void parse_float(double value, char *buffer, char fmt, int precision) @@ -442,7 +442,7 @@ static void cropzeros(char *buffer) while (*buffer == '0') buffer--; if (*buffer == '.') buffer--; while (buffer!=stop) - *++buffer=0; + *++buffer=0; } } @@ -505,332 +505,332 @@ static char *flt(char *str, double num, int size, int precision, char fmt, int f /*use O0 preventing consuming more stack*/ int __attribute__((optimize("O1"))) vsnprintf(char *buffer, size_t n, const char *format, va_list ap) { - const char *p = format; - char ch; - char *q = buffer; - size_t o = 0; /* Number of characters output */ - uintmax_t val = 0; - int rank = rank_int; /* Default rank */ - int width = 0; - int prec = -1; - int base; - size_t sz; - unsigned int flags = 0; - enum { - st_normal, /* Ground state */ - st_flags, /* Special flags */ - st_width, /* Field width */ - st_prec, /* Field precision */ - st_modifiers /* Length or conversion modifiers */ - } state = st_normal; - const char *sarg; /* %s string argument */ - char carg; /* %c char argument */ - int slen; /* String length */ + const char *p = format; + char ch; + char *q = buffer; + size_t o = 0; /* Number of characters output */ + uintmax_t val = 0; + int rank = rank_int; /* Default rank */ + int width = 0; + int prec = -1; + int base; + size_t sz; + unsigned int flags = 0; + enum { + st_normal, /* Ground state */ + st_flags, /* Special flags */ + st_width, /* Field width */ + st_prec, /* Field precision */ + st_modifiers /* Length or conversion modifiers */ + } state = st_normal; + const char *sarg; /* %s string argument */ + char carg; /* %c char argument */ + int slen; /* String length */ - while ((ch = *p++)) { - switch (state) { - case st_normal: - if (ch == '%') { - state = st_flags; - flags = 0; - rank = rank_int; - width = 0; - prec = -1; - } else { - EMIT(ch); - } - break; + while ((ch = *p++)) { + switch (state) { + case st_normal: + if (ch == '%') { + state = st_flags; + flags = 0; + rank = rank_int; + width = 0; + prec = -1; + } else { + EMIT(ch); + } + break; - case st_flags: - switch (ch) { - case '-': - flags |= FL_MINUS; - break; - case '+': - flags |= FL_PLUS; - break; - case '\'': - flags |= FL_TICK; - break; - case ' ': - flags |= FL_SPACE; - break; - case '#': - flags |= FL_HASH; - break; - case '0': - flags |= FL_ZERO; - break; - default: - state = st_width; - p--; /* Process this character again */ - break; - } - break; + case st_flags: + switch (ch) { + case '-': + flags |= FL_MINUS; + break; + case '+': + flags |= FL_PLUS; + break; + case '\'': + flags |= FL_TICK; + break; + case ' ': + flags |= FL_SPACE; + break; + case '#': + flags |= FL_HASH; + break; + case '0': + flags |= FL_ZERO; + break; + default: + state = st_width; + p--; /* Process this character again */ + break; + } + break; - case st_width: - if (ch >= '0' && ch <= '9') { - width = width * 10 + (ch - '0'); - } else if (ch == '*') { - width = va_arg(ap, int); - if (width < 0) { - width = -width; - flags |= FL_MINUS; - } - } else if (ch == '.') { - prec = 0; /* Precision given */ - state = st_prec; - } else { - state = st_modifiers; - p--; /* Process this character again */ - } - break; + case st_width: + if (ch >= '0' && ch <= '9') { + width = width * 10 + (ch - '0'); + } else if (ch == '*') { + width = va_arg(ap, int); + if (width < 0) { + width = -width; + flags |= FL_MINUS; + } + } else if (ch == '.') { + prec = 0; /* Precision given */ + state = st_prec; + } else { + state = st_modifiers; + p--; /* Process this character again */ + } + break; - case st_prec: - if (ch >= '0' && ch <= '9') { - prec = prec * 10 + (ch - '0'); - } else if (ch == '*') { - prec = va_arg(ap, int); - if (prec < 0) - prec = -1; - } else { - state = st_modifiers; - p--; /* Process this character again */ - } - break; + case st_prec: + if (ch >= '0' && ch <= '9') { + prec = prec * 10 + (ch - '0'); + } else if (ch == '*') { + prec = va_arg(ap, int); + if (prec < 0) + prec = -1; + } else { + state = st_modifiers; + p--; /* Process this character again */ + } + break; - case st_modifiers: - switch (ch) { - /* Length modifiers - nonterminal sequences */ - case 'h': - rank--; /* Shorter rank */ - break; - case 'l': - rank++; /* Longer rank */ - break; - case 'j': - rank = INTMAX_RANK; - break; - case 'z': - rank = SIZE_T_RANK; - break; - case 't': - rank = PTRDIFF_T_RANK; - break; - case 'L': - case 'q': - rank += 2; - break; - default: - /* Output modifiers - terminal sequences */ + case st_modifiers: + switch (ch) { + /* Length modifiers - nonterminal sequences */ + case 'h': + rank--; /* Shorter rank */ + break; + case 'l': + rank++; /* Longer rank */ + break; + case 'j': + rank = INTMAX_RANK; + break; + case 'z': + rank = SIZE_T_RANK; + break; + case 't': + rank = PTRDIFF_T_RANK; + break; + case 'L': + case 'q': + rank += 2; + break; + default: + /* Output modifiers - terminal sequences */ - /* Next state will be normal */ - state = st_normal; + /* Next state will be normal */ + state = st_normal; - /* Canonicalize rank */ - if (rank < MIN_RANK) - rank = MIN_RANK; - else if (rank > MAX_RANK) - rank = MAX_RANK; + /* Canonicalize rank */ + if (rank < MIN_RANK) + rank = MIN_RANK; + else if (rank > MAX_RANK) + rank = MAX_RANK; - switch (ch) { - case 'P': /* Upper case pointer */ - flags |= FL_UPPER; + switch (ch) { + case 'P': /* Upper case pointer */ + flags |= FL_UPPER; __attribute__ ((fallthrough)); - /* fall through */ - case 'p': /* Pointer */ - base = 16; - prec = (CHAR_BIT*sizeof(void *)+3)/4; - flags |= FL_HASH; - val = (uintmax_t)(uintptr_t) - va_arg(ap, void *); - goto is_integer; + /* fall through */ + case 'p': /* Pointer */ + base = 16; + prec = (CHAR_BIT*sizeof(void *)+3)/4; + flags |= FL_HASH; + val = (uintmax_t)(uintptr_t) + va_arg(ap, void *); + goto is_integer; - case 'd': /* Signed decimal output */ - case 'i': - base = 10; - flags |= FL_SIGNED; - switch (rank) { - case rank_char: - /* Yes, all these casts are - needed... */ - val = (uintmax_t)(intmax_t) - (signed char) - va_arg(ap, signed int); - break; - case rank_short: - val = (uintmax_t)(intmax_t) - (signed short) - va_arg(ap, signed int); - break; - case rank_int: - val = (uintmax_t)(intmax_t) - va_arg(ap, signed int); - break; - case rank_long: - val = (uintmax_t)(intmax_t) - va_arg(ap, signed long); - break; - case rank_longlong: - val = (uintmax_t)(intmax_t) - va_arg(ap, - signed long long); - break; - } - goto is_integer; - case 'o': /* Octal */ - base = 8; - goto is_unsigned; - case 'u': /* Unsigned decimal */ - base = 10; - goto is_unsigned; - case 'X': /* Upper case hexadecimal */ - flags |= FL_UPPER; + case 'd': /* Signed decimal output */ + case 'i': + base = 10; + flags |= FL_SIGNED; + switch (rank) { + case rank_char: + /* Yes, all these casts are + needed... */ + val = (uintmax_t)(intmax_t) + (signed char) + va_arg(ap, signed int); + break; + case rank_short: + val = (uintmax_t)(intmax_t) + (signed short) + va_arg(ap, signed int); + break; + case rank_int: + val = (uintmax_t)(intmax_t) + va_arg(ap, signed int); + break; + case rank_long: + val = (uintmax_t)(intmax_t) + va_arg(ap, signed long); + break; + case rank_longlong: + val = (uintmax_t)(intmax_t) + va_arg(ap, + signed long long); + break; + } + goto is_integer; + case 'o': /* Octal */ + base = 8; + goto is_unsigned; + case 'u': /* Unsigned decimal */ + base = 10; + goto is_unsigned; + case 'X': /* Upper case hexadecimal */ + flags |= FL_UPPER; __attribute__ ((fallthrough)); - /* fall through */ - case 'x': /* Hexadecimal */ - base = 16; - goto is_unsigned; + /* fall through */ + case 'x': /* Hexadecimal */ + base = 16; + goto is_unsigned; - is_unsigned: - switch (rank) { - case rank_char: - val = (uintmax_t) - (unsigned char) - va_arg(ap, unsigned - int); - break; - case rank_short: - val = (uintmax_t) - (unsigned short) - va_arg(ap, unsigned - int); - break; - case rank_int: - val = (uintmax_t) - va_arg(ap, unsigned - int); - break; - case rank_long: - val = (uintmax_t) - va_arg(ap, unsigned - long); - break; - case rank_longlong: - val = (uintmax_t) - va_arg(ap, unsigned - long long); - break; - } - /* fall through */ + is_unsigned: + switch (rank) { + case rank_char: + val = (uintmax_t) + (unsigned char) + va_arg(ap, unsigned + int); + break; + case rank_short: + val = (uintmax_t) + (unsigned short) + va_arg(ap, unsigned + int); + break; + case rank_int: + val = (uintmax_t) + va_arg(ap, unsigned + int); + break; + case rank_long: + val = (uintmax_t) + va_arg(ap, unsigned + long); + break; + case rank_longlong: + val = (uintmax_t) + va_arg(ap, unsigned + long long); + break; + } + /* fall through */ - is_integer: - sz = format_int(q, (o < n) ? n - o : 0, - val, flags, base, - width, prec); - q += sz; - o += sz; - break; + is_integer: + sz = format_int(q, (o < n) ? n - o : 0, + val, flags, base, + width, prec); + q += sz; + o += sz; + break; - case 'c': /* Character */ - carg = (char)va_arg(ap, int); - sarg = &carg; - slen = 1; - goto is_string; - case 's': /* String */ - sarg = va_arg(ap, const char *); - sarg = sarg ? sarg : "(null)"; - slen = strlen(sarg); - goto is_string; + case 'c': /* Character */ + carg = (char)va_arg(ap, int); + sarg = &carg; + slen = 1; + goto is_string; + case 's': /* String */ + sarg = va_arg(ap, const char *); + sarg = sarg ? sarg : "(null)"; + slen = strlen(sarg); + goto is_string; - is_string: - { - char sch; - int i; + is_string: + { + char sch; + int i; - if (prec != -1 && slen > prec) - slen = prec; + if (prec != -1 && slen > prec) + slen = prec; - if (width > slen - && !(flags & FL_MINUS)) { - char pad = - (flags & FL_ZERO) ? - '0' : ' '; - while (width > slen) { - EMIT(pad); - width--; - } - } - for (i = slen; i; i--) { - sch = *sarg++; - EMIT(sch); - } - if (width > slen - && (flags & FL_MINUS)) { - while (width > slen) { - EMIT(' '); - width--; - } - } - } - break; + if (width > slen + && !(flags & FL_MINUS)) { + char pad = + (flags & FL_ZERO) ? + '0' : ' '; + while (width > slen) { + EMIT(pad); + width--; + } + } + for (i = slen; i; i--) { + sch = *sarg++; + EMIT(sch); + } + if (width > slen + && (flags & FL_MINUS)) { + while (width > slen) { + EMIT(' '); + width--; + } + } + } + break; - case 'n': - { - /* Output the number of - characters written */ + case 'n': + { + /* Output the number of + characters written */ - switch (rank) { - case rank_char: - *va_arg(ap, - signed char *) - = o; - break; - case rank_short: - *va_arg(ap, - signed short *) - = o; - break; - case rank_int: - *va_arg(ap, - signed int *) - = o; - break; - case rank_long: - *va_arg(ap, - signed long *) - = o; - break; - case rank_longlong: - *va_arg(ap, - signed long long *) - = o; - break; - } - } - break; + switch (rank) { + case rank_char: + *va_arg(ap, + signed char *) + = o; + break; + case rank_short: + *va_arg(ap, + signed short *) + = o; + break; + case rank_int: + *va_arg(ap, + signed int *) + = o; + break; + case rank_long: + *va_arg(ap, + signed long *) + = o; + break; + case rank_longlong: + *va_arg(ap, + signed long long *) + = o; + break; + } + } + break; #ifndef DISABLE_PRINT_FLOAT - case 'f': - { - q = flt(q, va_arg(ap, double), width, prec, ch, SIGN); - continue; - } + case 'f': + { + q = flt(q, va_arg(ap, double), width, prec, ch, SIGN); + continue; + } #endif - default: /* Anything else, including % */ - EMIT(ch); - break; - } - } - } - } + default: /* Anything else, including % */ + EMIT(ch); + break; + } + } + } + } - /* Null-terminate the string */ - if (o < n) - *q = '\0'; /* No overflow */ - else if (n > 0) - buffer[n - 1] = '\0'; /* Overflow - terminate at end of buffer */ + /* Null-terminate the string */ + if (o < n) + *q = '\0'; /* No overflow */ + else if (n > 0) + buffer[n - 1] = '\0'; /* Overflow - terminate at end of buffer */ - return o; + return o; } #ifdef SYS_BIG_DEBUG_BUFFER @@ -841,7 +841,7 @@ static char string[512]; int vsprintf(char *buffer, const char *format, va_list ap) { - return vsnprintf(buffer, sizeof(string) - 32, format, ap); + return vsnprintf(buffer, sizeof(string) - 32, format, ap); } extern volatile bool sys_log_all_enable; @@ -902,25 +902,25 @@ int printf(const char *fmt, ...) int sprintf(char *buffer, const char *format, ...) { - va_list ap; - int rv; + va_list ap; + int rv; - va_start(ap, format); - rv = vsnprintf(buffer, ~(size_t) 0, format, ap); - va_end(ap); + va_start(ap, format); + rv = vsnprintf(buffer, ~(size_t) 0, format, ap); + va_end(ap); - return rv; + return rv; } int snprintf(char *buffer, size_t n, const char *format, ...) { - va_list ap; - int rv; + va_list ap; + int rv; - va_start(ap, format); - rv = vsnprintf(buffer, n, format, ap); - va_end(ap); - return rv; + va_start(ap, format); + rv = vsnprintf(buffer, n, format, ap); + va_end(ap); + return rv; } void vMainUARTPrintString(char *pcString) diff --git a/components/bl602/bl602/evb/src/sscanf.c b/components/bl602/bl602/evb/src/sscanf.c old mode 100755 new mode 100644 index 8d7be900..d3ed6bd0 --- a/components/bl602/bl602/evb/src/sscanf.c +++ b/components/bl602/bl602/evb/src/sscanf.c @@ -40,12 +40,12 @@ int sscanf(const char *str, const char *format, ...) { - va_list ap; - int rv; + va_list ap; + int rv; - va_start(ap, format); - rv = vsscanf(str, format, ap); - va_end(ap); + va_start(ap, format); + rv = vsscanf(str, format, ap); + va_end(ap); - return rv; + return rv; } diff --git a/components/bl602/bl602/evb/src/strntoumax.c b/components/bl602/bl602/evb/src/strntoumax.c old mode 100755 new mode 100644 index 0f8fb866..669d595e --- a/components/bl602/bl602/evb/src/strntoumax.c +++ b/components/bl602/bl602/evb/src/strntoumax.c @@ -44,67 +44,67 @@ static __inline int digitval(int ch) { - if (ch >= '0' && ch <= '9') { - return ch - '0'; - } else if (ch >= 'A' && ch <= 'Z') { - return ch - 'A' + 10; - } else if (ch >= 'a' && ch <= 'z') { - return ch - 'a' + 10; - } else { - return -1; - } + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } else if (ch >= 'A' && ch <= 'Z') { + return ch - 'A' + 10; + } else if (ch >= 'a' && ch <= 'z') { + return ch - 'a' + 10; + } else { + return -1; + } } uintmax_t strntoumax(const char *nptr, char **endptr, int base, size_t n) { - int minus = 0; - uintmax_t v = 0; - int d; + int minus = 0; + uintmax_t v = 0; + int d; - while (n && isspace((unsigned char)*nptr)) { - nptr++; - n--; - } + while (n && isspace((unsigned char)*nptr)) { + nptr++; + n--; + } - /* Single optional + or - */ - if (n) { - char c = *nptr; - if (c == '-' || c == '+') { - minus = (c == '-'); - nptr++; - n--; - } - } + /* Single optional + or - */ + if (n) { + char c = *nptr; + if (c == '-' || c == '+') { + minus = (c == '-'); + nptr++; + n--; + } + } - if (base == 0) { - if (n >= 2 && nptr[0] == '0' && - (nptr[1] == 'x' || nptr[1] == 'X')) { - n -= 2; - nptr += 2; - base = 16; - } else if (n >= 1 && nptr[0] == '0') { - n--; - nptr++; - base = 8; - } else { - base = 10; - } - } else if (base == 16) { - if (n >= 2 && nptr[0] == '0' && - (nptr[1] == 'x' || nptr[1] == 'X')) { - n -= 2; - nptr += 2; - } - } + if (base == 0) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + base = 16; + } else if (n >= 1 && nptr[0] == '0') { + n--; + nptr++; + base = 8; + } else { + base = 10; + } + } else if (base == 16) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + } + } - while (n && (d = digitval(*nptr)) >= 0 && d < base) { - v = v * base + d; - n--; - nptr++; - } + while (n && (d = digitval(*nptr)) >= 0 && d < base) { + v = v * base + d; + n--; + nptr++; + } - if (endptr) - *endptr = (char *)nptr; + if (endptr) + *endptr = (char *)nptr; - return minus ? -v : v; + return minus ? -v : v; } diff --git a/components/bl602/bl602/evb/src/vsscanf.c b/components/bl602/bl602/evb/src/vsscanf.c old mode 100755 new mode 100644 index 9a9a1175..9705ccbd --- a/components/bl602/bl602/evb/src/vsscanf.c +++ b/components/bl602/bl602/evb/src/vsscanf.c @@ -54,391 +54,391 @@ uintmax_t strntoumax(const char *nptr, char **endptr, int base, size_t n); enum flag { - FL_SPLAT = 0x01, /* Drop the value, do not assign */ - FL_INV = 0x02, /* Character-set with inverse */ - FL_WIDTH = 0x04, /* Field width specified */ - FL_MINUS = 0x08, /* Negative number */ + FL_SPLAT = 0x01, /* Drop the value, do not assign */ + FL_INV = 0x02, /* Character-set with inverse */ + FL_WIDTH = 0x04, /* Field width specified */ + FL_MINUS = 0x08, /* Negative number */ }; enum ranks { - rank_char = -2, - rank_short = -1, - rank_int = 0, - rank_long = 1, - rank_longlong = 2, - rank_ptr = INT_MAX /* Special value used for pointers */ + rank_char = -2, + rank_short = -1, + rank_int = 0, + rank_long = 1, + rank_longlong = 2, + rank_ptr = INT_MAX /* Special value used for pointers */ }; -#define MIN_RANK rank_char -#define MAX_RANK rank_longlong +#define MIN_RANK rank_char +#define MAX_RANK rank_longlong -#define INTMAX_RANK rank_longlong -#define SIZE_T_RANK rank_long -#define PTRDIFF_T_RANK rank_long +#define INTMAX_RANK rank_longlong +#define SIZE_T_RANK rank_long +#define PTRDIFF_T_RANK rank_long enum bail { - bail_none = 0, /* No error condition */ - bail_eof, /* Hit EOF */ - bail_err /* Conversion mismatch */ + bail_none = 0, /* No error condition */ + bail_eof, /* Hit EOF */ + bail_err /* Conversion mismatch */ }; static __inline const char *skipspace(const char *p) { - while (isspace((unsigned char)*p)) - p++; - return p; + while (isspace((unsigned char)*p)) + p++; + return p; } #undef set_bit static __inline void set_bit(unsigned long *bitmap, unsigned int bit) { - bitmap[bit / LONG_BIT] |= 1UL << (bit % LONG_BIT); + bitmap[bit / LONG_BIT] |= 1UL << (bit % LONG_BIT); } #undef test_bit static __inline int test_bit(unsigned long *bitmap, unsigned int bit) { - return (int)(bitmap[bit / LONG_BIT] >> (bit % LONG_BIT)) & 1; + return (int)(bitmap[bit / LONG_BIT] >> (bit % LONG_BIT)) & 1; } int vsscanf(const char *buffer, const char *format, va_list ap) { - const char *p = format; - char ch; - unsigned char uc; - const char *q = buffer; - const char *qq; - uintmax_t val = 0; - int rank = rank_int; /* Default rank */ - unsigned int width = UINT_MAX; - int base; - unsigned int flags = 0; - enum { - st_normal, /* Ground state */ - st_flags, /* Special flags */ - st_width, /* Field width */ - st_modifiers, /* Length or conversion modifiers */ - st_match_init, /* Initial state of %[ sequence */ - st_match, /* Main state of %[ sequence */ - st_match_range, /* After - in a %[ sequence */ - } state = st_normal; - char *sarg = NULL; /* %s %c or %[ string argument */ - enum bail bail = bail_none; - __UNUSED__ int sign; - int converted = 0; /* Successful conversions */ - unsigned long matchmap[((1 << CHAR_BIT) + (LONG_BIT - 1)) / LONG_BIT]; - int matchinv = 0; /* Is match map inverted? */ - unsigned char range_start = 0; + const char *p = format; + char ch; + unsigned char uc; + const char *q = buffer; + const char *qq; + uintmax_t val = 0; + int rank = rank_int; /* Default rank */ + unsigned int width = UINT_MAX; + int base; + unsigned int flags = 0; + enum { + st_normal, /* Ground state */ + st_flags, /* Special flags */ + st_width, /* Field width */ + st_modifiers, /* Length or conversion modifiers */ + st_match_init, /* Initial state of %[ sequence */ + st_match, /* Main state of %[ sequence */ + st_match_range, /* After - in a %[ sequence */ + } state = st_normal; + char *sarg = NULL; /* %s %c or %[ string argument */ + enum bail bail = bail_none; + __UNUSED__ int sign; + int converted = 0; /* Successful conversions */ + unsigned long matchmap[((1 << CHAR_BIT) + (LONG_BIT - 1)) / LONG_BIT]; + int matchinv = 0; /* Is match map inverted? */ + unsigned char range_start = 0; - while ((ch = *p++) && !bail) { - switch (state) { - case st_normal: - if (ch == '%') { - state = st_flags; - flags = 0; - rank = rank_int; - width = UINT_MAX; - } else if (isspace((unsigned char)ch)) { - q = skipspace(q); - } else { - if (*q == ch) - q++; - else - bail = bail_err; /* Match failure */ - } - break; + while ((ch = *p++) && !bail) { + switch (state) { + case st_normal: + if (ch == '%') { + state = st_flags; + flags = 0; + rank = rank_int; + width = UINT_MAX; + } else if (isspace((unsigned char)ch)) { + q = skipspace(q); + } else { + if (*q == ch) + q++; + else + bail = bail_err; /* Match failure */ + } + break; - case st_flags: - switch (ch) { - case '*': - flags |= FL_SPLAT; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - width = (ch - '0'); - state = st_width; - flags |= FL_WIDTH; - break; - default: - state = st_modifiers; - p--; /* Process this character again */ - break; - } - break; + case st_flags: + switch (ch) { + case '*': + flags |= FL_SPLAT; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + width = (ch - '0'); + state = st_width; + flags |= FL_WIDTH; + break; + default: + state = st_modifiers; + p--; /* Process this character again */ + break; + } + break; - case st_width: - if (ch >= '0' && ch <= '9') { - width = width * 10 + (ch - '0'); - } else { - state = st_modifiers; - p--; /* Process this character again */ - } - break; + case st_width: + if (ch >= '0' && ch <= '9') { + width = width * 10 + (ch - '0'); + } else { + state = st_modifiers; + p--; /* Process this character again */ + } + break; - case st_modifiers: - switch (ch) { - /* Length modifiers - nonterminal sequences */ - case 'h': - rank--; /* Shorter rank */ - break; - case 'l': - rank++; /* Longer rank */ - break; - case 'j': - rank = INTMAX_RANK; - break; - case 'z': - rank = SIZE_T_RANK; - break; - case 't': - rank = PTRDIFF_T_RANK; - break; - case 'L': - case 'q': - rank = rank_longlong; /* long double/long long */ - break; + case st_modifiers: + switch (ch) { + /* Length modifiers - nonterminal sequences */ + case 'h': + rank--; /* Shorter rank */ + break; + case 'l': + rank++; /* Longer rank */ + break; + case 'j': + rank = INTMAX_RANK; + break; + case 'z': + rank = SIZE_T_RANK; + break; + case 't': + rank = PTRDIFF_T_RANK; + break; + case 'L': + case 'q': + rank = rank_longlong; /* long double/long long */ + break; - default: - /* Output modifiers - terminal sequences */ - /* Next state will be normal */ - state = st_normal; + default: + /* Output modifiers - terminal sequences */ + /* Next state will be normal */ + state = st_normal; - /* Canonicalize rank */ - if (rank < MIN_RANK) - rank = MIN_RANK; - else if (rank > MAX_RANK) - rank = MAX_RANK; + /* Canonicalize rank */ + if (rank < MIN_RANK) + rank = MIN_RANK; + else if (rank > MAX_RANK) + rank = MAX_RANK; - switch (ch) { - case 'P': /* Upper case pointer */ - case 'p': /* Pointer */ - rank = rank_ptr; - base = 0; - sign = 0; - goto scan_int; + switch (ch) { + case 'P': /* Upper case pointer */ + case 'p': /* Pointer */ + rank = rank_ptr; + base = 0; + sign = 0; + goto scan_int; - case 'i': /* Base-independent integer */ - base = 0; - sign = 1; - goto scan_int; + case 'i': /* Base-independent integer */ + base = 0; + sign = 1; + goto scan_int; - case 'd': /* Decimal integer */ - base = 10; - sign = 1; - goto scan_int; + case 'd': /* Decimal integer */ + base = 10; + sign = 1; + goto scan_int; - case 'o': /* Octal integer */ - base = 8; - sign = 0; - goto scan_int; + case 'o': /* Octal integer */ + base = 8; + sign = 0; + goto scan_int; - case 'u': /* Unsigned decimal integer */ - base = 10; - sign = 0; - goto scan_int; + case 'u': /* Unsigned decimal integer */ + base = 10; + sign = 0; + goto scan_int; - case 'x': /* Hexadecimal integer */ - case 'X': - base = 16; - sign = 0; - goto scan_int; + case 'x': /* Hexadecimal integer */ + case 'X': + base = 16; + sign = 0; + goto scan_int; - case 'n': /* # of characters consumed */ - val = (q - buffer); - goto set_integer; + case 'n': /* # of characters consumed */ + val = (q - buffer); + goto set_integer; - scan_int: - q = skipspace(q); - if (!*q) { - bail = bail_eof; - break; - } - val = - strntoumax(q, (char **)&qq, base, - width); - if (qq == q) { - bail = bail_err; - break; - } - q = qq; - if (!(flags & FL_SPLAT)) - converted++; - /* fall through */ + scan_int: + q = skipspace(q); + if (!*q) { + bail = bail_eof; + break; + } + val = + strntoumax(q, (char **)&qq, base, + width); + if (qq == q) { + bail = bail_err; + break; + } + q = qq; + if (!(flags & FL_SPLAT)) + converted++; + /* fall through */ - set_integer: - if (!(flags & FL_SPLAT)) { - switch (rank) { - case rank_char: - *va_arg(ap, - unsigned char *) - = val; - break; - case rank_short: - *va_arg(ap, - unsigned short - *) = val; - break; - case rank_int: - *va_arg(ap, - unsigned int *) - = val; - break; - case rank_long: - *va_arg(ap, - unsigned long *) - = val; - break; - case rank_longlong: - *va_arg(ap, - unsigned long - long *) = val; - break; - case rank_ptr: - *va_arg(ap, void **) = - (void *) - (uintptr_t)val; - break; - } - } - break; + set_integer: + if (!(flags & FL_SPLAT)) { + switch (rank) { + case rank_char: + *va_arg(ap, + unsigned char *) + = val; + break; + case rank_short: + *va_arg(ap, + unsigned short + *) = val; + break; + case rank_int: + *va_arg(ap, + unsigned int *) + = val; + break; + case rank_long: + *va_arg(ap, + unsigned long *) + = val; + break; + case rank_longlong: + *va_arg(ap, + unsigned long + long *) = val; + break; + case rank_ptr: + *va_arg(ap, void **) = + (void *) + (uintptr_t)val; + break; + } + } + break; - case 'c': /* Character */ - /* Default width == 1 */ - width = (flags & FL_WIDTH) ? width : 1; - if (flags & FL_SPLAT) { - while (width--) { - if (!*q) { - bail = bail_eof; - break; - } - } - } else { - sarg = va_arg(ap, char *); - while (width--) { - if (!*q) { - bail = bail_eof; - break; - } - *sarg++ = *q++; - } - if (!bail) - converted++; - } - break; + case 'c': /* Character */ + /* Default width == 1 */ + width = (flags & FL_WIDTH) ? width : 1; + if (flags & FL_SPLAT) { + while (width--) { + if (!*q) { + bail = bail_eof; + break; + } + } + } else { + sarg = va_arg(ap, char *); + while (width--) { + if (!*q) { + bail = bail_eof; + break; + } + *sarg++ = *q++; + } + if (!bail) + converted++; + } + break; - case 's': /* String */ - uc = 1; /* Anything nonzero */ - if (flags & FL_SPLAT) { - while (width-- && (uc = *q) && - !isspace(uc)) { - q++; - } - } else { - char *sp; - sp = sarg = va_arg(ap, char *); - while (width-- && (uc = *q) && - !isspace(uc)) { - *sp++ = uc; - q++; - } - if (sarg != sp) { - /* Terminate output */ - *sp = '\0'; - converted++; - } - } - if (!uc) - bail = bail_eof; - break; + case 's': /* String */ + uc = 1; /* Anything nonzero */ + if (flags & FL_SPLAT) { + while (width-- && (uc = *q) && + !isspace(uc)) { + q++; + } + } else { + char *sp; + sp = sarg = va_arg(ap, char *); + while (width-- && (uc = *q) && + !isspace(uc)) { + *sp++ = uc; + q++; + } + if (sarg != sp) { + /* Terminate output */ + *sp = '\0'; + converted++; + } + } + if (!uc) + bail = bail_eof; + break; - case '[': /* Character range */ - sarg = (flags & FL_SPLAT) ? NULL - : va_arg(ap, char *); - state = st_match_init; - matchinv = 0; - memset(matchmap, 0, sizeof matchmap); - break; + case '[': /* Character range */ + sarg = (flags & FL_SPLAT) ? NULL + : va_arg(ap, char *); + state = st_match_init; + matchinv = 0; + memset(matchmap, 0, sizeof matchmap); + break; - case '%': /* %% sequence */ - if (*q == '%') - q++; - else - bail = bail_err; - break; + case '%': /* %% sequence */ + if (*q == '%') + q++; + else + bail = bail_err; + break; - default: /* Anything else */ - /* Unknown sequence */ - bail = bail_err; - break; - } - } - break; + default: /* Anything else */ + /* Unknown sequence */ + bail = bail_err; + break; + } + } + break; - case st_match_init: /* Initial state for %[ match */ - if (ch == '^' && !(flags & FL_INV)) { - matchinv = 1; - } else { - set_bit(matchmap, (unsigned char)ch); - state = st_match; - } - break; + case st_match_init: /* Initial state for %[ match */ + if (ch == '^' && !(flags & FL_INV)) { + matchinv = 1; + } else { + set_bit(matchmap, (unsigned char)ch); + state = st_match; + } + break; - case st_match: /* Main state for %[ match */ - if (ch == ']') { - goto match_run; - } else if (ch == '-') { - range_start = (unsigned char)ch; - state = st_match_range; - } else { - set_bit(matchmap, (unsigned char)ch); - } - break; + case st_match: /* Main state for %[ match */ + if (ch == ']') { + goto match_run; + } else if (ch == '-') { + range_start = (unsigned char)ch; + state = st_match_range; + } else { + set_bit(matchmap, (unsigned char)ch); + } + break; - case st_match_range: /* %[ match after - */ - if (ch == ']') { - /* - was last character */ - set_bit(matchmap, (unsigned char)'-'); - goto match_run; - } else { - int i; - for (i = range_start; i < (unsigned char)ch; - i++) - set_bit(matchmap, i); - state = st_match; - } - break; + case st_match_range: /* %[ match after - */ + if (ch == ']') { + /* - was last character */ + set_bit(matchmap, (unsigned char)'-'); + goto match_run; + } else { + int i; + for (i = range_start; i < (unsigned char)ch; + i++) + set_bit(matchmap, i); + state = st_match; + } + break; - match_run: /* Match expression finished */ - qq = q; - uc = 1; /* Anything nonzero */ - while (width && (uc = *q) - && test_bit(matchmap, uc)^matchinv) { - if (sarg) - *sarg++ = uc; - q++; - } - if (q != qq && sarg) { - *sarg = '\0'; - converted++; - } else { - bail = bail_err; - } - if (!uc) - bail = bail_eof; - break; - } - } + match_run: /* Match expression finished */ + qq = q; + uc = 1; /* Anything nonzero */ + while (width && (uc = *q) + && test_bit(matchmap, uc)^matchinv) { + if (sarg) + *sarg++ = uc; + q++; + } + if (q != qq && sarg) { + *sarg = '\0'; + converted++; + } else { + bail = bail_err; + } + if (!uc) + bail = bail_eof; + break; + } + } - if (bail == bail_eof && !converted) - converted = -1; /* Return EOF (-1) */ + if (bail == bail_eof && !converted) + converted = -1; /* Return EOF (-1) */ - return converted; + return converted; } diff --git a/components/bl602/bl602_std/bl602_std/Common/Common.mk b/components/bl602/bl602_std/bl602_std/Common/Common.mk index a7fe122c..2796c919 100644 --- a/components/bl602/bl602_std/bl602_std/Common/Common.mk +++ b/components/bl602/bl602_std/bl602_std/Common/Common.mk @@ -4,14 +4,14 @@ LOCAL_SRCS_FILE:= MODULE_DIR:= BSP/Common MODULE_OUT_DIR:= $(TARGET_OUT_PATH)/BSP/Common -COMMON_CFLAGS:= -COMMON_INCLUDE:= +COMMON_CFLAGS:= +COMMON_INCLUDE:= common_objs_target := -COM_EXCLUDE_DIR:= BSP/Common/mbedtls - +COM_EXCLUDE_DIR:= BSP/Common/mbedtls + COM_ALL_DIRS := $(shell find $(MODULE_DIR) -maxdepth 1 -mindepth 1 -type d) -COM_DIRS=$(filter-out $(COM_EXCLUDE_DIR), $(COM_ALL_DIRS)) +COM_DIRS=$(filter-out $(COM_EXCLUDE_DIR), $(COM_ALL_DIRS)) COM_MKS=$(foreach com_dir,$(COM_DIRS),$(wildcard $(com_dir)/*.mk)) #$(info $(COM_MKS)) diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/cipher_suite.mk b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/cipher_suite.mk index c6919256..193d24f9 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/cipher_suite.mk +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/cipher_suite.mk @@ -6,14 +6,14 @@ CIPHER_SUITE_INC := -I$(SUB_MODULE_DIR)/inc CIPHER_SUITE_CFLAGS := -COMMON_INCLUDE += -I $(MODULE_DIR)/cipher_suite/inc +COMMON_INCLUDE += -I $(MODULE_DIR)/cipher_suite/inc cipher_suite_sources := bflb_crypt.c bflb_hash.c bflb_ecdsa.c bflb_dsa.c cipher_suite_objs := $(addprefix $(SUB_MODULE_OUT_DIR)/, $(subst .c,.o,$(cipher_suite_sources))) common_objs_target += $(cipher_suite_objs) - + $(SUB_MODULE_OUT_DIR)/%.o:$(SUB_MODULE_SRC_DIR)/%.c @mkdir -p $(dir $@) @echo "cc $<" diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt.h b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt.h index e0385d60..9359dc40 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt.h +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt.h @@ -8,21 +8,21 @@ #include "bflb_platform.h" -#define bflb_crypt_printf bflb_platform_printf -#define bflb_crypt_printe bflb_platform_printf -#define bflb_crypt_printd bflb_platform_printf -#define bflb_crypt_printw bflb_platform_printf +#define bflb_crypt_printf bflb_platform_printf +#define bflb_crypt_printe bflb_platform_printf +#define bflb_crypt_printd bflb_platform_printf +#define bflb_crypt_printw bflb_platform_printf #define BFLB_CRYPT_OK 0 #define BFLB_CRYPT_ERROR -1 -#define BFLB_CRYPT_TYPE_AES_CBC 0 -#define BFLB_CRYPT_TYPE_AES_CTR 1 -#define BFLB_CRYPT_TYPE_CHACHA 2 -#define BFLB_CRYPT_TYPE_AES_CCM 3 -#define BFLB_CRYPT_TYPE_AES_GCM 4 -#define BFLB_CRYPT_TYPE_CHACHAPOLY1305 5 +#define BFLB_CRYPT_TYPE_AES_CBC 0 +#define BFLB_CRYPT_TYPE_AES_CTR 1 +#define BFLB_CRYPT_TYPE_CHACHA 2 +#define BFLB_CRYPT_TYPE_AES_CCM 3 +#define BFLB_CRYPT_TYPE_AES_GCM 4 +#define BFLB_CRYPT_TYPE_CHACHAPOLY1305 5 typedef struct tag_bflb_crypt_handle_t { @@ -35,27 +35,27 @@ typedef struct tag_bflb_crypt_handle_t int32_t bflb_crypt_init(bflb_crypt_handle_t *crypt_handle,uint8_t type); int32_t bflb_crypt_setkey(bflb_crypt_handle_t *aes_handle,const uint8_t *key, - uint8_t keytype,uint8_t key_len,const uint8_t *nonce,uint8_t nonce_len,uint8_t dir); + uint8_t keytype,uint8_t key_len,const uint8_t *nonce,uint8_t nonce_len,uint8_t dir); int32_t bflb_crypt_setadd(bflb_crypt_handle_t *aes_handle,const uint8_t *add, - uint8_t len,uint8_t dir); + uint8_t len,uint8_t dir); int32_t bflb_crypt_update(bflb_crypt_handle_t *aes_handle,const uint8_t *in, - uint32_t len,uint8_t *out); + uint32_t len,uint8_t *out); int32_t bflb_crypt_encrypt(bflb_crypt_handle_t *aes_handle,const uint8_t *in, - uint32_t len,size_t offset,uint8_t *out); + uint32_t len,size_t offset,uint8_t *out); int32_t bflb_crypt_encrypt_tag(bflb_crypt_handle_t *aes_handle,const uint8_t *in, - uint32_t in_len,const uint8_t *add,uint32_t add_len,size_t offset, - uint8_t *out,uint8_t *tag,uint8_t tag_len); + uint32_t in_len,const uint8_t *add,uint32_t add_len,size_t offset, + uint8_t *out,uint8_t *tag,uint8_t tag_len); int32_t bflb_crypt_auth_decrypt(bflb_crypt_handle_t *aes_handle,const uint8_t *in, - uint32_t in_len,const uint8_t *add,uint32_t add_len,size_t offset, - uint8_t *out,const uint8_t *tag,uint8_t tag_len); + uint32_t in_len,const uint8_t *add,uint32_t add_len,size_t offset, + uint8_t *out,const uint8_t *tag,uint8_t tag_len); int32_t bflb_crypt_decrypt(bflb_crypt_handle_t *aes_handle,const uint8_t *in, - uint32_t len,size_t offset,uint8_t *out); + uint32_t len,size_t offset,uint8_t *out); int32_t bflb_crypt_finish(bflb_crypt_handle_t *aes_handle,uint8_t *tag,uint32_t len); diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt_port.h b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt_port.h index 3fd4359b..b0b2a79f 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt_port.h +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_crypt_port.h @@ -15,9 +15,9 @@ #include "stdlib.h" #include "string.h" -#define BFLB_CRYPT_KEY_SIZE_MAX 32 +#define BFLB_CRYPT_KEY_SIZE_MAX 32 #define BFLB_CRYPT_NONCE_SIZE_MAX 16 -#define BFLB_CRYPT_BLK_SIZE 16 +#define BFLB_CRYPT_BLK_SIZE 16 #ifndef BFLB_CRYPT_HARDWARE typedef union tag_bflb_crypt_ctx_t @@ -33,13 +33,13 @@ typedef union tag_bflb_crypt_ctx_t typedef struct tag_bflb_crypt_cfg_t { #ifndef BFLB_CRYPT_HARDWARE - uint8_t key[BFLB_CRYPT_KEY_SIZE_MAX]; - //for general cipher,iv is 16 bytes, but for GCM vector test, there is a 60 bytes test - uint8_t iv_nonce[BFLB_CRYPT_NONCE_SIZE_MAX*4]; - uint8_t stream_block[BFLB_CRYPT_BLK_SIZE]; - uint8_t key_len; - uint8_t nonce_len; - uint8_t dir; + uint8_t key[BFLB_CRYPT_KEY_SIZE_MAX]; + //for general cipher,iv is 16 bytes, but for GCM vector test, there is a 60 bytes test + uint8_t iv_nonce[BFLB_CRYPT_NONCE_SIZE_MAX*4]; + uint8_t stream_block[BFLB_CRYPT_BLK_SIZE]; + uint8_t key_len; + uint8_t nonce_len; + uint8_t dir; #else #endif uint8_t type; diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_ecdsa_port.h b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_ecdsa_port.h index 90b0aa59..e3771b1a 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_ecdsa_port.h +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_ecdsa_port.h @@ -13,7 +13,7 @@ typedef union tag_bflb_ecdsa_ctx_t { #ifndef BFLB_PKA_HARDWARE - mbedtls_ecdsa_context ctx_ecdsa; + mbedtls_ecdsa_context ctx_ecdsa; #endif }bflb_ecdsa_ctx_t; diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash.h b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash.h index 7918e0c3..0ba25d6f 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash.h +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash.h @@ -26,7 +26,7 @@ typedef struct tag_bflb_hash_handle_t { bflb_hash_ctx_t hash_ctx; #ifdef BFLB_CRYPT_HARDWARE - uint32_t sha_padding[64/4]; //for sha finish compute, must located at OCRAM + uint32_t sha_padding[64/4]; //for sha finish compute, must located at OCRAM #endif uint8_t type; }bflb_hash_handle_t; diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash_port.h b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash_port.h index 34571a13..160c646f 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash_port.h +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/inc/bflb_hash_port.h @@ -21,7 +21,7 @@ typedef union tag_bflb_hash_ctx_t mbedtls_sha256_context ctx_sha256; mbedtls_sha512_context ctx_sha512; #else - uint32_t sha_buf[64/4]; //for sha finish compute, must located at OCRAM + uint32_t sha_buf[64/4]; //for sha finish compute, must located at OCRAM #endif }bflb_hash_ctx_t; diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_crypt.c b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_crypt.c index cb5f66ac..a73cb83a 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_crypt.c +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_crypt.c @@ -6,28 +6,28 @@ int32_t bflb_crypt_init_do(bflb_crypt_handle_t *crypt_handle,uint8_t type) int32_t ret = BFLB_CRYPT_OK; switch(type) - { - case BFLB_CRYPT_TYPE_AES_CBC: - case BFLB_CRYPT_TYPE_AES_CTR: - mbedtls_aes_init((mbedtls_aes_context*)&crypt_handle->crypt_ctx); - break; - case BFLB_CRYPT_TYPE_CHACHA: - memset((ChaCha*)&crypt_handle->crypt_ctx,0,sizeof(ChaCha)); - break; - case BFLB_CRYPT_TYPE_AES_CCM: - mbedtls_ccm_init((mbedtls_ccm_context *)&crypt_handle->crypt_ctx); - break; - case BFLB_CRYPT_TYPE_AES_GCM: - mbedtls_gcm_init((mbedtls_gcm_context *)&crypt_handle->crypt_ctx); - break; - case BFLB_CRYPT_TYPE_CHACHAPOLY1305: - memset((ChaChaPoly1305*)&crypt_handle->crypt_ctx,0,sizeof(ChaChaPoly1305)); - break; - default: - bflb_crypt_printe("unsupported type\r\n"); - ret=BFLB_CRYPT_ERROR; - break; - } + { + case BFLB_CRYPT_TYPE_AES_CBC: + case BFLB_CRYPT_TYPE_AES_CTR: + mbedtls_aes_init((mbedtls_aes_context*)&crypt_handle->crypt_ctx); + break; + case BFLB_CRYPT_TYPE_CHACHA: + memset((ChaCha*)&crypt_handle->crypt_ctx,0,sizeof(ChaCha)); + break; + case BFLB_CRYPT_TYPE_AES_CCM: + mbedtls_ccm_init((mbedtls_ccm_context *)&crypt_handle->crypt_ctx); + break; + case BFLB_CRYPT_TYPE_AES_GCM: + mbedtls_gcm_init((mbedtls_gcm_context *)&crypt_handle->crypt_ctx); + break; + case BFLB_CRYPT_TYPE_CHACHAPOLY1305: + memset((ChaChaPoly1305*)&crypt_handle->crypt_ctx,0,sizeof(ChaChaPoly1305)); + break; + default: + bflb_crypt_printe("unsupported type\r\n"); + ret=BFLB_CRYPT_ERROR; + break; + } return ret; } @@ -36,14 +36,14 @@ int32_t bflb_crypt_setkey_do(bflb_crypt_handle_t *crypt_handle,const uint8_t *ke { int32_t ret = BFLB_CRYPT_OK; - memset(crypt_handle->crypt_cfg.key,0,sizeof(crypt_handle->crypt_cfg.key)); - memset(crypt_handle->crypt_cfg.iv_nonce,0,sizeof(crypt_handle->crypt_cfg.iv_nonce)); - memset(crypt_handle->crypt_cfg.stream_block,0,sizeof(crypt_handle->crypt_cfg.stream_block)); + memset(crypt_handle->crypt_cfg.key,0,sizeof(crypt_handle->crypt_cfg.key)); + memset(crypt_handle->crypt_cfg.iv_nonce,0,sizeof(crypt_handle->crypt_cfg.iv_nonce)); + memset(crypt_handle->crypt_cfg.stream_block,0,sizeof(crypt_handle->crypt_cfg.stream_block)); - memcpy(crypt_handle->crypt_cfg.key,key,key_len); - memcpy(crypt_handle->crypt_cfg.iv_nonce,nonce,nonce_len); - crypt_handle->crypt_cfg.key_len=key_len; - crypt_handle->crypt_cfg.nonce_len=nonce_len; + memcpy(crypt_handle->crypt_cfg.key,key,key_len); + memcpy(crypt_handle->crypt_cfg.iv_nonce,nonce,nonce_len); + crypt_handle->crypt_cfg.key_len=key_len; + crypt_handle->crypt_cfg.nonce_len=nonce_len; switch(crypt_handle->crypt_cfg.type) { @@ -61,9 +61,9 @@ int32_t bflb_crypt_setkey_do(bflb_crypt_handle_t *crypt_handle,const uint8_t *ke key, key_len*8); break; case BFLB_CRYPT_TYPE_CHACHA: - ret|=Chacha_SetIV((ChaCha*)&crypt_handle->crypt_ctx, nonce, nonce_len,0); - ret|=Chacha_SetKey((ChaCha*)&crypt_handle->crypt_ctx, key, key_len); - break; + ret|=Chacha_SetIV((ChaCha*)&crypt_handle->crypt_ctx, nonce, nonce_len,0); + ret|=Chacha_SetKey((ChaCha*)&crypt_handle->crypt_ctx, key, key_len); + break; case BFLB_CRYPT_TYPE_AES_CCM: ret=mbedtls_ccm_setkey((mbedtls_ccm_context*)&crypt_handle->crypt_ctx, MBEDTLS_CIPHER_ID_AES, key, key_len*8 ) ; @@ -73,7 +73,7 @@ int32_t bflb_crypt_setkey_do(bflb_crypt_handle_t *crypt_handle,const uint8_t *ke MBEDTLS_CIPHER_ID_AES, key, key_len*8 ) ; break; case BFLB_CRYPT_TYPE_CHACHAPOLY1305: - break; + break; default: bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; @@ -119,13 +119,13 @@ int32_t bflb_crypt_encrypt_do(bflb_crypt_handle_t *crypt_handle,const uint8_t *i MBEDTLS_AES_ENCRYPT, len, crypt_handle->crypt_cfg.iv_nonce, in, out); break; case BFLB_CRYPT_TYPE_AES_CTR: - result=mbedtls_aes_crypt_ctr((mbedtls_aes_context*)&crypt_handle->crypt_ctx, - len, &offset2, crypt_handle->crypt_cfg.iv_nonce, crypt_handle->crypt_cfg.stream_block, - in, out ); - break; + result=mbedtls_aes_crypt_ctr((mbedtls_aes_context*)&crypt_handle->crypt_ctx, + len, &offset2, crypt_handle->crypt_cfg.iv_nonce, crypt_handle->crypt_cfg.stream_block, + in, out ); + break; case BFLB_CRYPT_TYPE_CHACHA: - result=Chacha_Process((ChaCha*)&crypt_handle->crypt_ctx,out,in,len); - break; + result=Chacha_Process((ChaCha*)&crypt_handle->crypt_ctx,out,in,len); + break; default: bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; @@ -153,13 +153,13 @@ int32_t bflb_crypt_encrypt_tag_do(bflb_crypt_handle_t *crypt_handle,const uint8_ add,add_len,in,out,tag_len,tag); break; case BFLB_CRYPT_TYPE_CHACHAPOLY1305: - result = ChaCha20Poly1305_Encrypt((ChaChaPoly1305*)&crypt_handle->crypt_ctx, - crypt_handle->crypt_cfg.key,crypt_handle->crypt_cfg.key_len, - crypt_handle->crypt_cfg.iv_nonce,crypt_handle->crypt_cfg.nonce_len, - add,add_len,in,in_len,out,tag,tag_len); - break; + result = ChaCha20Poly1305_Encrypt((ChaChaPoly1305*)&crypt_handle->crypt_ctx, + crypt_handle->crypt_cfg.key,crypt_handle->crypt_cfg.key_len, + crypt_handle->crypt_cfg.iv_nonce,crypt_handle->crypt_cfg.nonce_len, + add,add_len,in,in_len,out,tag,tag_len); + break; default: - bflb_crypt_printe("unsupported type\r\n"); + bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; } @@ -209,8 +209,8 @@ int32_t bflb_crypt_decrypt_do(bflb_crypt_handle_t *crypt_handle,const uint8_t *i in, out ); break; case BFLB_CRYPT_TYPE_CHACHA: - result=Chacha_Process((ChaCha*)&crypt_handle->crypt_ctx,out,in,len); - break; + result=Chacha_Process((ChaCha*)&crypt_handle->crypt_ctx,out,in,len); + break; default: bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; @@ -239,13 +239,13 @@ int32_t bflb_crypt_auth_decrypt_do(bflb_crypt_handle_t *crypt_handle,const uint8 add,add_len,tag,tag_len,in,out); break; case BFLB_CRYPT_TYPE_CHACHAPOLY1305: - result = ChaCha20Poly1305_Decrypt((ChaChaPoly1305*)&crypt_handle->crypt_ctx, - crypt_handle->crypt_cfg.key,crypt_handle->crypt_cfg.key_len, - crypt_handle->crypt_cfg.iv_nonce,crypt_handle->crypt_cfg.nonce_len, - add,add_len,in,in_len,tag,tag_len,out); - break; + result = ChaCha20Poly1305_Decrypt((ChaChaPoly1305*)&crypt_handle->crypt_ctx, + crypt_handle->crypt_cfg.key,crypt_handle->crypt_cfg.key_len, + crypt_handle->crypt_cfg.iv_nonce,crypt_handle->crypt_cfg.nonce_len, + add,add_len,in,in_len,tag,tag_len,out); + break; default: - bflb_crypt_printe("unsupported type\r\n"); + bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; } @@ -263,7 +263,7 @@ int32_t bflb_crypt_finish_do(bflb_crypt_handle_t *crypt_handle,uint8_t *tag,uint tag, len ); break; default: - bflb_crypt_printe("unsupported type\r\n"); + bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; } @@ -287,9 +287,9 @@ int32_t bflb_crypt_deinit_do(bflb_crypt_handle_t *crypt_handle) break; case BFLB_CRYPT_TYPE_CHACHA: case BFLB_CRYPT_TYPE_CHACHAPOLY1305: - break; + break; default: - bflb_crypt_printe("unsupported type\r\n"); + bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; } @@ -307,40 +307,40 @@ int32_t bflb_crypt_init_do(bflb_crypt_handle_t *crypt_handle,uint8_t type) int32_t bflb_crypt_setkey_do(bflb_crypt_handle_t *crypt_handle,const uint8_t *key, uint8_t keytype, uint8_t key_len, const uint8_t *nonce,uint8_t nonce_len,uint8_t dir) { - int32_t ret = BFLB_CRYPT_OK; + int32_t ret = BFLB_CRYPT_OK; - switch(crypt_handle->crypt_cfg.type) - { - case BFLB_CRYPT_TYPE_AES_CBC: - Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0); + switch(crypt_handle->crypt_cfg.type) + { + case BFLB_CRYPT_TYPE_AES_CBC: + Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0); Sec_Eng_AES_Init(&aesCtx,SEC_ENG_AES_ID0,SEC_ENG_AES_CBC,(SEC_ENG_AES_Key_Type)keytype, - BFLB_CRYPT_DIR_ENCRYPT==dir?SEC_ENG_AES_ENCRYPTION:SEC_ENG_AES_DECRYPTION); - break; - case BFLB_CRYPT_TYPE_AES_CTR: - Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0); - Sec_Eng_AES_Init(&aesCtx,SEC_ENG_AES_ID0,SEC_ENG_AES_CTR,(SEC_ENG_AES_Key_Type)keytype, - BFLB_CRYPT_DIR_ENCRYPT==dir?SEC_ENG_AES_ENCRYPTION:SEC_ENG_AES_DECRYPTION); - break; - case BFLB_CRYPT_TYPE_AES_CCM: - break; - case BFLB_CRYPT_TYPE_AES_GCM: - break; - case BFLB_CRYPT_TYPE_CHACHA: - case BFLB_CRYPT_TYPE_CHACHAPOLY1305: - break; - default: - bflb_crypt_printe("unsupported type\r\n"); - return BFLB_CRYPT_ERROR; - } + BFLB_CRYPT_DIR_ENCRYPT==dir?SEC_ENG_AES_ENCRYPTION:SEC_ENG_AES_DECRYPTION); + break; + case BFLB_CRYPT_TYPE_AES_CTR: + Sec_Eng_AES_Enable_BE(SEC_ENG_AES_ID0); + Sec_Eng_AES_Init(&aesCtx,SEC_ENG_AES_ID0,SEC_ENG_AES_CTR,(SEC_ENG_AES_Key_Type)keytype, + BFLB_CRYPT_DIR_ENCRYPT==dir?SEC_ENG_AES_ENCRYPTION:SEC_ENG_AES_DECRYPTION); + break; + case BFLB_CRYPT_TYPE_AES_CCM: + break; + case BFLB_CRYPT_TYPE_AES_GCM: + break; + case BFLB_CRYPT_TYPE_CHACHA: + case BFLB_CRYPT_TYPE_CHACHAPOLY1305: + break; + default: + bflb_crypt_printe("unsupported type\r\n"); + return BFLB_CRYPT_ERROR; + } - /* if key len is 0, means key is from efuse and *key value is key_sel value */ - if(key_len==0){ - Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0,SEC_ENG_AES_KEY_HW,key,nonce); - }else{ - Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0,SEC_ENG_AES_KEY_SW,key,nonce); - } + /* if key len is 0, means key is from efuse and *key value is key_sel value */ + if(key_len==0){ + Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0,SEC_ENG_AES_KEY_HW,key,nonce); + }else{ + Sec_Eng_AES_Set_Key_IV_BE(SEC_ENG_AES_ID0,SEC_ENG_AES_KEY_SW,key,nonce); + } - return ret; + return ret; } int32_t bflb_crypt_setadd_do(bflb_crypt_handle_t *crypt_handle,const uint8_t *add,uint8_t len, @@ -421,7 +421,7 @@ int32_t bflb_crypt_deinit_do(bflb_crypt_handle_t *crypt_handle) case BFLB_CRYPT_TYPE_AES_CTR: break; default: - bflb_crypt_printe("unsupported type\r\n"); + bflb_crypt_printe("unsupported type\r\n"); return BFLB_CRYPT_ERROR; } @@ -448,8 +448,8 @@ int32_t bflb_crypt_setkey(bflb_crypt_handle_t *crypt_handle,const uint8_t *key,u result=bflb_crypt_setkey_do(crypt_handle,key,keytype,key_len,nonce,nonce_len,dir); if(result!=BFLB_CRYPT_OK){ - bflb_crypt_printe("crypt set key fail\r\n"); - result=BFLB_CRYPT_ERROR; + bflb_crypt_printe("crypt set key fail\r\n"); + result=BFLB_CRYPT_ERROR; } return result; @@ -463,8 +463,8 @@ int32_t bflb_crypt_setadd(bflb_crypt_handle_t *crypt_handle,const uint8_t *add,u result = bflb_crypt_setadd_do(crypt_handle,add,len,dir); if(result!=BFLB_CRYPT_OK){ - bflb_crypt_printe("crypt set add fail\r\n"); - result=BFLB_CRYPT_ERROR; + bflb_crypt_printe("crypt set add fail\r\n"); + result=BFLB_CRYPT_ERROR; } return result; @@ -473,7 +473,7 @@ int32_t bflb_crypt_setadd(bflb_crypt_handle_t *crypt_handle,const uint8_t *add,u int32_t bflb_crypt_encrypt(bflb_crypt_handle_t *crypt_handle,const uint8_t *in,uint32_t len, size_t offset,uint8_t *out) { - int32_t result; + int32_t result; result=bflb_crypt_encrypt_do(crypt_handle,in,len, offset,out); @@ -490,13 +490,13 @@ int32_t bflb_crypt_encrypt_tag(bflb_crypt_handle_t *crypt_handle,const uint8_t * const uint8_t *add,uint32_t add_len,size_t offset,uint8_t *out, uint8_t *tag,uint8_t tag_len) { - int32_t result; + int32_t result; result= bflb_crypt_encrypt_tag_do(crypt_handle,in,in_len,add,add_len,offset,out,tag,tag_len); if( result != BFLB_CRYPT_OK) { - bflb_crypt_printe("crypt encrypt and tag fail\r\n"); + bflb_crypt_printe("crypt encrypt and tag fail\r\n"); return BFLB_CRYPT_ERROR; } @@ -506,7 +506,7 @@ int32_t bflb_crypt_encrypt_tag(bflb_crypt_handle_t *crypt_handle,const uint8_t * int32_t bflb_crypt_update(bflb_crypt_handle_t *crypt_handle,const uint8_t *in,uint32_t len, uint8_t *out) { - int32_t result; + int32_t result; result=bflb_crypt_update_do(crypt_handle,in,len,out); @@ -523,7 +523,7 @@ int32_t bflb_crypt_update(bflb_crypt_handle_t *crypt_handle,const uint8_t *in,ui int32_t bflb_crypt_decrypt(bflb_crypt_handle_t *crypt_handle,const uint8_t *in,uint32_t len, size_t offset,uint8_t *out) { - int32_t result; + int32_t result; result=bflb_crypt_decrypt_do(crypt_handle,in,len,offset,out); @@ -540,7 +540,7 @@ int32_t bflb_crypt_auth_decrypt(bflb_crypt_handle_t *crypt_handle,const uint8_t const uint8_t *add,uint32_t add_len,size_t offset,uint8_t *out, const uint8_t *tag,uint8_t tag_len) { - int32_t result; + int32_t result; result= bflb_crypt_auth_decrypt_do(crypt_handle,in,in_len,add,add_len,offset,out,tag,tag_len); @@ -555,7 +555,7 @@ int32_t bflb_crypt_auth_decrypt(bflb_crypt_handle_t *crypt_handle,const uint8_t int32_t bflb_crypt_finish(bflb_crypt_handle_t *crypt_handle,uint8_t *tag,uint32_t len) { - int32_t result; + int32_t result; result=bflb_crypt_finish_do(crypt_handle,tag,len); @@ -572,7 +572,7 @@ int32_t bflb_crypt_finish(bflb_crypt_handle_t *crypt_handle,uint8_t *tag,uint32_ int32_t bflb_crypt_deinit(bflb_crypt_handle_t *crypt_handle) { - bflb_crypt_deinit_do(crypt_handle); + bflb_crypt_deinit_do(crypt_handle); memset(crypt_handle,0,sizeof(bflb_crypt_handle_t)); return BFLB_CRYPT_OK; diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_ecdsa.c b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_ecdsa.c index 1855d550..ed689992 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_ecdsa.c +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_ecdsa.c @@ -1021,10 +1021,10 @@ int32_t bflb_ecdh_get_public_key( uint8_t id,const uint32_t *pkX,const uint32_t int32_t bflb_ecdsa_get_private_key( uint8_t id,uint32_t *private_key) { - if(bflb_ecc_get_random_value(private_key,(uint32_t *)secp256r1N,32)<0){ - return -1; - } - return 0; + if(bflb_ecc_get_random_value(private_key,(uint32_t *)secp256r1N,32)<0){ + return -1; + } + return 0; } int32_t bflb_ecdsa_sign( uint8_t id,const uint32_t *private_key,const uint32_t *random_k,const uint32_t *hash,uint32_t *r,uint32_t *s) diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_hash.c b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_hash.c index a7bff046..0c74f7b4 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_hash.c +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_hash.c @@ -32,8 +32,8 @@ int32_t bflb_hash_init(bflb_hash_handle_t *hash_handle,uint8_t type) switch(type) { case BFLB_HASH_TYPE_SHA1 : - ret=BFLB_HASH_ERROR; - bflb_hash_printe("unsupported type\r\n"); + ret=BFLB_HASH_ERROR; + bflb_hash_printe("unsupported type\r\n"); break; case BFLB_HASH_TYPE_SHA224: Sec_Eng_SHA256_Init(&shaCtx,SEC_ENG_SHA_ID0,SEC_ENG_SHA224,(uint32_t *)hash_handle->hash_ctx.sha_buf, @@ -45,8 +45,8 @@ int32_t bflb_hash_init(bflb_hash_handle_t *hash_handle,uint8_t type) break; case BFLB_HASH_TYPE_SHA384: case BFLB_HASH_TYPE_SHA512: - ret=BFLB_HASH_ERROR; - bflb_hash_printe("unsupported type\r\n"); + ret=BFLB_HASH_ERROR; + bflb_hash_printe("unsupported type\r\n"); break; default: bflb_hash_printe("unsupported type\r\n"); @@ -71,10 +71,10 @@ int32_t bflb_hash_start(bflb_hash_handle_t *hash_handle) case BFLB_HASH_TYPE_SHA1: break; case BFLB_HASH_TYPE_SHA224: - Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0); + Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0); break; case BFLB_HASH_TYPE_SHA256: - Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0); + Sec_Eng_SHA_Start(SEC_ENG_SHA_ID0); break; case BFLB_HASH_TYPE_SHA384: break; @@ -86,7 +86,7 @@ int32_t bflb_hash_start(bflb_hash_handle_t *hash_handle) } if(ret!=0){ - bflb_hash_printe("hash start fail\r\n"); + bflb_hash_printe("hash start fail\r\n"); ret=BFLB_HASH_ERROR; } return ret; @@ -100,11 +100,11 @@ int32_t bflb_hash_update(bflb_hash_handle_t *hash_handle,const uint8_t *in,uint3 { case BFLB_HASH_TYPE_SHA1: break; - case BFLB_HASH_TYPE_SHA224: - Sec_Eng_SHA256_Update(&shaCtx,SEC_ENG_SHA_ID0,in, len); - break; + case BFLB_HASH_TYPE_SHA224: + Sec_Eng_SHA256_Update(&shaCtx,SEC_ENG_SHA_ID0,in, len); + break; case BFLB_HASH_TYPE_SHA256: - Sec_Eng_SHA256_Update(&shaCtx,SEC_ENG_SHA_ID0,in, len); + Sec_Eng_SHA256_Update(&shaCtx,SEC_ENG_SHA_ID0,in, len); break; case BFLB_HASH_TYPE_SHA384: break; @@ -116,7 +116,7 @@ int32_t bflb_hash_update(bflb_hash_handle_t *hash_handle,const uint8_t *in,uint3 } if(ret!=0){ - bflb_hash_printe("hash update fail\r\n"); + bflb_hash_printe("hash update fail\r\n"); ret=BFLB_HASH_ERROR; } @@ -132,10 +132,10 @@ int32_t bflb_hash_finish(bflb_hash_handle_t *hash_handle,uint8_t *out) case BFLB_HASH_TYPE_SHA1: break; case BFLB_HASH_TYPE_SHA224: - Sec_Eng_SHA256_Finish(&shaCtx,SEC_ENG_SHA_ID0,out); - break; + Sec_Eng_SHA256_Finish(&shaCtx,SEC_ENG_SHA_ID0,out); + break; case BFLB_HASH_TYPE_SHA256: - Sec_Eng_SHA256_Finish(&shaCtx,SEC_ENG_SHA_ID0,out); + Sec_Eng_SHA256_Finish(&shaCtx,SEC_ENG_SHA_ID0,out); break; case BFLB_HASH_TYPE_SHA384: break; @@ -147,7 +147,7 @@ int32_t bflb_hash_finish(bflb_hash_handle_t *hash_handle,uint8_t *out) } if(ret!=0){ - bflb_hash_printe("hash finish fail\r\n"); + bflb_hash_printe("hash finish fail\r\n"); ret=BFLB_HASH_ERROR; } @@ -161,7 +161,7 @@ int32_t bflb_hash_deinit(bflb_hash_handle_t *hash_handle) case BFLB_HASH_TYPE_SHA1: break; case BFLB_HASH_TYPE_SHA224: - break; + break; case BFLB_HASH_TYPE_SHA256: break; case BFLB_HASH_TYPE_SHA384: diff --git a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_rsa.c b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_rsa.c index 8873ddfd..f2c58316 100644 --- a/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_rsa.c +++ b/components/bl602/bl602_std/bl602_std/Common/cipher_suite/src/bflb_rsa.c @@ -15,8 +15,8 @@ int32_t bflb_rsa_set_parameter(bflb_rsa_handle_t *rsa_handle,int type,uint8_t *v int32_t ret = BFLB_RSA_OK; mbedtls_rsa_context* rsa=(mbedtls_rsa_context*)&rsa_handle->rsa_ctx; - switch(type) - { + switch(type) + { case BFLB_RSA_PARA_N: mbedtls_mpi_read_binary(&rsa->N,value,len); rsa->len = ( mbedtls_mpi_bitlen( &rsa->N ) + 7 ) >> 3; @@ -45,7 +45,7 @@ int32_t bflb_rsa_set_parameter(bflb_rsa_handle_t *rsa_handle,int type,uint8_t *v default: ret=BFLB_RSA_ERROR; break; - } + } return ret; } @@ -55,7 +55,7 @@ int32_t bflb_rsa_check_private(bflb_rsa_handle_t *rsa_handle) int32_t ret = BFLB_RSA_OK; mbedtls_rsa_context* rsa=(mbedtls_rsa_context*)&rsa_handle->rsa_ctx; - if( ( ret = mbedtls_rsa_check_privkey( rsa ) ) != 0 ) + if( ( ret = mbedtls_rsa_check_privkey( rsa ) ) != 0 ) { bflb_rsa_printe("failed\r\n!rsa_check_privkey failed with -0x%0x\n", -ret ); return BFLB_RSA_ERROR; @@ -69,7 +69,7 @@ int32_t bflb_rsa_check_public(bflb_rsa_handle_t *rsa_handle) int32_t ret = BFLB_RSA_OK; mbedtls_rsa_context* rsa=(mbedtls_rsa_context*)&rsa_handle->rsa_ctx; - if( ( ret = mbedtls_rsa_check_pubkey( rsa ) ) != 0 ) + if( ( ret = mbedtls_rsa_check_pubkey( rsa ) ) != 0 ) { bflb_rsa_printe("failed\r\n!rsa_check_privkey failed with -0x%0x\n", -ret ); return BFLB_RSA_ERROR; @@ -84,8 +84,8 @@ int32_t bflb_rsa_sign( bflb_rsa_handle_t *rsa_handle,const uint8_t *hash, int32_t ret = BFLB_RSA_OK; mbedtls_rsa_context* rsa=(mbedtls_rsa_context*)&rsa_handle->rsa_ctx; - ret = mbedtls_rsa_pkcs1_sign( rsa, NULL, NULL, MBEDTLS_RSA_PRIVATE, - (mbedtls_md_type_t)bflb_hash_get_type(hashtype), + ret = mbedtls_rsa_pkcs1_sign( rsa, NULL, NULL, MBEDTLS_RSA_PRIVATE, + (mbedtls_md_type_t)bflb_hash_get_type(hashtype), hashlen, hash, sig ); if( ret != 0 ) { @@ -103,7 +103,7 @@ int32_t bflb_rsa_verify( bflb_rsa_handle_t *rsa_handle,const uint8_t *hash, mbedtls_rsa_context* rsa=(mbedtls_rsa_context*)&rsa_handle->rsa_ctx; ret = mbedtls_rsa_pkcs1_verify( rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, - (mbedtls_md_type_t)bflb_hash_get_type(hashtype), + (mbedtls_md_type_t)bflb_hash_get_type(hashtype), hashlen, hash, sig ); if( ret != 0 ) { diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/bits/ctype_base.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/bits/ctype_base.h index 4ae24dff..21238f6c 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/bits/ctype_base.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/bits/ctype_base.h @@ -7,22 +7,22 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION struct ctype_base { // Non-standard typedefs. - typedef const int* __to_type; + typedef const int* __to_type; // NB: Offsets into ctype::_M_table force a particular size // on the mask type. Because of this, we don't use an enum. - typedef char mask; - static const mask upper = _U; - static const mask lower = _L; - static const mask alpha = _U | _L; - static const mask digit = _N; - static const mask xdigit = _X | _N; - static const mask space = _S; - static const mask print = _P | _U | _L | _N | _B; - static const mask graph = _P | _U | _L | _N; - static const mask cntrl = _C; - static const mask punct = _P; - static const mask alnum = _U | _L | _N; + typedef char mask; + static const mask upper = _U; + static const mask lower = _L; + static const mask alpha = _U | _L; + static const mask digit = _N; + static const mask xdigit = _X | _N; + static const mask space = _S; + static const mask print = _P | _U | _L | _N | _B; + static const mask graph = _P | _U | _L | _N; + static const mask cntrl = _C; + static const mask punct = _P; + static const mask alnum = _U | _L | _N; }; _GLIBCXX_END_NAMESPACE_VERSION diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/ctype.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/ctype.h index f4433195..b6616ed8 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/ctype.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/ctype.h @@ -28,14 +28,14 @@ * blank = '\t' || ' ' (per POSIX requirement) */ enum { - __ctype_upper = _U, - __ctype_lower = _L, - __ctype_digit = _N, - __ctype_xdigit = _S, - __ctype_space = _P, - __ctype_print = _C, - __ctype_punct = _X, - __ctype_cntrl = _B + __ctype_upper = _U, + __ctype_lower = _L, + __ctype_digit = _N, + __ctype_xdigit = _S, + __ctype_space = _P, + __ctype_print = _C, + __ctype_punct = _X, + __ctype_cntrl = _B }; __extern int isalnum(int); @@ -58,69 +58,69 @@ extern const unsigned char __ctypes[]; __must_inline int __ctype_isalnum(int __c) { - return __ctypes[__c + 1] & - (__ctype_upper | __ctype_lower | __ctype_digit); + return __ctypes[__c + 1] & + (__ctype_upper | __ctype_lower | __ctype_digit); } __must_inline int __ctype_isalpha(int __c) { - return __ctypes[__c + 1] & (__ctype_upper | __ctype_lower); + return __ctypes[__c + 1] & (__ctype_upper | __ctype_lower); } __must_inline int __ctype_isascii(int __c) { - return !(__c & ~0x7f); + return !(__c & ~0x7f); } __must_inline int __ctype_isblank(int __c) { - return (__c == '\t') || (__c == ' '); + return (__c == '\t') || (__c == ' '); } __must_inline int __ctype_iscntrl(int __c) { - return __ctypes[__c + 1] & __ctype_cntrl; + return __ctypes[__c + 1] & __ctype_cntrl; } __must_inline int __ctype_isdigit(int __c) { - return ((unsigned)__c - '0') <= 9; + return ((unsigned)__c - '0') <= 9; } __must_inline int __ctype_isgraph(int __c) { - return __ctypes[__c + 1] & - (__ctype_upper | __ctype_lower | __ctype_digit | __ctype_punct); + return __ctypes[__c + 1] & + (__ctype_upper | __ctype_lower | __ctype_digit | __ctype_punct); } __must_inline int __ctype_islower(int __c) { - return __ctypes[__c + 1] & __ctype_lower; + return __ctypes[__c + 1] & __ctype_lower; } __must_inline int __ctype_isprint(int __c) { - return __ctypes[__c + 1] & __ctype_print; + return __ctypes[__c + 1] & __ctype_print; } __must_inline int __ctype_ispunct(int __c) { - return __ctypes[__c + 1] & __ctype_punct; + return __ctypes[__c + 1] & __ctype_punct; } __must_inline int __ctype_isspace(int __c) { - return __ctypes[__c + 1] & __ctype_space; + return __ctypes[__c + 1] & __ctype_space; } __must_inline int __ctype_isupper(int __c) { - return __ctypes[__c + 1] & __ctype_upper; + return __ctypes[__c + 1] & __ctype_upper; } __must_inline int __ctype_isxdigit(int __c) { - return __ctypes[__c + 1] & __ctype_xdigit; + return __ctypes[__c + 1] & __ctype_xdigit; } /* Note: this is decimal, not hex, to avoid accidental promotion to unsigned */ @@ -129,12 +129,12 @@ __must_inline int __ctype_isxdigit(int __c) __must_inline int __ctype_toupper(int __c) { - return __ctype_islower(__c) ? _toupper(__c) : __c; + return __ctype_islower(__c) ? _toupper(__c) : __c; } __must_inline int __ctype_tolower(int __c) { - return __ctype_isupper(__c) ? _tolower(__c) : __c; + return __ctype_isupper(__c) ? _tolower(__c) : __c; } -#endif /* _CTYPE_H */ +#endif /* _CTYPE_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/extern.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/extern.h index 47c3e848..ffcaecfa 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/extern.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/extern.h @@ -13,4 +13,4 @@ #define __alias(x) __attribute__((weak, alias(x))) -#endif /* _EXTERN_H */ +#endif /* _EXTERN_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/fnmatch.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/fnmatch.h index 1a62f778..d0268c17 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/fnmatch.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/fnmatch.h @@ -3,12 +3,12 @@ #include -#define FNM_NOMATCH 1 +#define FNM_NOMATCH 1 -#define FNM_PATHNAME 1 -#define FNM_FILE_NAME FNM_PATHNAME -#define FNM_NOESCAPE 2 -#define FNM_PERIOD 4 +#define FNM_PATHNAME 1 +#define FNM_FILE_NAME FNM_PATHNAME +#define FNM_NOESCAPE 2 +#define FNM_PERIOD 4 __extern int fnmatch(const char *, const char *, int); diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/inttypes.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/inttypes.h index 69a73225..47db5326 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/inttypes.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/inttypes.h @@ -12,7 +12,7 @@ static __inline intmax_t imaxabs(intmax_t __n) { - return (__n < (intmax_t) 0) ? -__n : __n; + return (__n < (intmax_t) 0) ? -__n : __n; } __extern intmax_t strtoimax(const char *, char **, int); @@ -24,204 +24,204 @@ __extern uintmax_t strntoumax(const char *, char **, int, size_t); #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) -#define PRId8 "d" -#define PRId16 "d" -#define PRId32 "d" -#define PRId64 __PRI64_RANK "d" +#define PRId8 "d" +#define PRId16 "d" +#define PRId32 "d" +#define PRId64 __PRI64_RANK "d" -#define PRIdLEAST8 "d" -#define PRIdLEAST16 "d" -#define PRIdLEAST32 "d" -#define PRIdLEAST64 __PRI64_RANK "d" +#define PRIdLEAST8 "d" +#define PRIdLEAST16 "d" +#define PRIdLEAST32 "d" +#define PRIdLEAST64 __PRI64_RANK "d" -#define PRIdFAST8 "d" -#define PRIdFAST16 __PRIFAST_RANK "d" -#define PRIdFAST32 __PRIFAST_RANK "d" -#define PRIdFAST64 __PRI64_RANK "d" +#define PRIdFAST8 "d" +#define PRIdFAST16 __PRIFAST_RANK "d" +#define PRIdFAST32 __PRIFAST_RANK "d" +#define PRIdFAST64 __PRI64_RANK "d" -#define PRIdMAX __PRI64_RANK "d" +#define PRIdMAX __PRI64_RANK "d" #define PRIdPTR __PRIPTR_RANK "d" -#define PRIi8 "i" -#define PRIi16 "i" -#define PRIi32 "i" -#define PRIi64 __PRI64_RANK "i" +#define PRIi8 "i" +#define PRIi16 "i" +#define PRIi32 "i" +#define PRIi64 __PRI64_RANK "i" -#define PRIiLEAST8 "i" -#define PRIiLEAST16 "i" -#define PRIiLEAST32 "i" -#define PRIiLEAST64 __PRI64_RANK "i" +#define PRIiLEAST8 "i" +#define PRIiLEAST16 "i" +#define PRIiLEAST32 "i" +#define PRIiLEAST64 __PRI64_RANK "i" -#define PRIiFAST8 "i" -#define PRIiFAST16 __PRIFAST_RANK "i" -#define PRIiFAST32 __PRIFAST_RANK "i" -#define PRIiFAST64 __PRI64_RANK "i" +#define PRIiFAST8 "i" +#define PRIiFAST16 __PRIFAST_RANK "i" +#define PRIiFAST32 __PRIFAST_RANK "i" +#define PRIiFAST64 __PRI64_RANK "i" -#define PRIiMAX __PRI64_RANK "i" +#define PRIiMAX __PRI64_RANK "i" #define PRIiPTR __PRIPTR_RANK "i" -#define PRIo8 "o" -#define PRIo16 "o" -#define PRIo32 "o" -#define PRIo64 __PRI64_RANK "o" +#define PRIo8 "o" +#define PRIo16 "o" +#define PRIo32 "o" +#define PRIo64 __PRI64_RANK "o" -#define PRIoLEAST8 "o" -#define PRIoLEAST16 "o" -#define PRIoLEAST32 "o" -#define PRIoLEAST64 __PRI64_RANK "o" +#define PRIoLEAST8 "o" +#define PRIoLEAST16 "o" +#define PRIoLEAST32 "o" +#define PRIoLEAST64 __PRI64_RANK "o" -#define PRIoFAST8 "o" -#define PRIoFAST16 __PRIFAST_RANK "o" -#define PRIoFAST32 __PRIFAST_RANK "o" -#define PRIoFAST64 __PRI64_RANK "o" +#define PRIoFAST8 "o" +#define PRIoFAST16 __PRIFAST_RANK "o" +#define PRIoFAST32 __PRIFAST_RANK "o" +#define PRIoFAST64 __PRI64_RANK "o" -#define PRIoMAX __PRI64_RANK "o" +#define PRIoMAX __PRI64_RANK "o" #define PRIoPTR __PRIPTR_RANK "o" -#define PRIu8 "u" -#define PRIu16 "u" -#define PRIu32 "u" -#define PRIu64 __PRI64_RANK "u" +#define PRIu8 "u" +#define PRIu16 "u" +#define PRIu32 "u" +#define PRIu64 __PRI64_RANK "u" -#define PRIuLEAST8 "u" -#define PRIuLEAST16 "u" -#define PRIuLEAST32 "u" -#define PRIuLEAST64 __PRI64_RANK "u" +#define PRIuLEAST8 "u" +#define PRIuLEAST16 "u" +#define PRIuLEAST32 "u" +#define PRIuLEAST64 __PRI64_RANK "u" -#define PRIuFAST8 "u" -#define PRIuFAST16 __PRIFAST_RANK "u" -#define PRIuFAST32 __PRIFAST_RANK "u" -#define PRIuFAST64 __PRI64_RANK "u" +#define PRIuFAST8 "u" +#define PRIuFAST16 __PRIFAST_RANK "u" +#define PRIuFAST32 __PRIFAST_RANK "u" +#define PRIuFAST64 __PRI64_RANK "u" -#define PRIuMAX __PRI64_RANK "u" +#define PRIuMAX __PRI64_RANK "u" #define PRIuPTR __PRIPTR_RANK "u" -#define PRIx8 "x" -#define PRIx16 "x" -#define PRIx32 "x" -#define PRIx64 __PRI64_RANK "x" +#define PRIx8 "x" +#define PRIx16 "x" +#define PRIx32 "x" +#define PRIx64 __PRI64_RANK "x" -#define PRIxLEAST8 "x" -#define PRIxLEAST16 "x" -#define PRIxLEAST32 "x" -#define PRIxLEAST64 __PRI64_RANK "x" +#define PRIxLEAST8 "x" +#define PRIxLEAST16 "x" +#define PRIxLEAST32 "x" +#define PRIxLEAST64 __PRI64_RANK "x" -#define PRIxFAST8 "x" -#define PRIxFAST16 __PRIFAST_RANK "x" -#define PRIxFAST32 __PRIFAST_RANK "x" -#define PRIxFAST64 __PRI64_RANK "x" +#define PRIxFAST8 "x" +#define PRIxFAST16 __PRIFAST_RANK "x" +#define PRIxFAST32 __PRIFAST_RANK "x" +#define PRIxFAST64 __PRI64_RANK "x" -#define PRIxMAX __PRI64_RANK "x" +#define PRIxMAX __PRI64_RANK "x" #define PRIxPTR __PRIPTR_RANK "x" -#define PRIX8 "X" -#define PRIX16 "X" -#define PRIX32 "X" -#define PRIX64 __PRI64_RANK "X" +#define PRIX8 "X" +#define PRIX16 "X" +#define PRIX32 "X" +#define PRIX64 __PRI64_RANK "X" -#define PRIXLEAST8 "X" -#define PRIXLEAST16 "X" -#define PRIXLEAST32 "X" -#define PRIXLEAST64 __PRI64_RANK "X" +#define PRIXLEAST8 "X" +#define PRIXLEAST16 "X" +#define PRIXLEAST32 "X" +#define PRIXLEAST64 __PRI64_RANK "X" -#define PRIXFAST8 "X" -#define PRIXFAST16 __PRIFAST_RANK "X" -#define PRIXFAST32 __PRIFAST_RANK "X" -#define PRIXFAST64 __PRI64_RANK "X" +#define PRIXFAST8 "X" +#define PRIXFAST16 __PRIFAST_RANK "X" +#define PRIXFAST32 __PRIFAST_RANK "X" +#define PRIXFAST64 __PRI64_RANK "X" -#define PRIXMAX __PRI64_RANK "X" +#define PRIXMAX __PRI64_RANK "X" #define PRIXPTR __PRIPTR_RANK "X" -#define SCNd8 "hhd" -#define SCNd16 "hd" -#define SCNd32 "d" -#define SCNd64 __PRI64_RANK "d" +#define SCNd8 "hhd" +#define SCNd16 "hd" +#define SCNd32 "d" +#define SCNd64 __PRI64_RANK "d" -#define SCNdLEAST8 "hhd" -#define SCNdLEAST16 "hd" -#define SCNdLEAST32 "d" -#define SCNdLEAST64 __PRI64_RANK "d" +#define SCNdLEAST8 "hhd" +#define SCNdLEAST16 "hd" +#define SCNdLEAST32 "d" +#define SCNdLEAST64 __PRI64_RANK "d" -#define SCNdFAST8 "hhd" -#define SCNdFAST16 __PRIFAST_RANK "d" -#define SCNdFAST32 __PRIFAST_RANK "d" -#define SCNdFAST64 __PRI64_RANK "d" +#define SCNdFAST8 "hhd" +#define SCNdFAST16 __PRIFAST_RANK "d" +#define SCNdFAST32 __PRIFAST_RANK "d" +#define SCNdFAST64 __PRI64_RANK "d" -#define SCNdMAX __PRI64_RANK "d" +#define SCNdMAX __PRI64_RANK "d" #define SCNdPTR __PRIPTR_RANK "d" -#define SCNi8 "hhi" -#define SCNi16 "hi" -#define SCNi32 "i" -#define SCNi64 __PRI64_RANK "i" +#define SCNi8 "hhi" +#define SCNi16 "hi" +#define SCNi32 "i" +#define SCNi64 __PRI64_RANK "i" -#define SCNiLEAST8 "hhi" -#define SCNiLEAST16 "hi" -#define SCNiLEAST32 "i" -#define SCNiLEAST64 __PRI64_RANK "i" +#define SCNiLEAST8 "hhi" +#define SCNiLEAST16 "hi" +#define SCNiLEAST32 "i" +#define SCNiLEAST64 __PRI64_RANK "i" -#define SCNiFAST8 "hhi" -#define SCNiFAST16 __PRIFAST_RANK "i" -#define SCNiFAST32 __PRIFAST_RANK "i" -#define SCNiFAST64 __PRI64_RANK "i" +#define SCNiFAST8 "hhi" +#define SCNiFAST16 __PRIFAST_RANK "i" +#define SCNiFAST32 __PRIFAST_RANK "i" +#define SCNiFAST64 __PRI64_RANK "i" -#define SCNiMAX __PRI64_RANK "i" +#define SCNiMAX __PRI64_RANK "i" #define SCNiPTR __PRIPTR_RANK "i" -#define SCNo8 "hho" -#define SCNo16 "ho" -#define SCNo32 "o" -#define SCNo64 __PRI64_RANK "o" +#define SCNo8 "hho" +#define SCNo16 "ho" +#define SCNo32 "o" +#define SCNo64 __PRI64_RANK "o" -#define SCNoLEAST8 "hho" -#define SCNoLEAST16 "ho" -#define SCNoLEAST32 "o" -#define SCNoLEAST64 __PRI64_RANK "o" +#define SCNoLEAST8 "hho" +#define SCNoLEAST16 "ho" +#define SCNoLEAST32 "o" +#define SCNoLEAST64 __PRI64_RANK "o" -#define SCNoFAST8 "hho" -#define SCNoFAST16 __PRIFAST_RANK "o" -#define SCNoFAST32 __PRIFAST_RANK "o" -#define SCNoFAST64 __PRI64_RANK "o" +#define SCNoFAST8 "hho" +#define SCNoFAST16 __PRIFAST_RANK "o" +#define SCNoFAST32 __PRIFAST_RANK "o" +#define SCNoFAST64 __PRI64_RANK "o" -#define SCNoMAX __PRI64_RANK "o" +#define SCNoMAX __PRI64_RANK "o" #define SCNoPTR __PRIPTR_RANK "o" -#define SCNu8 "hhu" -#define SCNu16 "hu" -#define SCNu32 "u" -#define SCNu64 __PRI64_RANK "u" +#define SCNu8 "hhu" +#define SCNu16 "hu" +#define SCNu32 "u" +#define SCNu64 __PRI64_RANK "u" -#define SCNuLEAST8 "hhu" -#define SCNuLEAST16 "hu" -#define SCNuLEAST32 "u" -#define SCNuLEAST64 __PRI64_RANK "u" +#define SCNuLEAST8 "hhu" +#define SCNuLEAST16 "hu" +#define SCNuLEAST32 "u" +#define SCNuLEAST64 __PRI64_RANK "u" -#define SCNuFAST8 "hhu" -#define SCNuFAST16 __PRIFAST_RANK "u" -#define SCNuFAST32 __PRIFAST_RANK "u" -#define SCNuFAST64 __PRI64_RANK "u" +#define SCNuFAST8 "hhu" +#define SCNuFAST16 __PRIFAST_RANK "u" +#define SCNuFAST32 __PRIFAST_RANK "u" +#define SCNuFAST64 __PRI64_RANK "u" -#define SCNuMAX __PRI64_RANK "u" +#define SCNuMAX __PRI64_RANK "u" #define SCNuPTR __PRIPTR_RANK "u" -#define SCNx8 "hhx" -#define SCNx16 "hx" -#define SCNx32 "x" -#define SCNx64 __PRI64_RANK "x" +#define SCNx8 "hhx" +#define SCNx16 "hx" +#define SCNx32 "x" +#define SCNx64 __PRI64_RANK "x" -#define SCNxLEAST8 "hhx" -#define SCNxLEAST16 "hx" -#define SCNxLEAST32 "x" -#define SCNxLEAST64 __PRI64_RANK "x" +#define SCNxLEAST8 "hhx" +#define SCNxLEAST16 "hx" +#define SCNxLEAST32 "x" +#define SCNxLEAST64 __PRI64_RANK "x" -#define SCNxFAST8 "hhx" -#define SCNxFAST16 __PRIFAST_RANK "x" -#define SCNxFAST32 __PRIFAST_RANK "x" -#define SCNxFAST64 __PRI64_RANK "x" +#define SCNxFAST8 "hhx" +#define SCNxFAST16 __PRIFAST_RANK "x" +#define SCNxFAST32 __PRIFAST_RANK "x" +#define SCNxFAST64 __PRI64_RANK "x" -#define SCNxMAX __PRI64_RANK "x" +#define SCNxMAX __PRI64_RANK "x" #define SCNxPTR __PRIPTR_RANK "x" #endif -#endif /* _INTTYPES_H */ +#endif /* _INTTYPES_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/libc_compiler.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/libc_compiler.h index 7e59ed42..04b4e3fc 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/libc_compiler.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/libc_compiler.h @@ -17,7 +17,7 @@ /* Most other C compilers have __cdecl as a keyword */ # endif #else -# define __cdecl /* Meaningless on non-i386 */ +# define __cdecl /* Meaningless on non-i386 */ #endif /* How to declare a function that *must* be inlined */ @@ -26,7 +26,7 @@ # if __GNUC__ >= 3 # ifdef __GNUC_STDC_INLINE__ # define __must_inline extern __inline__ \ - __attribute__((__gnu_inline__,__always_inline__)) + __attribute__((__gnu_inline__,__always_inline__)) # else # define __must_inline extern __inline__ __attribute__((__always_inline__)) # endif @@ -34,7 +34,7 @@ # define __must_inline extern __inline__ # endif #else -# define __must_inline __inline /* Just hope this works... */ +# define __must_inline __inline /* Just hope this works... */ # define __inline inline #endif diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/limits.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/limits.h index 2477b6d3..2b4829e3 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/limits.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/limits.h @@ -5,14 +5,14 @@ #ifndef _LIMITS_H #define _LIMITS_H -#define CHAR_BIT 8 -#define SHRT_BIT 16 -#define INT_BIT 32 -#define LONGLONG_BIT 64 +#define CHAR_BIT 8 +#define SHRT_BIT 16 +#define INT_BIT 32 +#define LONGLONG_BIT 64 -#define SCHAR_MIN (-128) -#define SCHAR_MAX 127 -#define UCHAR_MAX 255 +#define SCHAR_MIN (-128) +#define SCHAR_MAX 127 +#define UCHAR_MAX 255 #ifdef __CHAR_UNSIGNED__ # define CHAR_MIN 0 @@ -22,22 +22,22 @@ # define CHAR_MAX SCHAR_MAX #endif -#define SHRT_MIN (-32768) -#define SHRT_MAX 32767 -#define USHRT_MAX 65535 +#define SHRT_MIN (-32768) +#define SHRT_MAX 32767 +#define USHRT_MAX 65535 -#define INT_MIN (-2147483647-1) -#define INT_MAX 2147483647 -#define UINT_MAX 4294967295U +#define INT_MIN (-2147483647-1) +#define INT_MAX 2147483647 +#define UINT_MAX 4294967295U -#define LONGLONG_MIN (-9223372036854775807LL-1) -#define LONGLONG_MAX 9223372036854775807LL -#define ULONGLONG_MAX 18446744073709551615ULL +#define LONGLONG_MIN (-9223372036854775807LL-1) +#define LONGLONG_MAX 9223372036854775807LL +#define ULONGLONG_MAX 18446744073709551615ULL -#define LONG_BIT 32 +#define LONG_BIT 32 -#define LONG_MIN (-2147483647L-1) -#define LONG_MAX 2147483647L -#define ULONG_MAX 4294967295UL +#define LONG_MIN (-2147483647L-1) +#define LONG_MAX 2147483647L +#define ULONG_MAX 4294967295UL -#endif /* _LIMITS_H */ +#endif /* _LIMITS_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdbool.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdbool.h index d2708fdc..e7151865 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdbool.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdbool.h @@ -9,4 +9,4 @@ #define true 1 #define false 0 -#endif /* _STDBOOL_H */ +#endif /* _STDBOOL_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stddef.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stddef.h index b91705b6..a73e40e2 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stddef.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stddef.h @@ -26,4 +26,4 @@ typedef signed int wint_t; #undef offsetof #define offsetof(t,m) ((size_t)&((t *)0)->m) -#endif /* _STDDEF_H */ +#endif /* _STDDEF_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdint.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdint.h index 4ebcc5b1..d680abd4 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdint.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdint.h @@ -5,24 +5,24 @@ #ifndef _STDINT_H #define _STDINT_H -typedef signed char int8_t; -typedef short int int16_t; -typedef int int32_t; -typedef long long int int64_t; +typedef signed char int8_t; +typedef short int int16_t; +typedef int int32_t; +typedef long long int int64_t; -typedef unsigned char uint8_t; -typedef unsigned short int uint16_t; -typedef unsigned int uint32_t; -typedef unsigned long long int uint64_t; +typedef unsigned char uint8_t; +typedef unsigned short int uint16_t; +typedef unsigned int uint32_t; +typedef unsigned long long int uint64_t; -typedef int int_fast16_t; -typedef int int_fast32_t; +typedef int int_fast16_t; +typedef int int_fast32_t; -typedef unsigned int uint_fast16_t; -typedef unsigned int uint_fast32_t; +typedef unsigned int uint_fast16_t; +typedef unsigned int uint_fast32_t; -typedef int intptr_t; -typedef unsigned int uintptr_t; +typedef int intptr_t; +typedef unsigned int uintptr_t; #define __INT64_C(c) c ## LL #define __UINT64_C(c) c ## ULL @@ -30,99 +30,99 @@ typedef unsigned int uintptr_t; #define __PRI64_RANK "ll" #define __PRIFAST_RANK "" #define __PRIPTR_RANK "" -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; -typedef int8_t int_fast8_t; -typedef int64_t int_fast64_t; +typedef int8_t int_fast8_t; +typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint64_t uint_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint64_t uint_fast64_t; -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) -#define INT8_MIN (-128) -#define INT16_MIN (-32768) -#define INT32_MIN (-2147483647-1) -#define INT64_MIN (__INT64_C(-9223372036854775807)-1) +#define INT8_MIN (-128) +#define INT16_MIN (-32768) +#define INT32_MIN (-2147483647-1) +#define INT64_MIN (__INT64_C(-9223372036854775807)-1) -#define INT8_MAX (127) -#define INT16_MAX (32767) -#define INT32_MAX (2147483647) -#define INT64_MAX (__INT64_C(9223372036854775807)) +#define INT8_MAX (127) +#define INT16_MAX (32767) +#define INT32_MAX (2147483647) +#define INT64_MAX (__INT64_C(9223372036854775807)) -#define UINT8_MAX (255U) -#define UINT16_MAX (65535U) -#define UINT32_MAX (4294967295U) -#define UINT64_MAX (__UINT64_C(18446744073709551615)) +#define UINT8_MAX (255U) +#define UINT16_MAX (65535U) +#define UINT32_MAX (4294967295U) +#define UINT64_MAX (__UINT64_C(18446744073709551615)) -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MAX INT64_MAX +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST64_MIN INT64_MIN +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST64_MIN INT64_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST64_MAX INT64_MAX +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST64_MAX UINT64_MAX -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX -#define INT_FAST16_MIN INT32_MIN -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST16_MAX INT32_MAX -#define INT_FAST32_MAX INT32_MAX +#define INT_FAST16_MIN INT32_MIN +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST16_MAX INT32_MAX +#define INT_FAST32_MAX INT32_MAX #define UINT_FAST16_MAX UINT32_MAX #define UINT_FAST32_MAX UINT32_MAX -#define INTPTR_MIN INT32_MIN -#define INTPTR_MAX INT32_MAX -#define UINTPTR_MAX UINT32_MAX +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX -#define PTRDIFF_MIN INT32_MIN -#define PTRDIFF_MAX INT32_MAX +#define PTRDIFF_MIN INT32_MIN +#define PTRDIFF_MAX INT32_MAX #endif #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) -#define INT8_C(c) c -#define INT16_C(c) c -#define INT32_C(c) c -#define INT64_C(c) __INT64_C(c) +#define INT8_C(c) c +#define INT16_C(c) c +#define INT32_C(c) c +#define INT64_C(c) __INT64_C(c) -#define UINT8_C(c) c ## U -#define UINT16_C(c) c ## U -#define UINT32_C(c) c ## U -#define UINT64_C(c) __UINT64_C(c) +#define UINT8_C(c) c ## U +#define UINT16_C(c) c ## U +#define UINT32_C(c) c ## U +#define UINT64_C(c) __UINT64_C(c) -#define INT_LEAST8_C(c) INT8_C(c) +#define INT_LEAST8_C(c) INT8_C(c) #define INT_LEAST16_C(c) INT16_C(c) #define INT_LEAST32_C(c) INT32_C(c) #define INT_LEAST64_C(c) INT64_C(c) @@ -132,25 +132,25 @@ typedef uint64_t uintmax_t; #define UINT_LEAST32_C(c) UINT32_C(c) #define UINT_LEAST64_C(c) UINT64_C(c) -#define INT_FAST8_C(c) INT8_C(c) +#define INT_FAST8_C(c) INT8_C(c) #define INT_FAST64_C(c) INT64_C(c) #define UINT_FAST8_C(c) UINT8_C(c) #define UINT_FAST64_C(c) UINT64_C(c) -#define INTMAX_C(c) INT64_C(c) -#define UINTMAX_C(c) UINT64_C(c) +#define INTMAX_C(c) INT64_C(c) +#define UINTMAX_C(c) UINT64_C(c) -#define INT_FAST16_C(c) INT32_C(c) +#define INT_FAST16_C(c) INT32_C(c) #define INT_FAST32_C(c) INT32_C(c) #define UINT_FAST16_C(c) UINT32_C(c) #define UINT_FAST32_C(c) UINT32_C(c) -#define INTPTR_C(c) INT32_C(c) -#define UINTPTR_C(c) UINT32_C(c) +#define INTPTR_C(c) INT32_C(c) +#define UINTPTR_C(c) UINT32_C(c) #define PTRDIFF_C(c) INT32_C(c) #endif -#endif /* _STDINT_H */ +#endif /* _STDINT_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdio.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdio.h index 700a386a..30165a01 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdio.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdio.h @@ -18,4 +18,4 @@ __extern int vsnprintf(char *, size_t n, const char *, va_list); __extern int sscanf(const char *, const char *, ...); __extern int vsscanf(const char *, const char *, va_list); -#endif /* _STDIO_H */ +#endif /* _STDIO_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdlib.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdlib.h index 6077bfab..5d3e38ff 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdlib.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/stdlib.h @@ -14,7 +14,7 @@ static __inline int abs(int __n) { - return (__n < 0) ? -__n : __n; + return (__n < 0) ? -__n : __n; } __extern int atoi(const char *); __extern double atof(const char *); @@ -22,12 +22,12 @@ __extern long atol(const char *); __extern long long atoll(const char *); static __inline long labs(long __n) { - return (__n < 0L) ? -__n : __n; + return (__n < 0L) ? -__n : __n; } static __inline long long llabs(long long __n) { - return (__n < 0LL) ? -__n : __n; + return (__n < 0LL) ? -__n : __n; } __extern long strtol(const char *, char **, int); @@ -37,7 +37,7 @@ __extern unsigned long long strtoull(const char *, char **, int); typedef int (*__comparefunc_t) (const void *, const void *); __extern void *bsearch(const void *, const void *, size_t, size_t, - __comparefunc_t); + __comparefunc_t); __extern void qsort(void *, size_t, size_t, __comparefunc_t); __extern long jrand48(unsigned short *); @@ -53,4 +53,4 @@ __extern void srand(unsigned int __s); __extern long random(void); __extern void srandom(unsigned int __s); -#endif /* _STDLIB_H */ +#endif /* _STDLIB_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/string.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/string.h index f8f48a35..64531699 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/string.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/string.h @@ -41,4 +41,4 @@ __extern char *strtok(char *, const char *); __extern char *strtok_r(char *, const char *, char **); char *index(const char *s, int c); -#endif /* _STRING_H */ +#endif /* _STRING_H */ diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/inc/sys/types.h b/components/bl602/bl602_std/bl602_std/Common/libc/inc/sys/types.h index 4e776586..d75bea18 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/inc/sys/types.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/inc/sys/types.h @@ -81,13 +81,13 @@ typedef unsigned long useconds_t; #define FD_ZERO(p) memset((void *)(p), 0, sizeof(*(p))) typedef struct fd_set { - unsigned char fd_bits[(FD_SETSIZE + 7) / 8]; + unsigned char fd_bits[(FD_SETSIZE + 7) / 8]; } fd_set; #endif /* FD_SET */ #ifndef __ICCARM__ /* wmsdk: Added from sys/times.h and machine/types.h */ -#define _CLOCK_T_ unsigned long /* clock() */ +#define _CLOCK_T_ unsigned long /* clock() */ #ifndef __clock_t_defined typedef _CLOCK_T_ clock_t; #define __clock_t_defined diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/libc.mk b/components/bl602/bl602_std/bl602_std/Common/libc/libc.mk index 5f98fd49..a2be06a9 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/libc.mk +++ b/components/bl602/bl602_std/bl602_std/Common/libc/libc.mk @@ -5,7 +5,7 @@ SUB_MODULE_OUT_DIR:= $(MODULE_OUT_DIR)/libc SUB_MODULE_SRC_DIR := $(SUB_MODULE_DIR)/src COMMON_INCLUDE += -I $(MODULE_DIR)/libc/inc - + libc_sources := atof.c atoi.c atol.c libc_sources += atoll.c jrand48.c lrand48.c libc_sources += mrand48.c nrand48.c seed48.c diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/atof.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/atof.c index 97b074d9..c9771d8f 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/atof.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/atof.c @@ -16,87 +16,87 @@ static inline int digitval(int ch) { - if (ch >= '0' && ch <= '9') { - return ch - '0'; - } else if (ch >= 'A' && ch <= 'Z') { - return ch - 'A' + 10; - } else if (ch >= 'a' && ch <= 'z') { - return ch - 'a' + 10; - } else { - return -1; - } + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } else if (ch >= 'A' && ch <= 'Z') { + return ch - 'A' + 10; + } else if (ch >= 'a' && ch <= 'z') { + return ch - 'a' + 10; + } else { + return -1; + } } double strntof(const char *nptr, char **endptr, int base, size_t n) { - int minus = 0; - double v = 0.0, m = 0.0, divisor = 1.0; - int d; + int minus = 0; + double v = 0.0, m = 0.0, divisor = 1.0; + int d; - while (n && isspace((unsigned char)*nptr)) { - nptr++; - n--; - } + while (n && isspace((unsigned char)*nptr)) { + nptr++; + n--; + } - /* Single optional + or - */ - if (n) { - char c = *nptr; - if (c == '-' || c == '+') { - minus = (c == '-'); - nptr++; - n--; - } - } + /* Single optional + or - */ + if (n) { + char c = *nptr; + if (c == '-' || c == '+') { + minus = (c == '-'); + nptr++; + n--; + } + } - if (base == 0) { - if (n >= 2 && nptr[0] == '0' && - (nptr[1] == 'x' || nptr[1] == 'X')) { - n -= 2; - nptr += 2; - base = 16; - } else if (n >= 1 && nptr[0] == '0') { - n--; - nptr++; - base = 8; - } else { - base = 10; - } - } else if (base == 16) { - if (n >= 2 && nptr[0] == '0' && - (nptr[1] == 'x' || nptr[1] == 'X')) { - n -= 2; - nptr += 2; - } - } + if (base == 0) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + base = 16; + } else if (n >= 1 && nptr[0] == '0') { + n--; + nptr++; + base = 8; + } else { + base = 10; + } + } else if (base == 16) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + } + } - while (n && (d = digitval(*nptr)) >= 0 && d < base) { - v = v * base + d; - n--; - nptr++; - } + while (n && (d = digitval(*nptr)) >= 0 && d < base) { + v = v * base + d; + n--; + nptr++; + } - if (*nptr == '.') { - n--; - nptr++; - while (n && (d = digitval(*nptr)) >= 0 && d < base) { - m = m * base + d; - n--; - nptr++; - divisor *= 10.0; - } - } + if (*nptr == '.') { + n--; + nptr++; + while (n && (d = digitval(*nptr)) >= 0 && d < base) { + m = m * base + d; + n--; + nptr++; + divisor *= 10.0; + } + } - if (endptr) - *endptr = (char *)nptr; + if (endptr) + *endptr = (char *)nptr; - v = v + (m / divisor); + v = v + (m / divisor); - return minus ? -v : v; + return minus ? -v : v; } double atof(const char *nptr) { - return strntof(nptr, NULL, 0, strlen(nptr)); + return strntof(nptr, NULL, 0, strlen(nptr)); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/atox.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/atox.c index 9f95d5d2..9922930b 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/atox.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/atox.c @@ -15,5 +15,5 @@ TYPE NAME(const char *nptr) { - return (TYPE) strntoumax(nptr, (char **)NULL, 10, ~(size_t) 0); + return (TYPE) strntoumax(nptr, (char **)NULL, 10, ~(size_t) 0); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/bsearch.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/bsearch.c index 69c3b405..32791d8d 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/bsearch.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/bsearch.c @@ -9,23 +9,23 @@ #include void *bsearch(const void *key, const void *base, size_t nmemb, - size_t size, int (*cmp) (const void *, const void *)) + size_t size, int (*cmp) (const void *, const void *)) { - while (nmemb) { - size_t mididx = nmemb / 2; - const void *midobj = (const unsigned char *) base + - mididx * size; - int diff = cmp(key, midobj); + while (nmemb) { + size_t mididx = nmemb / 2; + const void *midobj = (const unsigned char *) base + + mididx * size; + int diff = cmp(key, midobj); - if (diff == 0) - return (void *)midobj; + if (diff == 0) + return (void *)midobj; - if (diff > 0) { - base = (const unsigned char *) midobj + size; - nmemb -= mididx + 1; - } else - nmemb = mididx; - } + if (diff > 0) { + base = (const unsigned char *) midobj + size; + nmemb -= mididx + 1; + } else + nmemb = mididx; + } - return NULL; + return NULL; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/common.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/common.c index b8834be4..48b2426c 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/common.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/common.c @@ -5,21 +5,21 @@ //#include void __assert_func(const char *file, int line, - const char *func, const char *failedexpr) + const char *func, const char *failedexpr) { #if 0 - printf("assertion \"%s\" failed: file \"%s\", line %d%s%s\n", - failedexpr, file, line, func ? ", function: " : "", - func ? func : ""); + printf("assertion \"%s\" failed: file \"%s\", line %d%s%s\n", + failedexpr, file, line, func ? ", function: " : "", + func ? func : ""); - /* Ensure that nothing runs after this */ - while (1) - ; + /* Ensure that nothing runs after this */ + while (1) + ; #endif } float strtof(const char *nptr, char **endptr) { -// printf("Float print not supported yet!\r\n"); - return 0; +// printf("Float print not supported yet!\r\n"); + return 0; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypefunc.h b/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypefunc.h index f9e247df..e7bb21ad 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypefunc.h +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypefunc.h @@ -7,7 +7,7 @@ #define __CTYPE_NO_INLINE #include -#define CTYPEFUNC(X) \ - int X(int c) { \ - return __ctype_##X(c); \ +#define CTYPEFUNC(X) \ + int X(int c) { \ + return __ctype_##X(c); \ } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypes.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypes.c index 45754480..69030fb7 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypes.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/ctypes.c @@ -12,277 +12,277 @@ #include const unsigned char __ctypes[257] = { - 0, /* EOF */ + 0, /* EOF */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl | __ctype_space, /* BS */ - __ctype_cntrl | __ctype_space, /* TAB */ - __ctype_cntrl | __ctype_space, /* LF */ - __ctype_cntrl | __ctype_space, /* VT */ - __ctype_cntrl | __ctype_space, /* FF */ - __ctype_cntrl | __ctype_space, /* CR */ - __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl | __ctype_space, /* BS */ + __ctype_cntrl | __ctype_space, /* TAB */ + __ctype_cntrl | __ctype_space, /* LF */ + __ctype_cntrl | __ctype_space, /* VT */ + __ctype_cntrl | __ctype_space, /* FF */ + __ctype_cntrl | __ctype_space, /* CR */ + __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ - __ctype_print | __ctype_space, /* space */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_space, /* space */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_digit | __ctype_xdigit, /* digit */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ - __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ - __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ - __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ - __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ - __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ + __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ + __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ + __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ + __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ + __ctype_print | __ctype_upper | __ctype_xdigit, /* A-F */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_upper, /* G-Z */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_upper, /* G-Z */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ - __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ - __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ - __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ - __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ - __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ + __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ + __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ + __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ + __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ + __ctype_print | __ctype_lower | __ctype_xdigit, /* a-f */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_lower, /* g-z */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_cntrl, /* control character */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_lower, /* g-z */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ - __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ + __ctype_cntrl, /* control character */ - __ctype_print | __ctype_space, /* NBSP */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_space, /* NBSP */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_upper, /* upper accented */ - __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_upper, /* upper accented */ + __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_punct, /* punctuation */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ - __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_punct, /* punctuation */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ + __ctype_print | __ctype_lower, /* lower accented */ }; diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/fnmatch.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/fnmatch.c index e1677fbb..cd6d180d 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/fnmatch.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/fnmatch.c @@ -12,65 +12,65 @@ int fnmatch(const char *p, const char *s, int flags) { - if (flags & FNM_PATHNAME && *s == '/') - return (*p != '/') || fnmatch(p+1, s+1, flags); - if (flags & FNM_PERIOD && *s == '.') - return (*p != '.') || fnmatch(p+1, s+1, flags); + if (flags & FNM_PATHNAME && *s == '/') + return (*p != '/') || fnmatch(p+1, s+1, flags); + if (flags & FNM_PERIOD && *s == '.') + return (*p != '.') || fnmatch(p+1, s+1, flags); - flags &= ~FNM_PERIOD; /* Only applies at beginning */ + flags &= ~FNM_PERIOD; /* Only applies at beginning */ - if (!(flags & FNM_NOESCAPE) && *p == '\\') { - p++; - return (*p != *s) || fnmatch(p+1, s+1, flags); - } + if (!(flags & FNM_NOESCAPE) && *p == '\\') { + p++; + return (*p != *s) || fnmatch(p+1, s+1, flags); + } - if (*s == '\0') { - while (*p == '*') - p++; - return (*p != '\0'); - } + if (*s == '\0') { + while (*p == '*') + p++; + return (*p != '\0'); + } - switch (*p) { - case '[': - { - int not = 0; - p++; - if (*p == '!') { - not = 1; - p++; - } - while ((*p != '\0') && (*p != ']')) { - int match = 0; - if (p[1] == '-') { - if ((*s >= *p) && (*s <= p[2])) - match = 1; - p += 3; - } else { - match = (*p == *s); - p++; - } - if (match ^ not) { - while ((*p != '\0') && (*p != ']')) - p++; - if (*p == ']') - return fnmatch(p+1, s+1, flags); - } - } - } - break; - case '*': - if (fnmatch(p, s+1, flags)) - return fnmatch(p+1, s, flags); - return 0; - case '\0': - if (*s == '\0') { - return 0; - } - break; - default: - if ((*p == *s) || (*p == '?')) - return fnmatch(p+1, s+1, flags); - break; - } - return 1; + switch (*p) { + case '[': + { + int not = 0; + p++; + if (*p == '!') { + not = 1; + p++; + } + while ((*p != '\0') && (*p != ']')) { + int match = 0; + if (p[1] == '-') { + if ((*s >= *p) && (*s <= p[2])) + match = 1; + p += 3; + } else { + match = (*p == *s); + p++; + } + if (match ^ not) { + while ((*p != '\0') && (*p != ']')) + p++; + if (*p == ']') + return fnmatch(p+1, s+1, flags); + } + } + } + break; + case '*': + if (fnmatch(p, s+1, flags)) + return fnmatch(p+1, s, flags); + return 0; + case '\0': + if (*s == '\0') { + return 0; + } + break; + default: + if ((*p == *s) || (*p == '?')) + return fnmatch(p+1, s+1, flags); + break; + } + return 1; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/jrand48.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/jrand48.c index f9c12179..16e7d13b 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/jrand48.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/jrand48.c @@ -11,18 +11,18 @@ long jrand48(unsigned short xsubi[3]) { - uint64_t x; + uint64_t x; - /* The xsubi[] array is littleendian by spec */ - x = (uint64_t) (uint16_t) xsubi[0] + - ((uint64_t) (uint16_t) xsubi[1] << 16) + - ((uint64_t) (uint16_t) xsubi[2] << 32); + /* The xsubi[] array is littleendian by spec */ + x = (uint64_t) (uint16_t) xsubi[0] + + ((uint64_t) (uint16_t) xsubi[1] << 16) + + ((uint64_t) (uint16_t) xsubi[2] << 32); - x = (0x5deece66dULL * x) + 0xb; + x = (0x5deece66dULL * x) + 0xb; - xsubi[0] = (unsigned short)(uint16_t) x; - xsubi[1] = (unsigned short)(uint16_t) (x >> 16); - xsubi[2] = (unsigned short)(uint16_t) (x >> 32); + xsubi[0] = (unsigned short)(uint16_t) x; + xsubi[1] = (unsigned short)(uint16_t) (x >> 16); + xsubi[2] = (unsigned short)(uint16_t) (x >> 32); - return (long)(int32_t) (x >> 16); + return (long)(int32_t) (x >> 16); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/lrand48.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/lrand48.c index 7c4f5235..2532fe4c 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/lrand48.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/lrand48.c @@ -9,19 +9,19 @@ #include #include -unsigned short __rand48_seed[3]; /* Common with mrand48.c, srand48.c */ +unsigned short __rand48_seed[3]; /* Common with mrand48.c, srand48.c */ long lrand48(void) { - return (uint32_t) jrand48(__rand48_seed) >> 1; + return (uint32_t) jrand48(__rand48_seed) >> 1; } int rand(void) { - return (int)lrand48(); + return (int)lrand48(); } long random(void) { - return lrand48(); + return lrand48(); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memccpy.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memccpy.c index 45dd351e..8e618351 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memccpy.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memccpy.c @@ -13,15 +13,15 @@ void *memccpy(void *dst, const void *src, int c, size_t n) { - char *q = dst; - const char *p = src; - char ch; + char *q = dst; + const char *p = src; + char ch; - while (n--) { - *q++ = ch = *p++; - if (ch == (char)c) - return q; - } + while (n--) { + *q++ = ch = *p++; + if (ch == (char)c) + return q; + } - return NULL; /* No instance of "c" found */ + return NULL; /* No instance of "c" found */ } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memchr.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memchr.c index ee6c790c..919713fe 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memchr.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memchr.c @@ -11,13 +11,13 @@ void *memchr(const void *s, int c, size_t n) { - const unsigned char *sp = s; + const unsigned char *sp = s; - while (n--) { - if (*sp == (unsigned char)c) - return (void *)sp; - sp++; - } + while (n--) { + if (*sp == (unsigned char)c) + return (void *)sp; + sp++; + } - return NULL; + return NULL; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memcmp.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memcmp.c index a5645597..fff5fa53 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memcmp.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memcmp.c @@ -10,14 +10,14 @@ int memcmp(const void *s1, const void *s2, size_t n) { - const unsigned char *c1 = s1, *c2 = s2; - int d = 0; + const unsigned char *c1 = s1, *c2 = s2; + int d = 0; - while (n--) { - d = (int)*c1++ - (int)*c2++; - if (d) - break; - } + while (n--) { + d = (int)*c1++ - (int)*c2++; + if (d) + break; + } - return d; + return d; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memcpy.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memcpy.c index 03a0f8ec..9e5154df 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memcpy.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memcpy.c @@ -7,10 +7,10 @@ void *memcpy(void *dst, const void *src, size_t n) { - const char *p = src; - char *q = dst; - while (n--) { - *q++ = *p++; - } - return dst; + const char *p = src; + char *q = dst; + while (n--) { + *q++ = *p++; + } + return dst; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memmem.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memmem.c index 385620b7..f6689ba1 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memmem.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memmem.c @@ -17,40 +17,40 @@ void *memmem(const void *haystack, size_t n, const void *needle, size_t m) { - const unsigned char *y = (const unsigned char *)haystack; - const unsigned char *x = (const unsigned char *)needle; + const unsigned char *y = (const unsigned char *)haystack; + const unsigned char *x = (const unsigned char *)needle; - size_t j, k, l; + size_t j, k, l; - if (m > n || !m || !n) - return NULL; + if (m > n || !m || !n) + return NULL; - if (1 != m) { - if (x[0] == x[1]) { - k = 2; - l = 1; - } else { - k = 1; - l = 2; - } + if (1 != m) { + if (x[0] == x[1]) { + k = 2; + l = 1; + } else { + k = 1; + l = 2; + } - j = 0; - while (j <= n - m) { - if (x[1] != y[j + 1]) { - j += k; - } else { - if (!memcmp(x + 2, y + j + 2, m - 2) - && x[0] == y[j]) - return (void *)&y[j]; - j += l; - } - } - } else - do { - if (*y == *x) - return (void *)y; - y++; - } while (--n); + j = 0; + while (j <= n - m) { + if (x[1] != y[j + 1]) { + j += k; + } else { + if (!memcmp(x + 2, y + j + 2, m - 2) + && x[0] == y[j]) + return (void *)&y[j]; + j += l; + } + } + } else + do { + if (*y == *x) + return (void *)y; + y++; + } while (--n); - return NULL; + return NULL; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memrchr.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memrchr.c index 6a9b8e7e..9fb936a5 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memrchr.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memrchr.c @@ -11,13 +11,13 @@ void *memrchr(const void *s, int c, size_t n) { - const unsigned char *sp = (const unsigned char *)s + n - 1; + const unsigned char *sp = (const unsigned char *)s + n - 1; - while (n--) { - if (*sp == (unsigned char)c) - return (void *)sp; - sp--; - } + while (n--) { + if (*sp == (unsigned char)c) + return (void *)sp; + sp--; + } - return NULL; + return NULL; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memset.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memset.c index b5692949..c9fa49b9 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memset.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memset.c @@ -7,9 +7,9 @@ void *memset(void *dst, int c, size_t n) { - char *q = dst; - while (n--) { - *q++ = c; - } - return dst; + char *q = dst; + while (n--) { + *q++ = c; + } + return dst; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/memswap.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/memswap.c index fcbdf3cd..ce4c51bb 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/memswap.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/memswap.c @@ -13,16 +13,16 @@ void memswap(void *m1, void *m2, size_t n) { - char *p = m1; - char *q = m2; - char tmp; + char *p = m1; + char *q = m2; + char tmp; - while (n--) { - tmp = *p; - *p = *q; - *q = tmp; + while (n--) { + tmp = *p; + *p = *q; + *q = tmp; - p++; - q++; - } + p++; + q++; + } } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/mrand48.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/mrand48.c index b3195bbd..f9d68bd3 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/mrand48.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/mrand48.c @@ -14,5 +14,5 @@ extern unsigned short __rand48_seed[3]; long mrand48(void) { - return jrand48(__rand48_seed); + return jrand48(__rand48_seed); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/nrand48.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/nrand48.c index c50e5dda..edee7f59 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/nrand48.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/nrand48.c @@ -11,5 +11,5 @@ long nrand48(unsigned short xsubi[3]) { - return (long)((uint32_t) jrand48(xsubi) >> 1); + return (long)((uint32_t) jrand48(xsubi) >> 1); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/qsort.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/qsort.c index 1c0ab3ba..4f271f50 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/qsort.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/qsort.c @@ -16,36 +16,36 @@ static __inline size_t newgap(size_t gap) { - gap = (gap * 10) / 13; - if (gap == 9 || gap == 10) - gap = 11; + gap = (gap * 10) / 13; + if (gap == 9 || gap == 10) + gap = 11; - if (gap < 1) - gap = 1; - return gap; + if (gap < 1) + gap = 1; + return gap; } void qsort(void *base, size_t nmemb, size_t size, - int (*compar) (const void *, const void *)) + int (*compar) (const void *, const void *)) { - size_t gap = nmemb; - size_t i, j; - char *p1, *p2; - int swapped; + size_t gap = nmemb; + size_t i, j; + char *p1, *p2; + int swapped; - if (!nmemb) - return; + if (!nmemb) + return; - do { - gap = newgap(gap); - swapped = 0; + do { + gap = newgap(gap); + swapped = 0; - for (i = 0, p1 = base; i < nmemb - gap; i++, p1 += size) { - j = i + gap; - if (compar(p1, p2 = (char *)base + j * size) > 0) { - memswap(p1, p2, size); - swapped = 1; - } - } - } while (gap > 1 || swapped); + for (i = 0, p1 = base; i < nmemb - gap; i++, p1 += size) { + j = i + gap; + if (compar(p1, p2 = (char *)base + j * size) > 0) { + memswap(p1, p2, size); + swapped = 1; + } + } + } while (gap > 1 || swapped); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/seed48.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/seed48.c index 357f3bf1..41bdbe70 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/seed48.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/seed48.c @@ -14,9 +14,9 @@ extern unsigned short __rand48_seed[3]; unsigned short *seed48(unsigned short int xsubi[3]) { - static unsigned short oldseed[3]; - memcpy(oldseed, __rand48_seed, sizeof __rand48_seed); - memcpy(__rand48_seed, xsubi, sizeof __rand48_seed); + static unsigned short oldseed[3]; + memcpy(oldseed, __rand48_seed, sizeof __rand48_seed); + memcpy(__rand48_seed, xsubi, sizeof __rand48_seed); - return oldseed; + return oldseed; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/snprintf.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/snprintf.c index 06c35552..6c470ee4 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/snprintf.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/snprintf.c @@ -11,11 +11,11 @@ int snprintf(char *buffer, size_t n, const char *format, ...) { - va_list ap; - int rv; + va_list ap; + int rv; - va_start(ap, format); - rv = vsnprintf(buffer, n, format, ap); - va_end(ap); - return rv; + va_start(ap, format); + rv = vsnprintf(buffer, n, format, ap); + va_end(ap); + return rv; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/sprintf.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/sprintf.c index 29111033..a9599670 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/sprintf.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/sprintf.c @@ -11,12 +11,12 @@ int sprintf(char *buffer, const char *format, ...) { - va_list ap; - int rv; + va_list ap; + int rv; - va_start(ap, format); - rv = vsnprintf(buffer, (~(size_t) 0)>>1, format, ap); - va_end(ap); + va_start(ap, format); + rv = vsnprintf(buffer, (~(size_t) 0)>>1, format, ap); + va_end(ap); - return rv; + return rv; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/srand48.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/srand48.c index f3412c32..9353e99f 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/srand48.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/srand48.c @@ -14,17 +14,17 @@ extern unsigned short __rand48_seed[3]; void srand48(long seedval) { - __rand48_seed[0] = 0x330e; - __rand48_seed[1] = (unsigned short)seedval; - __rand48_seed[2] = (unsigned short)((uint32_t) seedval >> 16); + __rand48_seed[0] = 0x330e; + __rand48_seed[1] = (unsigned short)seedval; + __rand48_seed[2] = (unsigned short)((uint32_t) seedval >> 16); } void srand(unsigned int __s) { - srand48(__s); + srand48(__s); } void srandom(unsigned int __s) { - srand48(__s); + srand48(__s); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/sscanf.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/sscanf.c index e6ac85bd..1b92a9bb 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/sscanf.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/sscanf.c @@ -11,12 +11,12 @@ int sscanf(const char *str, const char *format, ...) { - va_list ap; - int rv; + va_list ap; + int rv; - va_start(ap, format); - rv = vsscanf(str, format, ap); - va_end(ap); + va_start(ap, format); + rv = vsscanf(str, format, ap); + va_end(ap); - return rv; + return rv; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/stdlib.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/stdlib.c index 4c20d439..b55c8c33 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/stdlib.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/stdlib.c @@ -10,7 +10,7 @@ void *malloc(size_t size) { - return NULL; + return NULL; } void free(void *ptr) @@ -19,10 +19,10 @@ void free(void *ptr) void *calloc(size_t nmemb, size_t size) { - return NULL; + return NULL; } void *realloc(void *ptr, size_t size) { - return NULL; + return NULL; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcasecmp.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcasecmp.c index 7d42cc5e..7ff8001a 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcasecmp.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcasecmp.c @@ -11,18 +11,18 @@ int strcasecmp(const char *s1, const char *s2) { - const unsigned char *c1 = (const unsigned char *)s1; - const unsigned char *c2 = (const unsigned char *)s2; - unsigned char ch; - int d = 0; + const unsigned char *c1 = (const unsigned char *)s1; + const unsigned char *c2 = (const unsigned char *)s2; + unsigned char ch; + int d = 0; - while (1) { - /* toupper() expects an unsigned char (implicitly cast to int) - as input, and returns an int, which is exactly what we want. */ - d = toupper(ch = *c1++) - toupper(*c2++); - if (d || !ch) - break; - } + while (1) { + /* toupper() expects an unsigned char (implicitly cast to int) + as input, and returns an int, which is exactly what we want. */ + d = toupper(ch = *c1++) - toupper(*c2++); + if (d || !ch) + break; + } - return d; + return d; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcat.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcat.c index 0cd9377b..71e993dc 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcat.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcat.c @@ -10,6 +10,6 @@ char *strcat(char *dst, const char *src) { - strcpy(strchr(dst, '\0'), src); - return dst; + strcpy(strchr(dst, '\0'), src); + return dst; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strchr.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strchr.c index a9e99881..1d12990a 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strchr.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strchr.c @@ -12,11 +12,11 @@ __WEAK__ char *strchr(const char *s, int c) { - while (*s != (char)c) { - if (!*s) - return NULL; - s++; - } + while (*s != (char)c) { + if (!*s) + return NULL; + s++; + } - return (char *)s; + return (char *)s; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcmp.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcmp.c index 2a8f342d..df3fa67b 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcmp.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcmp.c @@ -10,16 +10,16 @@ int strcmp(const char *s1, const char *s2) { - const unsigned char *c1 = (const unsigned char *)s1; - const unsigned char *c2 = (const unsigned char *)s2; - unsigned char ch; - int d = 0; + const unsigned char *c1 = (const unsigned char *)s1; + const unsigned char *c2 = (const unsigned char *)s2; + unsigned char ch; + int d = 0; - while (1) { - d = (int)(ch = *c1++) - (int)*c2++; - if (d || !ch) - break; - } + while (1) { + d = (int)(ch = *c1++) - (int)*c2++; + if (d || !ch) + break; + } - return d; + return d; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcpy.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcpy.c index 68f291ae..c1a52020 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcpy.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcpy.c @@ -12,13 +12,13 @@ char *strcpy(char *dst, const char *src) { - char *q = dst; - const char *p = src; - char ch; + char *q = dst; + const char *p = src; + char ch; - do { - *q++ = ch = *p++; - } while (ch); + do { + *q++ = ch = *p++; + } while (ch); - return dst; + return dst; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcspn.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcspn.c index b0cd78a8..39b938de 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strcspn.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strcspn.c @@ -12,5 +12,5 @@ size_t strcspn(const char *s, const char *reject) { - return __strxspn(s, reject, 1); + return __strxspn(s, reject, 1); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcat.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcat.c index 7c0c6ad7..f2c576b8 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcat.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcat.c @@ -10,25 +10,25 @@ size_t strlcat(char *dst, const char *src, size_t size) { - size_t bytes = 0; - char *q = dst; - const char *p = src; - char ch; + size_t bytes = 0; + char *q = dst; + const char *p = src; + char ch; - while (bytes < size && *q) { - q++; - bytes++; - } - if (bytes == size) - return (bytes + strlen(src)); + while (bytes < size && *q) { + q++; + bytes++; + } + if (bytes == size) + return (bytes + strlen(src)); - while ((ch = *p++)) { - if (bytes + 1 < size) - *q++ = ch; + while ((ch = *p++)) { + if (bytes + 1 < size) + *q++ = ch; - bytes++; - } + bytes++; + } - *q = '\0'; - return bytes; + *q = '\0'; + return bytes; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcpy.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcpy.c index a1ca46e4..87997812 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcpy.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strlcpy.c @@ -10,21 +10,21 @@ size_t strlcpy(char *dst, const char *src, size_t size) { - size_t bytes = 0; - char *q = dst; - const char *p = src; - char ch; + size_t bytes = 0; + char *q = dst; + const char *p = src; + char ch; - while ((ch = *p++)) { - if (bytes + 1 < size) - *q++ = ch; + while ((ch = *p++)) { + if (bytes + 1 < size) + *q++ = ch; - bytes++; - } + bytes++; + } - /* If size == 0 there is no space for a final null... */ - if (size) - *q = '\0'; + /* If size == 0 there is no space for a final null... */ + if (size) + *q = '\0'; - return bytes; + return bytes; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strlen.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strlen.c index bf567988..e18a1909 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strlen.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strlen.c @@ -10,8 +10,8 @@ size_t strlen(const char *s) { - const char *ss = s; - while (*ss) - ss++; - return ss - s; + const char *ss = s; + while (*ss) + ss++; + return ss - s; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncasecmp.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncasecmp.c index b480b865..7fac7759 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncasecmp.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncasecmp.c @@ -11,18 +11,18 @@ int strncasecmp(const char *s1, const char *s2, size_t n) { - const unsigned char *c1 = (const unsigned char *)s1; - const unsigned char *c2 = (const unsigned char *)s2; - unsigned char ch; - int d = 0; + const unsigned char *c1 = (const unsigned char *)s1; + const unsigned char *c2 = (const unsigned char *)s2; + unsigned char ch; + int d = 0; - while (n--) { - /* toupper() expects an unsigned char (implicitly cast to int) - as input, and returns an int, which is exactly what we want. */ - d = toupper(ch = *c1++) - toupper(*c2++); - if (d || !ch) - break; - } + while (n--) { + /* toupper() expects an unsigned char (implicitly cast to int) + as input, and returns an int, which is exactly what we want. */ + d = toupper(ch = *c1++) - toupper(*c2++); + if (d || !ch) + break; + } - return d; + return d; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncat.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncat.c index e9a7f934..26737c09 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncat.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncat.c @@ -10,16 +10,16 @@ char *strncat(char *dst, const char *src, size_t n) { - char *q = strchr(dst, '\0'); - const char *p = src; - char ch; + char *q = strchr(dst, '\0'); + const char *p = src; + char ch; - while (n--) { - *q++ = ch = *p++; - if (!ch) - return dst; - } - *q = '\0'; + while (n--) { + *q++ = ch = *p++; + if (!ch) + return dst; + } + *q = '\0'; - return dst; + return dst; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncmp.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncmp.c index ffa85547..5a0dcba8 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncmp.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncmp.c @@ -10,16 +10,16 @@ int strncmp(const char *s1, const char *s2, size_t n) { - const unsigned char *c1 = (const unsigned char *)s1; - const unsigned char *c2 = (const unsigned char *)s2; - unsigned char ch; - int d = 0; + const unsigned char *c1 = (const unsigned char *)s1; + const unsigned char *c2 = (const unsigned char *)s2; + unsigned char ch; + int d = 0; - while (n--) { - d = (int)(ch = *c1++) - (int)*c2++; - if (d || !ch) - break; - } + while (n--) { + d = (int)(ch = *c1++) - (int)*c2++; + if (d || !ch) + break; + } - return d; + return d; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncpy.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncpy.c index 6ae3f466..b1d85ae1 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strncpy.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strncpy.c @@ -10,19 +10,19 @@ char *strncpy(char *dst, const char *src, size_t n) { - char *q = dst; - const char *p = src; - char ch; + char *q = dst; + const char *p = src; + char ch; - while (n) { - n--; - *q++ = ch = *p++; - if (!ch) - break; - } + while (n) { + n--; + *q++ = ch = *p++; + if (!ch) + break; + } - /* The specs say strncpy() fills the entire buffer with NUL. Sigh. */ - memset(q, 0, n); + /* The specs say strncpy() fills the entire buffer with NUL. Sigh. */ + memset(q, 0, n); - return dst; + return dst; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strnlen.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strnlen.c index fb60071d..b32a4e69 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strnlen.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strnlen.c @@ -10,13 +10,13 @@ size_t strnlen(const char *s, size_t maxlen) { - const char *ss = s; + const char *ss = s; - /* Important: the maxlen test must precede the reference through ss; - since the byte beyond the maximum may segfault */ - while ((maxlen > 0) && *ss) { - ss++; - maxlen--; - } - return ss - s; + /* Important: the maxlen test must precede the reference through ss; + since the byte beyond the maximum may segfault */ + while ((maxlen > 0) && *ss) { + ss++; + maxlen--; + } + return ss - s; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoimax.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoimax.c index e9187b80..072313e8 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoimax.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoimax.c @@ -14,5 +14,5 @@ intmax_t strntoimax(const char *nptr, char **endptr, int base, size_t n) { - return (intmax_t) strntoumax(nptr, endptr, base, n); + return (intmax_t) strntoumax(nptr, endptr, base, n); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoumax.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoumax.c index b66450f7..8b87093a 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoumax.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strntoumax.c @@ -15,67 +15,67 @@ static __inline int digitval(int ch) { - if (ch >= '0' && ch <= '9') { - return ch - '0'; - } else if (ch >= 'A' && ch <= 'Z') { - return ch - 'A' + 10; - } else if (ch >= 'a' && ch <= 'z') { - return ch - 'a' + 10; - } else { - return -1; - } + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } else if (ch >= 'A' && ch <= 'Z') { + return ch - 'A' + 10; + } else if (ch >= 'a' && ch <= 'z') { + return ch - 'a' + 10; + } else { + return -1; + } } uintmax_t strntoumax(const char *nptr, char **endptr, int base, size_t n) { - int minus = 0; - uintmax_t v = 0; - int d; + int minus = 0; + uintmax_t v = 0; + int d; - while (n && isspace((unsigned char)*nptr)) { - nptr++; - n--; - } + while (n && isspace((unsigned char)*nptr)) { + nptr++; + n--; + } - /* Single optional + or - */ - if (n) { - char c = *nptr; - if (c == '-' || c == '+') { - minus = (c == '-'); - nptr++; - n--; - } - } + /* Single optional + or - */ + if (n) { + char c = *nptr; + if (c == '-' || c == '+') { + minus = (c == '-'); + nptr++; + n--; + } + } - if (base == 0) { - if (n >= 2 && nptr[0] == '0' && - (nptr[1] == 'x' || nptr[1] == 'X')) { - n -= 2; - nptr += 2; - base = 16; - } else if (n >= 1 && nptr[0] == '0') { - n--; - nptr++; - base = 8; - } else { - base = 10; - } - } else if (base == 16) { - if (n >= 2 && nptr[0] == '0' && - (nptr[1] == 'x' || nptr[1] == 'X')) { - n -= 2; - nptr += 2; - } - } + if (base == 0) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + base = 16; + } else if (n >= 1 && nptr[0] == '0') { + n--; + nptr++; + base = 8; + } else { + base = 10; + } + } else if (base == 16) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + } + } - while (n && (d = digitval(*nptr)) >= 0 && d < base) { - v = v * base + d; - n--; - nptr++; - } + while (n && (d = digitval(*nptr)) >= 0 && d < base) { + v = v * base + d; + n--; + nptr++; + } - if (endptr) - *endptr = (char *)nptr; + if (endptr) + *endptr = (char *)nptr; - return minus ? -v : v; + return minus ? -v : v; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strpbrk.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strpbrk.c index 2c8d2b40..9c24e925 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strpbrk.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strpbrk.c @@ -12,7 +12,7 @@ char *strpbrk(const char *s, const char *accept) { - const char *ss = s + __strxspn(s, accept, 1); + const char *ss = s + __strxspn(s, accept, 1); - return *ss ? (char *)ss : NULL; + return *ss ? (char *)ss : NULL; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strrchr.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strrchr.c index 4bbae0c1..912f88ba 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strrchr.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strrchr.c @@ -10,13 +10,13 @@ char *strrchr(const char *s, int c) { - const char *found = NULL; + const char *found = NULL; - while (*s) { - if (*s == (char)c) - found = s; - s++; - } + while (*s) { + if (*s == (char)c) + found = s; + s++; + } - return (char *)found; + return (char *)found; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strsep.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strsep.c index 417e8e1a..e20aee64 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strsep.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strsep.c @@ -10,16 +10,16 @@ char *strsep(char **stringp, const char *delim) { - char *s = *stringp; - char *e; + char *s = *stringp; + char *e; - if (!s) - return NULL; + if (!s) + return NULL; - e = strpbrk(s, delim); - if (e) - *e++ = '\0'; + e = strpbrk(s, delim); + if (e) + *e++ = '\0'; - *stringp = e; - return s; + *stringp = e; + return s; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strspn.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strspn.c index cfa708b3..9f346af7 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strspn.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strspn.c @@ -12,5 +12,5 @@ size_t strspn(const char *s, const char *accept) { - return __strxspn(s, accept, 0); + return __strxspn(s, accept, 0); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strstr.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strstr.c index 762c5ff3..09a4f303 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strstr.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strstr.c @@ -11,6 +11,6 @@ char *strstr(const char *haystack, const char *needle) { - return (char *)memmem(haystack, strlen(haystack), needle, - strlen(needle)); + return (char *)memmem(haystack, strlen(haystack), needle, + strlen(needle)); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok.c index 9f730953..d5341c24 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok.c @@ -10,7 +10,7 @@ char *strtok(char *s, const char *delim) { - static char *holder; + static char *holder; - return strtok_r(s, delim, &holder); + return strtok_r(s, delim, &holder); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok_r.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok_r.c index be63d04d..ab6c4975 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok_r.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strtok_r.c @@ -6,12 +6,12 @@ char *strtok_r(char *s, const char *delim, char **holder) { - if (s) - *holder = s; + if (s) + *holder = s; - do { - s = strsep(holder, delim); - } while (s && !*s); + do { + s = strsep(holder, delim); + } while (s && !*s); - return s; + return s; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strtox.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strtox.c index 2646f49f..cdd1811d 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strtox.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strtox.c @@ -15,5 +15,5 @@ WEAK TYPE NAME(const char *nptr, char **endptr, int base) { - return (TYPE) strntoumax(nptr, endptr, base, ~(size_t) 0); + return (TYPE) strntoumax(nptr, endptr, base, ~(size_t) 0); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/strxspn.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/strxspn.c index f4969c56..a300ae32 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/strxspn.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/strxspn.c @@ -14,20 +14,20 @@ size_t __strxspn(const char *s, const char *map, int parity) { - char matchmap[UCHAR_MAX + 1]; - size_t n = 0; + char matchmap[UCHAR_MAX + 1]; + size_t n = 0; - /* Create bitmap */ - memset(matchmap, 0, sizeof matchmap); - while (*map) - matchmap[(unsigned char)*map++] = 1; + /* Create bitmap */ + memset(matchmap, 0, sizeof matchmap); + while (*map) + matchmap[(unsigned char)*map++] = 1; - /* Make sure the null character never matches */ - matchmap[0] = parity; + /* Make sure the null character never matches */ + matchmap[0] = parity; - /* Calculate span length */ - while (matchmap[(unsigned char)*s++] ^ parity) - n++; + /* Calculate span length */ + while (matchmap[(unsigned char)*s++] ^ parity) + n++; - return n; + return n; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/vsnprintf.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/vsnprintf.c index b4c56865..8925e46e 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/vsnprintf.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/vsnprintf.c @@ -17,484 +17,484 @@ #include enum flag { - FL_ZERO = 0x01, /* Zero modifier */ - FL_MINUS = 0x02, /* Minus modifier */ - FL_PLUS = 0x04, /* Plus modifier */ - FL_TICK = 0x08, /* ' modifier */ - FL_SPACE = 0x10, /* Space modifier */ - FL_HASH = 0x20, /* # modifier */ - FL_SIGNED = 0x40, /* Number is signed */ - FL_UPPER = 0x80 /* Upper case digits */ + FL_ZERO = 0x01, /* Zero modifier */ + FL_MINUS = 0x02, /* Minus modifier */ + FL_PLUS = 0x04, /* Plus modifier */ + FL_TICK = 0x08, /* ' modifier */ + FL_SPACE = 0x10, /* Space modifier */ + FL_HASH = 0x20, /* # modifier */ + FL_SIGNED = 0x40, /* Number is signed */ + FL_UPPER = 0x80 /* Upper case digits */ }; /* These may have to be adjusted on certain implementations */ enum ranks { - rank_char = -2, - rank_short = -1, - rank_int = 0, - rank_long = 1, - rank_longlong = 2 + rank_char = -2, + rank_short = -1, + rank_int = 0, + rank_long = 1, + rank_longlong = 2 }; -#define MIN_RANK rank_char -#define MAX_RANK rank_longlong +#define MIN_RANK rank_char +#define MAX_RANK rank_longlong -#define INTMAX_RANK rank_longlong -#define SIZE_T_RANK rank_long -#define PTRDIFF_T_RANK rank_long +#define INTMAX_RANK rank_longlong +#define SIZE_T_RANK rank_long +#define PTRDIFF_T_RANK rank_long #define EMIT(x) { if (o < n) { *q++ = (x); } o++; } static size_t format_int(char *q, size_t n, uintmax_t val, unsigned int flags, - int base, int width, int prec) + int base, int width, int prec) { - char *qq; - size_t o = 0, oo; - static const char lcdigits[] = "0123456789abcdef"; - static const char ucdigits[] = "0123456789ABCDEF"; - const char *digits; - uintmax_t tmpval; - int minus = 0; - int ndigits = 0, nchars; - int tickskip, b4tick; + char *qq; + size_t o = 0, oo; + static const char lcdigits[] = "0123456789abcdef"; + static const char ucdigits[] = "0123456789ABCDEF"; + const char *digits; + uintmax_t tmpval; + int minus = 0; + int ndigits = 0, nchars; + int tickskip, b4tick; - /* Select type of digits */ - digits = (flags & FL_UPPER) ? ucdigits : lcdigits; + /* Select type of digits */ + digits = (flags & FL_UPPER) ? ucdigits : lcdigits; - /* If signed, separate out the minus */ - if (flags & FL_SIGNED && (intmax_t) val < 0) { - minus = 1; - val = (uintmax_t) (-(intmax_t) val); - } + /* If signed, separate out the minus */ + if (flags & FL_SIGNED && (intmax_t) val < 0) { + minus = 1; + val = (uintmax_t) (-(intmax_t) val); + } - /* Count the number of digits needed. This returns zero for 0. */ - tmpval = val; - while (tmpval) { - tmpval /= base; - ndigits++; - } + /* Count the number of digits needed. This returns zero for 0. */ + tmpval = val; + while (tmpval) { + tmpval /= base; + ndigits++; + } - /* Adjust ndigits for size of output */ + /* Adjust ndigits for size of output */ - if (flags & FL_HASH && base == 8) { - if (prec < ndigits + 1) - prec = ndigits + 1; - } + if (flags & FL_HASH && base == 8) { + if (prec < ndigits + 1) + prec = ndigits + 1; + } - if (ndigits < prec) { - ndigits = prec; /* Mandatory number padding */ - } else if (val == 0) { - ndigits = 1; /* Zero still requires space */ - } + if (ndigits < prec) { + ndigits = prec; /* Mandatory number padding */ + } else if (val == 0) { + ndigits = 1; /* Zero still requires space */ + } - /* For ', figure out what the skip should be */ - if (flags & FL_TICK) { - tickskip = (base == 16) ? 4 : 3; - } else { - tickskip = ndigits; /* No tick marks */ - } + /* For ', figure out what the skip should be */ + if (flags & FL_TICK) { + tickskip = (base == 16) ? 4 : 3; + } else { + tickskip = ndigits; /* No tick marks */ + } - /* Tick marks aren't digits, but generated by the number converter */ - ndigits += (ndigits - 1) / tickskip; + /* Tick marks aren't digits, but generated by the number converter */ + ndigits += (ndigits - 1) / tickskip; - /* Now compute the number of nondigits */ - nchars = ndigits; + /* Now compute the number of nondigits */ + nchars = ndigits; - if (minus || (flags & (FL_PLUS | FL_SPACE))) - nchars++; /* Need space for sign */ - if ((flags & FL_HASH) && base == 16) { - nchars += 2; /* Add 0x for hex */ - } + if (minus || (flags & (FL_PLUS | FL_SPACE))) + nchars++; /* Need space for sign */ + if ((flags & FL_HASH) && base == 16) { + nchars += 2; /* Add 0x for hex */ + } - /* Emit early space padding */ - if (!(flags & (FL_MINUS | FL_ZERO)) && width > nchars) { - while (width > nchars) { - EMIT(' '); - width--; - } - } + /* Emit early space padding */ + if (!(flags & (FL_MINUS | FL_ZERO)) && width > nchars) { + while (width > nchars) { + EMIT(' '); + width--; + } + } - /* Emit nondigits */ - if (minus) { - EMIT('-'); - } else if (flags & FL_PLUS) { - EMIT('+'); - } else if (flags & FL_SPACE) { - EMIT(' '); - } + /* Emit nondigits */ + if (minus) { + EMIT('-'); + } else if (flags & FL_PLUS) { + EMIT('+'); + } else if (flags & FL_SPACE) { + EMIT(' '); + } - if ((flags & FL_HASH) && base == 16) { - EMIT('0'); - EMIT((flags & FL_UPPER) ? 'X' : 'x'); - } + if ((flags & FL_HASH) && base == 16) { + EMIT('0'); + EMIT((flags & FL_UPPER) ? 'X' : 'x'); + } - /* Emit zero padding */ - if ((flags & (FL_MINUS | FL_ZERO)) == FL_ZERO && width > ndigits) { - while (width > nchars) { - EMIT('0'); - width--; - } - } + /* Emit zero padding */ + if ((flags & (FL_MINUS | FL_ZERO)) == FL_ZERO && width > ndigits) { + while (width > nchars) { + EMIT('0'); + width--; + } + } - /* Generate the number. This is done from right to left. */ - q += ndigits; /* Advance the pointer to end of number */ - o += ndigits; - qq = q; - oo = o; /* Temporary values */ + /* Generate the number. This is done from right to left. */ + q += ndigits; /* Advance the pointer to end of number */ + o += ndigits; + qq = q; + oo = o; /* Temporary values */ - b4tick = tickskip; - while (ndigits > 0) { - if (!b4tick--) { - qq--; - oo--; - ndigits--; - if (oo < n) - *qq = '_'; - b4tick = tickskip - 1; - } - qq--; - oo--; - ndigits--; - if (oo < n) - *qq = digits[val % base]; - val /= base; - } + b4tick = tickskip; + while (ndigits > 0) { + if (!b4tick--) { + qq--; + oo--; + ndigits--; + if (oo < n) + *qq = '_'; + b4tick = tickskip - 1; + } + qq--; + oo--; + ndigits--; + if (oo < n) + *qq = digits[val % base]; + val /= base; + } - /* Emit late space padding */ - while ((flags & FL_MINUS) && width > nchars) { - EMIT(' '); - width--; - } + /* Emit late space padding */ + while ((flags & FL_MINUS) && width > nchars) { + EMIT(' '); + width--; + } - return o; + return o; } int vsnprintf(char *buffer, size_t n, const char *format, va_list ap) { - const char *p = format; - char ch; - char *q = buffer; - size_t o = 0; /* Number of characters output */ - uintmax_t val = 0; - int rank = rank_int; /* Default rank */ - int width = 0; - int prec = -1; - int base; - size_t sz; - unsigned int flags = 0; - enum { - st_normal, /* Ground state */ - st_flags, /* Special flags */ - st_width, /* Field width */ - st_prec, /* Field precision */ - st_modifiers /* Length or conversion modifiers */ - } state = st_normal; - const char *sarg; /* %s string argument */ - char carg; /* %c char argument */ - int slen; /* String length */ + const char *p = format; + char ch; + char *q = buffer; + size_t o = 0; /* Number of characters output */ + uintmax_t val = 0; + int rank = rank_int; /* Default rank */ + int width = 0; + int prec = -1; + int base; + size_t sz; + unsigned int flags = 0; + enum { + st_normal, /* Ground state */ + st_flags, /* Special flags */ + st_width, /* Field width */ + st_prec, /* Field precision */ + st_modifiers /* Length or conversion modifiers */ + } state = st_normal; + const char *sarg; /* %s string argument */ + char carg; /* %c char argument */ + int slen; /* String length */ - while ((ch = *p++)) { - switch (state) { - case st_normal: - if (ch == '%') { - state = st_flags; - flags = 0; - rank = rank_int; - width = 0; - prec = -1; - } else { - EMIT(ch); - } - break; + while ((ch = *p++)) { + switch (state) { + case st_normal: + if (ch == '%') { + state = st_flags; + flags = 0; + rank = rank_int; + width = 0; + prec = -1; + } else { + EMIT(ch); + } + break; - case st_flags: - switch (ch) { - case '-': - flags |= FL_MINUS; - break; - case '+': - flags |= FL_PLUS; - break; - case '\'': - flags |= FL_TICK; - break; - case ' ': - flags |= FL_SPACE; - break; - case '#': - flags |= FL_HASH; - break; - case '0': - flags |= FL_ZERO; - break; - default: - state = st_width; - p--; /* Process this character again */ - break; - } - break; + case st_flags: + switch (ch) { + case '-': + flags |= FL_MINUS; + break; + case '+': + flags |= FL_PLUS; + break; + case '\'': + flags |= FL_TICK; + break; + case ' ': + flags |= FL_SPACE; + break; + case '#': + flags |= FL_HASH; + break; + case '0': + flags |= FL_ZERO; + break; + default: + state = st_width; + p--; /* Process this character again */ + break; + } + break; - case st_width: - if (ch >= '0' && ch <= '9') { - width = width * 10 + (ch - '0'); - } else if (ch == '*') { - width = va_arg(ap, int); - if (width < 0) { - width = -width; - flags |= FL_MINUS; - } - } else if (ch == '.') { - prec = 0; /* Precision given */ - state = st_prec; - } else { - state = st_modifiers; - p--; /* Process this character again */ - } - break; + case st_width: + if (ch >= '0' && ch <= '9') { + width = width * 10 + (ch - '0'); + } else if (ch == '*') { + width = va_arg(ap, int); + if (width < 0) { + width = -width; + flags |= FL_MINUS; + } + } else if (ch == '.') { + prec = 0; /* Precision given */ + state = st_prec; + } else { + state = st_modifiers; + p--; /* Process this character again */ + } + break; - case st_prec: - if (ch >= '0' && ch <= '9') { - prec = prec * 10 + (ch - '0'); - } else if (ch == '*') { - prec = va_arg(ap, int); - if (prec < 0) - prec = -1; - } else { - state = st_modifiers; - p--; /* Process this character again */ - } - break; + case st_prec: + if (ch >= '0' && ch <= '9') { + prec = prec * 10 + (ch - '0'); + } else if (ch == '*') { + prec = va_arg(ap, int); + if (prec < 0) + prec = -1; + } else { + state = st_modifiers; + p--; /* Process this character again */ + } + break; - case st_modifiers: - switch (ch) { - /* Length modifiers - nonterminal sequences */ - case 'h': - rank--; /* Shorter rank */ - break; - case 'l': - rank++; /* Longer rank */ - break; - case 'j': - rank = INTMAX_RANK; - break; - case 'z': - rank = SIZE_T_RANK; - break; - case 't': - rank = PTRDIFF_T_RANK; - break; - case 'L': - case 'q': - rank += 2; - break; - default: - /* Output modifiers - terminal sequences */ + case st_modifiers: + switch (ch) { + /* Length modifiers - nonterminal sequences */ + case 'h': + rank--; /* Shorter rank */ + break; + case 'l': + rank++; /* Longer rank */ + break; + case 'j': + rank = INTMAX_RANK; + break; + case 'z': + rank = SIZE_T_RANK; + break; + case 't': + rank = PTRDIFF_T_RANK; + break; + case 'L': + case 'q': + rank += 2; + break; + default: + /* Output modifiers - terminal sequences */ - /* Next state will be normal */ - state = st_normal; + /* Next state will be normal */ + state = st_normal; - /* Canonicalize rank */ - if (rank < MIN_RANK) - rank = MIN_RANK; - else if (rank > MAX_RANK) - rank = MAX_RANK; + /* Canonicalize rank */ + if (rank < MIN_RANK) + rank = MIN_RANK; + else if (rank > MAX_RANK) + rank = MAX_RANK; - switch (ch) { - case 'P': /* Upper case pointer */ - flags |= FL_UPPER; - /* fall through */ - case 'p': /* Pointer */ - base = 16; - prec = (CHAR_BIT*sizeof(void *)+3)/4; - flags |= FL_HASH; - val = (uintmax_t)(uintptr_t) - va_arg(ap, void *); - goto is_integer; + switch (ch) { + case 'P': /* Upper case pointer */ + flags |= FL_UPPER; + /* fall through */ + case 'p': /* Pointer */ + base = 16; + prec = (CHAR_BIT*sizeof(void *)+3)/4; + flags |= FL_HASH; + val = (uintmax_t)(uintptr_t) + va_arg(ap, void *); + goto is_integer; - case 'd': /* Signed decimal output */ - case 'i': - base = 10; - flags |= FL_SIGNED; - switch (rank) { - case rank_char: - /* Yes, all these casts are - needed... */ - val = (uintmax_t)(intmax_t) - (signed char) - va_arg(ap, signed int); - break; - case rank_short: - val = (uintmax_t)(intmax_t) - (signed short) - va_arg(ap, signed int); - break; - case rank_int: - val = (uintmax_t)(intmax_t) - va_arg(ap, signed int); - break; - case rank_long: - val = (uintmax_t)(intmax_t) - va_arg(ap, signed long); - break; - case rank_longlong: - val = (uintmax_t)(intmax_t) - va_arg(ap, - signed long long); - break; - default: - break; - } - goto is_integer; - case 'o': /* Octal */ - base = 8; - goto is_unsigned; - case 'u': /* Unsigned decimal */ - base = 10; - goto is_unsigned; - case 'X': /* Upper case hexadecimal */ - flags |= FL_UPPER; - /* fall through */ - case 'x': /* Hexadecimal */ - base = 16; - goto is_unsigned; + case 'd': /* Signed decimal output */ + case 'i': + base = 10; + flags |= FL_SIGNED; + switch (rank) { + case rank_char: + /* Yes, all these casts are + needed... */ + val = (uintmax_t)(intmax_t) + (signed char) + va_arg(ap, signed int); + break; + case rank_short: + val = (uintmax_t)(intmax_t) + (signed short) + va_arg(ap, signed int); + break; + case rank_int: + val = (uintmax_t)(intmax_t) + va_arg(ap, signed int); + break; + case rank_long: + val = (uintmax_t)(intmax_t) + va_arg(ap, signed long); + break; + case rank_longlong: + val = (uintmax_t)(intmax_t) + va_arg(ap, + signed long long); + break; + default: + break; + } + goto is_integer; + case 'o': /* Octal */ + base = 8; + goto is_unsigned; + case 'u': /* Unsigned decimal */ + base = 10; + goto is_unsigned; + case 'X': /* Upper case hexadecimal */ + flags |= FL_UPPER; + /* fall through */ + case 'x': /* Hexadecimal */ + base = 16; + goto is_unsigned; - is_unsigned: - switch (rank) { - case rank_char: - val = (uintmax_t) - (unsigned char) - va_arg(ap, unsigned - int); - break; - case rank_short: - val = (uintmax_t) - (unsigned short) - va_arg(ap, unsigned - int); - break; - case rank_int: - val = (uintmax_t) - va_arg(ap, unsigned - int); - break; - case rank_long: - val = (uintmax_t) - va_arg(ap, unsigned - long); - break; - case rank_longlong: - val = (uintmax_t) - va_arg(ap, unsigned - long long); - break; - default: - break; - } - /* fall through */ + is_unsigned: + switch (rank) { + case rank_char: + val = (uintmax_t) + (unsigned char) + va_arg(ap, unsigned + int); + break; + case rank_short: + val = (uintmax_t) + (unsigned short) + va_arg(ap, unsigned + int); + break; + case rank_int: + val = (uintmax_t) + va_arg(ap, unsigned + int); + break; + case rank_long: + val = (uintmax_t) + va_arg(ap, unsigned + long); + break; + case rank_longlong: + val = (uintmax_t) + va_arg(ap, unsigned + long long); + break; + default: + break; + } + /* fall through */ - is_integer: - sz = format_int(q, (o < n) ? n - o : 0, - val, flags, base, - width, prec); - q += sz; - o += sz; - break; + is_integer: + sz = format_int(q, (o < n) ? n - o : 0, + val, flags, base, + width, prec); + q += sz; + o += sz; + break; - case 'c': /* Character */ - carg = (char)va_arg(ap, int); - sarg = &carg; - slen = 1; - goto is_string; - case 's': /* String */ - sarg = va_arg(ap, const char *); - sarg = sarg ? sarg : "(null)"; - slen = strlen(sarg); - goto is_string; + case 'c': /* Character */ + carg = (char)va_arg(ap, int); + sarg = &carg; + slen = 1; + goto is_string; + case 's': /* String */ + sarg = va_arg(ap, const char *); + sarg = sarg ? sarg : "(null)"; + slen = strlen(sarg); + goto is_string; - is_string: - { - char sch; - int i; + is_string: + { + char sch; + int i; - if (prec != -1 && slen > prec) - slen = prec; + if (prec != -1 && slen > prec) + slen = prec; - if (width > slen - && !(flags & FL_MINUS)) { - char pad = - (flags & FL_ZERO) ? - '0' : ' '; - while (width > slen) { - EMIT(pad); - width--; - } - } - for (i = slen; i; i--) { - sch = *sarg++; - EMIT(sch); - } - if (width > slen - && (flags & FL_MINUS)) { - while (width > slen) { - EMIT(' '); - width--; - } - } - } - break; + if (width > slen + && !(flags & FL_MINUS)) { + char pad = + (flags & FL_ZERO) ? + '0' : ' '; + while (width > slen) { + EMIT(pad); + width--; + } + } + for (i = slen; i; i--) { + sch = *sarg++; + EMIT(sch); + } + if (width > slen + && (flags & FL_MINUS)) { + while (width > slen) { + EMIT(' '); + width--; + } + } + } + break; - case 'n': - { - /* Output the number of - characters written */ + case 'n': + { + /* Output the number of + characters written */ - switch (rank) { - case rank_char: - *va_arg(ap, - signed char *) - = o; - break; - case rank_short: - *va_arg(ap, - signed short *) - = o; - break; - case rank_int: - *va_arg(ap, - signed int *) - = o; - break; - case rank_long: - *va_arg(ap, - signed long *) - = o; - break; - case rank_longlong: - *va_arg(ap, - signed long long *) - = o; - break; - default: - break; - } - } - break; + switch (rank) { + case rank_char: + *va_arg(ap, + signed char *) + = o; + break; + case rank_short: + *va_arg(ap, + signed short *) + = o; + break; + case rank_int: + *va_arg(ap, + signed int *) + = o; + break; + case rank_long: + *va_arg(ap, + signed long *) + = o; + break; + case rank_longlong: + *va_arg(ap, + signed long long *) + = o; + break; + default: + break; + } + } + break; - default: /* Anything else, including % */ - EMIT(ch); - break; - } - } + default: /* Anything else, including % */ + EMIT(ch); + break; + } + } default: break; - } - } + } + } - /* Null-terminate the string */ - if (o < n) - *q = '\0'; /* No overflow */ - else if (n > 0) - buffer[n - 1] = '\0'; /* Overflow - terminate at end of buffer */ + /* Null-terminate the string */ + if (o < n) + *q = '\0'; /* No overflow */ + else if (n > 0) + buffer[n - 1] = '\0'; /* Overflow - terminate at end of buffer */ - return o; + return o; } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/vsprintf.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/vsprintf.c index a991f55e..9d2f9344 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/vsprintf.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/vsprintf.c @@ -11,5 +11,5 @@ int vsprintf(char *buffer, const char *format, va_list ap) { - return vsnprintf(buffer, (~(size_t) 0)>>1, format, ap); + return vsnprintf(buffer, (~(size_t) 0)>>1, format, ap); } diff --git a/components/bl602/bl602_std/bl602_std/Common/libc/src/vsscanf.c b/components/bl602/bl602_std/bl602_std/Common/libc/src/vsscanf.c index 942e9eb2..345fdfa9 100644 --- a/components/bl602/bl602_std/bl602_std/Common/libc/src/vsscanf.c +++ b/components/bl602/bl602_std/bl602_std/Common/libc/src/vsscanf.c @@ -24,395 +24,395 @@ #endif enum flag { - FL_SPLAT = 0x01, /* Drop the value, do not assign */ - FL_INV = 0x02, /* Character-set with inverse */ - FL_WIDTH = 0x04, /* Field width specified */ - FL_MINUS = 0x08, /* Negative number */ + FL_SPLAT = 0x01, /* Drop the value, do not assign */ + FL_INV = 0x02, /* Character-set with inverse */ + FL_WIDTH = 0x04, /* Field width specified */ + FL_MINUS = 0x08, /* Negative number */ }; enum ranks { - rank_char = -2, - rank_short = -1, - rank_int = 0, - rank_long = 1, - rank_longlong = 2, - rank_ptr = INT_MAX /* Special value used for pointers */ + rank_char = -2, + rank_short = -1, + rank_int = 0, + rank_long = 1, + rank_longlong = 2, + rank_ptr = INT_MAX /* Special value used for pointers */ }; -#define MIN_RANK rank_char -#define MAX_RANK rank_longlong +#define MIN_RANK rank_char +#define MAX_RANK rank_longlong -#define INTMAX_RANK rank_longlong -#define SIZE_T_RANK rank_long -#define PTRDIFF_T_RANK rank_long +#define INTMAX_RANK rank_longlong +#define SIZE_T_RANK rank_long +#define PTRDIFF_T_RANK rank_long enum bail { - bail_none = 0, /* No error condition */ - bail_eof, /* Hit EOF */ - bail_err /* Conversion mismatch */ + bail_none = 0, /* No error condition */ + bail_eof, /* Hit EOF */ + bail_err /* Conversion mismatch */ }; static __inline const char *skipspace(const char *p) { - while (isspace((unsigned char)*p)) - p++; - return p; + while (isspace((unsigned char)*p)) + p++; + return p; } #undef set_bit static __inline void set_bit(unsigned long *bitmap, unsigned int bit) { - bitmap[bit / LONG_BIT] |= 1UL << (bit % LONG_BIT); + bitmap[bit / LONG_BIT] |= 1UL << (bit % LONG_BIT); } #undef test_bit static __inline int test_bit(unsigned long *bitmap, unsigned int bit) { - return (int)(bitmap[bit / LONG_BIT] >> (bit % LONG_BIT)) & 1; + return (int)(bitmap[bit / LONG_BIT] >> (bit % LONG_BIT)) & 1; } int vsscanf(const char *buffer, const char *format, va_list ap) { - const char *p = format; - char ch; - unsigned char uc; - const char *q = buffer; - const char *qq; - uintmax_t val = 0; - int rank = rank_int; /* Default rank */ - unsigned int width = UINT_MAX; - int base; - unsigned int flags = 0; - enum { - st_normal, /* Ground state */ - st_flags, /* Special flags */ - st_width, /* Field width */ - st_modifiers, /* Length or conversion modifiers */ - st_match_init, /* Initial state of %[ sequence */ - st_match, /* Main state of %[ sequence */ - st_match_range, /* After - in a %[ sequence */ - } state = st_normal; - char *sarg = NULL; /* %s %c or %[ string argument */ - enum bail bail = bail_none; - __UNUSED__ int sign; - int converted = 0; /* Successful conversions */ - unsigned long matchmap[((1 << CHAR_BIT) + (LONG_BIT - 1)) / LONG_BIT]; - int matchinv = 0; /* Is match map inverted? */ - unsigned char range_start = 0; + const char *p = format; + char ch; + unsigned char uc; + const char *q = buffer; + const char *qq; + uintmax_t val = 0; + int rank = rank_int; /* Default rank */ + unsigned int width = UINT_MAX; + int base; + unsigned int flags = 0; + enum { + st_normal, /* Ground state */ + st_flags, /* Special flags */ + st_width, /* Field width */ + st_modifiers, /* Length or conversion modifiers */ + st_match_init, /* Initial state of %[ sequence */ + st_match, /* Main state of %[ sequence */ + st_match_range, /* After - in a %[ sequence */ + } state = st_normal; + char *sarg = NULL; /* %s %c or %[ string argument */ + enum bail bail = bail_none; + __UNUSED__ int sign; + int converted = 0; /* Successful conversions */ + unsigned long matchmap[((1 << CHAR_BIT) + (LONG_BIT - 1)) / LONG_BIT]; + int matchinv = 0; /* Is match map inverted? */ + unsigned char range_start = 0; - while ((ch = *p++) && !bail) { - switch (state) { - case st_normal: - if (ch == '%') { - state = st_flags; - flags = 0; - rank = rank_int; - width = UINT_MAX; - } else if (isspace((unsigned char)ch)) { - q = skipspace(q); - } else { - if (*q == ch) - q++; - else - bail = bail_err; /* Match failure */ - } - break; + while ((ch = *p++) && !bail) { + switch (state) { + case st_normal: + if (ch == '%') { + state = st_flags; + flags = 0; + rank = rank_int; + width = UINT_MAX; + } else if (isspace((unsigned char)ch)) { + q = skipspace(q); + } else { + if (*q == ch) + q++; + else + bail = bail_err; /* Match failure */ + } + break; - case st_flags: - switch (ch) { - case '*': - flags |= FL_SPLAT; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - width = (ch - '0'); - state = st_width; - flags |= FL_WIDTH; - break; - default: - state = st_modifiers; - p--; /* Process this character again */ - break; - } - break; + case st_flags: + switch (ch) { + case '*': + flags |= FL_SPLAT; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + width = (ch - '0'); + state = st_width; + flags |= FL_WIDTH; + break; + default: + state = st_modifiers; + p--; /* Process this character again */ + break; + } + break; - case st_width: - if (ch >= '0' && ch <= '9') { - width = width * 10 + (ch - '0'); - } else { - state = st_modifiers; - p--; /* Process this character again */ - } - break; + case st_width: + if (ch >= '0' && ch <= '9') { + width = width * 10 + (ch - '0'); + } else { + state = st_modifiers; + p--; /* Process this character again */ + } + break; - case st_modifiers: - switch (ch) { - /* Length modifiers - nonterminal sequences */ - case 'h': - rank--; /* Shorter rank */ - break; - case 'l': - rank++; /* Longer rank */ - break; - case 'j': - rank = INTMAX_RANK; - break; - case 'z': - rank = SIZE_T_RANK; - break; - case 't': - rank = PTRDIFF_T_RANK; - break; - case 'L': - case 'q': - rank = rank_longlong; /* long double/long long */ - break; + case st_modifiers: + switch (ch) { + /* Length modifiers - nonterminal sequences */ + case 'h': + rank--; /* Shorter rank */ + break; + case 'l': + rank++; /* Longer rank */ + break; + case 'j': + rank = INTMAX_RANK; + break; + case 'z': + rank = SIZE_T_RANK; + break; + case 't': + rank = PTRDIFF_T_RANK; + break; + case 'L': + case 'q': + rank = rank_longlong; /* long double/long long */ + break; - default: - /* Output modifiers - terminal sequences */ - /* Next state will be normal */ - state = st_normal; + default: + /* Output modifiers - terminal sequences */ + /* Next state will be normal */ + state = st_normal; - /* Canonicalize rank */ - if (rank < MIN_RANK) - rank = MIN_RANK; - else if (rank > MAX_RANK) - rank = MAX_RANK; + /* Canonicalize rank */ + if (rank < MIN_RANK) + rank = MIN_RANK; + else if (rank > MAX_RANK) + rank = MAX_RANK; - switch (ch) { - case 'P': /* Upper case pointer */ - case 'p': /* Pointer */ - rank = rank_ptr; - base = 0; - sign = 0; - goto scan_int; + switch (ch) { + case 'P': /* Upper case pointer */ + case 'p': /* Pointer */ + rank = rank_ptr; + base = 0; + sign = 0; + goto scan_int; - case 'i': /* Base-independent integer */ - base = 0; - sign = 1; - goto scan_int; + case 'i': /* Base-independent integer */ + base = 0; + sign = 1; + goto scan_int; - case 'd': /* Decimal integer */ - base = 10; - sign = 1; - goto scan_int; + case 'd': /* Decimal integer */ + base = 10; + sign = 1; + goto scan_int; - case 'o': /* Octal integer */ - base = 8; - sign = 0; - goto scan_int; + case 'o': /* Octal integer */ + base = 8; + sign = 0; + goto scan_int; - case 'u': /* Unsigned decimal integer */ - base = 10; - sign = 0; - goto scan_int; + case 'u': /* Unsigned decimal integer */ + base = 10; + sign = 0; + goto scan_int; - case 'x': /* Hexadecimal integer */ - case 'X': - base = 16; - sign = 0; - goto scan_int; + case 'x': /* Hexadecimal integer */ + case 'X': + base = 16; + sign = 0; + goto scan_int; - case 'n': /* # of characters consumed */ - val = (q - buffer); - goto set_integer; + case 'n': /* # of characters consumed */ + val = (q - buffer); + goto set_integer; - scan_int: - q = skipspace(q); - if (!*q) { - bail = bail_eof; - break; - } - val = - strntoumax(q, (char **)&qq, base, - width); - if (qq == q) { - bail = bail_err; - break; - } - q = qq; - if (!(flags & FL_SPLAT)) - converted++; - /* fall through */ + scan_int: + q = skipspace(q); + if (!*q) { + bail = bail_eof; + break; + } + val = + strntoumax(q, (char **)&qq, base, + width); + if (qq == q) { + bail = bail_err; + break; + } + q = qq; + if (!(flags & FL_SPLAT)) + converted++; + /* fall through */ - set_integer: - if (!(flags & FL_SPLAT)) { - switch (rank) { - case rank_char: - *va_arg(ap, - unsigned char *) - = val; - break; - case rank_short: - *va_arg(ap, - unsigned short - *) = val; - break; - case rank_int: - *va_arg(ap, - unsigned int *) - = val; - break; - case rank_long: - *va_arg(ap, - unsigned long *) - = val; - break; - case rank_longlong: - *va_arg(ap, - unsigned long - long *) = val; - break; - case rank_ptr: - *va_arg(ap, void **) = - (void *) - (uintptr_t)val; - break; - default: - break; - } - } - break; + set_integer: + if (!(flags & FL_SPLAT)) { + switch (rank) { + case rank_char: + *va_arg(ap, + unsigned char *) + = val; + break; + case rank_short: + *va_arg(ap, + unsigned short + *) = val; + break; + case rank_int: + *va_arg(ap, + unsigned int *) + = val; + break; + case rank_long: + *va_arg(ap, + unsigned long *) + = val; + break; + case rank_longlong: + *va_arg(ap, + unsigned long + long *) = val; + break; + case rank_ptr: + *va_arg(ap, void **) = + (void *) + (uintptr_t)val; + break; + default: + break; + } + } + break; - case 'c': /* Character */ - /* Default width == 1 */ - width = (flags & FL_WIDTH) ? width : 1; - if (flags & FL_SPLAT) { - while (width--) { - if (!*q) { - bail = bail_eof; - break; - } - } - } else { - sarg = va_arg(ap, char *); - while (width--) { - if (!*q) { - bail = bail_eof; - break; - } - *sarg++ = *q++; - } - if (!bail) - converted++; - } - break; + case 'c': /* Character */ + /* Default width == 1 */ + width = (flags & FL_WIDTH) ? width : 1; + if (flags & FL_SPLAT) { + while (width--) { + if (!*q) { + bail = bail_eof; + break; + } + } + } else { + sarg = va_arg(ap, char *); + while (width--) { + if (!*q) { + bail = bail_eof; + break; + } + *sarg++ = *q++; + } + if (!bail) + converted++; + } + break; - case 's': /* String */ - uc = 1; /* Anything nonzero */ - if (flags & FL_SPLAT) { - while (width-- && (uc = *q) && - !isspace(uc)) { - q++; - } - } else { - char *sp; - sp = sarg = va_arg(ap, char *); - while (width-- && (uc = *q) && - !isspace(uc)) { - *sp++ = uc; - q++; - } - if (sarg != sp) { - /* Terminate output */ - *sp = '\0'; - converted++; - } - } - if (!uc) - bail = bail_eof; - break; + case 's': /* String */ + uc = 1; /* Anything nonzero */ + if (flags & FL_SPLAT) { + while (width-- && (uc = *q) && + !isspace(uc)) { + q++; + } + } else { + char *sp; + sp = sarg = va_arg(ap, char *); + while (width-- && (uc = *q) && + !isspace(uc)) { + *sp++ = uc; + q++; + } + if (sarg != sp) { + /* Terminate output */ + *sp = '\0'; + converted++; + } + } + if (!uc) + bail = bail_eof; + break; - case '[': /* Character range */ - sarg = (flags & FL_SPLAT) ? NULL - : va_arg(ap, char *); - state = st_match_init; - matchinv = 0; - memset(matchmap, 0, sizeof matchmap); - break; + case '[': /* Character range */ + sarg = (flags & FL_SPLAT) ? NULL + : va_arg(ap, char *); + state = st_match_init; + matchinv = 0; + memset(matchmap, 0, sizeof matchmap); + break; - case '%': /* %% sequence */ - if (*q == '%') - q++; - else - bail = bail_err; - break; + case '%': /* %% sequence */ + if (*q == '%') + q++; + else + bail = bail_err; + break; - default: /* Anything else */ - /* Unknown sequence */ - bail = bail_err; - break; - } - } - break; + default: /* Anything else */ + /* Unknown sequence */ + bail = bail_err; + break; + } + } + break; - case st_match_init: /* Initial state for %[ match */ - if (ch == '^' && !(flags & FL_INV)) { - matchinv = 1; - } else { - set_bit(matchmap, (unsigned char)ch); - state = st_match; - } - break; + case st_match_init: /* Initial state for %[ match */ + if (ch == '^' && !(flags & FL_INV)) { + matchinv = 1; + } else { + set_bit(matchmap, (unsigned char)ch); + state = st_match; + } + break; - case st_match: /* Main state for %[ match */ - if (ch == ']') { - goto match_run; - } else if (ch == '-') { - range_start = (unsigned char)ch; - state = st_match_range; - } else { - set_bit(matchmap, (unsigned char)ch); - } - break; + case st_match: /* Main state for %[ match */ + if (ch == ']') { + goto match_run; + } else if (ch == '-') { + range_start = (unsigned char)ch; + state = st_match_range; + } else { + set_bit(matchmap, (unsigned char)ch); + } + break; - case st_match_range: /* %[ match after - */ - if (ch == ']') { - /* - was last character */ - set_bit(matchmap, (unsigned char)'-'); - goto match_run; - } else { - int i; - for (i = range_start; i < (unsigned char)ch; - i++) - set_bit(matchmap, i); - state = st_match; - } - break; + case st_match_range: /* %[ match after - */ + if (ch == ']') { + /* - was last character */ + set_bit(matchmap, (unsigned char)'-'); + goto match_run; + } else { + int i; + for (i = range_start; i < (unsigned char)ch; + i++) + set_bit(matchmap, i); + state = st_match; + } + break; - match_run: /* Match expression finished */ - qq = q; - uc = 1; /* Anything nonzero */ - while (width && (uc = *q) - && test_bit(matchmap, uc)^matchinv) { - if (sarg) - *sarg++ = uc; - q++; - } - if (q != qq && sarg) { - *sarg = '\0'; - converted++; - } else { - bail = bail_err; - } - if (!uc) - bail = bail_eof; - break; - default: - break; - } - } + match_run: /* Match expression finished */ + qq = q; + uc = 1; /* Anything nonzero */ + while (width && (uc = *q) + && test_bit(matchmap, uc)^matchinv) { + if (sarg) + *sarg++ = uc; + q++; + } + if (q != qq && sarg) { + *sarg = '\0'; + converted++; + } else { + bail = bail_err; + } + if (!uc) + bail = bail_eof; + break; + default: + break; + } + } - if (bail == bail_eof && !converted) - converted = -1; /* Return EOF (-1) */ + if (bail == bail_eof && !converted) + converted = -1; /* Return EOF (-1) */ - return converted; + return converted; } diff --git a/components/bl602/bl602_std/bl602_std/Common/partition/partition.mk b/components/bl602/bl602_std/bl602_std/Common/partition/partition.mk index 415d4d70..0d638513 100644 --- a/components/bl602/bl602_std/bl602_std/Common/partition/partition.mk +++ b/components/bl602/bl602_std/bl602_std/Common/partition/partition.mk @@ -3,8 +3,8 @@ SUB_MODULE_OUT_DIR:= $(MODULE_OUT_DIR)/partition SUB_MODULE_SRC_DIR := $(SUB_MODULE_DIR) -COMMON_INCLUDE += -I $(MODULE_DIR)/partition - +COMMON_INCLUDE += -I $(MODULE_DIR)/partition + partition_sources := partition.c partition_objs := $(addprefix $(SUB_MODULE_OUT_DIR)/, $(subst .c,.o,$(partition_sources))) diff --git a/components/bl602/bl602_std/bl602_std/Common/platform_print/bflb_platform.h b/components/bl602/bl602_std/bl602_std/Common/platform_print/bflb_platform.h index 41eb3c7b..f3fbe57b 100644 --- a/components/bl602/bl602_std/bl602_std/Common/platform_print/bflb_platform.h +++ b/components/bl602/bl602_std/bl602_std/Common/platform_print/bflb_platform.h @@ -9,10 +9,10 @@ #include "mcu_sdk_version.h" #endif -void * pvPortMalloc( size_t xWantedSize ); -void* pvPortRealloc(void* ptr, size_t newsize); -void* pvPortCalloc(size_t numElements, size_t sizeOfElement); -void vPortFree( void *pv ); +void * pvPortMalloc( size_t xWantedSize ); +void* pvPortRealloc(void* ptr, size_t newsize); +void* pvPortCalloc(size_t numElements, size_t sizeOfElement); +void vPortFree( void *pv ); #define bflb_platform_malloc pvPortMalloc #define bflb_platform_free vPortFree diff --git a/components/bl602/bl602_std/bl602_std/Common/ring_buffer/ring_buffer.mk b/components/bl602/bl602_std/bl602_std/Common/ring_buffer/ring_buffer.mk index b3aac1cd..f56c437e 100644 --- a/components/bl602/bl602_std/bl602_std/Common/ring_buffer/ring_buffer.mk +++ b/components/bl602/bl602_std/bl602_std/Common/ring_buffer/ring_buffer.mk @@ -4,7 +4,7 @@ SUB_MODULE_OUT_DIR:= $(MODULE_OUT_DIR)/ring_buffer SUB_MODULE_SRC_DIR := $(SUB_MODULE_DIR) COMMON_INCLUDE += -I $(MODULE_DIR)/ring_buffer \ - + ring_buffer_sources := ring_buffer.c ring_buffer_objs := $(addprefix $(SUB_MODULE_OUT_DIR)/, $(subst .c,.o,$(ring_buffer_sources))) diff --git a/components/bl602/bl602_std/bl602_std/Common/sim_print/sim_print.mk b/components/bl602/bl602_std/bl602_std/Common/sim_print/sim_print.mk index 6c348ae2..465b9b02 100644 --- a/components/bl602/bl602_std/bl602_std/Common/sim_print/sim_print.mk +++ b/components/bl602/bl602_std/bl602_std/Common/sim_print/sim_print.mk @@ -8,7 +8,7 @@ ifeq ($(DV_TEST),y) COMMON_INCLUDE += -I $(MODULE_DIR)/sim_print endif -sim_print_sources := +sim_print_sources := sim_print_objs := $(addprefix $(SUB_MODULE_OUT_DIR)/, $(subst .c,.o,$(sim_print_sources))) diff --git a/components/bl602/bl602_std/bl602_std/Common/soft_crc/softcrc.mk b/components/bl602/bl602_std/bl602_std/Common/soft_crc/softcrc.mk index ded3fb4b..3e9d0332 100644 --- a/components/bl602/bl602_std/bl602_std/Common/soft_crc/softcrc.mk +++ b/components/bl602/bl602_std/bl602_std/Common/soft_crc/softcrc.mk @@ -12,7 +12,7 @@ softcrc_sources := softcrc.c softcrc_objs := $(addprefix $(SUB_MODULE_OUT_DIR)/, $(subst .c,.o,$(softcrc_sources))) common_objs_target += $(softcrc_objs) - + $(SUB_MODULE_OUT_DIR)/%.o:$(SUB_MODULE_SRC_DIR)/%.c @mkdir -p $(dir $@) @echo "cc $<" diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz.h b/components/bl602/bl602_std/bl602_std/Common/xz/xz.h index 1a44301e..2e051f94 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz.h +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz.h @@ -12,11 +12,11 @@ #define XZ_H #ifdef __KERNEL__ -# include -# include +# include +# include #else -# include -# include +# include +# include #endif #ifdef __cplusplus @@ -25,7 +25,7 @@ extern "C" { /* In Linux, this is used to make extern functions static when needed. */ #ifndef XZ_EXTERN -# define XZ_EXTERN extern +# define XZ_EXTERN extern #endif /** @@ -54,9 +54,9 @@ extern "C" { * be built with fewer features to minimize code size. */ enum xz_mode { - XZ_SINGLE, - XZ_PREALLOC, - XZ_DYNALLOC + XZ_SINGLE, + XZ_PREALLOC, + XZ_DYNALLOC }; /** @@ -110,15 +110,15 @@ enum xz_mode { * is used instead of XZ_BUF_ERROR. */ enum xz_ret { - XZ_OK, - XZ_STREAM_END, - XZ_UNSUPPORTED_CHECK, - XZ_MEM_ERROR, - XZ_MEMLIMIT_ERROR, - XZ_FORMAT_ERROR, - XZ_OPTIONS_ERROR, - XZ_DATA_ERROR, - XZ_BUF_ERROR + XZ_OK, + XZ_STREAM_END, + XZ_UNSUPPORTED_CHECK, + XZ_MEM_ERROR, + XZ_MEMLIMIT_ERROR, + XZ_FORMAT_ERROR, + XZ_OPTIONS_ERROR, + XZ_DATA_ERROR, + XZ_BUF_ERROR }; /** @@ -138,13 +138,13 @@ enum xz_ret { * the variables in_pos and out_pos are modified by the XZ code. */ struct xz_buf { - const uint8_t *in; - size_t in_pos; - size_t in_size; + const uint8_t *in; + size_t in_pos; + size_t in_size; - uint8_t *out; - size_t out_pos; - size_t out_size; + uint8_t *out; + size_t out_pos; + size_t out_size; }; /** @@ -244,11 +244,11 @@ XZ_EXTERN void xz_dec_end(struct xz_dec *s); * care about the functions below. */ #ifndef XZ_INTERNAL_CRC32 -# ifdef __KERNEL__ -# define XZ_INTERNAL_CRC32 0 -# else -# define XZ_INTERNAL_CRC32 1 -# endif +# ifdef __KERNEL__ +# define XZ_INTERNAL_CRC32 0 +# else +# define XZ_INTERNAL_CRC32 1 +# endif #endif /* @@ -256,15 +256,15 @@ XZ_EXTERN void xz_dec_end(struct xz_dec *s); * implementation is needed too. */ #ifndef XZ_USE_CRC64 -# undef XZ_INTERNAL_CRC64 -# define XZ_INTERNAL_CRC64 0 +# undef XZ_INTERNAL_CRC64 +# define XZ_INTERNAL_CRC64 0 #endif #ifndef XZ_INTERNAL_CRC64 -# ifdef __KERNEL__ -# error Using CRC64 in the kernel has not been implemented. -# else -# define XZ_INTERNAL_CRC64 1 -# endif +# ifdef __KERNEL__ +# error Using CRC64 in the kernel has not been implemented. +# else +# define XZ_INTERNAL_CRC64 1 +# endif #endif #if XZ_INTERNAL_CRC32 diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz.mk b/components/bl602/bl602_std/bl602_std/Common/xz/xz.mk index dc121962..70d58d85 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz.mk +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz.mk @@ -3,8 +3,8 @@ SUB_MODULE_OUT_DIR:= $(MODULE_OUT_DIR)/xz SUB_MODULE_SRC_DIR := $(SUB_MODULE_DIR) -COMMON_INCLUDE += -I $(MODULE_DIR)/xz - +COMMON_INCLUDE += -I $(MODULE_DIR)/xz + xz_sources := xz_crc32.c xz_dec_lzma2.c xz_dec_stream.c xz_decompress.c xz_port.c xz_objs := $(addprefix $(SUB_MODULE_OUT_DIR)/, $(subst .c,.o,$(xz_sources))) diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_config.h b/components/bl602/bl602_std/bl602_std/Common/xz/xz_config.h index 8023f1c4..8434d500 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_config.h +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_config.h @@ -34,7 +34,7 @@ extern void simple_free(void *p); #define memzero(buf, size) memset(buf, 0, size) #ifndef min -# define min(x, y) ((x) < (y) ? (x) : (y)) +# define min(x, y) ((x) < (y) ? (x) : (y)) #endif #define min_t(type, x, y) min(x, y) @@ -59,52 +59,52 @@ extern void simple_free(void *p); #undef __always_inline #ifndef __always_inline -# ifdef __GNUC__ -# define __always_inline \ - inline __attribute__((__always_inline__)) -# else -# define __always_inline inline -# endif +# ifdef __GNUC__ +# define __always_inline \ + inline __attribute__((__always_inline__)) +# else +# define __always_inline inline +# endif #endif /* Inline functions to access unaligned unsigned 32-bit integers */ #ifndef get_unaligned_le32 static inline uint32_t get_unaligned_le32(const uint8_t *buf) { - return (uint32_t)buf[0] - | ((uint32_t)buf[1] << 8) - | ((uint32_t)buf[2] << 16) - | ((uint32_t)buf[3] << 24); + return (uint32_t)buf[0] + | ((uint32_t)buf[1] << 8) + | ((uint32_t)buf[2] << 16) + | ((uint32_t)buf[3] << 24); } #endif #ifndef get_unaligned_be32 static inline uint32_t get_unaligned_be32(const uint8_t *buf) { - return (uint32_t)(buf[0] << 24) - | ((uint32_t)buf[1] << 16) - | ((uint32_t)buf[2] << 8) - | (uint32_t)buf[3]; + return (uint32_t)(buf[0] << 24) + | ((uint32_t)buf[1] << 16) + | ((uint32_t)buf[2] << 8) + | (uint32_t)buf[3]; } #endif #ifndef put_unaligned_le32 static inline void put_unaligned_le32(uint32_t val, uint8_t *buf) { - buf[0] = (uint8_t)val; - buf[1] = (uint8_t)(val >> 8); - buf[2] = (uint8_t)(val >> 16); - buf[3] = (uint8_t)(val >> 24); + buf[0] = (uint8_t)val; + buf[1] = (uint8_t)(val >> 8); + buf[2] = (uint8_t)(val >> 16); + buf[3] = (uint8_t)(val >> 24); } #endif #ifndef put_unaligned_be32 static inline void put_unaligned_be32(uint32_t val, uint8_t *buf) { - buf[0] = (uint8_t)(val >> 24); - buf[1] = (uint8_t)(val >> 16); - buf[2] = (uint8_t)(val >> 8); - buf[3] = (uint8_t)val; + buf[0] = (uint8_t)(val >> 24); + buf[1] = (uint8_t)(val >> 16); + buf[2] = (uint8_t)(val >> 8); + buf[3] = (uint8_t)val; } #endif @@ -114,7 +114,7 @@ static inline void put_unaligned_be32(uint32_t val, uint8_t *buf) * could save a few bytes in code size. */ #ifndef get_le32 -# define get_le32 get_unaligned_le32 +# define get_le32 get_unaligned_le32 #endif #endif diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc32.c b/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc32.c index d90aa0ee..1895cadf 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc32.c +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc32.c @@ -22,7 +22,7 @@ * See for details. */ #ifndef STATIC_RW_DATA -# define STATIC_RW_DATA static +# define STATIC_RW_DATA static #endif //STATIC_RW_DATA uint32_t xz_crc32_table[256]; @@ -31,31 +31,31 @@ extern const uint32_t crc32Tab[256]; XZ_EXTERN void xz_crc32_init(void) { #if 0 - const uint32_t poly = 0xEDB88320; + const uint32_t poly = 0xEDB88320; - uint32_t i; - uint32_t j; - uint32_t r; + uint32_t i; + uint32_t j; + uint32_t r; - for (i = 0; i < 256; ++i) { - r = i; - for (j = 0; j < 8; ++j) - r = (r >> 1) ^ (poly & ~((r & 1) - 1)); + for (i = 0; i < 256; ++i) { + r = i; + for (j = 0; j < 8; ++j) + r = (r >> 1) ^ (poly & ~((r & 1) - 1)); - xz_crc32_table[i] = r; - } + xz_crc32_table[i] = r; + } #endif - return; + return; } XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc) { - crc = ~crc; + crc = ~crc; - while (size != 0) { - crc = crc32Tab[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); - --size; - } + while (size != 0) { + crc = crc32Tab[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); + --size; + } - return ~crc; + return ~crc; } diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc64.c b/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc64.c index ca1caee8..d0d4d869 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc64.c +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_crc64.c @@ -13,38 +13,38 @@ #include "xz_private.h" #ifndef STATIC_RW_DATA -# define STATIC_RW_DATA static +# define STATIC_RW_DATA static #endif STATIC_RW_DATA uint64_t xz_crc64_table[256]; XZ_EXTERN void xz_crc64_init(void) { - const uint64_t poly = 0xC96C5795D7870F42; + const uint64_t poly = 0xC96C5795D7870F42; - uint32_t i; - uint32_t j; - uint64_t r; + uint32_t i; + uint32_t j; + uint64_t r; - for (i = 0; i < 256; ++i) { - r = i; - for (j = 0; j < 8; ++j) - r = (r >> 1) ^ (poly & ~((r & 1) - 1)); + for (i = 0; i < 256; ++i) { + r = i; + for (j = 0; j < 8; ++j) + r = (r >> 1) ^ (poly & ~((r & 1) - 1)); - xz_crc64_table[i] = r; - } + xz_crc64_table[i] = r; + } - return; + return; } XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc) { - crc = ~crc; + crc = ~crc; - while (size != 0) { - crc = xz_crc64_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); - --size; - } + while (size != 0) { + crc = xz_crc64_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8); + --size; + } - return ~crc; + return ~crc; } diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_bcj.c b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_bcj.c index a768e6d2..b18fc886 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_bcj.c +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_bcj.c @@ -17,62 +17,62 @@ #ifdef XZ_DEC_BCJ struct xz_dec_bcj { - /* Type of the BCJ filter being used */ - enum { - BCJ_X86 = 4, /* x86 or x86-64 */ - BCJ_POWERPC = 5, /* Big endian only */ - BCJ_IA64 = 6, /* Big or little endian */ - BCJ_ARM = 7, /* Little endian only */ - BCJ_ARMTHUMB = 8, /* Little endian only */ - BCJ_SPARC = 9 /* Big or little endian */ - } type; + /* Type of the BCJ filter being used */ + enum { + BCJ_X86 = 4, /* x86 or x86-64 */ + BCJ_POWERPC = 5, /* Big endian only */ + BCJ_IA64 = 6, /* Big or little endian */ + BCJ_ARM = 7, /* Little endian only */ + BCJ_ARMTHUMB = 8, /* Little endian only */ + BCJ_SPARC = 9 /* Big or little endian */ + } type; - /* - * Return value of the next filter in the chain. We need to preserve - * this information across calls, because we must not call the next - * filter anymore once it has returned XZ_STREAM_END. - */ - enum xz_ret ret; + /* + * Return value of the next filter in the chain. We need to preserve + * this information across calls, because we must not call the next + * filter anymore once it has returned XZ_STREAM_END. + */ + enum xz_ret ret; - /* True if we are operating in single-call mode. */ - bool single_call; + /* True if we are operating in single-call mode. */ + bool single_call; - /* - * Absolute position relative to the beginning of the uncompressed - * data (in a single .xz Block). We care only about the lowest 32 - * bits so this doesn't need to be uint64_t even with big files. - */ - uint32_t pos; + /* + * Absolute position relative to the beginning of the uncompressed + * data (in a single .xz Block). We care only about the lowest 32 + * bits so this doesn't need to be uint64_t even with big files. + */ + uint32_t pos; - /* x86 filter state */ - uint32_t x86_prev_mask; + /* x86 filter state */ + uint32_t x86_prev_mask; - /* Temporary space to hold the variables from struct xz_buf */ - uint8_t *out; - size_t out_pos; - size_t out_size; + /* Temporary space to hold the variables from struct xz_buf */ + uint8_t *out; + size_t out_pos; + size_t out_size; - struct { - /* Amount of already filtered data in the beginning of buf */ - size_t filtered; + struct { + /* Amount of already filtered data in the beginning of buf */ + size_t filtered; - /* Total amount of data currently stored in buf */ - size_t size; + /* Total amount of data currently stored in buf */ + size_t size; - /* - * Buffer to hold a mix of filtered and unfiltered data. This - * needs to be big enough to hold Alignment + 2 * Look-ahead: - * - * Type Alignment Look-ahead - * x86 1 4 - * PowerPC 4 0 - * IA-64 16 0 - * ARM 4 0 - * ARM-Thumb 2 2 - * SPARC 4 0 - */ - uint8_t buf[16]; - } temp; + /* + * Buffer to hold a mix of filtered and unfiltered data. This + * needs to be big enough to hold Alignment + 2 * Look-ahead: + * + * Type Alignment Look-ahead + * x86 1 4 + * PowerPC 4 0 + * IA-64 16 0 + * ARM 4 0 + * ARM-Thumb 2 2 + * SPARC 4 0 + */ + uint8_t buf[16]; + } temp; }; #ifdef XZ_DEC_X86 @@ -82,255 +82,255 @@ struct xz_dec_bcj { */ static inline int bcj_x86_test_msbyte(uint8_t b) { - return b == 0x00 || b == 0xFF; + return b == 0x00 || b == 0xFF; } static size_t bcj_x86(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - static const bool mask_to_allowed_status[8] - = { true, true, true, false, true, false, false, false }; + static const bool mask_to_allowed_status[8] + = { true, true, true, false, true, false, false, false }; - static const uint8_t mask_to_bit_num[8] = { 0, 1, 2, 2, 3, 3, 3, 3 }; + static const uint8_t mask_to_bit_num[8] = { 0, 1, 2, 2, 3, 3, 3, 3 }; - size_t i; - size_t prev_pos = (size_t)-1; - uint32_t prev_mask = s->x86_prev_mask; - uint32_t src; - uint32_t dest; - uint32_t j; - uint8_t b; + size_t i; + size_t prev_pos = (size_t)-1; + uint32_t prev_mask = s->x86_prev_mask; + uint32_t src; + uint32_t dest; + uint32_t j; + uint8_t b; - if (size <= 4) - return 0; + if (size <= 4) + return 0; - size -= 4; - for (i = 0; i < size; ++i) { - if ((buf[i] & 0xFE) != 0xE8) - continue; + size -= 4; + for (i = 0; i < size; ++i) { + if ((buf[i] & 0xFE) != 0xE8) + continue; - prev_pos = i - prev_pos; - if (prev_pos > 3) { - prev_mask = 0; - } else { - prev_mask = (prev_mask << (prev_pos - 1)) & 7; - if (prev_mask != 0) { - b = buf[i + 4 - mask_to_bit_num[prev_mask]]; - if (!mask_to_allowed_status[prev_mask] - || bcj_x86_test_msbyte(b)) { - prev_pos = i; - prev_mask = (prev_mask << 1) | 1; - continue; - } - } - } + prev_pos = i - prev_pos; + if (prev_pos > 3) { + prev_mask = 0; + } else { + prev_mask = (prev_mask << (prev_pos - 1)) & 7; + if (prev_mask != 0) { + b = buf[i + 4 - mask_to_bit_num[prev_mask]]; + if (!mask_to_allowed_status[prev_mask] + || bcj_x86_test_msbyte(b)) { + prev_pos = i; + prev_mask = (prev_mask << 1) | 1; + continue; + } + } + } - prev_pos = i; + prev_pos = i; - if (bcj_x86_test_msbyte(buf[i + 4])) { - src = get_unaligned_le32(buf + i + 1); - while (true) { - dest = src - (s->pos + (uint32_t)i + 5); - if (prev_mask == 0) - break; + if (bcj_x86_test_msbyte(buf[i + 4])) { + src = get_unaligned_le32(buf + i + 1); + while (true) { + dest = src - (s->pos + (uint32_t)i + 5); + if (prev_mask == 0) + break; - j = mask_to_bit_num[prev_mask] * 8; - b = (uint8_t)(dest >> (24 - j)); - if (!bcj_x86_test_msbyte(b)) - break; + j = mask_to_bit_num[prev_mask] * 8; + b = (uint8_t)(dest >> (24 - j)); + if (!bcj_x86_test_msbyte(b)) + break; - src = dest ^ (((uint32_t)1 << (32 - j)) - 1); - } + src = dest ^ (((uint32_t)1 << (32 - j)) - 1); + } - dest &= 0x01FFFFFF; - dest |= (uint32_t)0 - (dest & 0x01000000); - put_unaligned_le32(dest, buf + i + 1); - i += 4; - } else { - prev_mask = (prev_mask << 1) | 1; - } - } + dest &= 0x01FFFFFF; + dest |= (uint32_t)0 - (dest & 0x01000000); + put_unaligned_le32(dest, buf + i + 1); + i += 4; + } else { + prev_mask = (prev_mask << 1) | 1; + } + } - prev_pos = i - prev_pos; - s->x86_prev_mask = prev_pos > 3 ? 0 : prev_mask << (prev_pos - 1); - return i; + prev_pos = i - prev_pos; + s->x86_prev_mask = prev_pos > 3 ? 0 : prev_mask << (prev_pos - 1); + return i; } #endif #ifdef XZ_DEC_POWERPC static size_t bcj_powerpc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - size_t i; - uint32_t instr; + size_t i; + uint32_t instr; - for (i = 0; i + 4 <= size; i += 4) { - instr = get_unaligned_be32(buf + i); - if ((instr & 0xFC000003) == 0x48000001) { - instr &= 0x03FFFFFC; - instr -= s->pos + (uint32_t)i; - instr &= 0x03FFFFFC; - instr |= 0x48000001; - put_unaligned_be32(instr, buf + i); - } - } + for (i = 0; i + 4 <= size; i += 4) { + instr = get_unaligned_be32(buf + i); + if ((instr & 0xFC000003) == 0x48000001) { + instr &= 0x03FFFFFC; + instr -= s->pos + (uint32_t)i; + instr &= 0x03FFFFFC; + instr |= 0x48000001; + put_unaligned_be32(instr, buf + i); + } + } - return i; + return i; } #endif #ifdef XZ_DEC_IA64 static size_t bcj_ia64(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - static const uint8_t branch_table[32] = { - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 4, 4, 6, 6, 0, 0, 7, 7, - 4, 4, 0, 0, 4, 4, 0, 0 - }; + static const uint8_t branch_table[32] = { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 4, 4, 6, 6, 0, 0, 7, 7, + 4, 4, 0, 0, 4, 4, 0, 0 + }; - /* - * The local variables take a little bit stack space, but it's less - * than what LZMA2 decoder takes, so it doesn't make sense to reduce - * stack usage here without doing that for the LZMA2 decoder too. - */ + /* + * The local variables take a little bit stack space, but it's less + * than what LZMA2 decoder takes, so it doesn't make sense to reduce + * stack usage here without doing that for the LZMA2 decoder too. + */ - /* Loop counters */ - size_t i; - size_t j; + /* Loop counters */ + size_t i; + size_t j; - /* Instruction slot (0, 1, or 2) in the 128-bit instruction word */ - uint32_t slot; + /* Instruction slot (0, 1, or 2) in the 128-bit instruction word */ + uint32_t slot; - /* Bitwise offset of the instruction indicated by slot */ - uint32_t bit_pos; + /* Bitwise offset of the instruction indicated by slot */ + uint32_t bit_pos; - /* bit_pos split into byte and bit parts */ - uint32_t byte_pos; - uint32_t bit_res; + /* bit_pos split into byte and bit parts */ + uint32_t byte_pos; + uint32_t bit_res; - /* Address part of an instruction */ - uint32_t addr; + /* Address part of an instruction */ + uint32_t addr; - /* Mask used to detect which instructions to convert */ - uint32_t mask; + /* Mask used to detect which instructions to convert */ + uint32_t mask; - /* 41-bit instruction stored somewhere in the lowest 48 bits */ - uint64_t instr; + /* 41-bit instruction stored somewhere in the lowest 48 bits */ + uint64_t instr; - /* Instruction normalized with bit_res for easier manipulation */ - uint64_t norm; + /* Instruction normalized with bit_res for easier manipulation */ + uint64_t norm; - for (i = 0; i + 16 <= size; i += 16) { - mask = branch_table[buf[i] & 0x1F]; - for (slot = 0, bit_pos = 5; slot < 3; ++slot, bit_pos += 41) { - if (((mask >> slot) & 1) == 0) - continue; + for (i = 0; i + 16 <= size; i += 16) { + mask = branch_table[buf[i] & 0x1F]; + for (slot = 0, bit_pos = 5; slot < 3; ++slot, bit_pos += 41) { + if (((mask >> slot) & 1) == 0) + continue; - byte_pos = bit_pos >> 3; - bit_res = bit_pos & 7; - instr = 0; - for (j = 0; j < 6; ++j) - instr |= (uint64_t)(buf[i + j + byte_pos]) - << (8 * j); + byte_pos = bit_pos >> 3; + bit_res = bit_pos & 7; + instr = 0; + for (j = 0; j < 6; ++j) + instr |= (uint64_t)(buf[i + j + byte_pos]) + << (8 * j); - norm = instr >> bit_res; + norm = instr >> bit_res; - if (((norm >> 37) & 0x0F) == 0x05 - && ((norm >> 9) & 0x07) == 0) { - addr = (norm >> 13) & 0x0FFFFF; - addr |= ((uint32_t)(norm >> 36) & 1) << 20; - addr <<= 4; - addr -= s->pos + (uint32_t)i; - addr >>= 4; + if (((norm >> 37) & 0x0F) == 0x05 + && ((norm >> 9) & 0x07) == 0) { + addr = (norm >> 13) & 0x0FFFFF; + addr |= ((uint32_t)(norm >> 36) & 1) << 20; + addr <<= 4; + addr -= s->pos + (uint32_t)i; + addr >>= 4; - norm &= ~((uint64_t)0x8FFFFF << 13); - norm |= (uint64_t)(addr & 0x0FFFFF) << 13; - norm |= (uint64_t)(addr & 0x100000) - << (36 - 20); + norm &= ~((uint64_t)0x8FFFFF << 13); + norm |= (uint64_t)(addr & 0x0FFFFF) << 13; + norm |= (uint64_t)(addr & 0x100000) + << (36 - 20); - instr &= (1 << bit_res) - 1; - instr |= norm << bit_res; + instr &= (1 << bit_res) - 1; + instr |= norm << bit_res; - for (j = 0; j < 6; j++) - buf[i + j + byte_pos] - = (uint8_t)(instr >> (8 * j)); - } - } - } + for (j = 0; j < 6; j++) + buf[i + j + byte_pos] + = (uint8_t)(instr >> (8 * j)); + } + } + } - return i; + return i; } #endif #ifdef XZ_DEC_ARM static size_t bcj_arm(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - size_t i; - uint32_t addr; + size_t i; + uint32_t addr; - for (i = 0; i + 4 <= size; i += 4) { - if (buf[i + 3] == 0xEB) { - addr = (uint32_t)buf[i] | ((uint32_t)buf[i + 1] << 8) - | ((uint32_t)buf[i + 2] << 16); - addr <<= 2; - addr -= s->pos + (uint32_t)i + 8; - addr >>= 2; - buf[i] = (uint8_t)addr; - buf[i + 1] = (uint8_t)(addr >> 8); - buf[i + 2] = (uint8_t)(addr >> 16); - } - } + for (i = 0; i + 4 <= size; i += 4) { + if (buf[i + 3] == 0xEB) { + addr = (uint32_t)buf[i] | ((uint32_t)buf[i + 1] << 8) + | ((uint32_t)buf[i + 2] << 16); + addr <<= 2; + addr -= s->pos + (uint32_t)i + 8; + addr >>= 2; + buf[i] = (uint8_t)addr; + buf[i + 1] = (uint8_t)(addr >> 8); + buf[i + 2] = (uint8_t)(addr >> 16); + } + } - return i; + return i; } #endif #ifdef XZ_DEC_ARMTHUMB static size_t bcj_armthumb(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - size_t i; - uint32_t addr; + size_t i; + uint32_t addr; - for (i = 0; i + 4 <= size; i += 2) { - if ((buf[i + 1] & 0xF8) == 0xF0 - && (buf[i + 3] & 0xF8) == 0xF8) { - addr = (((uint32_t)buf[i + 1] & 0x07) << 19) - | ((uint32_t)buf[i] << 11) - | (((uint32_t)buf[i + 3] & 0x07) << 8) - | (uint32_t)buf[i + 2]; - addr <<= 1; - addr -= s->pos + (uint32_t)i + 4; - addr >>= 1; - buf[i + 1] = (uint8_t)(0xF0 | ((addr >> 19) & 0x07)); - buf[i] = (uint8_t)(addr >> 11); - buf[i + 3] = (uint8_t)(0xF8 | ((addr >> 8) & 0x07)); - buf[i + 2] = (uint8_t)addr; - i += 2; - } - } + for (i = 0; i + 4 <= size; i += 2) { + if ((buf[i + 1] & 0xF8) == 0xF0 + && (buf[i + 3] & 0xF8) == 0xF8) { + addr = (((uint32_t)buf[i + 1] & 0x07) << 19) + | ((uint32_t)buf[i] << 11) + | (((uint32_t)buf[i + 3] & 0x07) << 8) + | (uint32_t)buf[i + 2]; + addr <<= 1; + addr -= s->pos + (uint32_t)i + 4; + addr >>= 1; + buf[i + 1] = (uint8_t)(0xF0 | ((addr >> 19) & 0x07)); + buf[i] = (uint8_t)(addr >> 11); + buf[i + 3] = (uint8_t)(0xF8 | ((addr >> 8) & 0x07)); + buf[i + 2] = (uint8_t)addr; + i += 2; + } + } - return i; + return i; } #endif #ifdef XZ_DEC_SPARC static size_t bcj_sparc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) { - size_t i; - uint32_t instr; + size_t i; + uint32_t instr; - for (i = 0; i + 4 <= size; i += 4) { - instr = get_unaligned_be32(buf + i); - if ((instr >> 22) == 0x100 || (instr >> 22) == 0x1FF) { - instr <<= 2; - instr -= s->pos + (uint32_t)i; - instr >>= 2; - instr = ((uint32_t)0x40000000 - (instr & 0x400000)) - | 0x40000000 | (instr & 0x3FFFFF); - put_unaligned_be32(instr, buf + i); - } - } + for (i = 0; i + 4 <= size; i += 4) { + instr = get_unaligned_be32(buf + i); + if ((instr >> 22) == 0x100 || (instr >> 22) == 0x1FF) { + instr <<= 2; + instr -= s->pos + (uint32_t)i; + instr >>= 2; + instr = ((uint32_t)0x40000000 - (instr & 0x400000)) + | 0x40000000 | (instr & 0x3FFFFF); + put_unaligned_be32(instr, buf + i); + } + } - return i; + return i; } #endif @@ -343,52 +343,52 @@ static size_t bcj_sparc(struct xz_dec_bcj *s, uint8_t *buf, size_t size) * avoid pointers to static data (at least on x86). */ static void bcj_apply(struct xz_dec_bcj *s, - uint8_t *buf, size_t *pos, size_t size) + uint8_t *buf, size_t *pos, size_t size) { - size_t filtered; + size_t filtered; - buf += *pos; - size -= *pos; + buf += *pos; + size -= *pos; - switch (s->type) { + switch (s->type) { #ifdef XZ_DEC_X86 - case BCJ_X86: - filtered = bcj_x86(s, buf, size); - break; + case BCJ_X86: + filtered = bcj_x86(s, buf, size); + break; #endif #ifdef XZ_DEC_POWERPC - case BCJ_POWERPC: - filtered = bcj_powerpc(s, buf, size); - break; + case BCJ_POWERPC: + filtered = bcj_powerpc(s, buf, size); + break; #endif #ifdef XZ_DEC_IA64 - case BCJ_IA64: - filtered = bcj_ia64(s, buf, size); - break; + case BCJ_IA64: + filtered = bcj_ia64(s, buf, size); + break; #endif #ifdef XZ_DEC_ARM - case BCJ_ARM: - filtered = bcj_arm(s, buf, size); - break; + case BCJ_ARM: + filtered = bcj_arm(s, buf, size); + break; #endif #ifdef XZ_DEC_ARMTHUMB - case BCJ_ARMTHUMB: - filtered = bcj_armthumb(s, buf, size); - break; + case BCJ_ARMTHUMB: + filtered = bcj_armthumb(s, buf, size); + break; #endif #ifdef XZ_DEC_SPARC - case BCJ_SPARC: - filtered = bcj_sparc(s, buf, size); - break; + case BCJ_SPARC: + filtered = bcj_sparc(s, buf, size); + break; #endif - default: - /* Never reached but silence compiler warnings. */ - filtered = 0; - break; - } + default: + /* Never reached but silence compiler warnings. */ + filtered = 0; + break; + } - *pos += filtered; - s->pos += filtered; + *pos += filtered; + s->pos += filtered; } /* @@ -398,15 +398,15 @@ static void bcj_apply(struct xz_dec_bcj *s, */ static void bcj_flush(struct xz_dec_bcj *s, struct xz_buf *b) { - size_t copy_size; + size_t copy_size; - copy_size = min_t(size_t, s->temp.filtered, b->out_size - b->out_pos); - memcpy(b->out + b->out_pos, s->temp.buf, copy_size); - b->out_pos += copy_size; + copy_size = min_t(size_t, s->temp.filtered, b->out_size - b->out_pos); + memcpy(b->out + b->out_pos, s->temp.buf, copy_size); + b->out_pos += copy_size; - s->temp.filtered -= copy_size; - s->temp.size -= copy_size; - memmove(s->temp.buf, s->temp.buf + copy_size, s->temp.size); + s->temp.filtered -= copy_size; + s->temp.size -= copy_size; + memmove(s->temp.buf, s->temp.buf + copy_size, s->temp.size); } /* @@ -415,160 +415,160 @@ static void bcj_flush(struct xz_dec_bcj *s, struct xz_buf *b) * some buffering. */ XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, - struct xz_dec_lzma2 *lzma2, - struct xz_buf *b) + struct xz_dec_lzma2 *lzma2, + struct xz_buf *b) { - size_t out_start; + size_t out_start; - /* - * Flush pending already filtered data to the output buffer. Return - * immediatelly if we couldn't flush everything, or if the next - * filter in the chain had already returned XZ_STREAM_END. - */ - if (s->temp.filtered > 0) { - bcj_flush(s, b); - if (s->temp.filtered > 0) - return XZ_OK; + /* + * Flush pending already filtered data to the output buffer. Return + * immediatelly if we couldn't flush everything, or if the next + * filter in the chain had already returned XZ_STREAM_END. + */ + if (s->temp.filtered > 0) { + bcj_flush(s, b); + if (s->temp.filtered > 0) + return XZ_OK; - if (s->ret == XZ_STREAM_END) - return XZ_STREAM_END; - } + if (s->ret == XZ_STREAM_END) + return XZ_STREAM_END; + } - /* - * If we have more output space than what is currently pending in - * temp, copy the unfiltered data from temp to the output buffer - * and try to fill the output buffer by decoding more data from the - * next filter in the chain. Apply the BCJ filter on the new data - * in the output buffer. If everything cannot be filtered, copy it - * to temp and rewind the output buffer position accordingly. - * - * This needs to be always run when temp.size == 0 to handle a special - * case where the output buffer is full and the next filter has no - * more output coming but hasn't returned XZ_STREAM_END yet. - */ - if (s->temp.size < b->out_size - b->out_pos || s->temp.size == 0) { - out_start = b->out_pos; - memcpy(b->out + b->out_pos, s->temp.buf, s->temp.size); - b->out_pos += s->temp.size; + /* + * If we have more output space than what is currently pending in + * temp, copy the unfiltered data from temp to the output buffer + * and try to fill the output buffer by decoding more data from the + * next filter in the chain. Apply the BCJ filter on the new data + * in the output buffer. If everything cannot be filtered, copy it + * to temp and rewind the output buffer position accordingly. + * + * This needs to be always run when temp.size == 0 to handle a special + * case where the output buffer is full and the next filter has no + * more output coming but hasn't returned XZ_STREAM_END yet. + */ + if (s->temp.size < b->out_size - b->out_pos || s->temp.size == 0) { + out_start = b->out_pos; + memcpy(b->out + b->out_pos, s->temp.buf, s->temp.size); + b->out_pos += s->temp.size; - s->ret = xz_dec_lzma2_run(lzma2, b); - if (s->ret != XZ_STREAM_END - && (s->ret != XZ_OK || s->single_call)) - return s->ret; + s->ret = xz_dec_lzma2_run(lzma2, b); + if (s->ret != XZ_STREAM_END + && (s->ret != XZ_OK || s->single_call)) + return s->ret; - bcj_apply(s, b->out, &out_start, b->out_pos); + bcj_apply(s, b->out, &out_start, b->out_pos); - /* - * As an exception, if the next filter returned XZ_STREAM_END, - * we can do that too, since the last few bytes that remain - * unfiltered are meant to remain unfiltered. - */ - if (s->ret == XZ_STREAM_END) - return XZ_STREAM_END; + /* + * As an exception, if the next filter returned XZ_STREAM_END, + * we can do that too, since the last few bytes that remain + * unfiltered are meant to remain unfiltered. + */ + if (s->ret == XZ_STREAM_END) + return XZ_STREAM_END; - s->temp.size = b->out_pos - out_start; - b->out_pos -= s->temp.size; - memcpy(s->temp.buf, b->out + b->out_pos, s->temp.size); + s->temp.size = b->out_pos - out_start; + b->out_pos -= s->temp.size; + memcpy(s->temp.buf, b->out + b->out_pos, s->temp.size); - /* - * If there wasn't enough input to the next filter to fill - * the output buffer with unfiltered data, there's no point - * to try decoding more data to temp. - */ - if (b->out_pos + s->temp.size < b->out_size) - return XZ_OK; - } + /* + * If there wasn't enough input to the next filter to fill + * the output buffer with unfiltered data, there's no point + * to try decoding more data to temp. + */ + if (b->out_pos + s->temp.size < b->out_size) + return XZ_OK; + } - /* - * We have unfiltered data in temp. If the output buffer isn't full - * yet, try to fill the temp buffer by decoding more data from the - * next filter. Apply the BCJ filter on temp. Then we hopefully can - * fill the actual output buffer by copying filtered data from temp. - * A mix of filtered and unfiltered data may be left in temp; it will - * be taken care on the next call to this function. - */ - if (b->out_pos < b->out_size) { - /* Make b->out{,_pos,_size} temporarily point to s->temp. */ - s->out = b->out; - s->out_pos = b->out_pos; - s->out_size = b->out_size; - b->out = s->temp.buf; - b->out_pos = s->temp.size; - b->out_size = sizeof(s->temp.buf); + /* + * We have unfiltered data in temp. If the output buffer isn't full + * yet, try to fill the temp buffer by decoding more data from the + * next filter. Apply the BCJ filter on temp. Then we hopefully can + * fill the actual output buffer by copying filtered data from temp. + * A mix of filtered and unfiltered data may be left in temp; it will + * be taken care on the next call to this function. + */ + if (b->out_pos < b->out_size) { + /* Make b->out{,_pos,_size} temporarily point to s->temp. */ + s->out = b->out; + s->out_pos = b->out_pos; + s->out_size = b->out_size; + b->out = s->temp.buf; + b->out_pos = s->temp.size; + b->out_size = sizeof(s->temp.buf); - s->ret = xz_dec_lzma2_run(lzma2, b); + s->ret = xz_dec_lzma2_run(lzma2, b); - s->temp.size = b->out_pos; - b->out = s->out; - b->out_pos = s->out_pos; - b->out_size = s->out_size; + s->temp.size = b->out_pos; + b->out = s->out; + b->out_pos = s->out_pos; + b->out_size = s->out_size; - if (s->ret != XZ_OK && s->ret != XZ_STREAM_END) - return s->ret; + if (s->ret != XZ_OK && s->ret != XZ_STREAM_END) + return s->ret; - bcj_apply(s, s->temp.buf, &s->temp.filtered, s->temp.size); + bcj_apply(s, s->temp.buf, &s->temp.filtered, s->temp.size); - /* - * If the next filter returned XZ_STREAM_END, we mark that - * everything is filtered, since the last unfiltered bytes - * of the stream are meant to be left as is. - */ - if (s->ret == XZ_STREAM_END) - s->temp.filtered = s->temp.size; + /* + * If the next filter returned XZ_STREAM_END, we mark that + * everything is filtered, since the last unfiltered bytes + * of the stream are meant to be left as is. + */ + if (s->ret == XZ_STREAM_END) + s->temp.filtered = s->temp.size; - bcj_flush(s, b); - if (s->temp.filtered > 0) - return XZ_OK; - } + bcj_flush(s, b); + if (s->temp.filtered > 0) + return XZ_OK; + } - return s->ret; + return s->ret; } XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(bool single_call) { - struct xz_dec_bcj *s = kmalloc(sizeof(*s), GFP_KERNEL); - if (s != NULL) - s->single_call = single_call; + struct xz_dec_bcj *s = kmalloc(sizeof(*s), GFP_KERNEL); + if (s != NULL) + s->single_call = single_call; - return s; + return s; } XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id) { - switch (id) { + switch (id) { #ifdef XZ_DEC_X86 - case BCJ_X86: + case BCJ_X86: #endif #ifdef XZ_DEC_POWERPC - case BCJ_POWERPC: + case BCJ_POWERPC: #endif #ifdef XZ_DEC_IA64 - case BCJ_IA64: + case BCJ_IA64: #endif #ifdef XZ_DEC_ARM - case BCJ_ARM: + case BCJ_ARM: #endif #ifdef XZ_DEC_ARMTHUMB - case BCJ_ARMTHUMB: + case BCJ_ARMTHUMB: #endif #ifdef XZ_DEC_SPARC - case BCJ_SPARC: + case BCJ_SPARC: #endif - break; + break; - default: - /* Unsupported Filter ID */ - return XZ_OPTIONS_ERROR; - } + default: + /* Unsupported Filter ID */ + return XZ_OPTIONS_ERROR; + } - s->type = id; - s->ret = XZ_OK; - s->pos = 0; - s->x86_prev_mask = 0; - s->temp.filtered = 0; - s->temp.size = 0; + s->type = id; + s->ret = XZ_OK; + s->pos = 0; + s->x86_prev_mask = 0; + s->temp.filtered = 0; + s->temp.size = 0; - return XZ_OK; + return XZ_OK; } #endif diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_lzma2.c b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_lzma2.c index d40ee5a0..ad4756f4 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_lzma2.c +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_lzma2.c @@ -42,237 +42,237 @@ * buffer directly. */ struct dictionary { - /* Beginning of the history buffer */ - uint8_t *buf; + /* Beginning of the history buffer */ + uint8_t *buf; - /* Old position in buf (before decoding more data) */ - size_t start; + /* Old position in buf (before decoding more data) */ + size_t start; - /* Position in buf */ - size_t pos; + /* Position in buf */ + size_t pos; - /* - * How full dictionary is. This is used to detect corrupt input that - * would read beyond the beginning of the uncompressed stream. - */ - size_t full; + /* + * How full dictionary is. This is used to detect corrupt input that + * would read beyond the beginning of the uncompressed stream. + */ + size_t full; - /* Write limit; we don't write to buf[limit] or later bytes. */ - size_t limit; + /* Write limit; we don't write to buf[limit] or later bytes. */ + size_t limit; - /* - * End of the dictionary buffer. In multi-call mode, this is - * the same as the dictionary size. In single-call mode, this - * indicates the size of the output buffer. - */ - size_t end; + /* + * End of the dictionary buffer. In multi-call mode, this is + * the same as the dictionary size. In single-call mode, this + * indicates the size of the output buffer. + */ + size_t end; - /* - * Size of the dictionary as specified in Block Header. This is used - * together with "full" to detect corrupt input that would make us - * read beyond the beginning of the uncompressed stream. - */ - uint32_t size; + /* + * Size of the dictionary as specified in Block Header. This is used + * together with "full" to detect corrupt input that would make us + * read beyond the beginning of the uncompressed stream. + */ + uint32_t size; - /* - * Maximum allowed dictionary size in multi-call mode. - * This is ignored in single-call mode. - */ - uint32_t size_max; + /* + * Maximum allowed dictionary size in multi-call mode. + * This is ignored in single-call mode. + */ + uint32_t size_max; - /* - * Amount of memory currently allocated for the dictionary. - * This is used only with XZ_DYNALLOC. (With XZ_PREALLOC, - * size_max is always the same as the allocated size.) - */ - uint32_t allocated; + /* + * Amount of memory currently allocated for the dictionary. + * This is used only with XZ_DYNALLOC. (With XZ_PREALLOC, + * size_max is always the same as the allocated size.) + */ + uint32_t allocated; - /* Operation mode */ - enum xz_mode mode; + /* Operation mode */ + enum xz_mode mode; }; /* Range decoder */ struct rc_dec { - uint32_t range; - uint32_t code; + uint32_t range; + uint32_t code; - /* - * Number of initializing bytes remaining to be read - * by rc_read_init(). - */ - uint32_t init_bytes_left; + /* + * Number of initializing bytes remaining to be read + * by rc_read_init(). + */ + uint32_t init_bytes_left; - /* - * Buffer from which we read our input. It can be either - * temp.buf or the caller-provided input buffer. - */ - const uint8_t *in; - size_t in_pos; - size_t in_limit; + /* + * Buffer from which we read our input. It can be either + * temp.buf or the caller-provided input buffer. + */ + const uint8_t *in; + size_t in_pos; + size_t in_limit; }; /* Probabilities for a length decoder. */ struct lzma_len_dec { - /* Probability of match length being at least 10 */ - uint16_t choice; + /* Probability of match length being at least 10 */ + uint16_t choice; - /* Probability of match length being at least 18 */ - uint16_t choice2; + /* Probability of match length being at least 18 */ + uint16_t choice2; - /* Probabilities for match lengths 2-9 */ - uint16_t low[POS_STATES_MAX][LEN_LOW_SYMBOLS]; + /* Probabilities for match lengths 2-9 */ + uint16_t low[POS_STATES_MAX][LEN_LOW_SYMBOLS]; - /* Probabilities for match lengths 10-17 */ - uint16_t mid[POS_STATES_MAX][LEN_MID_SYMBOLS]; + /* Probabilities for match lengths 10-17 */ + uint16_t mid[POS_STATES_MAX][LEN_MID_SYMBOLS]; - /* Probabilities for match lengths 18-273 */ - uint16_t high[LEN_HIGH_SYMBOLS]; + /* Probabilities for match lengths 18-273 */ + uint16_t high[LEN_HIGH_SYMBOLS]; }; struct lzma_dec { - /* Distances of latest four matches */ - uint32_t rep0; - uint32_t rep1; - uint32_t rep2; - uint32_t rep3; + /* Distances of latest four matches */ + uint32_t rep0; + uint32_t rep1; + uint32_t rep2; + uint32_t rep3; - /* Types of the most recently seen LZMA symbols */ - enum lzma_state state; + /* Types of the most recently seen LZMA symbols */ + enum lzma_state state; - /* - * Length of a match. This is updated so that dict_repeat can - * be called again to finish repeating the whole match. - */ - uint32_t len; + /* + * Length of a match. This is updated so that dict_repeat can + * be called again to finish repeating the whole match. + */ + uint32_t len; - /* - * LZMA properties or related bit masks (number of literal - * context bits, a mask dervied from the number of literal - * position bits, and a mask dervied from the number - * position bits) - */ - uint32_t lc; - uint32_t literal_pos_mask; /* (1 << lp) - 1 */ - uint32_t pos_mask; /* (1 << pb) - 1 */ + /* + * LZMA properties or related bit masks (number of literal + * context bits, a mask dervied from the number of literal + * position bits, and a mask dervied from the number + * position bits) + */ + uint32_t lc; + uint32_t literal_pos_mask; /* (1 << lp) - 1 */ + uint32_t pos_mask; /* (1 << pb) - 1 */ - /* If 1, it's a match. Otherwise it's a single 8-bit literal. */ - uint16_t is_match[STATES][POS_STATES_MAX]; + /* If 1, it's a match. Otherwise it's a single 8-bit literal. */ + uint16_t is_match[STATES][POS_STATES_MAX]; - /* If 1, it's a repeated match. The distance is one of rep0 .. rep3. */ - uint16_t is_rep[STATES]; + /* If 1, it's a repeated match. The distance is one of rep0 .. rep3. */ + uint16_t is_rep[STATES]; - /* - * If 0, distance of a repeated match is rep0. - * Otherwise check is_rep1. - */ - uint16_t is_rep0[STATES]; + /* + * If 0, distance of a repeated match is rep0. + * Otherwise check is_rep1. + */ + uint16_t is_rep0[STATES]; - /* - * If 0, distance of a repeated match is rep1. - * Otherwise check is_rep2. - */ - uint16_t is_rep1[STATES]; + /* + * If 0, distance of a repeated match is rep1. + * Otherwise check is_rep2. + */ + uint16_t is_rep1[STATES]; - /* If 0, distance of a repeated match is rep2. Otherwise it is rep3. */ - uint16_t is_rep2[STATES]; + /* If 0, distance of a repeated match is rep2. Otherwise it is rep3. */ + uint16_t is_rep2[STATES]; - /* - * If 1, the repeated match has length of one byte. Otherwise - * the length is decoded from rep_len_decoder. - */ - uint16_t is_rep0_long[STATES][POS_STATES_MAX]; + /* + * If 1, the repeated match has length of one byte. Otherwise + * the length is decoded from rep_len_decoder. + */ + uint16_t is_rep0_long[STATES][POS_STATES_MAX]; - /* - * Probability tree for the highest two bits of the match - * distance. There is a separate probability tree for match - * lengths of 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273]. - */ - uint16_t dist_slot[DIST_STATES][DIST_SLOTS]; + /* + * Probability tree for the highest two bits of the match + * distance. There is a separate probability tree for match + * lengths of 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273]. + */ + uint16_t dist_slot[DIST_STATES][DIST_SLOTS]; - /* - * Probility trees for additional bits for match distance - * when the distance is in the range [4, 127]. - */ - uint16_t dist_special[FULL_DISTANCES - DIST_MODEL_END]; + /* + * Probility trees for additional bits for match distance + * when the distance is in the range [4, 127]. + */ + uint16_t dist_special[FULL_DISTANCES - DIST_MODEL_END]; - /* - * Probability tree for the lowest four bits of a match - * distance that is equal to or greater than 128. - */ - uint16_t dist_align[ALIGN_SIZE]; + /* + * Probability tree for the lowest four bits of a match + * distance that is equal to or greater than 128. + */ + uint16_t dist_align[ALIGN_SIZE]; - /* Length of a normal match */ - struct lzma_len_dec match_len_dec; + /* Length of a normal match */ + struct lzma_len_dec match_len_dec; - /* Length of a repeated match */ - struct lzma_len_dec rep_len_dec; + /* Length of a repeated match */ + struct lzma_len_dec rep_len_dec; - /* Probabilities of literals */ - uint16_t literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE]; + /* Probabilities of literals */ + uint16_t literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE]; }; struct lzma2_dec { - /* Position in xz_dec_lzma2_run(). */ - enum lzma2_seq { - SEQ_CONTROL, - SEQ_UNCOMPRESSED_1, - SEQ_UNCOMPRESSED_2, - SEQ_COMPRESSED_0, - SEQ_COMPRESSED_1, - SEQ_PROPERTIES, - SEQ_LZMA_PREPARE, - SEQ_LZMA_RUN, - SEQ_COPY - } sequence; + /* Position in xz_dec_lzma2_run(). */ + enum lzma2_seq { + SEQ_CONTROL, + SEQ_UNCOMPRESSED_1, + SEQ_UNCOMPRESSED_2, + SEQ_COMPRESSED_0, + SEQ_COMPRESSED_1, + SEQ_PROPERTIES, + SEQ_LZMA_PREPARE, + SEQ_LZMA_RUN, + SEQ_COPY + } sequence; - /* Next position after decoding the compressed size of the chunk. */ - enum lzma2_seq next_sequence; + /* Next position after decoding the compressed size of the chunk. */ + enum lzma2_seq next_sequence; - /* Uncompressed size of LZMA chunk (2 MiB at maximum) */ - uint32_t uncompressed; + /* Uncompressed size of LZMA chunk (2 MiB at maximum) */ + uint32_t uncompressed; - /* - * Compressed size of LZMA chunk or compressed/uncompressed - * size of uncompressed chunk (64 KiB at maximum) - */ - uint32_t compressed; + /* + * Compressed size of LZMA chunk or compressed/uncompressed + * size of uncompressed chunk (64 KiB at maximum) + */ + uint32_t compressed; - /* - * True if dictionary reset is needed. This is false before - * the first chunk (LZMA or uncompressed). - */ - bool need_dict_reset; + /* + * True if dictionary reset is needed. This is false before + * the first chunk (LZMA or uncompressed). + */ + bool need_dict_reset; - /* - * True if new LZMA properties are needed. This is false - * before the first LZMA chunk. - */ - bool need_props; + /* + * True if new LZMA properties are needed. This is false + * before the first LZMA chunk. + */ + bool need_props; }; struct xz_dec_lzma2 { - /* - * The order below is important on x86 to reduce code size and - * it shouldn't hurt on other platforms. Everything up to and - * including lzma.pos_mask are in the first 128 bytes on x86-32, - * which allows using smaller instructions to access those - * variables. On x86-64, fewer variables fit into the first 128 - * bytes, but this is still the best order without sacrificing - * the readability by splitting the structures. - */ - struct rc_dec rc; - struct dictionary dict; - struct lzma2_dec lzma2; - struct lzma_dec lzma; + /* + * The order below is important on x86 to reduce code size and + * it shouldn't hurt on other platforms. Everything up to and + * including lzma.pos_mask are in the first 128 bytes on x86-32, + * which allows using smaller instructions to access those + * variables. On x86-64, fewer variables fit into the first 128 + * bytes, but this is still the best order without sacrificing + * the readability by splitting the structures. + */ + struct rc_dec rc; + struct dictionary dict; + struct lzma2_dec lzma2; + struct lzma_dec lzma; - /* - * Temporary buffer which holds small number of input bytes between - * decoder calls. See lzma2_lzma() for details. - */ - struct { - uint32_t size; - uint8_t buf[3 * LZMA_IN_REQUIRED]; - } temp; + /* + * Temporary buffer which holds small number of input bytes between + * decoder calls. See lzma2_lzma() for details. + */ + struct { + uint32_t size; + uint8_t buf[3 * LZMA_IN_REQUIRED]; + } temp; }; /************** @@ -285,30 +285,30 @@ struct xz_dec_lzma2 { */ static void dict_reset(struct dictionary *dict, struct xz_buf *b) { - if (DEC_IS_SINGLE(dict->mode)) { - dict->buf = b->out + b->out_pos; - dict->end = b->out_size - b->out_pos; - } + if (DEC_IS_SINGLE(dict->mode)) { + dict->buf = b->out + b->out_pos; + dict->end = b->out_size - b->out_pos; + } - dict->start = 0; - dict->pos = 0; - dict->limit = 0; - dict->full = 0; + dict->start = 0; + dict->pos = 0; + dict->limit = 0; + dict->full = 0; } /* Set dictionary write limit */ static void dict_limit(struct dictionary *dict, size_t out_max) { - if (dict->end - dict->pos <= out_max) - dict->limit = dict->end; - else - dict->limit = dict->pos + out_max; + if (dict->end - dict->pos <= out_max) + dict->limit = dict->end; + else + dict->limit = dict->pos + out_max; } /* Return true if at least one byte can be written into the dictionary. */ static inline bool dict_has_space(const struct dictionary *dict) { - return dict->pos < dict->limit; + return dict->pos < dict->limit; } /* @@ -319,12 +319,12 @@ static inline bool dict_has_space(const struct dictionary *dict) */ static inline uint32_t dict_get(const struct dictionary *dict, uint32_t dist) { - size_t offset = dict->pos - dist - 1; + size_t offset = dict->pos - dist - 1; - if (dist >= dict->pos) - offset += dict->end; + if (dist >= dict->pos) + offset += dict->end; - return dict->full > 0 ? dict->buf[offset] : 0; + return dict->full > 0 ? dict->buf[offset] : 0; } /* @@ -332,10 +332,10 @@ static inline uint32_t dict_get(const struct dictionary *dict, uint32_t dist) */ static inline void dict_put(struct dictionary *dict, uint8_t byte) { - dict->buf[dict->pos++] = byte; + dict->buf[dict->pos++] = byte; - if (dict->full < dict->pos) - dict->full = dict->pos; + if (dict->full < dict->pos) + dict->full = dict->pos; } /* @@ -345,67 +345,67 @@ static inline void dict_put(struct dictionary *dict, uint8_t byte) */ static bool dict_repeat(struct dictionary *dict, uint32_t *len, uint32_t dist) { - size_t back; - uint32_t left; + size_t back; + uint32_t left; - if (dist >= dict->full || dist >= dict->size) - return false; + if (dist >= dict->full || dist >= dict->size) + return false; - left = min_t(size_t, dict->limit - dict->pos, *len); - *len -= left; + left = min_t(size_t, dict->limit - dict->pos, *len); + *len -= left; - back = dict->pos - dist - 1; - if (dist >= dict->pos) - back += dict->end; + back = dict->pos - dist - 1; + if (dist >= dict->pos) + back += dict->end; - do { - dict->buf[dict->pos++] = dict->buf[back++]; - if (back == dict->end) - back = 0; - } while (--left > 0); + do { + dict->buf[dict->pos++] = dict->buf[back++]; + if (back == dict->end) + back = 0; + } while (--left > 0); - if (dict->full < dict->pos) - dict->full = dict->pos; + if (dict->full < dict->pos) + dict->full = dict->pos; - return true; + return true; } /* Copy uncompressed data as is from input to dictionary and output buffers. */ static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b, - uint32_t *left) + uint32_t *left) { - size_t copy_size; + size_t copy_size; - while (*left > 0 && b->in_pos < b->in_size - && b->out_pos < b->out_size) { - copy_size = min(b->in_size - b->in_pos, - b->out_size - b->out_pos); - if (copy_size > dict->end - dict->pos) - copy_size = dict->end - dict->pos; - if (copy_size > *left) - copy_size = *left; + while (*left > 0 && b->in_pos < b->in_size + && b->out_pos < b->out_size) { + copy_size = min(b->in_size - b->in_pos, + b->out_size - b->out_pos); + if (copy_size > dict->end - dict->pos) + copy_size = dict->end - dict->pos; + if (copy_size > *left) + copy_size = *left; - *left -= copy_size; + *left -= copy_size; - memcpy(dict->buf + dict->pos, b->in + b->in_pos, copy_size); - dict->pos += copy_size; + memcpy(dict->buf + dict->pos, b->in + b->in_pos, copy_size); + dict->pos += copy_size; - if (dict->full < dict->pos) - dict->full = dict->pos; + if (dict->full < dict->pos) + dict->full = dict->pos; - if (DEC_IS_MULTI(dict->mode)) { - if (dict->pos == dict->end) - dict->pos = 0; + if (DEC_IS_MULTI(dict->mode)) { + if (dict->pos == dict->end) + dict->pos = 0; - memcpy(b->out + b->out_pos, b->in + b->in_pos, - copy_size); - } + memcpy(b->out + b->out_pos, b->in + b->in_pos, + copy_size); + } - dict->start = dict->pos; + dict->start = dict->pos; - b->out_pos += copy_size; - b->in_pos += copy_size; - } + b->out_pos += copy_size; + b->in_pos += copy_size; + } } /* @@ -415,19 +415,19 @@ static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b, */ static uint32_t dict_flush(struct dictionary *dict, struct xz_buf *b) { - size_t copy_size = dict->pos - dict->start; + size_t copy_size = dict->pos - dict->start; - if (DEC_IS_MULTI(dict->mode)) { - if (dict->pos == dict->end) - dict->pos = 0; + if (DEC_IS_MULTI(dict->mode)) { + if (dict->pos == dict->end) + dict->pos = 0; - memcpy(b->out + b->out_pos, dict->buf + dict->start, - copy_size); - } + memcpy(b->out + b->out_pos, dict->buf + dict->start, + copy_size); + } - dict->start = dict->pos; - b->out_pos += copy_size; - return copy_size; + dict->start = dict->pos; + b->out_pos += copy_size; + return copy_size; } /***************** @@ -437,9 +437,9 @@ static uint32_t dict_flush(struct dictionary *dict, struct xz_buf *b) /* Reset the range decoder. */ static void rc_reset(struct rc_dec *rc) { - rc->range = (uint32_t)-1; - rc->code = 0; - rc->init_bytes_left = RC_INIT_BYTES; + rc->range = (uint32_t)-1; + rc->code = 0; + rc->init_bytes_left = RC_INIT_BYTES; } /* @@ -448,21 +448,21 @@ static void rc_reset(struct rc_dec *rc) */ static bool rc_read_init(struct rc_dec *rc, struct xz_buf *b) { - while (rc->init_bytes_left > 0) { - if (b->in_pos == b->in_size) - return false; + while (rc->init_bytes_left > 0) { + if (b->in_pos == b->in_size) + return false; - rc->code = (rc->code << 8) + b->in[b->in_pos++]; - --rc->init_bytes_left; - } + rc->code = (rc->code << 8) + b->in[b->in_pos++]; + --rc->init_bytes_left; + } - return true; + return true; } /* Return true if there may not be enough input for the next decoding loop. */ static inline bool rc_limit_exceeded(const struct rc_dec *rc) { - return rc->in_pos > rc->in_limit; + return rc->in_pos > rc->in_limit; } /* @@ -471,16 +471,16 @@ static inline bool rc_limit_exceeded(const struct rc_dec *rc) */ static inline bool rc_is_finished(const struct rc_dec *rc) { - return rc->code == 0; + return rc->code == 0; } /* Read the next input byte if needed. */ static __always_inline void rc_normalize(struct rc_dec *rc) { - if (rc->range < RC_TOP_VALUE) { - rc->range <<= RC_SHIFT_BITS; - rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++]; - } + if (rc->range < RC_TOP_VALUE) { + rc->range <<= RC_SHIFT_BITS; + rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++]; + } } /* @@ -496,72 +496,72 @@ static __always_inline void rc_normalize(struct rc_dec *rc) */ static __always_inline int rc_bit(struct rc_dec *rc, uint16_t *prob) { - uint32_t bound; - int bit; + uint32_t bound; + int bit; - rc_normalize(rc); - bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob; - if (rc->code < bound) { - rc->range = bound; - *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS; - bit = 0; - } else { - rc->range -= bound; - rc->code -= bound; - *prob -= *prob >> RC_MOVE_BITS; - bit = 1; - } + rc_normalize(rc); + bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob; + if (rc->code < bound) { + rc->range = bound; + *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS; + bit = 0; + } else { + rc->range -= bound; + rc->code -= bound; + *prob -= *prob >> RC_MOVE_BITS; + bit = 1; + } - return bit; + return bit; } /* Decode a bittree starting from the most significant bit. */ static __always_inline uint32_t rc_bittree(struct rc_dec *rc, - uint16_t *probs, uint32_t limit) + uint16_t *probs, uint32_t limit) { - uint32_t symbol = 1; + uint32_t symbol = 1; - do { - if (rc_bit(rc, &probs[symbol])) - symbol = (symbol << 1) + 1; - else - symbol <<= 1; - } while (symbol < limit); + do { + if (rc_bit(rc, &probs[symbol])) + symbol = (symbol << 1) + 1; + else + symbol <<= 1; + } while (symbol < limit); - return symbol; + return symbol; } /* Decode a bittree starting from the least significant bit. */ static __always_inline void rc_bittree_reverse(struct rc_dec *rc, - uint16_t *probs, - uint32_t *dest, uint32_t limit) + uint16_t *probs, + uint32_t *dest, uint32_t limit) { - uint32_t symbol = 1; - uint32_t i = 0; + uint32_t symbol = 1; + uint32_t i = 0; - do { - if (rc_bit(rc, &probs[symbol])) { - symbol = (symbol << 1) + 1; - *dest += 1 << i; - } else { - symbol <<= 1; - } - } while (++i < limit); + do { + if (rc_bit(rc, &probs[symbol])) { + symbol = (symbol << 1) + 1; + *dest += 1 << i; + } else { + symbol <<= 1; + } + } while (++i < limit); } /* Decode direct bits (fixed fifty-fifty probability) */ static inline void rc_direct(struct rc_dec *rc, uint32_t *dest, uint32_t limit) { - uint32_t mask; + uint32_t mask; - do { - rc_normalize(rc); - rc->range >>= 1; - rc->code -= rc->range; - mask = (uint32_t)0 - (rc->code >> 31); - rc->code += rc->range & mask; - *dest = (*dest << 1) + (mask + 1); - } while (--limit > 0); + do { + rc_normalize(rc); + rc->range >>= 1; + rc->code -= rc->range; + mask = (uint32_t)0 - (rc->code >> 31); + rc->code += rc->range & mask; + *dest = (*dest << 1) + (mask + 1); + } while (--limit > 0); } /******** @@ -571,114 +571,114 @@ static inline void rc_direct(struct rc_dec *rc, uint32_t *dest, uint32_t limit) /* Get pointer to literal coder probability array. */ static uint16_t *lzma_literal_probs(struct xz_dec_lzma2 *s) { - uint32_t prev_byte = dict_get(&s->dict, 0); - uint32_t low = prev_byte >> (8 - s->lzma.lc); - uint32_t high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc; - return s->lzma.literal[low + high]; + uint32_t prev_byte = dict_get(&s->dict, 0); + uint32_t low = prev_byte >> (8 - s->lzma.lc); + uint32_t high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc; + return s->lzma.literal[low + high]; } /* Decode a literal (one 8-bit byte) */ static void lzma_literal(struct xz_dec_lzma2 *s) { - uint16_t *probs; - uint32_t symbol; - uint32_t match_byte; - uint32_t match_bit; - uint32_t offset; - uint32_t i; + uint16_t *probs; + uint32_t symbol; + uint32_t match_byte; + uint32_t match_bit; + uint32_t offset; + uint32_t i; - probs = lzma_literal_probs(s); + probs = lzma_literal_probs(s); - if (lzma_state_is_literal(s->lzma.state)) { - symbol = rc_bittree(&s->rc, probs, 0x100); - } else { - symbol = 1; - match_byte = dict_get(&s->dict, s->lzma.rep0) << 1; - offset = 0x100; + if (lzma_state_is_literal(s->lzma.state)) { + symbol = rc_bittree(&s->rc, probs, 0x100); + } else { + symbol = 1; + match_byte = dict_get(&s->dict, s->lzma.rep0) << 1; + offset = 0x100; - do { - match_bit = match_byte & offset; - match_byte <<= 1; - i = offset + match_bit + symbol; + do { + match_bit = match_byte & offset; + match_byte <<= 1; + i = offset + match_bit + symbol; - if (rc_bit(&s->rc, &probs[i])) { - symbol = (symbol << 1) + 1; - offset &= match_bit; - } else { - symbol <<= 1; - offset &= ~match_bit; - } - } while (symbol < 0x100); - } + if (rc_bit(&s->rc, &probs[i])) { + symbol = (symbol << 1) + 1; + offset &= match_bit; + } else { + symbol <<= 1; + offset &= ~match_bit; + } + } while (symbol < 0x100); + } - dict_put(&s->dict, (uint8_t)symbol); - lzma_state_literal(&s->lzma.state); + dict_put(&s->dict, (uint8_t)symbol); + lzma_state_literal(&s->lzma.state); } /* Decode the length of the match into s->lzma.len. */ static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l, - uint32_t pos_state) + uint32_t pos_state) { - uint16_t *probs; - uint32_t limit; + uint16_t *probs; + uint32_t limit; - if (!rc_bit(&s->rc, &l->choice)) { - probs = l->low[pos_state]; - limit = LEN_LOW_SYMBOLS; - s->lzma.len = MATCH_LEN_MIN; - } else { - if (!rc_bit(&s->rc, &l->choice2)) { - probs = l->mid[pos_state]; - limit = LEN_MID_SYMBOLS; - s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS; - } else { - probs = l->high; - limit = LEN_HIGH_SYMBOLS; - s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS - + LEN_MID_SYMBOLS; - } - } + if (!rc_bit(&s->rc, &l->choice)) { + probs = l->low[pos_state]; + limit = LEN_LOW_SYMBOLS; + s->lzma.len = MATCH_LEN_MIN; + } else { + if (!rc_bit(&s->rc, &l->choice2)) { + probs = l->mid[pos_state]; + limit = LEN_MID_SYMBOLS; + s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS; + } else { + probs = l->high; + limit = LEN_HIGH_SYMBOLS; + s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS + + LEN_MID_SYMBOLS; + } + } - s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit; + s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit; } /* Decode a match. The distance will be stored in s->lzma.rep0. */ static void lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state) { - uint16_t *probs; - uint32_t dist_slot; - uint32_t limit; + uint16_t *probs; + uint32_t dist_slot; + uint32_t limit; - lzma_state_match(&s->lzma.state); + lzma_state_match(&s->lzma.state); - s->lzma.rep3 = s->lzma.rep2; - s->lzma.rep2 = s->lzma.rep1; - s->lzma.rep1 = s->lzma.rep0; + s->lzma.rep3 = s->lzma.rep2; + s->lzma.rep2 = s->lzma.rep1; + s->lzma.rep1 = s->lzma.rep0; - lzma_len(s, &s->lzma.match_len_dec, pos_state); + lzma_len(s, &s->lzma.match_len_dec, pos_state); - probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)]; - dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS; + probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)]; + dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS; - if (dist_slot < DIST_MODEL_START) { - s->lzma.rep0 = dist_slot; - } else { - limit = (dist_slot >> 1) - 1; - s->lzma.rep0 = 2 + (dist_slot & 1); + if (dist_slot < DIST_MODEL_START) { + s->lzma.rep0 = dist_slot; + } else { + limit = (dist_slot >> 1) - 1; + s->lzma.rep0 = 2 + (dist_slot & 1); - if (dist_slot < DIST_MODEL_END) { - s->lzma.rep0 <<= limit; - probs = s->lzma.dist_special + s->lzma.rep0 - - dist_slot - 1; - rc_bittree_reverse(&s->rc, probs, - &s->lzma.rep0, limit); - } else { - rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS); - s->lzma.rep0 <<= ALIGN_BITS; - rc_bittree_reverse(&s->rc, s->lzma.dist_align, - &s->lzma.rep0, ALIGN_BITS); - } - } + if (dist_slot < DIST_MODEL_END) { + s->lzma.rep0 <<= limit; + probs = s->lzma.dist_special + s->lzma.rep0 + - dist_slot - 1; + rc_bittree_reverse(&s->rc, probs, + &s->lzma.rep0, limit); + } else { + rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS); + s->lzma.rep0 <<= ALIGN_BITS; + rc_bittree_reverse(&s->rc, s->lzma.dist_align, + &s->lzma.rep0, ALIGN_BITS); + } + } } /* @@ -687,77 +687,77 @@ static void lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state) */ static void lzma_rep_match(struct xz_dec_lzma2 *s, uint32_t pos_state) { - uint32_t tmp; + uint32_t tmp; - if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) { - if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[ - s->lzma.state][pos_state])) { - lzma_state_short_rep(&s->lzma.state); - s->lzma.len = 1; - return; - } - } else { - if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) { - tmp = s->lzma.rep1; - } else { - if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) { - tmp = s->lzma.rep2; - } else { - tmp = s->lzma.rep3; - s->lzma.rep3 = s->lzma.rep2; - } + if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) { + if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[ + s->lzma.state][pos_state])) { + lzma_state_short_rep(&s->lzma.state); + s->lzma.len = 1; + return; + } + } else { + if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) { + tmp = s->lzma.rep1; + } else { + if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) { + tmp = s->lzma.rep2; + } else { + tmp = s->lzma.rep3; + s->lzma.rep3 = s->lzma.rep2; + } - s->lzma.rep2 = s->lzma.rep1; - } + s->lzma.rep2 = s->lzma.rep1; + } - s->lzma.rep1 = s->lzma.rep0; - s->lzma.rep0 = tmp; - } + s->lzma.rep1 = s->lzma.rep0; + s->lzma.rep0 = tmp; + } - lzma_state_long_rep(&s->lzma.state); - lzma_len(s, &s->lzma.rep_len_dec, pos_state); + lzma_state_long_rep(&s->lzma.state); + lzma_len(s, &s->lzma.rep_len_dec, pos_state); } /* LZMA decoder core */ static bool lzma_main(struct xz_dec_lzma2 *s) { - uint32_t pos_state; + uint32_t pos_state; - /* - * If the dictionary was reached during the previous call, try to - * finish the possibly pending repeat in the dictionary. - */ - if (dict_has_space(&s->dict) && s->lzma.len > 0) - dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0); + /* + * If the dictionary was reached during the previous call, try to + * finish the possibly pending repeat in the dictionary. + */ + if (dict_has_space(&s->dict) && s->lzma.len > 0) + dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0); - /* - * Decode more LZMA symbols. One iteration may consume up to - * LZMA_IN_REQUIRED - 1 bytes. - */ - while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) { - pos_state = s->dict.pos & s->lzma.pos_mask; + /* + * Decode more LZMA symbols. One iteration may consume up to + * LZMA_IN_REQUIRED - 1 bytes. + */ + while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) { + pos_state = s->dict.pos & s->lzma.pos_mask; - if (!rc_bit(&s->rc, &s->lzma.is_match[ - s->lzma.state][pos_state])) { - lzma_literal(s); - } else { - if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state])) - lzma_rep_match(s, pos_state); - else - lzma_match(s, pos_state); + if (!rc_bit(&s->rc, &s->lzma.is_match[ + s->lzma.state][pos_state])) { + lzma_literal(s); + } else { + if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state])) + lzma_rep_match(s, pos_state); + else + lzma_match(s, pos_state); - if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0)) - return false; - } - } + if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0)) + return false; + } + } - /* - * Having the range decoder always normalized when we are outside - * this function makes it easier to correctly handle end of the chunk. - */ - rc_normalize(&s->rc); + /* + * Having the range decoder always normalized when we are outside + * this function makes it easier to correctly handle end of the chunk. + */ + rc_normalize(&s->rc); - return true; + return true; } /* @@ -766,29 +766,29 @@ static bool lzma_main(struct xz_dec_lzma2 *s) */ static void lzma_reset(struct xz_dec_lzma2 *s) { - uint16_t *probs; - size_t i; + uint16_t *probs; + size_t i; - s->lzma.state = STATE_LIT_LIT; - s->lzma.rep0 = 0; - s->lzma.rep1 = 0; - s->lzma.rep2 = 0; - s->lzma.rep3 = 0; + s->lzma.state = STATE_LIT_LIT; + s->lzma.rep0 = 0; + s->lzma.rep1 = 0; + s->lzma.rep2 = 0; + s->lzma.rep3 = 0; - /* - * All probabilities are initialized to the same value. This hack - * makes the code smaller by avoiding a separate loop for each - * probability array. - * - * This could be optimized so that only that part of literal - * probabilities that are actually required. In the common case - * we would write 12 KiB less. - */ - probs = s->lzma.is_match[0]; - for (i = 0; i < PROBS_TOTAL; ++i) - probs[i] = RC_BIT_MODEL_TOTAL / 2; + /* + * All probabilities are initialized to the same value. This hack + * makes the code smaller by avoiding a separate loop for each + * probability array. + * + * This could be optimized so that only that part of literal + * probabilities that are actually required. In the common case + * we would write 12 KiB less. + */ + probs = s->lzma.is_match[0]; + for (i = 0; i < PROBS_TOTAL; ++i) + probs[i] = RC_BIT_MODEL_TOTAL / 2; - rc_reset(&s->rc); + rc_reset(&s->rc); } /* @@ -798,33 +798,33 @@ static void lzma_reset(struct xz_dec_lzma2 *s) */ static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props) { - if (props > (4 * 5 + 4) * 9 + 8) - return false; + if (props > (4 * 5 + 4) * 9 + 8) + return false; - s->lzma.pos_mask = 0; - while (props >= 9 * 5) { - props -= 9 * 5; - ++s->lzma.pos_mask; - } + s->lzma.pos_mask = 0; + while (props >= 9 * 5) { + props -= 9 * 5; + ++s->lzma.pos_mask; + } - s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1; + s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1; - s->lzma.literal_pos_mask = 0; - while (props >= 9) { - props -= 9; - ++s->lzma.literal_pos_mask; - } + s->lzma.literal_pos_mask = 0; + while (props >= 9) { + props -= 9; + ++s->lzma.literal_pos_mask; + } - s->lzma.lc = props; + s->lzma.lc = props; - if (s->lzma.lc + s->lzma.literal_pos_mask > 4) - return false; + if (s->lzma.lc + s->lzma.literal_pos_mask > 4) + return false; - s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1; + s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1; - lzma_reset(s); + lzma_reset(s); - return true; + return true; } /********* @@ -845,83 +845,83 @@ static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props) */ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) { - size_t in_avail; - uint32_t tmp; + size_t in_avail; + uint32_t tmp; - in_avail = b->in_size - b->in_pos; - if (s->temp.size > 0 || s->lzma2.compressed == 0) { - tmp = 2 * LZMA_IN_REQUIRED - s->temp.size; - if (tmp > s->lzma2.compressed - s->temp.size) - tmp = s->lzma2.compressed - s->temp.size; - if (tmp > in_avail) - tmp = in_avail; + in_avail = b->in_size - b->in_pos; + if (s->temp.size > 0 || s->lzma2.compressed == 0) { + tmp = 2 * LZMA_IN_REQUIRED - s->temp.size; + if (tmp > s->lzma2.compressed - s->temp.size) + tmp = s->lzma2.compressed - s->temp.size; + if (tmp > in_avail) + tmp = in_avail; - memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp); + memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp); - if (s->temp.size + tmp == s->lzma2.compressed) { - memzero(s->temp.buf + s->temp.size + tmp, - sizeof(s->temp.buf) - - s->temp.size - tmp); - s->rc.in_limit = s->temp.size + tmp; - } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) { - s->temp.size += tmp; - b->in_pos += tmp; - return true; - } else { - s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED; - } + if (s->temp.size + tmp == s->lzma2.compressed) { + memzero(s->temp.buf + s->temp.size + tmp, + sizeof(s->temp.buf) + - s->temp.size - tmp); + s->rc.in_limit = s->temp.size + tmp; + } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) { + s->temp.size += tmp; + b->in_pos += tmp; + return true; + } else { + s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED; + } - s->rc.in = s->temp.buf; - s->rc.in_pos = 0; + s->rc.in = s->temp.buf; + s->rc.in_pos = 0; - if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp) - return false; + if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp) + return false; - s->lzma2.compressed -= s->rc.in_pos; + s->lzma2.compressed -= s->rc.in_pos; - if (s->rc.in_pos < s->temp.size) { - s->temp.size -= s->rc.in_pos; - memmove(s->temp.buf, s->temp.buf + s->rc.in_pos, - s->temp.size); - return true; - } + if (s->rc.in_pos < s->temp.size) { + s->temp.size -= s->rc.in_pos; + memmove(s->temp.buf, s->temp.buf + s->rc.in_pos, + s->temp.size); + return true; + } - b->in_pos += s->rc.in_pos - s->temp.size; - s->temp.size = 0; - } + b->in_pos += s->rc.in_pos - s->temp.size; + s->temp.size = 0; + } - in_avail = b->in_size - b->in_pos; - if (in_avail >= LZMA_IN_REQUIRED) { - s->rc.in = b->in; - s->rc.in_pos = b->in_pos; + in_avail = b->in_size - b->in_pos; + if (in_avail >= LZMA_IN_REQUIRED) { + s->rc.in = b->in; + s->rc.in_pos = b->in_pos; - if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED) - s->rc.in_limit = b->in_pos + s->lzma2.compressed; - else - s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED; + if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED) + s->rc.in_limit = b->in_pos + s->lzma2.compressed; + else + s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED; - if (!lzma_main(s)) - return false; + if (!lzma_main(s)) + return false; - in_avail = s->rc.in_pos - b->in_pos; - if (in_avail > s->lzma2.compressed) - return false; + in_avail = s->rc.in_pos - b->in_pos; + if (in_avail > s->lzma2.compressed) + return false; - s->lzma2.compressed -= in_avail; - b->in_pos = s->rc.in_pos; - } + s->lzma2.compressed -= in_avail; + b->in_pos = s->rc.in_pos; + } - in_avail = b->in_size - b->in_pos; - if (in_avail < LZMA_IN_REQUIRED) { - if (in_avail > s->lzma2.compressed) - in_avail = s->lzma2.compressed; + in_avail = b->in_size - b->in_pos; + if (in_avail < LZMA_IN_REQUIRED) { + if (in_avail > s->lzma2.compressed) + in_avail = s->lzma2.compressed; - memcpy(s->temp.buf, b->in + b->in_pos, in_avail); - s->temp.size = in_avail; - b->in_pos += in_avail; - } + memcpy(s->temp.buf, b->in + b->in_pos, in_avail); + s->temp.size = in_avail; + b->in_pos += in_avail; + } - return true; + return true; } /* @@ -929,251 +929,251 @@ static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b) * decoding or copying of uncompressed chunks to other functions. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, - struct xz_buf *b) + struct xz_buf *b) { - uint32_t tmp; + uint32_t tmp; - while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) { - switch (s->lzma2.sequence) { - case SEQ_CONTROL: - /* - * LZMA2 control byte - * - * Exact values: - * 0x00 End marker - * 0x01 Dictionary reset followed by - * an uncompressed chunk - * 0x02 Uncompressed chunk (no dictionary reset) - * - * Highest three bits (s->control & 0xE0): - * 0xE0 Dictionary reset, new properties and state - * reset, followed by LZMA compressed chunk - * 0xC0 New properties and state reset, followed - * by LZMA compressed chunk (no dictionary - * reset) - * 0xA0 State reset using old properties, - * followed by LZMA compressed chunk (no - * dictionary reset) - * 0x80 LZMA chunk (no dictionary or state reset) - * - * For LZMA compressed chunks, the lowest five bits - * (s->control & 1F) are the highest bits of the - * uncompressed size (bits 16-20). - * - * A new LZMA2 stream must begin with a dictionary - * reset. The first LZMA chunk must set new - * properties and reset the LZMA state. - * - * Values that don't match anything described above - * are invalid and we return XZ_DATA_ERROR. - */ - tmp = b->in[b->in_pos++]; + while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) { + switch (s->lzma2.sequence) { + case SEQ_CONTROL: + /* + * LZMA2 control byte + * + * Exact values: + * 0x00 End marker + * 0x01 Dictionary reset followed by + * an uncompressed chunk + * 0x02 Uncompressed chunk (no dictionary reset) + * + * Highest three bits (s->control & 0xE0): + * 0xE0 Dictionary reset, new properties and state + * reset, followed by LZMA compressed chunk + * 0xC0 New properties and state reset, followed + * by LZMA compressed chunk (no dictionary + * reset) + * 0xA0 State reset using old properties, + * followed by LZMA compressed chunk (no + * dictionary reset) + * 0x80 LZMA chunk (no dictionary or state reset) + * + * For LZMA compressed chunks, the lowest five bits + * (s->control & 1F) are the highest bits of the + * uncompressed size (bits 16-20). + * + * A new LZMA2 stream must begin with a dictionary + * reset. The first LZMA chunk must set new + * properties and reset the LZMA state. + * + * Values that don't match anything described above + * are invalid and we return XZ_DATA_ERROR. + */ + tmp = b->in[b->in_pos++]; - if (tmp == 0x00) - return XZ_STREAM_END; + if (tmp == 0x00) + return XZ_STREAM_END; - if (tmp >= 0xE0 || tmp == 0x01) { - s->lzma2.need_props = true; - s->lzma2.need_dict_reset = false; - dict_reset(&s->dict, b); - } else if (s->lzma2.need_dict_reset) { - return XZ_DATA_ERROR; - } + if (tmp >= 0xE0 || tmp == 0x01) { + s->lzma2.need_props = true; + s->lzma2.need_dict_reset = false; + dict_reset(&s->dict, b); + } else if (s->lzma2.need_dict_reset) { + return XZ_DATA_ERROR; + } - if (tmp >= 0x80) { - s->lzma2.uncompressed = (tmp & 0x1F) << 16; - s->lzma2.sequence = SEQ_UNCOMPRESSED_1; + if (tmp >= 0x80) { + s->lzma2.uncompressed = (tmp & 0x1F) << 16; + s->lzma2.sequence = SEQ_UNCOMPRESSED_1; - if (tmp >= 0xC0) { - /* - * When there are new properties, - * state reset is done at - * SEQ_PROPERTIES. - */ - s->lzma2.need_props = false; - s->lzma2.next_sequence - = SEQ_PROPERTIES; + if (tmp >= 0xC0) { + /* + * When there are new properties, + * state reset is done at + * SEQ_PROPERTIES. + */ + s->lzma2.need_props = false; + s->lzma2.next_sequence + = SEQ_PROPERTIES; - } else if (s->lzma2.need_props) { - return XZ_DATA_ERROR; + } else if (s->lzma2.need_props) { + return XZ_DATA_ERROR; - } else { - s->lzma2.next_sequence - = SEQ_LZMA_PREPARE; - if (tmp >= 0xA0) - lzma_reset(s); - } - } else { - if (tmp > 0x02) - return XZ_DATA_ERROR; + } else { + s->lzma2.next_sequence + = SEQ_LZMA_PREPARE; + if (tmp >= 0xA0) + lzma_reset(s); + } + } else { + if (tmp > 0x02) + return XZ_DATA_ERROR; - s->lzma2.sequence = SEQ_COMPRESSED_0; - s->lzma2.next_sequence = SEQ_COPY; - } + s->lzma2.sequence = SEQ_COMPRESSED_0; + s->lzma2.next_sequence = SEQ_COPY; + } - break; + break; - case SEQ_UNCOMPRESSED_1: - s->lzma2.uncompressed - += (uint32_t)b->in[b->in_pos++] << 8; - s->lzma2.sequence = SEQ_UNCOMPRESSED_2; - break; + case SEQ_UNCOMPRESSED_1: + s->lzma2.uncompressed + += (uint32_t)b->in[b->in_pos++] << 8; + s->lzma2.sequence = SEQ_UNCOMPRESSED_2; + break; - case SEQ_UNCOMPRESSED_2: - s->lzma2.uncompressed - += (uint32_t)b->in[b->in_pos++] + 1; - s->lzma2.sequence = SEQ_COMPRESSED_0; - break; + case SEQ_UNCOMPRESSED_2: + s->lzma2.uncompressed + += (uint32_t)b->in[b->in_pos++] + 1; + s->lzma2.sequence = SEQ_COMPRESSED_0; + break; - case SEQ_COMPRESSED_0: - s->lzma2.compressed - = (uint32_t)b->in[b->in_pos++] << 8; - s->lzma2.sequence = SEQ_COMPRESSED_1; - break; + case SEQ_COMPRESSED_0: + s->lzma2.compressed + = (uint32_t)b->in[b->in_pos++] << 8; + s->lzma2.sequence = SEQ_COMPRESSED_1; + break; - case SEQ_COMPRESSED_1: - s->lzma2.compressed - += (uint32_t)b->in[b->in_pos++] + 1; - s->lzma2.sequence = s->lzma2.next_sequence; - break; + case SEQ_COMPRESSED_1: + s->lzma2.compressed + += (uint32_t)b->in[b->in_pos++] + 1; + s->lzma2.sequence = s->lzma2.next_sequence; + break; - case SEQ_PROPERTIES: - if (!lzma_props(s, b->in[b->in_pos++])) - return XZ_DATA_ERROR; + case SEQ_PROPERTIES: + if (!lzma_props(s, b->in[b->in_pos++])) + return XZ_DATA_ERROR; - s->lzma2.sequence = SEQ_LZMA_PREPARE; + s->lzma2.sequence = SEQ_LZMA_PREPARE; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_LZMA_PREPARE: - if (s->lzma2.compressed < RC_INIT_BYTES) - return XZ_DATA_ERROR; + case SEQ_LZMA_PREPARE: + if (s->lzma2.compressed < RC_INIT_BYTES) + return XZ_DATA_ERROR; - if (!rc_read_init(&s->rc, b)) - return XZ_OK; + if (!rc_read_init(&s->rc, b)) + return XZ_OK; - s->lzma2.compressed -= RC_INIT_BYTES; - s->lzma2.sequence = SEQ_LZMA_RUN; + s->lzma2.compressed -= RC_INIT_BYTES; + s->lzma2.sequence = SEQ_LZMA_RUN; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_LZMA_RUN: - /* - * Set dictionary limit to indicate how much we want - * to be encoded at maximum. Decode new data into the - * dictionary. Flush the new data from dictionary to - * b->out. Check if we finished decoding this chunk. - * In case the dictionary got full but we didn't fill - * the output buffer yet, we may run this loop - * multiple times without changing s->lzma2.sequence. - */ - dict_limit(&s->dict, min_t(size_t, - b->out_size - b->out_pos, - s->lzma2.uncompressed)); - if (!lzma2_lzma(s, b)) - return XZ_DATA_ERROR; + case SEQ_LZMA_RUN: + /* + * Set dictionary limit to indicate how much we want + * to be encoded at maximum. Decode new data into the + * dictionary. Flush the new data from dictionary to + * b->out. Check if we finished decoding this chunk. + * In case the dictionary got full but we didn't fill + * the output buffer yet, we may run this loop + * multiple times without changing s->lzma2.sequence. + */ + dict_limit(&s->dict, min_t(size_t, + b->out_size - b->out_pos, + s->lzma2.uncompressed)); + if (!lzma2_lzma(s, b)) + return XZ_DATA_ERROR; - s->lzma2.uncompressed -= dict_flush(&s->dict, b); + s->lzma2.uncompressed -= dict_flush(&s->dict, b); - if (s->lzma2.uncompressed == 0) { - if (s->lzma2.compressed > 0 || s->lzma.len > 0 - || !rc_is_finished(&s->rc)) - return XZ_DATA_ERROR; + if (s->lzma2.uncompressed == 0) { + if (s->lzma2.compressed > 0 || s->lzma.len > 0 + || !rc_is_finished(&s->rc)) + return XZ_DATA_ERROR; - rc_reset(&s->rc); - s->lzma2.sequence = SEQ_CONTROL; + rc_reset(&s->rc); + s->lzma2.sequence = SEQ_CONTROL; - } else if (b->out_pos == b->out_size - || (b->in_pos == b->in_size - && s->temp.size - < s->lzma2.compressed)) { - return XZ_OK; - } + } else if (b->out_pos == b->out_size + || (b->in_pos == b->in_size + && s->temp.size + < s->lzma2.compressed)) { + return XZ_OK; + } - break; + break; - case SEQ_COPY: - dict_uncompressed(&s->dict, b, &s->lzma2.compressed); - if (s->lzma2.compressed > 0) - return XZ_OK; + case SEQ_COPY: + dict_uncompressed(&s->dict, b, &s->lzma2.compressed); + if (s->lzma2.compressed > 0) + return XZ_OK; - s->lzma2.sequence = SEQ_CONTROL; - break; - default: - break; - } - } + s->lzma2.sequence = SEQ_CONTROL; + break; + default: + break; + } + } - return XZ_OK; + return XZ_OK; } XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, - uint32_t dict_max) + uint32_t dict_max) { - struct xz_dec_lzma2 *s = kmalloc(sizeof(*s), GFP_KERNEL); - if (s == NULL) - return NULL; + struct xz_dec_lzma2 *s = kmalloc(sizeof(*s), GFP_KERNEL); + if (s == NULL) + return NULL; - s->dict.mode = mode; - s->dict.size_max = dict_max; + s->dict.mode = mode; + s->dict.size_max = dict_max; - if (DEC_IS_PREALLOC(mode)) { - s->dict.buf = vmalloc(dict_max); - if (s->dict.buf == NULL) { - kfree(s); - return NULL; - } - } else if (DEC_IS_DYNALLOC(mode)) { - s->dict.buf = NULL; - s->dict.allocated = 0; - } + if (DEC_IS_PREALLOC(mode)) { + s->dict.buf = vmalloc(dict_max); + if (s->dict.buf == NULL) { + kfree(s); + return NULL; + } + } else if (DEC_IS_DYNALLOC(mode)) { + s->dict.buf = NULL; + s->dict.allocated = 0; + } - return s; + return s; } XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props) { - /* This limits dictionary size to 3 GiB to keep parsing simpler. */ - if (props > 39) - return XZ_OPTIONS_ERROR; + /* This limits dictionary size to 3 GiB to keep parsing simpler. */ + if (props > 39) + return XZ_OPTIONS_ERROR; - s->dict.size = 2 + (props & 1); - s->dict.size <<= (props >> 1) + 11; + s->dict.size = 2 + (props & 1); + s->dict.size <<= (props >> 1) + 11; - if (DEC_IS_MULTI(s->dict.mode)) { - if (s->dict.size > s->dict.size_max) - return XZ_MEMLIMIT_ERROR; + if (DEC_IS_MULTI(s->dict.mode)) { + if (s->dict.size > s->dict.size_max) + return XZ_MEMLIMIT_ERROR; - s->dict.end = s->dict.size; + s->dict.end = s->dict.size; - if (DEC_IS_DYNALLOC(s->dict.mode)) { - if (s->dict.allocated < s->dict.size) { - vfree(s->dict.buf); - s->dict.buf = vmalloc(s->dict.size); - if (s->dict.buf == NULL) { - s->dict.allocated = 0; - return XZ_MEM_ERROR; - } - } - } - } + if (DEC_IS_DYNALLOC(s->dict.mode)) { + if (s->dict.allocated < s->dict.size) { + vfree(s->dict.buf); + s->dict.buf = vmalloc(s->dict.size); + if (s->dict.buf == NULL) { + s->dict.allocated = 0; + return XZ_MEM_ERROR; + } + } + } + } - s->lzma.len = 0; + s->lzma.len = 0; - s->lzma2.sequence = SEQ_CONTROL; - s->lzma2.need_dict_reset = true; + s->lzma2.sequence = SEQ_CONTROL; + s->lzma2.need_dict_reset = true; - s->temp.size = 0; + s->temp.size = 0; - return XZ_OK; + return XZ_OK; } XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s) { - if (DEC_IS_MULTI(s->dict.mode)) - vfree(s->dict.buf); + if (DEC_IS_MULTI(s->dict.mode)) + vfree(s->dict.buf); - kfree(s); + kfree(s); } diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_stream.c b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_stream.c index fb3699d2..8a9e2330 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_stream.c +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_stream.c @@ -11,151 +11,151 @@ #include "xz_stream.h" #ifdef XZ_USE_CRC64 -# define IS_CRC64(check_type) ((check_type) == XZ_CHECK_CRC64) +# define IS_CRC64(check_type) ((check_type) == XZ_CHECK_CRC64) #else -# define IS_CRC64(check_type) false +# define IS_CRC64(check_type) false #endif /* Hash used to validate the Index field */ struct xz_dec_hash { - vli_type unpadded; - vli_type uncompressed; - uint32_t crc32; + vli_type unpadded; + vli_type uncompressed; + uint32_t crc32; }; struct xz_dec { - /* Position in dec_main() */ - enum { - SEQ_STREAM_HEADER, - SEQ_BLOCK_START, - SEQ_BLOCK_HEADER, - SEQ_BLOCK_UNCOMPRESS, - SEQ_BLOCK_PADDING, - SEQ_BLOCK_CHECK, - SEQ_INDEX, - SEQ_INDEX_PADDING, - SEQ_INDEX_CRC32, - SEQ_STREAM_FOOTER - } sequence; + /* Position in dec_main() */ + enum { + SEQ_STREAM_HEADER, + SEQ_BLOCK_START, + SEQ_BLOCK_HEADER, + SEQ_BLOCK_UNCOMPRESS, + SEQ_BLOCK_PADDING, + SEQ_BLOCK_CHECK, + SEQ_INDEX, + SEQ_INDEX_PADDING, + SEQ_INDEX_CRC32, + SEQ_STREAM_FOOTER + } sequence; - /* Position in variable-length integers and Check fields */ - uint32_t pos; + /* Position in variable-length integers and Check fields */ + uint32_t pos; - /* Variable-length integer decoded by dec_vli() */ - vli_type vli; + /* Variable-length integer decoded by dec_vli() */ + vli_type vli; - /* Saved in_pos and out_pos */ - size_t in_start; - size_t out_start; + /* Saved in_pos and out_pos */ + size_t in_start; + size_t out_start; #ifdef XZ_USE_CRC64 - /* CRC32 or CRC64 value in Block or CRC32 value in Index */ - uint64_t crc; + /* CRC32 or CRC64 value in Block or CRC32 value in Index */ + uint64_t crc; #else - /* CRC32 value in Block or Index */ - uint32_t crc; + /* CRC32 value in Block or Index */ + uint32_t crc; #endif - /* Type of the integrity check calculated from uncompressed data */ - enum xz_check check_type; + /* Type of the integrity check calculated from uncompressed data */ + enum xz_check check_type; - /* Operation mode */ - enum xz_mode mode; + /* Operation mode */ + enum xz_mode mode; - /* - * True if the next call to xz_dec_run() is allowed to return - * XZ_BUF_ERROR. - */ - bool allow_buf_error; + /* + * True if the next call to xz_dec_run() is allowed to return + * XZ_BUF_ERROR. + */ + bool allow_buf_error; - /* Information stored in Block Header */ - struct { - /* - * Value stored in the Compressed Size field, or - * VLI_UNKNOWN if Compressed Size is not present. - */ - vli_type compressed; + /* Information stored in Block Header */ + struct { + /* + * Value stored in the Compressed Size field, or + * VLI_UNKNOWN if Compressed Size is not present. + */ + vli_type compressed; - /* - * Value stored in the Uncompressed Size field, or - * VLI_UNKNOWN if Uncompressed Size is not present. - */ - vli_type uncompressed; + /* + * Value stored in the Uncompressed Size field, or + * VLI_UNKNOWN if Uncompressed Size is not present. + */ + vli_type uncompressed; - /* Size of the Block Header field */ - uint32_t size; - } block_header; + /* Size of the Block Header field */ + uint32_t size; + } block_header; - /* Information collected when decoding Blocks */ - struct { - /* Observed compressed size of the current Block */ - vli_type compressed; + /* Information collected when decoding Blocks */ + struct { + /* Observed compressed size of the current Block */ + vli_type compressed; - /* Observed uncompressed size of the current Block */ - vli_type uncompressed; + /* Observed uncompressed size of the current Block */ + vli_type uncompressed; - /* Number of Blocks decoded so far */ - vli_type count; + /* Number of Blocks decoded so far */ + vli_type count; - /* - * Hash calculated from the Block sizes. This is used to - * validate the Index field. - */ - struct xz_dec_hash hash; - } block; + /* + * Hash calculated from the Block sizes. This is used to + * validate the Index field. + */ + struct xz_dec_hash hash; + } block; - /* Variables needed when verifying the Index field */ - struct { - /* Position in dec_index() */ - enum { - SEQ_INDEX_COUNT, - SEQ_INDEX_UNPADDED, - SEQ_INDEX_UNCOMPRESSED - } sequence; + /* Variables needed when verifying the Index field */ + struct { + /* Position in dec_index() */ + enum { + SEQ_INDEX_COUNT, + SEQ_INDEX_UNPADDED, + SEQ_INDEX_UNCOMPRESSED + } sequence; - /* Size of the Index in bytes */ - vli_type size; + /* Size of the Index in bytes */ + vli_type size; - /* Number of Records (matches block.count in valid files) */ - vli_type count; + /* Number of Records (matches block.count in valid files) */ + vli_type count; - /* - * Hash calculated from the Records (matches block.hash in - * valid files). - */ - struct xz_dec_hash hash; - } index; + /* + * Hash calculated from the Records (matches block.hash in + * valid files). + */ + struct xz_dec_hash hash; + } index; - /* - * Temporary buffer needed to hold Stream Header, Block Header, - * and Stream Footer. The Block Header is the biggest (1 KiB) - * so we reserve space according to that. buf[] has to be aligned - * to a multiple of four bytes; the size_t variables before it - * should guarantee this. - */ - struct { - size_t pos; - size_t size; - uint8_t buf[1024]; - } temp; + /* + * Temporary buffer needed to hold Stream Header, Block Header, + * and Stream Footer. The Block Header is the biggest (1 KiB) + * so we reserve space according to that. buf[] has to be aligned + * to a multiple of four bytes; the size_t variables before it + * should guarantee this. + */ + struct { + size_t pos; + size_t size; + uint8_t buf[1024]; + } temp; - struct xz_dec_lzma2 *lzma2; + struct xz_dec_lzma2 *lzma2; #ifdef XZ_DEC_BCJ - struct xz_dec_bcj *bcj; - bool bcj_active; + struct xz_dec_bcj *bcj; + bool bcj_active; #endif }; #ifdef XZ_DEC_ANY_CHECK /* Sizes of the Check field with different Check IDs */ static const uint8_t check_sizes[16] = { - 0, - 4, 4, 4, - 8, 8, 8, - 16, 16, 16, - 32, 32, 32, - 64, 64, 64 + 0, + 4, 4, 4, + 8, 8, 8, + 16, 16, 16, + 32, 32, 32, + 64, 64, 64 }; #endif @@ -167,51 +167,51 @@ static const uint8_t check_sizes[16] = { */ static bool fill_temp(struct xz_dec *s, struct xz_buf *b) { - size_t copy_size = min_t(size_t, - b->in_size - b->in_pos, s->temp.size - s->temp.pos); + size_t copy_size = min_t(size_t, + b->in_size - b->in_pos, s->temp.size - s->temp.pos); - memcpy(s->temp.buf + s->temp.pos, b->in + b->in_pos, copy_size); - b->in_pos += copy_size; - s->temp.pos += copy_size; + memcpy(s->temp.buf + s->temp.pos, b->in + b->in_pos, copy_size); + b->in_pos += copy_size; + s->temp.pos += copy_size; - if (s->temp.pos == s->temp.size) { - s->temp.pos = 0; - return true; - } + if (s->temp.pos == s->temp.size) { + s->temp.pos = 0; + return true; + } - return false; + return false; } /* Decode a variable-length integer (little-endian base-128 encoding) */ static enum xz_ret dec_vli(struct xz_dec *s, const uint8_t *in, - size_t *in_pos, size_t in_size) + size_t *in_pos, size_t in_size) { - uint8_t byte; + uint8_t byte; - if (s->pos == 0) - s->vli = 0; + if (s->pos == 0) + s->vli = 0; - while (*in_pos < in_size) { - byte = in[*in_pos]; - ++*in_pos; + while (*in_pos < in_size) { + byte = in[*in_pos]; + ++*in_pos; - s->vli |= (vli_type)(byte & 0x7F) << s->pos; + s->vli |= (vli_type)(byte & 0x7F) << s->pos; - if ((byte & 0x80) == 0) { - /* Don't allow non-minimal encodings. */ - if (byte == 0 && s->pos != 0) - return XZ_DATA_ERROR; + if ((byte & 0x80) == 0) { + /* Don't allow non-minimal encodings. */ + if (byte == 0 && s->pos != 0) + return XZ_DATA_ERROR; - s->pos = 0; - return XZ_STREAM_END; - } + s->pos = 0; + return XZ_STREAM_END; + } - s->pos += 7; - if (s->pos == 7 * VLI_BYTES_MAX) - return XZ_DATA_ERROR; - } + s->pos += 7; + if (s->pos == 7 * VLI_BYTES_MAX) + return XZ_DATA_ERROR; + } - return XZ_OK; + return XZ_OK; } /* @@ -228,79 +228,79 @@ static enum xz_ret dec_vli(struct xz_dec *s, const uint8_t *in, */ static enum xz_ret dec_block(struct xz_dec *s, struct xz_buf *b) { - enum xz_ret ret; + enum xz_ret ret; - s->in_start = b->in_pos; - s->out_start = b->out_pos; + s->in_start = b->in_pos; + s->out_start = b->out_pos; #ifdef XZ_DEC_BCJ - if (s->bcj_active) - ret = xz_dec_bcj_run(s->bcj, s->lzma2, b); - else + if (s->bcj_active) + ret = xz_dec_bcj_run(s->bcj, s->lzma2, b); + else #endif - ret = xz_dec_lzma2_run(s->lzma2, b); + ret = xz_dec_lzma2_run(s->lzma2, b); - s->block.compressed += b->in_pos - s->in_start; - s->block.uncompressed += b->out_pos - s->out_start; + s->block.compressed += b->in_pos - s->in_start; + s->block.uncompressed += b->out_pos - s->out_start; - /* - * There is no need to separately check for VLI_UNKNOWN, since - * the observed sizes are always smaller than VLI_UNKNOWN. - */ - if (s->block.compressed > s->block_header.compressed - || s->block.uncompressed - > s->block_header.uncompressed) - return XZ_DATA_ERROR; + /* + * There is no need to separately check for VLI_UNKNOWN, since + * the observed sizes are always smaller than VLI_UNKNOWN. + */ + if (s->block.compressed > s->block_header.compressed + || s->block.uncompressed + > s->block_header.uncompressed) + return XZ_DATA_ERROR; - if (s->check_type == XZ_CHECK_CRC32) - s->crc = xz_crc32(b->out + s->out_start, - b->out_pos - s->out_start, s->crc); + if (s->check_type == XZ_CHECK_CRC32) + s->crc = xz_crc32(b->out + s->out_start, + b->out_pos - s->out_start, s->crc); #ifdef XZ_USE_CRC64 - else if (s->check_type == XZ_CHECK_CRC64) - s->crc = xz_crc64(b->out + s->out_start, - b->out_pos - s->out_start, s->crc); + else if (s->check_type == XZ_CHECK_CRC64) + s->crc = xz_crc64(b->out + s->out_start, + b->out_pos - s->out_start, s->crc); #endif - if (ret == XZ_STREAM_END) { - if (s->block_header.compressed != VLI_UNKNOWN - && s->block_header.compressed - != s->block.compressed) - return XZ_DATA_ERROR; + if (ret == XZ_STREAM_END) { + if (s->block_header.compressed != VLI_UNKNOWN + && s->block_header.compressed + != s->block.compressed) + return XZ_DATA_ERROR; - if (s->block_header.uncompressed != VLI_UNKNOWN - && s->block_header.uncompressed - != s->block.uncompressed) - return XZ_DATA_ERROR; + if (s->block_header.uncompressed != VLI_UNKNOWN + && s->block_header.uncompressed + != s->block.uncompressed) + return XZ_DATA_ERROR; - s->block.hash.unpadded += s->block_header.size - + s->block.compressed; + s->block.hash.unpadded += s->block_header.size + + s->block.compressed; #ifdef XZ_DEC_ANY_CHECK - s->block.hash.unpadded += check_sizes[s->check_type]; + s->block.hash.unpadded += check_sizes[s->check_type]; #else - if (s->check_type == XZ_CHECK_CRC32) - s->block.hash.unpadded += 4; - else if (IS_CRC64(s->check_type)) - s->block.hash.unpadded += 8; + if (s->check_type == XZ_CHECK_CRC32) + s->block.hash.unpadded += 4; + else if (IS_CRC64(s->check_type)) + s->block.hash.unpadded += 8; #endif - s->block.hash.uncompressed += s->block.uncompressed; - s->block.hash.crc32 = xz_crc32( - (const uint8_t *)&s->block.hash, - sizeof(s->block.hash), s->block.hash.crc32); + s->block.hash.uncompressed += s->block.uncompressed; + s->block.hash.crc32 = xz_crc32( + (const uint8_t *)&s->block.hash, + sizeof(s->block.hash), s->block.hash.crc32); - ++s->block.count; - } + ++s->block.count; + } - return ret; + return ret; } /* Update the Index size and the CRC32 value. */ static void index_update(struct xz_dec *s, const struct xz_buf *b) { - size_t in_used = b->in_pos - s->in_start; - s->index.size += in_used; - s->crc = xz_crc32(b->in + s->in_start, in_used, s->crc); + size_t in_used = b->in_pos - s->in_start; + s->index.size += in_used; + s->crc = xz_crc32(b->in + s->in_start, in_used, s->crc); } /* @@ -313,50 +313,50 @@ static void index_update(struct xz_dec *s, const struct xz_buf *b) */ static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b) { - enum xz_ret ret; + enum xz_ret ret; - do { - ret = dec_vli(s, b->in, &b->in_pos, b->in_size); - if (ret != XZ_STREAM_END) { - index_update(s, b); - return ret; - } + do { + ret = dec_vli(s, b->in, &b->in_pos, b->in_size); + if (ret != XZ_STREAM_END) { + index_update(s, b); + return ret; + } - switch (s->index.sequence) { - case SEQ_INDEX_COUNT: - s->index.count = s->vli; + switch (s->index.sequence) { + case SEQ_INDEX_COUNT: + s->index.count = s->vli; - /* - * Validate that the Number of Records field - * indicates the same number of Records as - * there were Blocks in the Stream. - */ - if (s->index.count != s->block.count) - return XZ_DATA_ERROR; + /* + * Validate that the Number of Records field + * indicates the same number of Records as + * there were Blocks in the Stream. + */ + if (s->index.count != s->block.count) + return XZ_DATA_ERROR; - s->index.sequence = SEQ_INDEX_UNPADDED; - break; + s->index.sequence = SEQ_INDEX_UNPADDED; + break; - case SEQ_INDEX_UNPADDED: - s->index.hash.unpadded += s->vli; - s->index.sequence = SEQ_INDEX_UNCOMPRESSED; - break; + case SEQ_INDEX_UNPADDED: + s->index.hash.unpadded += s->vli; + s->index.sequence = SEQ_INDEX_UNCOMPRESSED; + break; - case SEQ_INDEX_UNCOMPRESSED: - s->index.hash.uncompressed += s->vli; - s->index.hash.crc32 = xz_crc32( - (const uint8_t *)&s->index.hash, - sizeof(s->index.hash), - s->index.hash.crc32); - --s->index.count; - s->index.sequence = SEQ_INDEX_UNPADDED; - break; - default: - break; - } - } while (s->index.count > 0); + case SEQ_INDEX_UNCOMPRESSED: + s->index.hash.uncompressed += s->vli; + s->index.hash.crc32 = xz_crc32( + (const uint8_t *)&s->index.hash, + sizeof(s->index.hash), + s->index.hash.crc32); + --s->index.count; + s->index.sequence = SEQ_INDEX_UNPADDED; + break; + default: + break; + } + } while (s->index.count > 0); - return XZ_STREAM_END; + return XZ_STREAM_END; } /* @@ -365,23 +365,23 @@ static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b) * The "bits" argument allows using the same code for both CRC32 and CRC64. */ static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b, - uint32_t bits) + uint32_t bits) { - do { - if (b->in_pos == b->in_size) - return XZ_OK; + do { + if (b->in_pos == b->in_size) + return XZ_OK; - if (((s->crc >> s->pos) & 0xFF) != b->in[b->in_pos++]) - return XZ_DATA_ERROR; + if (((s->crc >> s->pos) & 0xFF) != b->in[b->in_pos++]) + return XZ_DATA_ERROR; - s->pos += 8; + s->pos += 8; - } while (s->pos < bits); + } while (s->pos < bits); - s->crc = 0; - s->pos = 0; + s->crc = 0; + s->pos = 0; - return XZ_STREAM_END; + return XZ_STREAM_END; } #ifdef XZ_DEC_ANY_CHECK @@ -391,373 +391,373 @@ static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b, */ static bool check_skip(struct xz_dec *s, struct xz_buf *b) { - while (s->pos < check_sizes[s->check_type]) { - if (b->in_pos == b->in_size) - return false; + while (s->pos < check_sizes[s->check_type]) { + if (b->in_pos == b->in_size) + return false; - ++b->in_pos; - ++s->pos; - } + ++b->in_pos; + ++s->pos; + } - s->pos = 0; + s->pos = 0; - return true; + return true; } #endif /* Decode the Stream Header field (the first 12 bytes of the .xz Stream). */ static enum xz_ret dec_stream_header(struct xz_dec *s) { - if (!memeq(s->temp.buf, HEADER_MAGIC, HEADER_MAGIC_SIZE)) - return XZ_FORMAT_ERROR; + if (!memeq(s->temp.buf, HEADER_MAGIC, HEADER_MAGIC_SIZE)) + return XZ_FORMAT_ERROR; - if (xz_crc32(s->temp.buf + HEADER_MAGIC_SIZE, 2, 0) - != get_le32(s->temp.buf + HEADER_MAGIC_SIZE + 2)) - return XZ_DATA_ERROR; + if (xz_crc32(s->temp.buf + HEADER_MAGIC_SIZE, 2, 0) + != get_le32(s->temp.buf + HEADER_MAGIC_SIZE + 2)) + return XZ_DATA_ERROR; - if (s->temp.buf[HEADER_MAGIC_SIZE] != 0) - return XZ_OPTIONS_ERROR; + if (s->temp.buf[HEADER_MAGIC_SIZE] != 0) + return XZ_OPTIONS_ERROR; - /* - * Of integrity checks, we support none (Check ID = 0), - * CRC32 (Check ID = 1), and optionally CRC64 (Check ID = 4). - * However, if XZ_DEC_ANY_CHECK is defined, we will accept other - * check types too, but then the check won't be verified and - * a warning (XZ_UNSUPPORTED_CHECK) will be given. - */ - s->check_type = s->temp.buf[HEADER_MAGIC_SIZE + 1]; + /* + * Of integrity checks, we support none (Check ID = 0), + * CRC32 (Check ID = 1), and optionally CRC64 (Check ID = 4). + * However, if XZ_DEC_ANY_CHECK is defined, we will accept other + * check types too, but then the check won't be verified and + * a warning (XZ_UNSUPPORTED_CHECK) will be given. + */ + s->check_type = s->temp.buf[HEADER_MAGIC_SIZE + 1]; #ifdef XZ_DEC_ANY_CHECK - if (s->check_type > XZ_CHECK_MAX) - return XZ_OPTIONS_ERROR; + if (s->check_type > XZ_CHECK_MAX) + return XZ_OPTIONS_ERROR; - if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) - return XZ_UNSUPPORTED_CHECK; + if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) + return XZ_UNSUPPORTED_CHECK; #else - if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) - return XZ_OPTIONS_ERROR; + if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)) + return XZ_OPTIONS_ERROR; #endif - return XZ_OK; + return XZ_OK; } /* Decode the Stream Footer field (the last 12 bytes of the .xz Stream) */ static enum xz_ret dec_stream_footer(struct xz_dec *s) { - if (!memeq(s->temp.buf + 10, FOOTER_MAGIC, FOOTER_MAGIC_SIZE)) - return XZ_DATA_ERROR; + if (!memeq(s->temp.buf + 10, FOOTER_MAGIC, FOOTER_MAGIC_SIZE)) + return XZ_DATA_ERROR; - if (xz_crc32(s->temp.buf + 4, 6, 0) != get_le32(s->temp.buf)) - return XZ_DATA_ERROR; + if (xz_crc32(s->temp.buf + 4, 6, 0) != get_le32(s->temp.buf)) + return XZ_DATA_ERROR; - /* - * Validate Backward Size. Note that we never added the size of the - * Index CRC32 field to s->index.size, thus we use s->index.size / 4 - * instead of s->index.size / 4 - 1. - */ - if ((s->index.size >> 2) != get_le32(s->temp.buf + 4)) - return XZ_DATA_ERROR; + /* + * Validate Backward Size. Note that we never added the size of the + * Index CRC32 field to s->index.size, thus we use s->index.size / 4 + * instead of s->index.size / 4 - 1. + */ + if ((s->index.size >> 2) != get_le32(s->temp.buf + 4)) + return XZ_DATA_ERROR; - if (s->temp.buf[8] != 0 || s->temp.buf[9] != s->check_type) - return XZ_DATA_ERROR; + if (s->temp.buf[8] != 0 || s->temp.buf[9] != s->check_type) + return XZ_DATA_ERROR; - /* - * Use XZ_STREAM_END instead of XZ_OK to be more convenient - * for the caller. - */ - return XZ_STREAM_END; + /* + * Use XZ_STREAM_END instead of XZ_OK to be more convenient + * for the caller. + */ + return XZ_STREAM_END; } /* Decode the Block Header and initialize the filter chain. */ static enum xz_ret dec_block_header(struct xz_dec *s) { - enum xz_ret ret; + enum xz_ret ret; - /* - * Validate the CRC32. We know that the temp buffer is at least - * eight bytes so this is safe. - */ - s->temp.size -= 4; - if (xz_crc32(s->temp.buf, s->temp.size, 0) - != get_le32(s->temp.buf + s->temp.size)) - return XZ_DATA_ERROR; + /* + * Validate the CRC32. We know that the temp buffer is at least + * eight bytes so this is safe. + */ + s->temp.size -= 4; + if (xz_crc32(s->temp.buf, s->temp.size, 0) + != get_le32(s->temp.buf + s->temp.size)) + return XZ_DATA_ERROR; - s->temp.pos = 2; + s->temp.pos = 2; - /* - * Catch unsupported Block Flags. We support only one or two filters - * in the chain, so we catch that with the same test. - */ + /* + * Catch unsupported Block Flags. We support only one or two filters + * in the chain, so we catch that with the same test. + */ #ifdef XZ_DEC_BCJ - if (s->temp.buf[1] & 0x3E) + if (s->temp.buf[1] & 0x3E) #else - if (s->temp.buf[1] & 0x3F) + if (s->temp.buf[1] & 0x3F) #endif - return XZ_OPTIONS_ERROR; + return XZ_OPTIONS_ERROR; - /* Compressed Size */ - if (s->temp.buf[1] & 0x40) { - if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) - != XZ_STREAM_END) - return XZ_DATA_ERROR; + /* Compressed Size */ + if (s->temp.buf[1] & 0x40) { + if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) + != XZ_STREAM_END) + return XZ_DATA_ERROR; - s->block_header.compressed = s->vli; - } else { - s->block_header.compressed = VLI_UNKNOWN; - } + s->block_header.compressed = s->vli; + } else { + s->block_header.compressed = VLI_UNKNOWN; + } - /* Uncompressed Size */ - if (s->temp.buf[1] & 0x80) { - if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) - != XZ_STREAM_END) - return XZ_DATA_ERROR; + /* Uncompressed Size */ + if (s->temp.buf[1] & 0x80) { + if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size) + != XZ_STREAM_END) + return XZ_DATA_ERROR; - s->block_header.uncompressed = s->vli; - } else { - s->block_header.uncompressed = VLI_UNKNOWN; - } + s->block_header.uncompressed = s->vli; + } else { + s->block_header.uncompressed = VLI_UNKNOWN; + } #ifdef XZ_DEC_BCJ - /* If there are two filters, the first one must be a BCJ filter. */ - s->bcj_active = s->temp.buf[1] & 0x01; - if (s->bcj_active) { - if (s->temp.size - s->temp.pos < 2) - return XZ_OPTIONS_ERROR; + /* If there are two filters, the first one must be a BCJ filter. */ + s->bcj_active = s->temp.buf[1] & 0x01; + if (s->bcj_active) { + if (s->temp.size - s->temp.pos < 2) + return XZ_OPTIONS_ERROR; - ret = xz_dec_bcj_reset(s->bcj, s->temp.buf[s->temp.pos++]); - if (ret != XZ_OK) - return ret; + ret = xz_dec_bcj_reset(s->bcj, s->temp.buf[s->temp.pos++]); + if (ret != XZ_OK) + return ret; - /* - * We don't support custom start offset, - * so Size of Properties must be zero. - */ - if (s->temp.buf[s->temp.pos++] != 0x00) - return XZ_OPTIONS_ERROR; - } + /* + * We don't support custom start offset, + * so Size of Properties must be zero. + */ + if (s->temp.buf[s->temp.pos++] != 0x00) + return XZ_OPTIONS_ERROR; + } #endif - /* Valid Filter Flags always take at least two bytes. */ - if (s->temp.size - s->temp.pos < 2) - return XZ_DATA_ERROR; + /* Valid Filter Flags always take at least two bytes. */ + if (s->temp.size - s->temp.pos < 2) + return XZ_DATA_ERROR; - /* Filter ID = LZMA2 */ - if (s->temp.buf[s->temp.pos++] != 0x21) - return XZ_OPTIONS_ERROR; + /* Filter ID = LZMA2 */ + if (s->temp.buf[s->temp.pos++] != 0x21) + return XZ_OPTIONS_ERROR; - /* Size of Properties = 1-byte Filter Properties */ - if (s->temp.buf[s->temp.pos++] != 0x01) - return XZ_OPTIONS_ERROR; + /* Size of Properties = 1-byte Filter Properties */ + if (s->temp.buf[s->temp.pos++] != 0x01) + return XZ_OPTIONS_ERROR; - /* Filter Properties contains LZMA2 dictionary size. */ - if (s->temp.size - s->temp.pos < 1) - return XZ_DATA_ERROR; + /* Filter Properties contains LZMA2 dictionary size. */ + if (s->temp.size - s->temp.pos < 1) + return XZ_DATA_ERROR; - ret = xz_dec_lzma2_reset(s->lzma2, s->temp.buf[s->temp.pos++]); - if (ret != XZ_OK) - return ret; + ret = xz_dec_lzma2_reset(s->lzma2, s->temp.buf[s->temp.pos++]); + if (ret != XZ_OK) + return ret; - /* The rest must be Header Padding. */ - while (s->temp.pos < s->temp.size) - if (s->temp.buf[s->temp.pos++] != 0x00) - return XZ_OPTIONS_ERROR; + /* The rest must be Header Padding. */ + while (s->temp.pos < s->temp.size) + if (s->temp.buf[s->temp.pos++] != 0x00) + return XZ_OPTIONS_ERROR; - s->temp.pos = 0; - s->block.compressed = 0; - s->block.uncompressed = 0; + s->temp.pos = 0; + s->block.compressed = 0; + s->block.uncompressed = 0; - return XZ_OK; + return XZ_OK; } static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) { - enum xz_ret ret; + enum xz_ret ret; - /* - * Store the start position for the case when we are in the middle - * of the Index field. - */ - s->in_start = b->in_pos; + /* + * Store the start position for the case when we are in the middle + * of the Index field. + */ + s->in_start = b->in_pos; - while (true) { - switch (s->sequence) { - case SEQ_STREAM_HEADER: - /* - * Stream Header is copied to s->temp, and then - * decoded from there. This way if the caller - * gives us only little input at a time, we can - * still keep the Stream Header decoding code - * simple. Similar approach is used in many places - * in this file. - */ - if (!fill_temp(s, b)) - return XZ_OK; + while (true) { + switch (s->sequence) { + case SEQ_STREAM_HEADER: + /* + * Stream Header is copied to s->temp, and then + * decoded from there. This way if the caller + * gives us only little input at a time, we can + * still keep the Stream Header decoding code + * simple. Similar approach is used in many places + * in this file. + */ + if (!fill_temp(s, b)) + return XZ_OK; - /* - * If dec_stream_header() returns - * XZ_UNSUPPORTED_CHECK, it is still possible - * to continue decoding if working in multi-call - * mode. Thus, update s->sequence before calling - * dec_stream_header(). - */ - s->sequence = SEQ_BLOCK_START; + /* + * If dec_stream_header() returns + * XZ_UNSUPPORTED_CHECK, it is still possible + * to continue decoding if working in multi-call + * mode. Thus, update s->sequence before calling + * dec_stream_header(). + */ + s->sequence = SEQ_BLOCK_START; - ret = dec_stream_header(s); - if (ret != XZ_OK) - return ret; + ret = dec_stream_header(s); + if (ret != XZ_OK) + return ret; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_BLOCK_START: - /* We need one byte of input to continue. */ - if (b->in_pos == b->in_size) - return XZ_OK; + case SEQ_BLOCK_START: + /* We need one byte of input to continue. */ + if (b->in_pos == b->in_size) + return XZ_OK; - /* See if this is the beginning of the Index field. */ - if (b->in[b->in_pos] == 0) { - s->in_start = b->in_pos++; - s->sequence = SEQ_INDEX; - break; - } + /* See if this is the beginning of the Index field. */ + if (b->in[b->in_pos] == 0) { + s->in_start = b->in_pos++; + s->sequence = SEQ_INDEX; + break; + } - /* - * Calculate the size of the Block Header and - * prepare to decode it. - */ - s->block_header.size - = ((uint32_t)b->in[b->in_pos] + 1) * 4; + /* + * Calculate the size of the Block Header and + * prepare to decode it. + */ + s->block_header.size + = ((uint32_t)b->in[b->in_pos] + 1) * 4; - s->temp.size = s->block_header.size; - s->temp.pos = 0; - s->sequence = SEQ_BLOCK_HEADER; + s->temp.size = s->block_header.size; + s->temp.pos = 0; + s->sequence = SEQ_BLOCK_HEADER; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_BLOCK_HEADER: - if (!fill_temp(s, b)) - return XZ_OK; + case SEQ_BLOCK_HEADER: + if (!fill_temp(s, b)) + return XZ_OK; - ret = dec_block_header(s); - if (ret != XZ_OK) - return ret; + ret = dec_block_header(s); + if (ret != XZ_OK) + return ret; - s->sequence = SEQ_BLOCK_UNCOMPRESS; + s->sequence = SEQ_BLOCK_UNCOMPRESS; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_BLOCK_UNCOMPRESS: - ret = dec_block(s, b); - if (ret != XZ_STREAM_END) - return ret; + case SEQ_BLOCK_UNCOMPRESS: + ret = dec_block(s, b); + if (ret != XZ_STREAM_END) + return ret; - s->sequence = SEQ_BLOCK_PADDING; + s->sequence = SEQ_BLOCK_PADDING; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_BLOCK_PADDING: - /* - * Size of Compressed Data + Block Padding - * must be a multiple of four. We don't need - * s->block.compressed for anything else - * anymore, so we use it here to test the size - * of the Block Padding field. - */ - while (s->block.compressed & 3) { - if (b->in_pos == b->in_size) - return XZ_OK; + case SEQ_BLOCK_PADDING: + /* + * Size of Compressed Data + Block Padding + * must be a multiple of four. We don't need + * s->block.compressed for anything else + * anymore, so we use it here to test the size + * of the Block Padding field. + */ + while (s->block.compressed & 3) { + if (b->in_pos == b->in_size) + return XZ_OK; - if (b->in[b->in_pos++] != 0) - return XZ_DATA_ERROR; + if (b->in[b->in_pos++] != 0) + return XZ_DATA_ERROR; - ++s->block.compressed; - } + ++s->block.compressed; + } - s->sequence = SEQ_BLOCK_CHECK; + s->sequence = SEQ_BLOCK_CHECK; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_BLOCK_CHECK: - if (s->check_type == XZ_CHECK_CRC32) { - ret = crc_validate(s, b, 32); - if (ret != XZ_STREAM_END) - return ret; - } - else if (IS_CRC64(s->check_type)) { - ret = crc_validate(s, b, 64); - if (ret != XZ_STREAM_END) - return ret; - } + case SEQ_BLOCK_CHECK: + if (s->check_type == XZ_CHECK_CRC32) { + ret = crc_validate(s, b, 32); + if (ret != XZ_STREAM_END) + return ret; + } + else if (IS_CRC64(s->check_type)) { + ret = crc_validate(s, b, 64); + if (ret != XZ_STREAM_END) + return ret; + } #ifdef XZ_DEC_ANY_CHECK - else if (!check_skip(s, b)) { - return XZ_OK; - } + else if (!check_skip(s, b)) { + return XZ_OK; + } #endif - s->sequence = SEQ_BLOCK_START; - break; + s->sequence = SEQ_BLOCK_START; + break; - case SEQ_INDEX: - ret = dec_index(s, b); - if (ret != XZ_STREAM_END) - return ret; + case SEQ_INDEX: + ret = dec_index(s, b); + if (ret != XZ_STREAM_END) + return ret; - s->sequence = SEQ_INDEX_PADDING; + s->sequence = SEQ_INDEX_PADDING; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_INDEX_PADDING: - while ((s->index.size + (b->in_pos - s->in_start)) - & 3) { - if (b->in_pos == b->in_size) { - index_update(s, b); - return XZ_OK; - } + case SEQ_INDEX_PADDING: + while ((s->index.size + (b->in_pos - s->in_start)) + & 3) { + if (b->in_pos == b->in_size) { + index_update(s, b); + return XZ_OK; + } - if (b->in[b->in_pos++] != 0) - return XZ_DATA_ERROR; - } + if (b->in[b->in_pos++] != 0) + return XZ_DATA_ERROR; + } - /* Finish the CRC32 value and Index size. */ - index_update(s, b); + /* Finish the CRC32 value and Index size. */ + index_update(s, b); - /* Compare the hashes to validate the Index field. */ - if (!memeq(&s->block.hash, &s->index.hash, - sizeof(s->block.hash))) - return XZ_DATA_ERROR; + /* Compare the hashes to validate the Index field. */ + if (!memeq(&s->block.hash, &s->index.hash, + sizeof(s->block.hash))) + return XZ_DATA_ERROR; - s->sequence = SEQ_INDEX_CRC32; + s->sequence = SEQ_INDEX_CRC32; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_INDEX_CRC32: - ret = crc_validate(s, b, 32); - if (ret != XZ_STREAM_END) - return ret; + case SEQ_INDEX_CRC32: + ret = crc_validate(s, b, 32); + if (ret != XZ_STREAM_END) + return ret; - s->temp.size = STREAM_HEADER_SIZE; - s->sequence = SEQ_STREAM_FOOTER; + s->temp.size = STREAM_HEADER_SIZE; + s->sequence = SEQ_STREAM_FOOTER; - /* Fall through */ + /* Fall through */ __attribute__ ((fallthrough)); - case SEQ_STREAM_FOOTER: - if (!fill_temp(s, b)) - return XZ_OK; + case SEQ_STREAM_FOOTER: + if (!fill_temp(s, b)) + return XZ_OK; - return dec_stream_footer(s); - default: - break; - } - } + return dec_stream_footer(s); + default: + break; + } + } - /* Never reached */ + /* Never reached */ } /* @@ -787,89 +787,89 @@ static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b) */ XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b) { - size_t in_start; - size_t out_start; - enum xz_ret ret; + size_t in_start; + size_t out_start; + enum xz_ret ret; - if (DEC_IS_SINGLE(s->mode)) - xz_dec_reset(s); + if (DEC_IS_SINGLE(s->mode)) + xz_dec_reset(s); - in_start = b->in_pos; - out_start = b->out_pos; - ret = dec_main(s, b); + in_start = b->in_pos; + out_start = b->out_pos; + ret = dec_main(s, b); - if (DEC_IS_SINGLE(s->mode)) { - if (ret == XZ_OK) - ret = b->in_pos == b->in_size - ? XZ_DATA_ERROR : XZ_BUF_ERROR; + if (DEC_IS_SINGLE(s->mode)) { + if (ret == XZ_OK) + ret = b->in_pos == b->in_size + ? XZ_DATA_ERROR : XZ_BUF_ERROR; - if (ret != XZ_STREAM_END) { - b->in_pos = in_start; - b->out_pos = out_start; - } + if (ret != XZ_STREAM_END) { + b->in_pos = in_start; + b->out_pos = out_start; + } - } else if (ret == XZ_OK && in_start == b->in_pos - && out_start == b->out_pos) { - if (s->allow_buf_error) - ret = XZ_BUF_ERROR; + } else if (ret == XZ_OK && in_start == b->in_pos + && out_start == b->out_pos) { + if (s->allow_buf_error) + ret = XZ_BUF_ERROR; - s->allow_buf_error = true; - } else { - s->allow_buf_error = false; - } + s->allow_buf_error = true; + } else { + s->allow_buf_error = false; + } - return ret; + return ret; } XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32_t dict_max) { - struct xz_dec *s = kmalloc(sizeof(*s), GFP_KERNEL); - if (s == NULL) - return NULL; + struct xz_dec *s = kmalloc(sizeof(*s), GFP_KERNEL); + if (s == NULL) + return NULL; - s->mode = mode; + s->mode = mode; #ifdef XZ_DEC_BCJ - s->bcj = xz_dec_bcj_create(DEC_IS_SINGLE(mode)); - if (s->bcj == NULL) - goto error_bcj; + s->bcj = xz_dec_bcj_create(DEC_IS_SINGLE(mode)); + if (s->bcj == NULL) + goto error_bcj; #endif - s->lzma2 = xz_dec_lzma2_create(mode, dict_max); - if (s->lzma2 == NULL) - goto error_lzma2; + s->lzma2 = xz_dec_lzma2_create(mode, dict_max); + if (s->lzma2 == NULL) + goto error_lzma2; - xz_dec_reset(s); - return s; + xz_dec_reset(s); + return s; error_lzma2: #ifdef XZ_DEC_BCJ - xz_dec_bcj_end(s->bcj); + xz_dec_bcj_end(s->bcj); error_bcj: #endif - kfree(s); - return NULL; + kfree(s); + return NULL; } XZ_EXTERN void xz_dec_reset(struct xz_dec *s) { - s->sequence = SEQ_STREAM_HEADER; - s->allow_buf_error = false; - s->pos = 0; - s->crc = 0; - memzero(&s->block, sizeof(s->block)); - memzero(&s->index, sizeof(s->index)); - s->temp.pos = 0; - s->temp.size = STREAM_HEADER_SIZE; + s->sequence = SEQ_STREAM_HEADER; + s->allow_buf_error = false; + s->pos = 0; + s->crc = 0; + memzero(&s->block, sizeof(s->block)); + memzero(&s->index, sizeof(s->index)); + s->temp.pos = 0; + s->temp.size = STREAM_HEADER_SIZE; } XZ_EXTERN void xz_dec_end(struct xz_dec *s) { - if (s != NULL) { - xz_dec_lzma2_end(s->lzma2); + if (s != NULL) { + xz_dec_lzma2_end(s->lzma2); #ifdef XZ_DEC_BCJ - xz_dec_bcj_end(s->bcj); + xz_dec_bcj_end(s->bcj); #endif - kfree(s); - } + kfree(s); + } } diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_test.c b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_test.c index da28a19d..275aa32f 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_test.c +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_dec_test.c @@ -50,9 +50,9 @@ static uint8_t buffer_out[1024]; * A few of the fields are never modified so we initialize them here. */ static struct xz_buf buffers = { - .in = buffer_in, - .out = buffer_out, - .out_size = sizeof(buffer_out) + .in = buffer_in, + .out = buffer_out, + .out_size = sizeof(buffer_out) }; /* @@ -63,32 +63,32 @@ static uint32_t crc; static int xz_dec_test_open(struct inode *i, struct file *f) { - if (device_is_open) - return -EBUSY; + if (device_is_open) + return -EBUSY; - device_is_open = true; + device_is_open = true; - xz_dec_reset(state); - ret = XZ_OK; - crc = 0xFFFFFFFF; + xz_dec_reset(state); + ret = XZ_OK; + crc = 0xFFFFFFFF; - buffers.in_pos = 0; - buffers.in_size = 0; - buffers.out_pos = 0; + buffers.in_pos = 0; + buffers.in_size = 0; + buffers.out_pos = 0; - printk(KERN_INFO DEVICE_NAME ": opened\n"); - return 0; + printk(KERN_INFO DEVICE_NAME ": opened\n"); + return 0; } static int xz_dec_test_release(struct inode *i, struct file *f) { - device_is_open = false; + device_is_open = false; - if (ret == XZ_OK) - printk(KERN_INFO DEVICE_NAME ": input was truncated\n"); + if (ret == XZ_OK) + printk(KERN_INFO DEVICE_NAME ": input was truncated\n"); - printk(KERN_INFO DEVICE_NAME ": closed\n"); - return 0; + printk(KERN_INFO DEVICE_NAME ": closed\n"); + return 0; } /* @@ -100,110 +100,110 @@ static int xz_dec_test_release(struct inode *i, struct file *f) * after the first Stream is considered to be garbage. */ static ssize_t xz_dec_test_write(struct file *file, const char __user *buf, - size_t size, loff_t *pos) + size_t size, loff_t *pos) { - size_t remaining; + size_t remaining; - if (ret != XZ_OK) { - if (size > 0) - printk(KERN_INFO DEVICE_NAME ": %zu bytes of " - "garbage at the end of the file\n", - size); + if (ret != XZ_OK) { + if (size > 0) + printk(KERN_INFO DEVICE_NAME ": %zu bytes of " + "garbage at the end of the file\n", + size); - return -ENOSPC; - } + return -ENOSPC; + } - printk(KERN_INFO DEVICE_NAME ": decoding %zu bytes of input\n", - size); + printk(KERN_INFO DEVICE_NAME ": decoding %zu bytes of input\n", + size); - remaining = size; - while ((remaining > 0 || buffers.out_pos == buffers.out_size) - && ret == XZ_OK) { - if (buffers.in_pos == buffers.in_size) { - buffers.in_pos = 0; - buffers.in_size = min(remaining, sizeof(buffer_in)); - if (copy_from_user(buffer_in, buf, buffers.in_size)) - return -EFAULT; + remaining = size; + while ((remaining > 0 || buffers.out_pos == buffers.out_size) + && ret == XZ_OK) { + if (buffers.in_pos == buffers.in_size) { + buffers.in_pos = 0; + buffers.in_size = min(remaining, sizeof(buffer_in)); + if (copy_from_user(buffer_in, buf, buffers.in_size)) + return -EFAULT; - buf += buffers.in_size; - remaining -= buffers.in_size; - } + buf += buffers.in_size; + remaining -= buffers.in_size; + } - buffers.out_pos = 0; - ret = xz_dec_run(state, &buffers); - crc = crc32(crc, buffer_out, buffers.out_pos); - } + buffers.out_pos = 0; + ret = xz_dec_run(state, &buffers); + crc = crc32(crc, buffer_out, buffers.out_pos); + } - switch (ret) { - case XZ_OK: - printk(KERN_INFO DEVICE_NAME ": XZ_OK\n"); - return size; + switch (ret) { + case XZ_OK: + printk(KERN_INFO DEVICE_NAME ": XZ_OK\n"); + return size; - case XZ_STREAM_END: - printk(KERN_INFO DEVICE_NAME ": XZ_STREAM_END, " - "CRC32 = 0x%08X\n", ~crc); - return size - remaining - (buffers.in_size - buffers.in_pos); + case XZ_STREAM_END: + printk(KERN_INFO DEVICE_NAME ": XZ_STREAM_END, " + "CRC32 = 0x%08X\n", ~crc); + return size - remaining - (buffers.in_size - buffers.in_pos); - case XZ_MEMLIMIT_ERROR: - printk(KERN_INFO DEVICE_NAME ": XZ_MEMLIMIT_ERROR\n"); - break; + case XZ_MEMLIMIT_ERROR: + printk(KERN_INFO DEVICE_NAME ": XZ_MEMLIMIT_ERROR\n"); + break; - case XZ_FORMAT_ERROR: - printk(KERN_INFO DEVICE_NAME ": XZ_FORMAT_ERROR\n"); - break; + case XZ_FORMAT_ERROR: + printk(KERN_INFO DEVICE_NAME ": XZ_FORMAT_ERROR\n"); + break; - case XZ_OPTIONS_ERROR: - printk(KERN_INFO DEVICE_NAME ": XZ_OPTIONS_ERROR\n"); - break; + case XZ_OPTIONS_ERROR: + printk(KERN_INFO DEVICE_NAME ": XZ_OPTIONS_ERROR\n"); + break; - case XZ_DATA_ERROR: - printk(KERN_INFO DEVICE_NAME ": XZ_DATA_ERROR\n"); - break; + case XZ_DATA_ERROR: + printk(KERN_INFO DEVICE_NAME ": XZ_DATA_ERROR\n"); + break; - case XZ_BUF_ERROR: - printk(KERN_INFO DEVICE_NAME ": XZ_BUF_ERROR\n"); - break; + case XZ_BUF_ERROR: + printk(KERN_INFO DEVICE_NAME ": XZ_BUF_ERROR\n"); + break; - default: - printk(KERN_INFO DEVICE_NAME ": Bug detected!\n"); - break; - } + default: + printk(KERN_INFO DEVICE_NAME ": Bug detected!\n"); + break; + } - return -EIO; + return -EIO; } /* Allocate the XZ decoder state and register the character device. */ static int __init xz_dec_test_init(void) { - static const struct file_operations fileops = { - .owner = THIS_MODULE, - .open = &xz_dec_test_open, - .release = &xz_dec_test_release, - .write = &xz_dec_test_write - }; + static const struct file_operations fileops = { + .owner = THIS_MODULE, + .open = &xz_dec_test_open, + .release = &xz_dec_test_release, + .write = &xz_dec_test_write + }; - state = xz_dec_init(XZ_PREALLOC, DICT_MAX); - if (state == NULL) - return -ENOMEM; + state = xz_dec_init(XZ_PREALLOC, DICT_MAX); + if (state == NULL) + return -ENOMEM; - device_major = register_chrdev(0, DEVICE_NAME, &fileops); - if (device_major < 0) { - xz_dec_end(state); - return device_major; - } + device_major = register_chrdev(0, DEVICE_NAME, &fileops); + if (device_major < 0) { + xz_dec_end(state); + return device_major; + } - printk(KERN_INFO DEVICE_NAME ": module loaded\n"); - printk(KERN_INFO DEVICE_NAME ": Create a device node with " - "'mknod " DEVICE_NAME " c %d 0' and write .xz files " - "to it.\n", device_major); - return 0; + printk(KERN_INFO DEVICE_NAME ": module loaded\n"); + printk(KERN_INFO DEVICE_NAME ": Create a device node with " + "'mknod " DEVICE_NAME " c %d 0' and write .xz files " + "to it.\n", device_major); + return 0; } static void __exit xz_dec_test_exit(void) { - unregister_chrdev(device_major, DEVICE_NAME); - xz_dec_end(state); - printk(KERN_INFO DEVICE_NAME ": module unloaded\n"); + unregister_chrdev(device_major, DEVICE_NAME); + xz_dec_end(state); + printk(KERN_INFO DEVICE_NAME ": module unloaded\n"); } module_init(xz_dec_test_init); diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_decompress.c b/components/bl602/bl602_std/bl602_std/Common/xz/xz_decompress.c index 9991e510..777b9b19 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_decompress.c +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_decompress.c @@ -25,34 +25,34 @@ int xz_uncompress_init(struct xz_buf *stream, uint8_t *sbuf, uint8_t *dbuf) stream->out_pos = 0; stream->out_size = 0; - return 0; + return 0; } int xz_uncompress_stream(struct xz_buf *stream, uint8_t *sbuf, uint32_t slen, - uint8_t *dbuf, uint32_t dlen, uint32_t *decomp_len) + uint8_t *dbuf, uint32_t dlen, uint32_t *decomp_len) { - int status; - *decomp_len = 0; + int status; + *decomp_len = 0; - if (stream->in_pos == stream->in_size) { - stream->in_size = slen; - stream->in_pos = 0; - } + if (stream->in_pos == stream->in_size) { + stream->in_size = slen; + stream->in_pos = 0; + } - if (stream->out_pos == stream->out_size) { - stream->out_size = dlen; - stream->out_pos = 0; - } + if (stream->out_pos == stream->out_size) { + stream->out_size = dlen; + stream->out_pos = 0; + } - status = xz_dec_run(s, stream); + status = xz_dec_run(s, stream); - if ((status == XZ_STREAM_END) || (stream->out_pos == stream->out_size)) - *decomp_len = stream->out_pos; + if ((status == XZ_STREAM_END) || (stream->out_pos == stream->out_size)) + *decomp_len = stream->out_pos; - return status; + return status; } void xz_uncompress_end() { - xz_dec_end(s); + xz_dec_end(s); } diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_lzma2.h b/components/bl602/bl602_std/bl602_std/Common/xz/xz_lzma2.h index 071d67be..aa05d956 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_lzma2.h +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_lzma2.h @@ -40,18 +40,18 @@ * either short or long repeated match, and NONLIT means any non-literal. */ enum lzma_state { - STATE_LIT_LIT, - STATE_MATCH_LIT_LIT, - STATE_REP_LIT_LIT, - STATE_SHORTREP_LIT_LIT, - STATE_MATCH_LIT, - STATE_REP_LIT, - STATE_SHORTREP_LIT, - STATE_LIT_MATCH, - STATE_LIT_LONGREP, - STATE_LIT_SHORTREP, - STATE_NONLIT_MATCH, - STATE_NONLIT_REP + STATE_LIT_LIT, + STATE_MATCH_LIT_LIT, + STATE_REP_LIT_LIT, + STATE_SHORTREP_LIT_LIT, + STATE_MATCH_LIT, + STATE_REP_LIT, + STATE_SHORTREP_LIT, + STATE_LIT_MATCH, + STATE_LIT_LONGREP, + STATE_LIT_SHORTREP, + STATE_NONLIT_MATCH, + STATE_NONLIT_REP }; /* Total number of states */ @@ -63,36 +63,36 @@ enum lzma_state { /* Indicate that the latest symbol was a literal. */ static inline void lzma_state_literal(enum lzma_state *state) { - if (*state <= STATE_SHORTREP_LIT_LIT) - *state = STATE_LIT_LIT; - else if (*state <= STATE_LIT_SHORTREP) - *state -= 3; - else - *state -= 6; + if (*state <= STATE_SHORTREP_LIT_LIT) + *state = STATE_LIT_LIT; + else if (*state <= STATE_LIT_SHORTREP) + *state -= 3; + else + *state -= 6; } /* Indicate that the latest symbol was a match. */ static inline void lzma_state_match(enum lzma_state *state) { - *state = *state < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH; + *state = *state < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH; } /* Indicate that the latest state was a long repeated match. */ static inline void lzma_state_long_rep(enum lzma_state *state) { - *state = *state < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP; + *state = *state < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP; } /* Indicate that the latest symbol was a short match. */ static inline void lzma_state_short_rep(enum lzma_state *state) { - *state = *state < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP; + *state = *state < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP; } /* Test if the previous symbol was a literal. */ static inline bool lzma_state_is_literal(enum lzma_state state) { - return state < LIT_STATES; + return state < LIT_STATES; } /* Each literal coder is divided in three sections: @@ -146,8 +146,8 @@ static inline bool lzma_state_is_literal(enum lzma_state state) */ static inline uint32_t lzma_get_dist_state(uint32_t len) { - return len < DIST_STATES + MATCH_LEN_MIN - ? len - MATCH_LEN_MIN : DIST_STATES - 1; + return len < DIST_STATES + MATCH_LEN_MIN + ? len - MATCH_LEN_MIN : DIST_STATES - 1; } /* diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_private.h b/components/bl602/bl602_std/bl602_std/Common/xz/xz_private.h index 482b90f3..77d52b41 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_private.h +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_private.h @@ -11,51 +11,51 @@ #define XZ_PRIVATE_H #ifdef __KERNEL__ -# include -# include -# include - /* XZ_PREBOOT may be defined only via decompress_unxz.c. */ -# ifndef XZ_PREBOOT -# include -# include -# include -# ifdef CONFIG_XZ_DEC_X86 -# define XZ_DEC_X86 -# endif -# ifdef CONFIG_XZ_DEC_POWERPC -# define XZ_DEC_POWERPC -# endif -# ifdef CONFIG_XZ_DEC_IA64 -# define XZ_DEC_IA64 -# endif -# ifdef CONFIG_XZ_DEC_ARM -# define XZ_DEC_ARM -# endif -# ifdef CONFIG_XZ_DEC_ARMTHUMB -# define XZ_DEC_ARMTHUMB -# endif -# ifdef CONFIG_XZ_DEC_SPARC -# define XZ_DEC_SPARC -# endif -# define memeq(a, b, size) (memcmp(a, b, size) == 0) -# define memzero(buf, size) memset(buf, 0, size) -# endif -# define get_le32(p) le32_to_cpup((const uint32_t *)(p)) +# include +# include +# include + /* XZ_PREBOOT may be defined only via decompress_unxz.c. */ +# ifndef XZ_PREBOOT +# include +# include +# include +# ifdef CONFIG_XZ_DEC_X86 +# define XZ_DEC_X86 +# endif +# ifdef CONFIG_XZ_DEC_POWERPC +# define XZ_DEC_POWERPC +# endif +# ifdef CONFIG_XZ_DEC_IA64 +# define XZ_DEC_IA64 +# endif +# ifdef CONFIG_XZ_DEC_ARM +# define XZ_DEC_ARM +# endif +# ifdef CONFIG_XZ_DEC_ARMTHUMB +# define XZ_DEC_ARMTHUMB +# endif +# ifdef CONFIG_XZ_DEC_SPARC +# define XZ_DEC_SPARC +# endif +# define memeq(a, b, size) (memcmp(a, b, size) == 0) +# define memzero(buf, size) memset(buf, 0, size) +# endif +# define get_le32(p) le32_to_cpup((const uint32_t *)(p)) #else - /* - * For userspace builds, use a separate header to define the required - * macros and functions. This makes it easier to adapt the code into - * different environments and avoids clutter in the Linux kernel tree. - */ -# include "xz_config.h" + /* + * For userspace builds, use a separate header to define the required + * macros and functions. This makes it easier to adapt the code into + * different environments and avoids clutter in the Linux kernel tree. + */ +# include "xz_config.h" #endif /* If no specific decoding mode is requested, enable support for all modes. */ #if !defined(XZ_DEC_SINGLE) && !defined(XZ_DEC_PREALLOC) \ - && !defined(XZ_DEC_DYNALLOC) -# define XZ_DEC_SINGLE -# define XZ_DEC_PREALLOC -# define XZ_DEC_DYNALLOC + && !defined(XZ_DEC_DYNALLOC) +# define XZ_DEC_SINGLE +# define XZ_DEC_PREALLOC +# define XZ_DEC_DYNALLOC #endif /* @@ -64,29 +64,29 @@ * false at compile time and thus allow the compiler to omit unneeded code. */ #ifdef XZ_DEC_SINGLE -# define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE) +# define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE) #else -# define DEC_IS_SINGLE(mode) (false) +# define DEC_IS_SINGLE(mode) (false) #endif #ifdef XZ_DEC_PREALLOC -# define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC) +# define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC) #else -# define DEC_IS_PREALLOC(mode) (false) +# define DEC_IS_PREALLOC(mode) (false) #endif #ifdef XZ_DEC_DYNALLOC -# define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC) +# define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC) #else -# define DEC_IS_DYNALLOC(mode) (false) +# define DEC_IS_DYNALLOC(mode) (false) #endif #if !defined(XZ_DEC_SINGLE) -# define DEC_IS_MULTI(mode) (true) +# define DEC_IS_MULTI(mode) (true) #elif defined(XZ_DEC_PREALLOC) || defined(XZ_DEC_DYNALLOC) -# define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE) +# define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE) #else -# define DEC_IS_MULTI(mode) (false) +# define DEC_IS_MULTI(mode) (false) #endif /* @@ -94,12 +94,12 @@ * XZ_DEC_BCJ is used to enable generic support for BCJ decoders. */ #ifndef XZ_DEC_BCJ -# if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) \ - || defined(XZ_DEC_IA64) || defined(XZ_DEC_ARM) \ - || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) \ - || defined(XZ_DEC_SPARC) -# define XZ_DEC_BCJ -# endif +# if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) \ + || defined(XZ_DEC_IA64) || defined(XZ_DEC_ARM) \ + || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) \ + || defined(XZ_DEC_SPARC) +# define XZ_DEC_BCJ +# endif #endif /* @@ -107,7 +107,7 @@ * before calling xz_dec_lzma2_run(). */ XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, - uint32_t dict_max); + uint32_t dict_max); /* * Decode the LZMA2 properties (one byte) and reset the decoder. Return @@ -116,11 +116,11 @@ XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode, * decoder doesn't support. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, - uint8_t props); + uint8_t props); /* Decode raw LZMA2 stream from b->in to b->out. */ XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s, - struct xz_buf *b); + struct xz_buf *b); /* Free the memory allocated for the LZMA2 decoder. */ XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s); @@ -146,8 +146,8 @@ XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id); * must be called directly. */ XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s, - struct xz_dec_lzma2 *lzma2, - struct xz_buf *b); + struct xz_dec_lzma2 *lzma2, + struct xz_buf *b); /* Free the memory allocated for the BCJ filters. */ #define xz_dec_bcj_end(s) kfree(s) diff --git a/components/bl602/bl602_std/bl602_std/Common/xz/xz_stream.h b/components/bl602/bl602_std/bl602_std/Common/xz/xz_stream.h index 66cb5a70..6c4f8cd2 100644 --- a/components/bl602/bl602_std/bl602_std/Common/xz/xz_stream.h +++ b/components/bl602/bl602_std/bl602_std/Common/xz/xz_stream.h @@ -11,10 +11,10 @@ #define XZ_STREAM_H #if defined(__KERNEL__) && !XZ_INTERNAL_CRC32 -# include -# undef crc32 -# define xz_crc32(buf, size, crc) \ - (~crc32_le(~(uint32_t)(crc), buf, size)) +# include +# undef crc32 +# define xz_crc32(buf, size, crc) \ + (~crc32_le(~(uint32_t)(crc), buf, size)) #endif /* @@ -50,10 +50,10 @@ typedef uint64_t vli_type; /* Integrity Check types */ enum xz_check { - XZ_CHECK_NONE = 0, - XZ_CHECK_CRC32 = 1, - XZ_CHECK_CRC64 = 4, - XZ_CHECK_SHA256 = 10 + XZ_CHECK_NONE = 0, + XZ_CHECK_CRC32 = 1, + XZ_CHECK_CRC64 = 4, + XZ_CHECK_SHA256 = 10 }; /* Maximum possible Check ID */ diff --git a/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/bl602.h b/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/bl602.h index af3f61bf..05bc302a 100644 --- a/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/bl602.h +++ b/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/bl602.h @@ -152,32 +152,32 @@ typedef enum /** * @brief BL602 Memory Map Definitions */ -#define BL602_FLASH_XIP_BASE 0x23000000 -#define BL602_FLASH_XIP_END (0x23000000+16*1024*1024) -#define BL602_FLASH_XIP_REMAP0_BASE 0x33000000 -#define BL602_FLASH_XIP_REMAP0_END (0x33000000+16*1024*1024) -#define BL602_FLASH_XIP_REMAP1_BASE 0x43000000 -#define BL602_FLASH_XIP_REMAP1_END (0x43000000+16*1024*1024) -#define BL602_FLASH_XIP_REMAP2_BASE 0x53000000 -#define BL602_FLASH_XIP_REMAP2_END (0x53000000+16*1024*1024) +#define BL602_FLASH_XIP_BASE 0x23000000 +#define BL602_FLASH_XIP_END (0x23000000+16*1024*1024) +#define BL602_FLASH_XIP_REMAP0_BASE 0x33000000 +#define BL602_FLASH_XIP_REMAP0_END (0x33000000+16*1024*1024) +#define BL602_FLASH_XIP_REMAP1_BASE 0x43000000 +#define BL602_FLASH_XIP_REMAP1_END (0x43000000+16*1024*1024) +#define BL602_FLASH_XIP_REMAP2_BASE 0x53000000 +#define BL602_FLASH_XIP_REMAP2_END (0x53000000+16*1024*1024) -#define BL602_WRAM_BASE 0x42020000 -#define BL602_WRAM_END (0x42020000+176*1024) -#define BL602_WRAM_REMAP0_BASE 0x22020000 -#define BL602_WRAM_REMAP0_END (0x22020000+176*1024) -#define BL602_WRAM_REMAP1_BASE 0x32020000 -#define BL602_WRAM_REMAP1_END (0x32020000+176*1024) -#define BL602_WRAM_REMAP2_BASE 0x52020000 -#define BL602_WRAM_REMAP2_END (0x52020000+176*1024) +#define BL602_WRAM_BASE 0x42020000 +#define BL602_WRAM_END (0x42020000+176*1024) +#define BL602_WRAM_REMAP0_BASE 0x22020000 +#define BL602_WRAM_REMAP0_END (0x22020000+176*1024) +#define BL602_WRAM_REMAP1_BASE 0x32020000 +#define BL602_WRAM_REMAP1_END (0x32020000+176*1024) +#define BL602_WRAM_REMAP2_BASE 0x52020000 +#define BL602_WRAM_REMAP2_END (0x52020000+176*1024) -#define BL602_TCM_BASE 0x22008000 -#define BL602_TCM_END (0x22008000+(96+176)*1024) -#define BL602_TCM_REMAP0_BASE 0x32008000 -#define BL602_TCM_REMAP0_END (0x32008000+(96+176)*1024) -#define BL602_TCM_REMAP1_BASE 0x42008000 -#define BL602_TCM_REMAP1_END (0x42008000+(96+176)*1024) -#define BL602_TCM_REMAP2_BASE 0x52008000 -#define BL602_TCM_REMAP2_END (0x52008000+(96+176)*1024) +#define BL602_TCM_BASE 0x22008000 +#define BL602_TCM_END (0x22008000+(96+176)*1024) +#define BL602_TCM_REMAP0_BASE 0x32008000 +#define BL602_TCM_REMAP0_END (0x32008000+(96+176)*1024) +#define BL602_TCM_REMAP1_BASE 0x42008000 +#define BL602_TCM_REMAP1_END (0x42008000+(96+176)*1024) +#define BL602_TCM_REMAP2_BASE 0x52008000 +#define BL602_TCM_REMAP2_END (0x52008000+(96+176)*1024) /*@} end of group Memory_Map_Section */ /* BL602 peripherals base address */ diff --git a/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/sec_dbg_reg.h b/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/sec_dbg_reg.h index 9bc28e0a..8fb66feb 100644 --- a/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/sec_dbg_reg.h +++ b/components/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals/sec_dbg_reg.h @@ -1,212 +1,212 @@ -/** - ****************************************************************************** - * @file sec_dbg_reg.h - * @version V1.2 - * @date 2019-11-04 - * @brief This file is the description of.IP register - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * 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. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * 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 __SEC_DBG_REG_H__ -#define __SEC_DBG_REG_H__ - -#include "bl602.h" - -/* 0x0 : sd_chip_id_low */ -#define SEC_DBG_SD_CHIP_ID_LOW_OFFSET (0x0) -#define SEC_DBG_SD_CHIP_ID_LOW SEC_DBG_SD_CHIP_ID_LOW -#define SEC_DBG_SD_CHIP_ID_LOW_POS (0U) -#define SEC_DBG_SD_CHIP_ID_LOW_LEN (32U) -#define SEC_DBG_SD_CHIP_ID_LOW_MSK (((1U<
© COPYRIGHT(c) 2019 Bouffalo Lab
+ * + * 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. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * 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 __SEC_DBG_REG_H__ +#define __SEC_DBG_REG_H__ + +#include "bl602.h" + +/* 0x0 : sd_chip_id_low */ +#define SEC_DBG_SD_CHIP_ID_LOW_OFFSET (0x0) +#define SEC_DBG_SD_CHIP_ID_LOW SEC_DBG_SD_CHIP_ID_LOW +#define SEC_DBG_SD_CHIP_ID_LOW_POS (0U) +#define SEC_DBG_SD_CHIP_ID_LOW_LEN (32U) +#define SEC_DBG_SD_CHIP_ID_LOW_MSK (((1U<
© COPYRIGHT(c) 2019 Bouffalo Lab
- * - * 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. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * 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 __TZC_NSEC_REG_H__ -#define __TZC_NSEC_REG_H__ - -#include "bl602.h" - -/* 0x40 : tzc_rom_ctrl */ -#define TZC_NSEC_TZC_ROM_CTRL_OFFSET (0x40) -#define TZC_NSEC_TZC_ROM0_R0_ID0_EN TZC_NSEC_TZC_ROM0_R0_ID0_EN -#define TZC_NSEC_TZC_ROM0_R0_ID0_EN_POS (0U) -#define TZC_NSEC_TZC_ROM0_R0_ID0_EN_LEN (1U) -#define TZC_NSEC_TZC_ROM0_R0_ID0_EN_MSK (((1U<
© COPYRIGHT(c) 2019 Bouffalo Lab
+ * + * 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. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * 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 __TZC_NSEC_REG_H__ +#define __TZC_NSEC_REG_H__ + +#include "bl602.h" + +/* 0x40 : tzc_rom_ctrl */ +#define TZC_NSEC_TZC_ROM_CTRL_OFFSET (0x40) +#define TZC_NSEC_TZC_ROM0_R0_ID0_EN TZC_NSEC_TZC_ROM0_R0_ID0_EN +#define TZC_NSEC_TZC_ROM0_R0_ID0_EN_POS (0U) +#define TZC_NSEC_TZC_ROM0_R0_ID0_EN_LEN (1U) +#define TZC_NSEC_TZC_ROM0_R0_ID0_EN_MSK (((1U<
© COPYRIGHT(c) 2020 Bouffalo Lab
- * - * 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. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * 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 __TZC_SEC_REG_H__ -#define __TZC_SEC_REG_H__ - -#include "bl602.h" - -/* 0x40 : tzc_rom_ctrl */ -#define TZC_SEC_TZC_ROM_CTRL_OFFSET (0x40) -#define TZC_SEC_TZC_ROM0_R0_ID0_EN TZC_SEC_TZC_ROM0_R0_ID0_EN -#define TZC_SEC_TZC_ROM0_R0_ID0_EN_POS (0U) -#define TZC_SEC_TZC_ROM0_R0_ID0_EN_LEN (1U) -#define TZC_SEC_TZC_ROM0_R0_ID0_EN_MSK (((1U<
© COPYRIGHT(c) 2020 Bouffalo Lab
+ * + * 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. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * 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 __TZC_SEC_REG_H__ +#define __TZC_SEC_REG_H__ + +#include "bl602.h" + +/* 0x40 : tzc_rom_ctrl */ +#define TZC_SEC_TZC_ROM_CTRL_OFFSET (0x40) +#define TZC_SEC_TZC_ROM0_R0_ID0_EN TZC_SEC_TZC_ROM0_R0_ID0_EN +#define TZC_SEC_TZC_ROM0_R0_ID0_EN_POS (0U) +#define TZC_SEC_TZC_ROM0_R0_ID0_EN_LEN (1U) +#define TZC_SEC_TZC_ROM0_R0_ID0_EN_MSK (((1U<> 24); - res &= 0xFF0000FF; /* only for sure */ - res |= ((value >> 8) & 0x0000FF00) | ((value << 8) & 0x00FF0000); - - return res; -} - -__attribute__((always_inline)) __STATIC_INLINE uint32_t __REV16(uint32_t value) -{ - return __builtin_bswap16(value); -} - -extern void clic_enable_interrupt (uint32_t source); -extern void clic_disable_interrupt ( uint32_t source); -extern void clic_set_pending(uint32_t source); -extern void clic_clear_pending(uint32_t source); - -#define NVIC_EnableIRQ clic_enable_interrupt - -#define NVIC_DisableIRQ clic_disable_interrupt - -#define NVIC_ClearPendingIRQ clic_clear_pending - -//#define __set_MSP(val) __ASM volatile ("lw sp,0(%0)":: "r"(val)) -#define __set_MSP(msp) __ASM volatile ("add sp, x0, %0":: "r"(msp)) - -#endif /* __CMSIS_COMPATIBLE_GCC_H */ +#ifndef __CMSIS_COMPATIBLE_GCC_H +#define __CMSIS_COMPATIBLE_GCC_H + +/* CMSIS compiler specific defines */ +#ifndef __ASM + #define __ASM __asm +#endif +#ifndef __INLINE + #define __INLINE inline +#endif +#ifndef __ALWAYS_INLINE + #define __ALWAYS_INLINE inline __attribute__((always_inline)) +#endif +#ifndef __STATIC_INLINE + #define __STATIC_INLINE static inline +#endif +#ifndef __NO_RETURN + #define __NO_RETURN __attribute__((noreturn)) +#endif +#ifndef __USED + #define __USED __attribute__((used)) +#endif +#ifndef __WEAK + #define __WEAK __attribute__((weak)) +#endif +#ifndef __PACKED + #define __PACKED __attribute__((packed, aligned(1))) +#endif +#ifndef __PACKED_STRUCT + #define __PACKED_STRUCT struct __attribute__((packed, aligned(1))) +#endif +#ifndef __PACKED_UNION + #define __PACKED_UNION union __attribute__((packed, aligned(1))) +#endif +#ifndef __IRQ + #define __IRQ __attribute__((interrupt)) +#endif +#ifndef __IRQ_ALIGN64 + #define __IRQ_ALIGN64 __attribute__((interrupt,aligned(64))) +#endif +#ifndef ALIGN4 +#define ALIGN4 __attribute((aligned (4))) +#endif +/** + \brief No Operation + \details No Operation does nothing. This instruction can be used for code alignment purposes. + */ +//__attribute__((always_inline)) __STATIC_INLINE void __NOP(void) +//{ +// __ASM volatile ("nop"); +//} +#define __NOP() __ASM volatile ("nop") /* This implementation generates debug information */ + +/** + \brief Wait For Interrupt + \details Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. + */ +//__attribute__((always_inline)) __STATIC_INLINE void __WFI(void) +//{ +// __ASM volatile ("wfi"); +//} +#define __WFI() __ASM volatile ("wfi") /* This implementation generates debug information */ + + +/** + \brief Wait For Event + \details Wait For Event is a hint instruction that permits the processor to enter + a low-power state until one of a number of events occurs. + */ +//__attribute__((always_inline)) __STATIC_INLINE void __WFE(void) +//{ +// __ASM volatile ("wfe"); +//} +#define __WFE() __ASM volatile ("wfe") /* This implementation generates debug information */ + + +/** + \brief Send Event + \details Send Event is a hint instruction. It causes an event to be signaled to the CPU. + */ +//__attribute__((always_inline)) __STATIC_INLINE void __SEV(void) +//{ +// __ASM volatile ("sev"); +//} +#define __SEV() __ASM volatile ("sev") /* This implementation generates debug information */ + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) +{ + __ASM volatile ("csrsi mstatus, 8"); +} + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void) +{ + __ASM volatile ("csrci mstatus, 8"); +} + +__attribute__((always_inline)) __STATIC_INLINE uint32_t __REV(uint32_t value) +{ + //return __builtin_bswap32(value); + uint32_t res = 0; + + res = (value << 24) | (value >> 24); + res &= 0xFF0000FF; /* only for sure */ + res |= ((value >> 8) & 0x0000FF00) | ((value << 8) & 0x00FF0000); + + return res; +} + +__attribute__((always_inline)) __STATIC_INLINE uint32_t __REV16(uint32_t value) +{ + return __builtin_bswap16(value); +} + +extern void clic_enable_interrupt (uint32_t source); +extern void clic_disable_interrupt ( uint32_t source); +extern void clic_set_pending(uint32_t source); +extern void clic_clear_pending(uint32_t source); + +#define NVIC_EnableIRQ clic_enable_interrupt + +#define NVIC_DisableIRQ clic_disable_interrupt + +#define NVIC_ClearPendingIRQ clic_clear_pending + +//#define __set_MSP(val) __ASM volatile ("lw sp,0(%0)":: "r"(val)) +#define __set_MSP(msp) __ASM volatile ("add sp, x0, %0":: "r"(msp)) + +#endif /* __CMSIS_COMPATIBLE_GCC_H */ diff --git a/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/bl602_startup.mk b/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/bl602_startup.mk index 3a028262..f52fc04f 100644 --- a/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/bl602_startup.mk +++ b/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/bl602_startup.mk @@ -9,7 +9,7 @@ STARTUP_MODULE_OUT_DIR:= $(TARGET_OUT_PATH)/startup # CFLAGS and included dirs for startup STARTUP_CFLAGS:= -STARTUP_INCLUDE:= -I$(MODULE_DIR)/BSP/RISCV/Device/Bouffalo/$(DEVICE)/Startup +STARTUP_INCLUDE:= -I$(MODULE_DIR)/BSP/RISCV/Device/Bouffalo/$(DEVICE)/Startup ifeq ($(BOOTROM),n) LOCAL_ASM_FILE:= GCC/entry.S @@ -18,14 +18,14 @@ STARTUP_INCLUDE += -I$(MODULE_DIR)/ChipTest/BootROM STARTUP_INCLUDE += -I$(MODULE_DIR)/ChipTest/BootROM/bl602port endif -startup_objs:= $(addprefix $(STARTUP_MODULE_OUT_DIR)/,$(subst .c,.o,$(LOCAL_SRCS_FILE))) +startup_objs:= $(addprefix $(STARTUP_MODULE_OUT_DIR)/,$(subst .c,.o,$(LOCAL_SRCS_FILE))) startup_objs+= $(addprefix $(STARTUP_MODULE_OUT_DIR)/,$(subst .S,.o,$(LOCAL_ASM_FILE))) $(STARTUP_MODULE_OUT_DIR)/%.o:$(STARTUP_MODULE_DIR)/%.c @mkdir -p $(dir $@) @echo "cc $<" $(AT)$(CC) -c $(GLOBAL_CFLAGS) $(STARTUP_CFLAGS) $(GLOBAL_INCLUDE) $(COMMON_INCLUDE) $(STARTUP_INCLUDE) $< -o $@ - + $(STARTUP_MODULE_OUT_DIR)/%.o:$(STARTUP_MODULE_DIR)/%.S @mkdir -p $(dir $@) @echo "cc $<" diff --git a/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/interrupt.c b/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/interrupt.c index 64649ccc..4587d31f 100644 --- a/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/interrupt.c +++ b/components/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup/interrupt.c @@ -107,7 +107,7 @@ const pFunc __Vectors[] __attribute__ ((section(".init"),aligned(64))) = { I2C_IRQHandler, /* 16 + 32 */ 0, /* 16 + 33 */ PWM_IRQHandler, /* 16 + 34 */ - 0, /* 16 + 35 */ + 0, /* 16 + 35 */ TIMER_CH0_IRQHandler, /* 16 + 36 */ TIMER_CH1_IRQHandler, /* 16 + 37 */ TIMER_WDT_IRQHandler, /* 16 + 38 */ @@ -127,8 +127,8 @@ const pFunc __Vectors[] __attribute__ ((section(".init"),aligned(64))) = { HBN_OUT1_IRQHandler, /* 16 + 52 */ BOR_IRQHandler, /* 16 + 53 */ WIFI_IRQHandler, /* 16 + 54 */ - BZ_PHY_IRQHandler, /* 16 + 55 */ - BLE_IRQHandler, /* 16 + 56 */ + BZ_PHY_IRQHandler, /* 16 + 55 */ + BLE_IRQHandler, /* 16 + 56 */ MAC_TXRX_TIMER_IRQHandler, /* 16 + 57 */ MAC_TXRX_MISC_IRQHandler, /* 16 + 58 */ MAC_RX_TRG_IRQHandler, /* 16 + 59 */ diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_gpio.h b/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_gpio.h index aa446e20..8c5905f9 100644 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_gpio.h +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_gpio.h @@ -1,386 +1,386 @@ -/** - ****************************************************************************** - * @file bl602_gpio.h - * @version V1.2 - * @date 2019-12-14 - * @brief This file is the description of.IP register - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2019 Bouffalo Lab

- * - * 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. - * 3. Neither the name of Bouffalo Lab nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * 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 __BL602_GPIO_H__ -#define __BL602_GPIO_H__ - - -typedef enum -{ - GLB_GPIO_PIN_0 = 0, - GLB_GPIO_PIN_1, - GLB_GPIO_PIN_2, - GLB_GPIO_PIN_3, - GLB_GPIO_PIN_4, - GLB_GPIO_PIN_5, - GLB_GPIO_PIN_6, - GLB_GPIO_PIN_7, - GLB_GPIO_PIN_8, - GLB_GPIO_PIN_9, - GLB_GPIO_PIN_10, - GLB_GPIO_PIN_11, - GLB_GPIO_PIN_12, - GLB_GPIO_PIN_13, - GLB_GPIO_PIN_14, - GLB_GPIO_PIN_15, - GLB_GPIO_PIN_16, - GLB_GPIO_PIN_17, - GLB_GPIO_PIN_18, - GLB_GPIO_PIN_19, - GLB_GPIO_PIN_20, - GLB_GPIO_PIN_21, - GLB_GPIO_PIN_22, - GLB_GPIO_PIN_MAX, -}GLB_GPIO_Type; - -#define GPIO_MODE_INPUT ((uint32_t)0x00000000U) /*!< Input Floating Mode */ -#define GPIO_MODE_OUTPUT ((uint32_t)0x00000001U) /*!< Output Push Pull Mode */ -#define GPIO_MODE_AF ((uint32_t)0x00000002U) /*!< Alternate function */ -#define GPIO_PULL_UP ((uint32_t)0x00000000U) /*!< GPIO pull up */ -#define GPIO_PULL_DOWN ((uint32_t)0x00000001U) /*!< GPIO pull down */ -#define GPIO_PULL_NONE ((uint32_t)0x00000002U) /*!< GPIO no pull up or down */ - typedef enum { GPIO_FUN_SDIO = 1, GPIO_FUN_FLASH = 2, GPIO_FUN_SPI = 4, GPIO_FUN_I2C = 6, GPIO_FUN_UART = 7, GPIO_FUN_PWM = 8, GPIO_FUN_EXT_PA = 9, GPIO_FUN_ANALOG = 10, GPIO_FUN_SWGPIO = 11, GPIO_FUN_JTAG = 14, }GLB_GPIO_FUNC_Type; - -typedef struct -{ - uint8_t gpioPin; - uint8_t gpioFun; - uint8_t gpioMode; - uint8_t pullType; - uint8_t drive; - uint8_t smtCtrl; -}GLB_GPIO_Cfg_Type; - -/* GPIO0 function definition */ -#define GPIO0_FUN_SDIO_CLK 1 -#define GPIO0_FUN_SF_D1 2 -#define GPIO0_FUN_UNUSED3 3 -#define GPIO0_FUN_SPI_MISO_SPI_MOSI 4 -#define GPIO0_FUN_UNUSED5 5 -#define GPIO0_FUN_I2C_SCL 6 -#define GPIO0_FUN_UART_SIG0 7 -#define GPIO0_FUN_PWM_CH0 8 -#define GPIO0_FUN_FEM_GPIO_0 9 -#define GPIO0_FUN_ATEST_IN 10 -#define GPIO0_FUN_SWGPIO_0 11 -#define GPIO0_FUN_E21_TMS 14 -/* GPIO1 function definition */ -#define GPIO1_FUN_SDIO_CMD 1 -#define GPIO1_FUN_SF_D2 2 -#define GPIO1_FUN_UNUSED3 3 -#define GPIO1_FUN_SPI_MOSI_SPI_MISO 4 -#define GPIO1_FUN_UNUSED5 5 -#define GPIO1_FUN_I2C_SDA 6 -#define GPIO1_FUN_UART_SIG1 7 -#define GPIO1_FUN_PWM_CH1 8 -#define GPIO1_FUN_FEM_GPIO_1 9 -#define GPIO1_FUN_ATEST_IP 10 -#define GPIO1_FUN_SWGPIO_1 11 -#define GPIO1_FUN_E21_TDI 14 -/* GPIO2 function definition */ -#define GPIO2_FUN_SDIO_DAT0 1 -#define GPIO2_FUN_SF_D3 2 -#define GPIO2_FUN_UNUSED3 3 -#define GPIO2_FUN_SPI_SS 4 -#define GPIO2_FUN_UNUSED5 5 -#define GPIO2_FUN_I2C_SCL 6 -#define GPIO2_FUN_UART_SIG2 7 -#define GPIO2_FUN_PWM_CH2 8 -#define GPIO2_FUN_FEM_GPIO_2 9 -#define GPIO2_FUN_ATEST_QN 10 -#define GPIO2_FUN_SWGPIO_2 11 -#define GPIO2_FUN_E21_TCK 14 -/* GPIO3 function definition */ -#define GPIO3_FUN_SDIO_DAT1 1 -#define GPIO3_FUN_UNUSED2 2 -#define GPIO3_FUN_UNUSED3 3 -#define GPIO3_FUN_SPI_SCLK 4 -#define GPIO3_FUN_UNUSED5 5 -#define GPIO3_FUN_I2C_SDA 6 -#define GPIO3_FUN_UART_SIG3 7 -#define GPIO3_FUN_PWM_CH3 8 -#define GPIO3_FUN_FEM_GPIO_3 9 -#define GPIO3_FUN_ATEST_QP 10 -#define GPIO3_FUN_SWGPIO_3 11 -#define GPIO3_FUN_E21_TDO 14 -/* GPIO4 function definition */ -#define GPIO4_FUN_SDIO_DAT2 1 -#define GPIO4_FUN_UNUSED2 2 -#define GPIO4_FUN_UNUSED3 3 -#define GPIO4_FUN_SPI_MISO_SPI_MOSI 4 -#define GPIO4_FUN_UNUSED5 5 -#define GPIO4_FUN_I2C_SCL 6 -#define GPIO4_FUN_UART_SIG4 7 -#define GPIO4_FUN_PWM_CH4 8 -#define GPIO4_FUN_FEM_GPIO_0 9 -#define GPIO4_FUN_GPIP_CH1 10 -#define GPIO4_FUN_SWGPIO_4 11 -#define GPIO4_FUN_E21_TMS 14 -/* GPIO5 function definition */ -#define GPIO5_FUN_SDIO_DAT3 1 -#define GPIO5_FUN_UNUSED2 2 -#define GPIO5_FUN_UNUSED3 3 -#define GPIO5_FUN_SPI_MOSI_SPI_MISO 4 -#define GPIO5_FUN_UNUSED5 5 -#define GPIO5_FUN_I2C_SDA 6 -#define GPIO5_FUN_UART_SIG5 7 -#define GPIO5_FUN_PWM_CH0 8 -#define GPIO5_FUN_FEM_GPIO_1 9 -#define GPIO5_FUN_GPIP_CH4 10 -#define GPIO5_FUN_SWGPIO_5 11 -#define GPIO5_FUN_E21_TDI 14 -/* GPIO6 function definition */ -#define GPIO6_FUN_UNUSED1 1 -#define GPIO6_FUN_UNUSED2 2 -#define GPIO6_FUN_UNUSED3 3 -#define GPIO6_FUN_SPI_SS 4 -#define GPIO6_FUN_UNUSED5 5 -#define GPIO6_FUN_I2C_SCL 6 -#define GPIO6_FUN_UART_SIG6 7 -#define GPIO6_FUN_PWM_CH1 8 -#define GPIO6_FUN_FEM_GPIO_2 9 -#define GPIO6_FUN_GPIP_CH5 10 -#define GPIO6_FUN_SWGPIO_6 11 -#define GPIO6_FUN_E21_TCK 14 -/* GPIO7 function definition */ -#define GPIO7_FUN_UNUSED1 1 -#define GPIO7_FUN_UNUSED2 2 -#define GPIO7_FUN_UNUSED3 3 -#define GPIO7_FUN_SPI_SCLK 4 -#define GPIO7_FUN_UNUSED5 5 -#define GPIO7_FUN_I2C_SDA 6 -#define GPIO7_FUN_UART_SIG7 7 -#define GPIO7_FUN_PWM_CH2 8 -#define GPIO7_FUN_FEM_GPIO_3 9 -#define GPIO7_FUN_UNUSED10 10 -#define GPIO7_FUN_SWGPIO_7 11 -#define GPIO7_FUN_E21_TDO 14 -/* GPIO8 function definition */ -#define GPIO8_FUN_UNUSED1 1 -#define GPIO8_FUN_UNUSED2 2 -#define GPIO8_FUN_UNUSED3 3 -#define GPIO8_FUN_SPI_MISO_SPI_MOSI 4 -#define GPIO8_FUN_UNUSED5 5 -#define GPIO8_FUN_I2C_SCL 6 -#define GPIO8_FUN_UART_SIG0 7 -#define GPIO8_FUN_PWM_CH3 8 -#define GPIO8_FUN_FEM_GPIO_0 9 -#define GPIO8_FUN_UNUSED10 10 -#define GPIO8_FUN_SWGPIO_8 11 -#define GPIO8_FUN_E21_TMS 14 -/* GPIO9 function definition */ -#define GPIO9_FUN_UNUSED1 1 -#define GPIO9_FUN_UNUSED2 2 -#define GPIO9_FUN_UNUSED3 3 -#define GPIO9_FUN_SPI_MOSI_SPI_MISO 4 -#define GPIO9_FUN_UNUSED5 5 -#define GPIO9_FUN_I2C_SDA 6 -#define GPIO9_FUN_UART_SIG1 7 -#define GPIO9_FUN_PWM_CH4 8 -#define GPIO9_FUN_FEM_GPIO_1 9 -#define GPIO9_FUN_GPIP_CH6_GPIP_CH7 10 -#define GPIO9_FUN_SWGPIO_9 11 -#define GPIO9_FUN_E21_TDI 14 -/* GPIO10 function definition */ -#define GPIO10_FUN_UNUSED1 1 -#define GPIO10_FUN_UNUSED2 2 -#define GPIO10_FUN_UNUSED3 3 -#define GPIO10_FUN_SPI_SS 4 -#define GPIO10_FUN_UNUSED5 5 -#define GPIO10_FUN_I2C_SCL 6 -#define GPIO10_FUN_UART_SIG2 7 -#define GPIO10_FUN_PWM_CH0 8 -#define GPIO10_FUN_FEM_GPIO_2 9 -#define GPIO10_FUN_MICBIAS_GPIP_CH8_GPIP_CH9 10 -#define GPIO10_FUN_SWGPIO_10 11 -#define GPIO10_FUN_E21_TCK 14 -/* GPIO11 function definition */ -#define GPIO11_FUN_UNUSED1 1 -#define GPIO11_FUN_UNUSED2 2 -#define GPIO11_FUN_UNUSED3 3 -#define GPIO11_FUN_SPI_SCLK 4 -#define GPIO11_FUN_UNUSED5 5 -#define GPIO11_FUN_I2C_SDA 6 -#define GPIO11_FUN_UART_SIG3 7 -#define GPIO11_FUN_PWM_CH1 8 -#define GPIO11_FUN_FEM_GPIO_3 9 -#define GPIO11_FUN_IRLED_OUT_GPIP_CH10 10 -#define GPIO11_FUN_SWGPIO_11 11 -#define GPIO11_FUN_E21_TDO 14 -/* GPIO12 function definition */ -#define GPIO12_FUN_UNUSED1 1 -#define GPIO12_FUN_UNUSED2 2 -#define GPIO12_FUN_UNUSED3 3 -#define GPIO12_FUN_SPI_MISO_SPI_MOSI 4 -#define GPIO12_FUN_UNUSED5 5 -#define GPIO12_FUN_I2C_SCL 6 -#define GPIO12_FUN_UART_SIG4 7 -#define GPIO12_FUN_PWM_CH2 8 -#define GPIO12_FUN_FEM_GPIO_0 9 -#define GPIO12_FUN_GPIP_CH0_GPADC_VREF_EXT 10 -#define GPIO12_FUN_SWGPIO_12 11 -#define GPIO12_FUN_E21_TMS 14 -/* GPIO13 function definition */ -#define GPIO13_FUN_UNUSED1 1 -#define GPIO13_FUN_UNUSED2 2 -#define GPIO13_FUN_UNUSED3 3 -#define GPIO13_FUN_SPI_MOSI_SPI_MISO 4 -#define GPIO13_FUN_UNUSED5 5 -#define GPIO13_FUN_I2C_SDA 6 -#define GPIO13_FUN_UART_SIG5 7 -#define GPIO13_FUN_PWM_CH3 8 -#define GPIO13_FUN_FEM_GPIO_1 9 -#define GPIO13_FUN_GPIP_CH3 10 -#define GPIO13_FUN_SWGPIO_13 11 -#define GPIO13_FUN_E21_TDI 14 -/* GPIO14 function definition */ -#define GPIO14_FUN_UNUSED1 1 -#define GPIO14_FUN_UNUSED2 2 -#define GPIO14_FUN_UNUSED3 3 -#define GPIO14_FUN_SPI_SS 4 -#define GPIO14_FUN_UNUSED5 5 -#define GPIO14_FUN_I2C_SCL 6 -#define GPIO14_FUN_UART_SIG6 7 -#define GPIO14_FUN_PWM_CH4 8 -#define GPIO14_FUN_FEM_GPIO_2 9 -#define GPIO14_FUN_GPIP_CH2 10 -#define GPIO14_FUN_SWGPIO_14 11 -#define GPIO14_FUN_E21_TCK 14 -/* GPIO15 function definition */ -#define GPIO15_FUN_UNUSED1 1 -#define GPIO15_FUN_UNUSED2 2 -#define GPIO15_FUN_UNUSED3 3 -#define GPIO15_FUN_SPI_SCLK 4 -#define GPIO15_FUN_UNUSED5 5 -#define GPIO15_FUN_I2C_SDA 6 -#define GPIO15_FUN_UART_SIG7 7 -#define GPIO15_FUN_PWM_CH0 8 -#define GPIO15_FUN_FEM_GPIO_3 9 -#define GPIO15_FUN_PSW_IRRCV_OUT_GPIP_CH11 10 -#define GPIO15_FUN_SWGPIO_15 11 -#define GPIO15_FUN_E21_TDO 14 -/* GPIO16 function definition */ -#define GPIO16_FUN_UNUSED1 1 -#define GPIO16_FUN_UNUSED2 2 -#define GPIO16_FUN_UNUSED3 3 -#define GPIO16_FUN_SPI_MISO_SPI_MOSI 4 -#define GPIO16_FUN_UNUSED5 5 -#define GPIO16_FUN_I2C_SCL 6 -#define GPIO16_FUN_UART_SIG0 7 -#define GPIO16_FUN_PWM_CH1 8 -#define GPIO16_FUN_FEM_GPIO_0 9 -#define GPIO16_FUN_UNUSED10 10 -#define GPIO16_FUN_SWGPIO_16 11 -#define GPIO16_FUN_E21_TMS 14 -/* GPIO17 function definition */ -#define GPIO17_FUN_UNUSED1 1 -#define GPIO17_FUN_SF_D3 2 -#define GPIO17_FUN_UNUSED3 3 -#define GPIO17_FUN_SPI_MOSI_SPI_MISO 4 -#define GPIO17_FUN_UNUSED5 5 -#define GPIO17_FUN_I2C_SDA 6 -#define GPIO17_FUN_UART_SIG1 7 -#define GPIO17_FUN_PWM_CH2 8 -#define GPIO17_FUN_FEM_GPIO_1 9 -#define GPIO17_FUN_PMIP_DC_TP_OUT 10 -#define GPIO17_FUN_SWGPIO_17 11 -#define GPIO17_FUN_E21_TDI 14 -/* GPIO18 function definition */ -#define GPIO18_FUN_UNUSED1 1 -#define GPIO18_FUN_SF_D2 2 -#define GPIO18_FUN_UNUSED3 3 -#define GPIO18_FUN_SPI_SS 4 -#define GPIO18_FUN_UNUSED5 5 -#define GPIO18_FUN_I2C_SCL 6 -#define GPIO18_FUN_UART_SIG2 7 -#define GPIO18_FUN_PWM_CH3 8 -#define GPIO18_FUN_FEM_GPIO_2 9 -#define GPIO18_FUN_UNUSED10 10 -#define GPIO18_FUN_SWGPIO_18 11 -#define GPIO18_FUN_E21_TCK 14 -/* GPIO19 function definition */ -#define GPIO19_FUN_UNUSED1 1 -#define GPIO19_FUN_SF_D1 2 -#define GPIO19_FUN_UNUSED3 3 -#define GPIO19_FUN_SPI_SCLK 4 -#define GPIO19_FUN_UNUSED5 5 -#define GPIO19_FUN_I2C_SDA 6 -#define GPIO19_FUN_UART_SIG3 7 -#define GPIO19_FUN_PWM_CH4 8 -#define GPIO19_FUN_FEM_GPIO_3 9 -#define GPIO19_FUN_UNUSED10 10 -#define GPIO19_FUN_SWGPIO_19 11 -#define GPIO19_FUN_E21_TDO 14 -/* GPIO20 function definition */ -#define GPIO20_FUN_UNUSED1 1 -#define GPIO20_FUN_SF_D0 2 -#define GPIO20_FUN_UNUSED3 3 -#define GPIO20_FUN_SPI_MISO_SPI_MOSI 4 -#define GPIO20_FUN_UNUSED5 5 -#define GPIO20_FUN_I2C_SCL 6 -#define GPIO20_FUN_UART_SIG4 7 -#define GPIO20_FUN_PWM_CH0 8 -#define GPIO20_FUN_FEM_GPIO_0 9 -#define GPIO20_FUN_UNUSED10 10 -#define GPIO20_FUN_SWGPIO_20 11 -#define GPIO20_FUN_E21_TMS 14 -/* GPIO21 function definition */ -#define GPIO21_FUN_UNUSED1 1 -#define GPIO21_FUN_SF_CS 2 -#define GPIO21_FUN_UNUSED3 3 -#define GPIO21_FUN_SPI_MOSI_SPI_MISO 4 -#define GPIO21_FUN_UNUSED5 5 -#define GPIO21_FUN_I2C_SDA 6 -#define GPIO21_FUN_UART_SIG5 7 -#define GPIO21_FUN_PWM_CH1 8 -#define GPIO21_FUN_FEM_GPIO_1 9 -#define GPIO21_FUN_UNUSED10 10 -#define GPIO21_FUN_SWGPIO_21 11 -#define GPIO21_FUN_E21_TDI 14 -/* GPIO22 function definition */ -#define GPIO22_FUN_UNUSED1 1 -#define GPIO22_FUN_SF_CLK_OUT 2 -#define GPIO22_FUN_UNUSED3 3 -#define GPIO22_FUN_SPI_SS 4 -#define GPIO22_FUN_UNUSED5 5 -#define GPIO22_FUN_I2C_SCL 6 -#define GPIO22_FUN_UART_SIG6 7 -#define GPIO22_FUN_PWM_CH2 8 -#define GPIO22_FUN_FEM_GPIO_2 9 -#define GPIO22_FUN_UNUSED10 10 -#define GPIO22_FUN_SWGPIO_22 11 -#define GPIO22_FUN_E21_TCK 14 - -#endif /*__BL602_GPIO_H__ */ +/** + ****************************************************************************** + * @file bl602_gpio.h + * @version V1.2 + * @date 2019-12-14 + * @brief This file is the description of.IP register + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2019 Bouffalo Lab

+ * + * 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. + * 3. Neither the name of Bouffalo Lab nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * 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 __BL602_GPIO_H__ +#define __BL602_GPIO_H__ + + +typedef enum +{ + GLB_GPIO_PIN_0 = 0, + GLB_GPIO_PIN_1, + GLB_GPIO_PIN_2, + GLB_GPIO_PIN_3, + GLB_GPIO_PIN_4, + GLB_GPIO_PIN_5, + GLB_GPIO_PIN_6, + GLB_GPIO_PIN_7, + GLB_GPIO_PIN_8, + GLB_GPIO_PIN_9, + GLB_GPIO_PIN_10, + GLB_GPIO_PIN_11, + GLB_GPIO_PIN_12, + GLB_GPIO_PIN_13, + GLB_GPIO_PIN_14, + GLB_GPIO_PIN_15, + GLB_GPIO_PIN_16, + GLB_GPIO_PIN_17, + GLB_GPIO_PIN_18, + GLB_GPIO_PIN_19, + GLB_GPIO_PIN_20, + GLB_GPIO_PIN_21, + GLB_GPIO_PIN_22, + GLB_GPIO_PIN_MAX, +}GLB_GPIO_Type; + +#define GPIO_MODE_INPUT ((uint32_t)0x00000000U) /*!< Input Floating Mode */ +#define GPIO_MODE_OUTPUT ((uint32_t)0x00000001U) /*!< Output Push Pull Mode */ +#define GPIO_MODE_AF ((uint32_t)0x00000002U) /*!< Alternate function */ +#define GPIO_PULL_UP ((uint32_t)0x00000000U) /*!< GPIO pull up */ +#define GPIO_PULL_DOWN ((uint32_t)0x00000001U) /*!< GPIO pull down */ +#define GPIO_PULL_NONE ((uint32_t)0x00000002U) /*!< GPIO no pull up or down */ + typedef enum { GPIO_FUN_SDIO = 1, GPIO_FUN_FLASH = 2, GPIO_FUN_SPI = 4, GPIO_FUN_I2C = 6, GPIO_FUN_UART = 7, GPIO_FUN_PWM = 8, GPIO_FUN_EXT_PA = 9, GPIO_FUN_ANALOG = 10, GPIO_FUN_SWGPIO = 11, GPIO_FUN_JTAG = 14, }GLB_GPIO_FUNC_Type; + +typedef struct +{ + uint8_t gpioPin; + uint8_t gpioFun; + uint8_t gpioMode; + uint8_t pullType; + uint8_t drive; + uint8_t smtCtrl; +}GLB_GPIO_Cfg_Type; + +/* GPIO0 function definition */ +#define GPIO0_FUN_SDIO_CLK 1 +#define GPIO0_FUN_SF_D1 2 +#define GPIO0_FUN_UNUSED3 3 +#define GPIO0_FUN_SPI_MISO_SPI_MOSI 4 +#define GPIO0_FUN_UNUSED5 5 +#define GPIO0_FUN_I2C_SCL 6 +#define GPIO0_FUN_UART_SIG0 7 +#define GPIO0_FUN_PWM_CH0 8 +#define GPIO0_FUN_FEM_GPIO_0 9 +#define GPIO0_FUN_ATEST_IN 10 +#define GPIO0_FUN_SWGPIO_0 11 +#define GPIO0_FUN_E21_TMS 14 +/* GPIO1 function definition */ +#define GPIO1_FUN_SDIO_CMD 1 +#define GPIO1_FUN_SF_D2 2 +#define GPIO1_FUN_UNUSED3 3 +#define GPIO1_FUN_SPI_MOSI_SPI_MISO 4 +#define GPIO1_FUN_UNUSED5 5 +#define GPIO1_FUN_I2C_SDA 6 +#define GPIO1_FUN_UART_SIG1 7 +#define GPIO1_FUN_PWM_CH1 8 +#define GPIO1_FUN_FEM_GPIO_1 9 +#define GPIO1_FUN_ATEST_IP 10 +#define GPIO1_FUN_SWGPIO_1 11 +#define GPIO1_FUN_E21_TDI 14 +/* GPIO2 function definition */ +#define GPIO2_FUN_SDIO_DAT0 1 +#define GPIO2_FUN_SF_D3 2 +#define GPIO2_FUN_UNUSED3 3 +#define GPIO2_FUN_SPI_SS 4 +#define GPIO2_FUN_UNUSED5 5 +#define GPIO2_FUN_I2C_SCL 6 +#define GPIO2_FUN_UART_SIG2 7 +#define GPIO2_FUN_PWM_CH2 8 +#define GPIO2_FUN_FEM_GPIO_2 9 +#define GPIO2_FUN_ATEST_QN 10 +#define GPIO2_FUN_SWGPIO_2 11 +#define GPIO2_FUN_E21_TCK 14 +/* GPIO3 function definition */ +#define GPIO3_FUN_SDIO_DAT1 1 +#define GPIO3_FUN_UNUSED2 2 +#define GPIO3_FUN_UNUSED3 3 +#define GPIO3_FUN_SPI_SCLK 4 +#define GPIO3_FUN_UNUSED5 5 +#define GPIO3_FUN_I2C_SDA 6 +#define GPIO3_FUN_UART_SIG3 7 +#define GPIO3_FUN_PWM_CH3 8 +#define GPIO3_FUN_FEM_GPIO_3 9 +#define GPIO3_FUN_ATEST_QP 10 +#define GPIO3_FUN_SWGPIO_3 11 +#define GPIO3_FUN_E21_TDO 14 +/* GPIO4 function definition */ +#define GPIO4_FUN_SDIO_DAT2 1 +#define GPIO4_FUN_UNUSED2 2 +#define GPIO4_FUN_UNUSED3 3 +#define GPIO4_FUN_SPI_MISO_SPI_MOSI 4 +#define GPIO4_FUN_UNUSED5 5 +#define GPIO4_FUN_I2C_SCL 6 +#define GPIO4_FUN_UART_SIG4 7 +#define GPIO4_FUN_PWM_CH4 8 +#define GPIO4_FUN_FEM_GPIO_0 9 +#define GPIO4_FUN_GPIP_CH1 10 +#define GPIO4_FUN_SWGPIO_4 11 +#define GPIO4_FUN_E21_TMS 14 +/* GPIO5 function definition */ +#define GPIO5_FUN_SDIO_DAT3 1 +#define GPIO5_FUN_UNUSED2 2 +#define GPIO5_FUN_UNUSED3 3 +#define GPIO5_FUN_SPI_MOSI_SPI_MISO 4 +#define GPIO5_FUN_UNUSED5 5 +#define GPIO5_FUN_I2C_SDA 6 +#define GPIO5_FUN_UART_SIG5 7 +#define GPIO5_FUN_PWM_CH0 8 +#define GPIO5_FUN_FEM_GPIO_1 9 +#define GPIO5_FUN_GPIP_CH4 10 +#define GPIO5_FUN_SWGPIO_5 11 +#define GPIO5_FUN_E21_TDI 14 +/* GPIO6 function definition */ +#define GPIO6_FUN_UNUSED1 1 +#define GPIO6_FUN_UNUSED2 2 +#define GPIO6_FUN_UNUSED3 3 +#define GPIO6_FUN_SPI_SS 4 +#define GPIO6_FUN_UNUSED5 5 +#define GPIO6_FUN_I2C_SCL 6 +#define GPIO6_FUN_UART_SIG6 7 +#define GPIO6_FUN_PWM_CH1 8 +#define GPIO6_FUN_FEM_GPIO_2 9 +#define GPIO6_FUN_GPIP_CH5 10 +#define GPIO6_FUN_SWGPIO_6 11 +#define GPIO6_FUN_E21_TCK 14 +/* GPIO7 function definition */ +#define GPIO7_FUN_UNUSED1 1 +#define GPIO7_FUN_UNUSED2 2 +#define GPIO7_FUN_UNUSED3 3 +#define GPIO7_FUN_SPI_SCLK 4 +#define GPIO7_FUN_UNUSED5 5 +#define GPIO7_FUN_I2C_SDA 6 +#define GPIO7_FUN_UART_SIG7 7 +#define GPIO7_FUN_PWM_CH2 8 +#define GPIO7_FUN_FEM_GPIO_3 9 +#define GPIO7_FUN_UNUSED10 10 +#define GPIO7_FUN_SWGPIO_7 11 +#define GPIO7_FUN_E21_TDO 14 +/* GPIO8 function definition */ +#define GPIO8_FUN_UNUSED1 1 +#define GPIO8_FUN_UNUSED2 2 +#define GPIO8_FUN_UNUSED3 3 +#define GPIO8_FUN_SPI_MISO_SPI_MOSI 4 +#define GPIO8_FUN_UNUSED5 5 +#define GPIO8_FUN_I2C_SCL 6 +#define GPIO8_FUN_UART_SIG0 7 +#define GPIO8_FUN_PWM_CH3 8 +#define GPIO8_FUN_FEM_GPIO_0 9 +#define GPIO8_FUN_UNUSED10 10 +#define GPIO8_FUN_SWGPIO_8 11 +#define GPIO8_FUN_E21_TMS 14 +/* GPIO9 function definition */ +#define GPIO9_FUN_UNUSED1 1 +#define GPIO9_FUN_UNUSED2 2 +#define GPIO9_FUN_UNUSED3 3 +#define GPIO9_FUN_SPI_MOSI_SPI_MISO 4 +#define GPIO9_FUN_UNUSED5 5 +#define GPIO9_FUN_I2C_SDA 6 +#define GPIO9_FUN_UART_SIG1 7 +#define GPIO9_FUN_PWM_CH4 8 +#define GPIO9_FUN_FEM_GPIO_1 9 +#define GPIO9_FUN_GPIP_CH6_GPIP_CH7 10 +#define GPIO9_FUN_SWGPIO_9 11 +#define GPIO9_FUN_E21_TDI 14 +/* GPIO10 function definition */ +#define GPIO10_FUN_UNUSED1 1 +#define GPIO10_FUN_UNUSED2 2 +#define GPIO10_FUN_UNUSED3 3 +#define GPIO10_FUN_SPI_SS 4 +#define GPIO10_FUN_UNUSED5 5 +#define GPIO10_FUN_I2C_SCL 6 +#define GPIO10_FUN_UART_SIG2 7 +#define GPIO10_FUN_PWM_CH0 8 +#define GPIO10_FUN_FEM_GPIO_2 9 +#define GPIO10_FUN_MICBIAS_GPIP_CH8_GPIP_CH9 10 +#define GPIO10_FUN_SWGPIO_10 11 +#define GPIO10_FUN_E21_TCK 14 +/* GPIO11 function definition */ +#define GPIO11_FUN_UNUSED1 1 +#define GPIO11_FUN_UNUSED2 2 +#define GPIO11_FUN_UNUSED3 3 +#define GPIO11_FUN_SPI_SCLK 4 +#define GPIO11_FUN_UNUSED5 5 +#define GPIO11_FUN_I2C_SDA 6 +#define GPIO11_FUN_UART_SIG3 7 +#define GPIO11_FUN_PWM_CH1 8 +#define GPIO11_FUN_FEM_GPIO_3 9 +#define GPIO11_FUN_IRLED_OUT_GPIP_CH10 10 +#define GPIO11_FUN_SWGPIO_11 11 +#define GPIO11_FUN_E21_TDO 14 +/* GPIO12 function definition */ +#define GPIO12_FUN_UNUSED1 1 +#define GPIO12_FUN_UNUSED2 2 +#define GPIO12_FUN_UNUSED3 3 +#define GPIO12_FUN_SPI_MISO_SPI_MOSI 4 +#define GPIO12_FUN_UNUSED5 5 +#define GPIO12_FUN_I2C_SCL 6 +#define GPIO12_FUN_UART_SIG4 7 +#define GPIO12_FUN_PWM_CH2 8 +#define GPIO12_FUN_FEM_GPIO_0 9 +#define GPIO12_FUN_GPIP_CH0_GPADC_VREF_EXT 10 +#define GPIO12_FUN_SWGPIO_12 11 +#define GPIO12_FUN_E21_TMS 14 +/* GPIO13 function definition */ +#define GPIO13_FUN_UNUSED1 1 +#define GPIO13_FUN_UNUSED2 2 +#define GPIO13_FUN_UNUSED3 3 +#define GPIO13_FUN_SPI_MOSI_SPI_MISO 4 +#define GPIO13_FUN_UNUSED5 5 +#define GPIO13_FUN_I2C_SDA 6 +#define GPIO13_FUN_UART_SIG5 7 +#define GPIO13_FUN_PWM_CH3 8 +#define GPIO13_FUN_FEM_GPIO_1 9 +#define GPIO13_FUN_GPIP_CH3 10 +#define GPIO13_FUN_SWGPIO_13 11 +#define GPIO13_FUN_E21_TDI 14 +/* GPIO14 function definition */ +#define GPIO14_FUN_UNUSED1 1 +#define GPIO14_FUN_UNUSED2 2 +#define GPIO14_FUN_UNUSED3 3 +#define GPIO14_FUN_SPI_SS 4 +#define GPIO14_FUN_UNUSED5 5 +#define GPIO14_FUN_I2C_SCL 6 +#define GPIO14_FUN_UART_SIG6 7 +#define GPIO14_FUN_PWM_CH4 8 +#define GPIO14_FUN_FEM_GPIO_2 9 +#define GPIO14_FUN_GPIP_CH2 10 +#define GPIO14_FUN_SWGPIO_14 11 +#define GPIO14_FUN_E21_TCK 14 +/* GPIO15 function definition */ +#define GPIO15_FUN_UNUSED1 1 +#define GPIO15_FUN_UNUSED2 2 +#define GPIO15_FUN_UNUSED3 3 +#define GPIO15_FUN_SPI_SCLK 4 +#define GPIO15_FUN_UNUSED5 5 +#define GPIO15_FUN_I2C_SDA 6 +#define GPIO15_FUN_UART_SIG7 7 +#define GPIO15_FUN_PWM_CH0 8 +#define GPIO15_FUN_FEM_GPIO_3 9 +#define GPIO15_FUN_PSW_IRRCV_OUT_GPIP_CH11 10 +#define GPIO15_FUN_SWGPIO_15 11 +#define GPIO15_FUN_E21_TDO 14 +/* GPIO16 function definition */ +#define GPIO16_FUN_UNUSED1 1 +#define GPIO16_FUN_UNUSED2 2 +#define GPIO16_FUN_UNUSED3 3 +#define GPIO16_FUN_SPI_MISO_SPI_MOSI 4 +#define GPIO16_FUN_UNUSED5 5 +#define GPIO16_FUN_I2C_SCL 6 +#define GPIO16_FUN_UART_SIG0 7 +#define GPIO16_FUN_PWM_CH1 8 +#define GPIO16_FUN_FEM_GPIO_0 9 +#define GPIO16_FUN_UNUSED10 10 +#define GPIO16_FUN_SWGPIO_16 11 +#define GPIO16_FUN_E21_TMS 14 +/* GPIO17 function definition */ +#define GPIO17_FUN_UNUSED1 1 +#define GPIO17_FUN_SF_D3 2 +#define GPIO17_FUN_UNUSED3 3 +#define GPIO17_FUN_SPI_MOSI_SPI_MISO 4 +#define GPIO17_FUN_UNUSED5 5 +#define GPIO17_FUN_I2C_SDA 6 +#define GPIO17_FUN_UART_SIG1 7 +#define GPIO17_FUN_PWM_CH2 8 +#define GPIO17_FUN_FEM_GPIO_1 9 +#define GPIO17_FUN_PMIP_DC_TP_OUT 10 +#define GPIO17_FUN_SWGPIO_17 11 +#define GPIO17_FUN_E21_TDI 14 +/* GPIO18 function definition */ +#define GPIO18_FUN_UNUSED1 1 +#define GPIO18_FUN_SF_D2 2 +#define GPIO18_FUN_UNUSED3 3 +#define GPIO18_FUN_SPI_SS 4 +#define GPIO18_FUN_UNUSED5 5 +#define GPIO18_FUN_I2C_SCL 6 +#define GPIO18_FUN_UART_SIG2 7 +#define GPIO18_FUN_PWM_CH3 8 +#define GPIO18_FUN_FEM_GPIO_2 9 +#define GPIO18_FUN_UNUSED10 10 +#define GPIO18_FUN_SWGPIO_18 11 +#define GPIO18_FUN_E21_TCK 14 +/* GPIO19 function definition */ +#define GPIO19_FUN_UNUSED1 1 +#define GPIO19_FUN_SF_D1 2 +#define GPIO19_FUN_UNUSED3 3 +#define GPIO19_FUN_SPI_SCLK 4 +#define GPIO19_FUN_UNUSED5 5 +#define GPIO19_FUN_I2C_SDA 6 +#define GPIO19_FUN_UART_SIG3 7 +#define GPIO19_FUN_PWM_CH4 8 +#define GPIO19_FUN_FEM_GPIO_3 9 +#define GPIO19_FUN_UNUSED10 10 +#define GPIO19_FUN_SWGPIO_19 11 +#define GPIO19_FUN_E21_TDO 14 +/* GPIO20 function definition */ +#define GPIO20_FUN_UNUSED1 1 +#define GPIO20_FUN_SF_D0 2 +#define GPIO20_FUN_UNUSED3 3 +#define GPIO20_FUN_SPI_MISO_SPI_MOSI 4 +#define GPIO20_FUN_UNUSED5 5 +#define GPIO20_FUN_I2C_SCL 6 +#define GPIO20_FUN_UART_SIG4 7 +#define GPIO20_FUN_PWM_CH0 8 +#define GPIO20_FUN_FEM_GPIO_0 9 +#define GPIO20_FUN_UNUSED10 10 +#define GPIO20_FUN_SWGPIO_20 11 +#define GPIO20_FUN_E21_TMS 14 +/* GPIO21 function definition */ +#define GPIO21_FUN_UNUSED1 1 +#define GPIO21_FUN_SF_CS 2 +#define GPIO21_FUN_UNUSED3 3 +#define GPIO21_FUN_SPI_MOSI_SPI_MISO 4 +#define GPIO21_FUN_UNUSED5 5 +#define GPIO21_FUN_I2C_SDA 6 +#define GPIO21_FUN_UART_SIG5 7 +#define GPIO21_FUN_PWM_CH1 8 +#define GPIO21_FUN_FEM_GPIO_1 9 +#define GPIO21_FUN_UNUSED10 10 +#define GPIO21_FUN_SWGPIO_21 11 +#define GPIO21_FUN_E21_TDI 14 +/* GPIO22 function definition */ +#define GPIO22_FUN_UNUSED1 1 +#define GPIO22_FUN_SF_CLK_OUT 2 +#define GPIO22_FUN_UNUSED3 3 +#define GPIO22_FUN_SPI_SS 4 +#define GPIO22_FUN_UNUSED5 5 +#define GPIO22_FUN_I2C_SCL 6 +#define GPIO22_FUN_UART_SIG6 7 +#define GPIO22_FUN_PWM_CH2 8 +#define GPIO22_FUN_FEM_GPIO_2 9 +#define GPIO22_FUN_UNUSED10 10 +#define GPIO22_FUN_SWGPIO_22 11 +#define GPIO22_FUN_E21_TCK 14 + +#endif /*__BL602_GPIO_H__ */ diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_mfg_flash.h b/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_mfg_flash.h old mode 100755 new mode 100644 diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_mfg_media.h b/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_mfg_media.h old mode 100755 new mode 100644 diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_sdu.h b/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_sdu.h index 72387513..d0f9f88d 100644 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_sdu.h +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Inc/bl602_sdu.h @@ -1,194 +1,194 @@ -#ifndef __BL602_SDU_H__ -#define __BL602_SDU_H__ - -#include "bl602.h" -#include "bl602_common.h" - -#define NUM_FUNC 1 -#define FUNC_WIFI 0 - -// SDIO I/O Enable -#define BL_SDIO_IO_ENABLE SDU_BASE + 0x00000002 -//CCCR (Fn0) Registers - -// SDIO Device Sleep -#define BL_SDIO_DEV_SLEEP SDU_BASE + 0x00000092 - -// Start Address of CCR -#define BL_SDIO_CCR_BASE SDU_BASE + 0x00000100 -// Address offset of CCR between two functions -#define BL_SDIO_CCR_FUNC_OFFSET 0x00000100 - - -// Address for sdio block size information -#define SDIO_FN1_BLK_SIZE_0 (SDU_BASE + 0x00000028) -#define SDIO_FN1_BLK_SIZE_1 (SDU_BASE + 0x00000029) -#define SDIO_FN1_BLK_SIZE_1_MASK 0x01 - -#define BL_FUNC_SCRATCH_BASE SDU_BASE + 0x00000160 - -typedef struct -{ - uint8_t HostToCardEvent; // 0x100/200 - uint8_t HostIntCause; // 0x101/201 - uint8_t HostIntMask; // 0x102/202 - uint8_t HostIntStatus; // 0x103/203 - uint16_t RdBitMap; // 0x104/204 - uint16_t WrBitMap; // 0x106/206 - uint16_t RdLen[16]; // 0x108/208 - uint8_t HostTransferStatus;// 0x128/228 - uint8_t reserved1[0x130-0x128-1]; - uint8_t CardToHostEvent; // 0x130/230 - uint8_t reserved2[3]; - uint8_t CardIntMask; // 0x134/234 - uint8_t reserved3[3]; - uint8_t CardIntStatus; // 0x138/238 - uint8_t reserved4[3]; - uint8_t CardIntMode; // 0x13C/23C - uint8_t reserved5[3]; - uint32_t SqReadBase; // 0x140/240 - uint32_t SqWriteBase; // 0x144/244 - uint8_t RdIdx; // 0x148/248 - uint8_t WrIdx; // 0x149/249 - uint8_t DnldQueueWrPtr; // 0x14A/24A - uint8_t UpldQueueWrPtr; // 0x14B/24B - uint8_t DnldQueue[8]; // 0x14C/24C - uint8_t UpldQueue[8]; // 0x154/254 - uint8_t ChipRev; // 0x15C //RO - uint8_t reserved6; // 0x15D //NOT_DEFINE - uint8_t IPRev0; // 0x15E //RO - uint8_t IPRev1; // 0x15F //RO - uint8_t reserved7[4]; // 0x160/260 - uint16_t Scratch2; // 0x164/264 - uint16_t Scratch1; // 0x166/266 - uint8_t Ocr0; // 0x168/268 - uint8_t Ocr1; // 0x169/269 - uint8_t Ocr2; // 0x16A/26A - uint8_t Config; // 0x16B/26B - uint32_t Config2; // 0x16C/26C - uint32_t Debug; // 0x170/270 - uint32_t DmaAddr; // 0x174/274 - uint8_t IoPort[3]; // 0x178/278 -} __attribute__((packed)) HidSdio_RegMap_t, *pHidSdio_RegMap_t; - -// Common I/O Area Registers (CIA) Offset -// -// Bit Def. Host To Card Interrupt Event (Offset 0x100/200) -#define SDIO_HCR_CONFIG_HostPwrUp (1<<1) - -// Bit Def. Host Transfer Status (Offset 0x128/228) -#define SDIO_CCR_HOST_INT_DnLdReStart (1<<0) -#define SDIO_CCR_HOST_INT_UpLdReStart (1<<1) -#define SDIO_CCR_HOST_INT_DnLdCRC_err (1<<2) - -// Bit Def. Card To Host Interrupt Event (Offset 0x130/230) -#define SDIO_CCR_CS_DnLdRdy (1<<0) -#define SDIO_CCR_CS_UpLdRdy (1<<1) -#define SDIO_CCR_CS_ReadCISRdy (1<<2) -#define SDIO_CCR_CS_IORdy (1<<3) - - -// Bit Def. Card Interrupt Mask (Offset 0x134/234) -#define SDIO_CCR_CIM_DnLdOvr (1<<0) -#define SDIO_CCR_CIM_UpLdOvr (1<<1) -#define SDIO_CCR_CIM_Abort (1<<2) -#define SDIO_CCR_CIM_PwrDn (1<<3) -#define SDIO_CCR_CIM_PwrUp (1<<4) - -#define SDIO_CCR_CIM_MASK 0x0007 - - -// Bit Def. Card Interrupt Status (Offset 0x138/238) -#define SDIO_CCR_CIC_DnLdOvr (1<<0) -#define SDIO_CCR_CIC_UpLdOvr (1<<1) -#define SDIO_CCR_CIC_Abort (1<<2) -#define SDIO_CCR_CIC_PwrDn (1<<3) -#define SDIO_CCR_CIC_PwrUp (1<<4) - - - -#define SDIO_CCR_CIC_MASK 0x001F - -// Bit Def. Card Interrupt RSR (Offset 0x13C/23C) -#define SDIO_CCR_CIO_DnLdOvr (1<<0) -#define SDIO_CCR_CIO_UpLdOvr (1<<1) -#define SDIO_CCR_CIO_Abort (1<<2) -#define SDIO_CCR_CIO_PwrDn (1<<3) -#define SDIO_CCR_CIO_PwrUp (1<<4) -#define SDIO_CCR_CIO_MASK 0x001F - - -//Config2 register mask -#define CONFIG2_MSK 0x00000C00 - - -//CardIntMode register mask - -#define CARD_INT_MODE_MSK 0x00000003 -#define HOST_INT_MSK 0x00000002 - -//============================================================================= -// PUBLIC MACROS -//============================================================================= - -#define BL_REGS8(x) (*(volatile unsigned char *)(x)) -#define BL_REGS16(x) (*(volatile unsigned short *)(x)) -#define BL_REGS32(x) (*(volatile unsigned long *)(x)) - -#define BL_READ_REGS8(reg,val) ((val) = BL_REGS8(reg)) -#define BL_READ_REGS16(reg,val) ((val) = BL_REGS16(reg)) -#define BL_READ_REGS32(reg,val) ((val) = BL_REGS32(reg)) -#define BL_READ_BYTE(reg,val) ((val) = BL_REGS8(reg)) -#define BL_READ_HWORD(reg,val) ((val) = BL_REGS16(reg)) /*half word; */ -#define BL_READ_WORD(reg,val) ((val) = BL_REGS32(reg)) /*32 bits */ - -#define BL_WRITE_REGS8(reg,val) (BL_REGS8(reg) = (val)) -#define BL_WRITE_REGS16(reg,val) (BL_REGS16(reg) = (val)) -#define BL_WRITE_REGS32(reg,val) (BL_REGS32(reg) = (val)) -#define BL_WRITE_BYTE(reg,val) (BL_REGS8(reg) = (val)) -#define BL_WRITE_HWORD(reg,val) (BL_REGS16(reg) = (val)) /*half word; */ -#define BL_WRITE_WORD(reg,val) (BL_REGS32(reg) = (val)) /*32 bits */ -// Write uint32 to a low 16-bit register and a high 16-bit register -#define WRITE2REGS(lo,hi,u32) \ - BL_WRITE_HWORD(lo, (uint16_t)((u32) & 0xffff)); \ - BL_WRITE_HWORD(hi, (uint16_t)(((u32) >> 16) & 0xffff)) - -#define BL_REGS8_SETBITS(reg, val) (BL_REGS8(reg) |= (uint8)(val)) -#define BL_REGS16_SETBITS(reg, val) (BL_REGS16(reg) |= (uint16)(val)) -#define BL_REGS32_SETBITS(reg, val) (BL_REGS32(reg) |= (val)) -#define BL_REGS8_CLRBITS(reg, val) (BL_REGS8(reg) = (uint8)(BL_REGS8(reg)&~(val))) -#define BL_REGS16_CLRBITS(reg, val) (BL_REGS16(reg) = (uint16)(BL_REGS16(reg)&~(val))) -#define BL_REGS32_CLRBITS(reg, val) (BL_REGS32(reg) = (BL_REGS32(reg)&~(val))) - -//============================================================================= -// ENUM TYPE DEFINITION -//============================================================================= - -/******************************************************************/ -/*! - * \enum SDIO_CMD_TYPE - * - *******************************************************************/ -typedef enum -{ - IOCTL_GET_CONFIG = 0, /*!< Get configuration info */ - - - /* HID IOCTLs*/ - IOCTL_HID_GET_BLOCK_SIZE, /*!< Get Block size */ - -} SDIO_CMD_TYPE; - -//============================================================================= -// FUNCTION DECLARATION -//============================================================================= -extern void sdio_GEN_CARD2HOST_INT(uint32_t port_id, uint16_t value); -extern uint32_t sdio_ioctl(uint32_t port_id, SDIO_CMD_TYPE cmd, void *arg); - -//============================================================================= -// Variable DECLARATION -//============================================================================= -extern volatile pHidSdio_RegMap_t SdioFuncReg[]; -extern uint8_t flag_mport[]; -#endif /* __BL602_SDU_H__ */ - +#ifndef __BL602_SDU_H__ +#define __BL602_SDU_H__ + +#include "bl602.h" +#include "bl602_common.h" + +#define NUM_FUNC 1 +#define FUNC_WIFI 0 + +// SDIO I/O Enable +#define BL_SDIO_IO_ENABLE SDU_BASE + 0x00000002 +//CCCR (Fn0) Registers + +// SDIO Device Sleep +#define BL_SDIO_DEV_SLEEP SDU_BASE + 0x00000092 + +// Start Address of CCR +#define BL_SDIO_CCR_BASE SDU_BASE + 0x00000100 +// Address offset of CCR between two functions +#define BL_SDIO_CCR_FUNC_OFFSET 0x00000100 + + +// Address for sdio block size information +#define SDIO_FN1_BLK_SIZE_0 (SDU_BASE + 0x00000028) +#define SDIO_FN1_BLK_SIZE_1 (SDU_BASE + 0x00000029) +#define SDIO_FN1_BLK_SIZE_1_MASK 0x01 + +#define BL_FUNC_SCRATCH_BASE SDU_BASE + 0x00000160 + +typedef struct +{ + uint8_t HostToCardEvent; // 0x100/200 + uint8_t HostIntCause; // 0x101/201 + uint8_t HostIntMask; // 0x102/202 + uint8_t HostIntStatus; // 0x103/203 + uint16_t RdBitMap; // 0x104/204 + uint16_t WrBitMap; // 0x106/206 + uint16_t RdLen[16]; // 0x108/208 + uint8_t HostTransferStatus;// 0x128/228 + uint8_t reserved1[0x130-0x128-1]; + uint8_t CardToHostEvent; // 0x130/230 + uint8_t reserved2[3]; + uint8_t CardIntMask; // 0x134/234 + uint8_t reserved3[3]; + uint8_t CardIntStatus; // 0x138/238 + uint8_t reserved4[3]; + uint8_t CardIntMode; // 0x13C/23C + uint8_t reserved5[3]; + uint32_t SqReadBase; // 0x140/240 + uint32_t SqWriteBase; // 0x144/244 + uint8_t RdIdx; // 0x148/248 + uint8_t WrIdx; // 0x149/249 + uint8_t DnldQueueWrPtr; // 0x14A/24A + uint8_t UpldQueueWrPtr; // 0x14B/24B + uint8_t DnldQueue[8]; // 0x14C/24C + uint8_t UpldQueue[8]; // 0x154/254 + uint8_t ChipRev; // 0x15C //RO + uint8_t reserved6; // 0x15D //NOT_DEFINE + uint8_t IPRev0; // 0x15E //RO + uint8_t IPRev1; // 0x15F //RO + uint8_t reserved7[4]; // 0x160/260 + uint16_t Scratch2; // 0x164/264 + uint16_t Scratch1; // 0x166/266 + uint8_t Ocr0; // 0x168/268 + uint8_t Ocr1; // 0x169/269 + uint8_t Ocr2; // 0x16A/26A + uint8_t Config; // 0x16B/26B + uint32_t Config2; // 0x16C/26C + uint32_t Debug; // 0x170/270 + uint32_t DmaAddr; // 0x174/274 + uint8_t IoPort[3]; // 0x178/278 +} __attribute__((packed)) HidSdio_RegMap_t, *pHidSdio_RegMap_t; + +// Common I/O Area Registers (CIA) Offset +// +// Bit Def. Host To Card Interrupt Event (Offset 0x100/200) +#define SDIO_HCR_CONFIG_HostPwrUp (1<<1) + +// Bit Def. Host Transfer Status (Offset 0x128/228) +#define SDIO_CCR_HOST_INT_DnLdReStart (1<<0) +#define SDIO_CCR_HOST_INT_UpLdReStart (1<<1) +#define SDIO_CCR_HOST_INT_DnLdCRC_err (1<<2) + +// Bit Def. Card To Host Interrupt Event (Offset 0x130/230) +#define SDIO_CCR_CS_DnLdRdy (1<<0) +#define SDIO_CCR_CS_UpLdRdy (1<<1) +#define SDIO_CCR_CS_ReadCISRdy (1<<2) +#define SDIO_CCR_CS_IORdy (1<<3) + + +// Bit Def. Card Interrupt Mask (Offset 0x134/234) +#define SDIO_CCR_CIM_DnLdOvr (1<<0) +#define SDIO_CCR_CIM_UpLdOvr (1<<1) +#define SDIO_CCR_CIM_Abort (1<<2) +#define SDIO_CCR_CIM_PwrDn (1<<3) +#define SDIO_CCR_CIM_PwrUp (1<<4) + +#define SDIO_CCR_CIM_MASK 0x0007 + + +// Bit Def. Card Interrupt Status (Offset 0x138/238) +#define SDIO_CCR_CIC_DnLdOvr (1<<0) +#define SDIO_CCR_CIC_UpLdOvr (1<<1) +#define SDIO_CCR_CIC_Abort (1<<2) +#define SDIO_CCR_CIC_PwrDn (1<<3) +#define SDIO_CCR_CIC_PwrUp (1<<4) + + + +#define SDIO_CCR_CIC_MASK 0x001F + +// Bit Def. Card Interrupt RSR (Offset 0x13C/23C) +#define SDIO_CCR_CIO_DnLdOvr (1<<0) +#define SDIO_CCR_CIO_UpLdOvr (1<<1) +#define SDIO_CCR_CIO_Abort (1<<2) +#define SDIO_CCR_CIO_PwrDn (1<<3) +#define SDIO_CCR_CIO_PwrUp (1<<4) +#define SDIO_CCR_CIO_MASK 0x001F + + +//Config2 register mask +#define CONFIG2_MSK 0x00000C00 + + +//CardIntMode register mask + +#define CARD_INT_MODE_MSK 0x00000003 +#define HOST_INT_MSK 0x00000002 + +//============================================================================= +// PUBLIC MACROS +//============================================================================= + +#define BL_REGS8(x) (*(volatile unsigned char *)(x)) +#define BL_REGS16(x) (*(volatile unsigned short *)(x)) +#define BL_REGS32(x) (*(volatile unsigned long *)(x)) + +#define BL_READ_REGS8(reg,val) ((val) = BL_REGS8(reg)) +#define BL_READ_REGS16(reg,val) ((val) = BL_REGS16(reg)) +#define BL_READ_REGS32(reg,val) ((val) = BL_REGS32(reg)) +#define BL_READ_BYTE(reg,val) ((val) = BL_REGS8(reg)) +#define BL_READ_HWORD(reg,val) ((val) = BL_REGS16(reg)) /*half word; */ +#define BL_READ_WORD(reg,val) ((val) = BL_REGS32(reg)) /*32 bits */ + +#define BL_WRITE_REGS8(reg,val) (BL_REGS8(reg) = (val)) +#define BL_WRITE_REGS16(reg,val) (BL_REGS16(reg) = (val)) +#define BL_WRITE_REGS32(reg,val) (BL_REGS32(reg) = (val)) +#define BL_WRITE_BYTE(reg,val) (BL_REGS8(reg) = (val)) +#define BL_WRITE_HWORD(reg,val) (BL_REGS16(reg) = (val)) /*half word; */ +#define BL_WRITE_WORD(reg,val) (BL_REGS32(reg) = (val)) /*32 bits */ +// Write uint32 to a low 16-bit register and a high 16-bit register +#define WRITE2REGS(lo,hi,u32) \ + BL_WRITE_HWORD(lo, (uint16_t)((u32) & 0xffff)); \ + BL_WRITE_HWORD(hi, (uint16_t)(((u32) >> 16) & 0xffff)) + +#define BL_REGS8_SETBITS(reg, val) (BL_REGS8(reg) |= (uint8)(val)) +#define BL_REGS16_SETBITS(reg, val) (BL_REGS16(reg) |= (uint16)(val)) +#define BL_REGS32_SETBITS(reg, val) (BL_REGS32(reg) |= (val)) +#define BL_REGS8_CLRBITS(reg, val) (BL_REGS8(reg) = (uint8)(BL_REGS8(reg)&~(val))) +#define BL_REGS16_CLRBITS(reg, val) (BL_REGS16(reg) = (uint16)(BL_REGS16(reg)&~(val))) +#define BL_REGS32_CLRBITS(reg, val) (BL_REGS32(reg) = (BL_REGS32(reg)&~(val))) + +//============================================================================= +// ENUM TYPE DEFINITION +//============================================================================= + +/******************************************************************/ +/*! + * \enum SDIO_CMD_TYPE + * + *******************************************************************/ +typedef enum +{ + IOCTL_GET_CONFIG = 0, /*!< Get configuration info */ + + + /* HID IOCTLs*/ + IOCTL_HID_GET_BLOCK_SIZE, /*!< Get Block size */ + +} SDIO_CMD_TYPE; + +//============================================================================= +// FUNCTION DECLARATION +//============================================================================= +extern void sdio_GEN_CARD2HOST_INT(uint32_t port_id, uint16_t value); +extern uint32_t sdio_ioctl(uint32_t port_id, SDIO_CMD_TYPE cmd, void *arg); + +//============================================================================= +// Variable DECLARATION +//============================================================================= +extern volatile pHidSdio_RegMap_t SdioFuncReg[]; +extern uint8_t flag_mport[]; +#endif /* __BL602_SDU_H__ */ + diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_dac.c b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_dac.c index 3afcabc0..22fa478c 100644 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_dac.c +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_dac.c @@ -188,9 +188,9 @@ void GPIP_Set_DAC_ChanB_SRC_SEL(GPIP_DAC_ChanB_SRC_Type src) CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(src)); - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_B_SEL,src); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_B_SEL,src); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); } /****************************************************************************//** @@ -207,9 +207,9 @@ void GPIP_Set_DAC_ChanA_SRC_SEL(GPIP_DAC_ChanA_SRC_Type src) CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(src)); - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_A_SEL,src); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_A_SEL,src); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); } /****************************************************************************//** @@ -222,13 +222,13 @@ void GPIP_Set_DAC_ChanA_SRC_SEL(GPIP_DAC_ChanA_SRC_Type src) *******************************************************************************/ void GPIP_Set_DAC_Mod_SEL(GPIP_DAC_MOD_Type mod) { - uint32_t tmpVal; + uint32_t tmpVal; - CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(mod)); + CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(mod)); - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_MODE,mod); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_MODE,mod); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); } /****************************************************************************//** @@ -241,11 +241,11 @@ void GPIP_Set_DAC_Mod_SEL(GPIP_DAC_MOD_Type mod) *******************************************************************************/ void GPIP_DAC_ChanB_Enable(void) { - uint32_t tmpVal; + uint32_t tmpVal; - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BIT(tmpVal,GPIP_GPDAC_EN2); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BIT(tmpVal,GPIP_GPDAC_EN2); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); } /****************************************************************************//** @@ -258,11 +258,11 @@ void GPIP_DAC_ChanB_Enable(void) *******************************************************************************/ void GPIP_DAC_ChanB_Disable(void) { - uint32_t tmpVal; + uint32_t tmpVal; - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_CLR_REG_BIT(tmpVal,GPIP_GPDAC_EN2); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_CLR_REG_BIT(tmpVal,GPIP_GPDAC_EN2); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); } /****************************************************************************//** @@ -275,11 +275,11 @@ void GPIP_DAC_ChanB_Disable(void) *******************************************************************************/ void GPIP_DAC_ChanA_Enable(void) { - uint32_t tmpVal; + uint32_t tmpVal; - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BIT(tmpVal,GPIP_GPDAC_EN); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BIT(tmpVal,GPIP_GPDAC_EN); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); } /****************************************************************************//** @@ -292,11 +292,11 @@ void GPIP_DAC_ChanA_Enable(void) *******************************************************************************/ void GPIP_DAC_ChanA_Disable(void) { - uint32_t tmpVal; + uint32_t tmpVal; - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_CLR_REG_BIT(tmpVal,GPIP_GPDAC_EN); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_CLR_REG_BIT(tmpVal,GPIP_GPDAC_EN); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); } /****************************************************************************//** @@ -309,13 +309,13 @@ void GPIP_DAC_ChanA_Disable(void) *******************************************************************************/ void GPIP_Set_DAC_DMA_TX_FORMAT_SEL(GPIP_DAC_DMA_TX_FORMAT_Type fmt) { - uint32_t tmpVal; + uint32_t tmpVal; - CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(fmt)); + CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(fmt)); - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_DMA_FORMAT,fmt); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_DMA_FORMAT,fmt); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); } /****************************************************************************//** @@ -328,11 +328,11 @@ void GPIP_Set_DAC_DMA_TX_FORMAT_SEL(GPIP_DAC_DMA_TX_FORMAT_Type fmt) *******************************************************************************/ void GPIP_Set_DAC_DMA_TX_Enable(void) { - uint32_t tmpVal; + uint32_t tmpVal; - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); - tmpVal=BL_SET_REG_BIT(tmpVal,GPIP_GPDAC_DMA_TX_EN); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); + tmpVal=BL_SET_REG_BIT(tmpVal,GPIP_GPDAC_DMA_TX_EN); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); } /****************************************************************************//** @@ -345,11 +345,11 @@ void GPIP_Set_DAC_DMA_TX_Enable(void) *******************************************************************************/ void GPIP_Set_DAC_DMA_TX_Disable(void) { - uint32_t tmpVal; + uint32_t tmpVal; - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); - tmpVal=BL_CLR_REG_BIT(tmpVal,GPIP_GPDAC_DMA_TX_EN); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); + tmpVal=BL_CLR_REG_BIT(tmpVal,GPIP_GPDAC_DMA_TX_EN); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); } /****************************************************************************//** @@ -362,7 +362,7 @@ void GPIP_Set_DAC_DMA_TX_Disable(void) *******************************************************************************/ void GPIP_DAC_DMA_WriteData(uint32_t data) { - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_WDATA,data); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_WDATA,data); } /****************************************************************************//** @@ -375,11 +375,11 @@ void GPIP_DAC_DMA_WriteData(uint32_t data) *******************************************************************************/ BL_Err_Type GLB_GPIP_DAC_Init(GLB_GPIP_DAC_Cfg_Type* cfg) { - uint32_t tmpVal; + uint32_t tmpVal; - CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); - CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(cfg->mod)); - CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(cfg->dmaFmt)); + CHECK_PARAM(IS_GLB_DAC_REF_SEL_TYPE(cfg->refSel)); + CHECK_PARAM(IS_GPIP_DAC_MOD_TYPE(cfg->mod)); + CHECK_PARAM(IS_GPIP_DAC_DMA_TX_FORMAT_TYPE(cfg->dmaFmt)); /* AON Set DAC config */ tmpVal=BL_RD_REG(GLB_BASE,GLB_GPDAC_CTRL); @@ -410,16 +410,16 @@ BL_Err_Type GLB_GPIP_DAC_Init(GLB_GPIP_DAC_Cfg_Type* cfg) return ERROR;/*512K mode only used in DMA mode*/ } - /* GPIP Set DAC config */ - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_MODE,cfg->mod); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + /* GPIP Set DAC config */ + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_MODE,cfg->mod); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); - /* GPIP Set DMA config */ - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_DMA_TX_EN,cfg->dmaEn); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_DMA_FORMAT,cfg->dmaFmt); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); + /* GPIP Set DMA config */ + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_DMA_TX_EN,cfg->dmaEn); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_DMA_FORMAT,cfg->dmaFmt); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_DMA_CONFIG,tmpVal); return SUCCESS; } @@ -434,21 +434,21 @@ BL_Err_Type GLB_GPIP_DAC_Init(GLB_GPIP_DAC_Cfg_Type* cfg) *******************************************************************************/ void GLB_GPIP_DAC_Set_ChanA_Config(GLB_GPIP_DAC_ChanA_Cfg_Type *cfg) { - uint32_t tmpVal; + uint32_t tmpVal; - CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(cfg->src)); + CHECK_PARAM(IS_GPIP_DAC_CHANA_SRC_TYPE(cfg->src)); - /* GPIP select source */ - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_A_SEL,cfg->src); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + /* GPIP select source */ + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_A_SEL,cfg->src); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); - /* GPIP enable or disable channel */ - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_EN,cfg->chanEn); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + /* GPIP enable or disable channel */ + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_EN,cfg->chanEn); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); - /* AON enable or disable channel */ + /* AON enable or disable channel */ tmpVal=BL_RD_REG(GLB_BASE,GLB_GPDAC_ACTRL); tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_GPDAC_IOA_EN,cfg->outputEn); tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_GPDAC_A_EN,cfg->chanCovtEn); @@ -465,21 +465,21 @@ void GLB_GPIP_DAC_Set_ChanA_Config(GLB_GPIP_DAC_ChanA_Cfg_Type *cfg) *******************************************************************************/ void GLB_GPIP_DAC_Set_ChanB_Config(GLB_GPIP_DAC_ChanB_Cfg_Type *cfg) { - uint32_t tmpVal; + uint32_t tmpVal; - CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(cfg->src)); + CHECK_PARAM(IS_GPIP_DAC_CHANB_SRC_TYPE(cfg->src)); - /* GPIP select source */ - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_B_SEL,cfg->src); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + /* GPIP select source */ + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_CH_B_SEL,cfg->src); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); - /* GPIP enable or disable channel */ - tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); - tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_EN2,cfg->chanEn); - BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); + /* GPIP enable or disable channel */ + tmpVal=BL_RD_REG(GPIP_BASE,GPIP_GPDAC_CONFIG); + tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GPIP_GPDAC_EN2,cfg->chanEn); + BL_WR_REG(GPIP_BASE,GPIP_GPDAC_CONFIG,tmpVal); - /* AON enable or disable channel */ + /* AON enable or disable channel */ tmpVal=BL_RD_REG(GLB_BASE,GLB_GPDAC_BCTRL); tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_GPDAC_IOB_EN,cfg->outputEn); tmpVal=BL_SET_REG_BITS_VAL(tmpVal,GLB_GPDAC_B_EN,cfg->chanCovtEn); diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_efuse.c b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_efuse.c index 297930d0..bccfee1e 100644 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_efuse.c +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_efuse.c @@ -1,500 +1,500 @@ -#include "bl602_glb.h" -#include "bl602_mfg_efuse.h" -#include "bl602_ef_ctrl.h" - -static uint8_t rf_cal_slots=3; -extern void main(void); -#define RF_CAL_SLOT_CFG_OFFSET (4*13) -#ifdef BFLB_MCU_SDK -#include "bflb_platform.h" -#define mfg_print MSG -#else -#define mfg_print printf -#endif - -uint8_t mfg_efuse_get_rf_cal_slots(void) -{ -#if 0 - uint8_t *pslot; - pslot=(uint8_t *)((((uint32_t)main)&0xfff00000)+RF_CAL_SLOT_CFG_OFFSET); - if(*pslot!=0){ - rf_cal_slots=*pslot; - } -#endif - return rf_cal_slots; -} - -void mfg_efuse_set_rf_cal_slots(uint8_t slots) -{ - rf_cal_slots=slots; -} - -uint8_t mfg_efuse_is_xtal_capcode_slot_empty(uint8_t reload) -{ - uint8_t empty=0; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=1&&EF_Ctrl_Is_CapCode_Slot_Empty(0,reload)){ - mfg_print("Empty slot:%d\r\n",0); - empty=1; - }else if(rf_cal_slots>=2&&EF_Ctrl_Is_CapCode_Slot_Empty(1,reload)){ - mfg_print("Empty slot:%d\r\n",1); - empty=1; - }else if(rf_cal_slots>=3&&EF_Ctrl_Is_CapCode_Slot_Empty(2,reload)){ - mfg_print("Empty slot:%d\r\n",2); - empty=1; - }else{ - mfg_print("No empty slot found\r\n"); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - return empty; -} - -int8_t mfg_efuse_write_xtal_capcode_pre(uint8_t capcode,uint8_t program) -{ - BL_Err_Type ret=SUCCESS; - uint8_t slot=0xff; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=1&&EF_Ctrl_Is_CapCode_Slot_Empty(0,1)){ - slot=0; - }else if(rf_cal_slots>=2&&EF_Ctrl_Is_CapCode_Slot_Empty(1,1)){ - slot=1; - }else if(rf_cal_slots>=3&&EF_Ctrl_Is_CapCode_Slot_Empty(2,1)){ - slot=2; - }else{ - mfg_print("No empty slot found\r\n"); - } - - if(slot!=0xff){ - ret=EF_Ctrl_Write_CapCode_Opt(slot,capcode,program); - mfg_print("Write slot:%d\r\n",slot); - } - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -void mfg_efuse_write_xtal_capcode(void) -{ - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - EF_Ctrl_Program_Direct_R0(0,NULL,0); - while(SET==EF_Ctrl_Busy()); - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif -} - -int8_t mfg_efuse_read_xtal_capcode(uint8_t *capcode,uint8_t reload) -{ - uint8_t slot=0xff; - BL_Err_Type ret=ERROR; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=3&&(!EF_Ctrl_Is_CapCode_Slot_Empty(2,reload))){ - slot=2; - }else if(rf_cal_slots>=2&&(!EF_Ctrl_Is_CapCode_Slot_Empty(1,reload))){ - slot=1; - }else if(rf_cal_slots>=1&&(!EF_Ctrl_Is_CapCode_Slot_Empty(0,reload))){ - slot=0; - } - - if(slot!=0xff){ - mfg_print("Read slot:%d\r\n",slot); - ret=EF_Ctrl_Read_CapCode_Opt(slot,capcode,reload); - }else{ - mfg_print("No written slot found\r\n"); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -uint8_t mfg_efuse_is_poweroffset_slot_empty(uint8_t reload) -{ - uint8_t empty=0; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=1&&EF_Ctrl_Is_PowerOffset_Slot_Empty(0,reload)){ - mfg_print("Empty slot:%d\r\n",0); - empty=1; - }else if(rf_cal_slots>=2&&EF_Ctrl_Is_PowerOffset_Slot_Empty(1,reload)){ - mfg_print("Empty slot:%d\r\n",1); - empty=1; - }else if(rf_cal_slots>=3&&EF_Ctrl_Is_PowerOffset_Slot_Empty(2,reload)){ - mfg_print("Empty slot:%d\r\n",2); - empty=1; - }else{ - mfg_print("No empty slot found\r\n"); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - return empty; -} - -int8_t mfg_efuse_write_poweroffset_pre(int8_t pwrOffset[14],uint8_t program) -{ - BL_Err_Type ret=SUCCESS; - uint8_t slot=0xff; - int8_t pwrOffsetTmp[3]; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); - -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=1&&EF_Ctrl_Is_PowerOffset_Slot_Empty(0,1)){ - slot=0; - }else if(rf_cal_slots>=2&&EF_Ctrl_Is_PowerOffset_Slot_Empty(1,1)){ - slot=1; - }else if(rf_cal_slots>=3&&EF_Ctrl_Is_PowerOffset_Slot_Empty(2,1)){ - slot=2; - }else{ - mfg_print("No empty slot found\r\n"); - } - - if(slot!=0xff){ - pwrOffsetTmp[0]=pwrOffset[0]; - pwrOffsetTmp[1]=pwrOffset[6]; - pwrOffsetTmp[2]=pwrOffset[12]; - ret=EF_Ctrl_Write_PowerOffset_Opt(slot,pwrOffsetTmp,program); - mfg_print("Write slot:%d\r\n",slot); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -void mfg_efuse_write_poweroffset(void) -{ - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - EF_Ctrl_Program_Direct_R0(0,NULL,0); - while(SET==EF_Ctrl_Busy()); - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif -} - -int8_t mfg_efuse_read_poweroffset(int8_t pwrOffset[14],uint8_t reload) -{ - uint8_t slot=0xff; - BL_Err_Type ret=ERROR; - int8_t pwrOffsetTmp[3]; - - int32_t step=0; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); - -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=3&&(!EF_Ctrl_Is_PowerOffset_Slot_Empty(2,reload))){ - slot=2; - }else if(rf_cal_slots>=2&&(!EF_Ctrl_Is_PowerOffset_Slot_Empty(1,reload))){ - slot=1; - }else if(rf_cal_slots>=1&&(!EF_Ctrl_Is_PowerOffset_Slot_Empty(0,reload))){ - slot=0; - } - - if(slot!=0xff){ - mfg_print("Read slot:%d\r\n",slot); - ret=EF_Ctrl_Read_PowerOffset_Opt(slot,pwrOffsetTmp,reload); - memset(pwrOffset,0,14); - - pwrOffset[0]=pwrOffsetTmp[0]; - - step=(pwrOffsetTmp[1]-pwrOffsetTmp[0])*100/6; - pwrOffset[1]=(step+50)/100+pwrOffsetTmp[0]; - pwrOffset[2]=(step*2+50)/100+pwrOffsetTmp[0]; - pwrOffset[3]=(step*3+50)/100+pwrOffsetTmp[0]; - pwrOffset[4]=(step*4+50)/100+pwrOffsetTmp[0]; - pwrOffset[5]=(step*5+50)/100+pwrOffsetTmp[0]; - - pwrOffset[6]=pwrOffsetTmp[1]; - - step=(pwrOffsetTmp[2]-pwrOffsetTmp[1])*100/6; - pwrOffset[7]=(step+50)/100+pwrOffsetTmp[1]; - pwrOffset[8]=(step*2+50)/100+pwrOffsetTmp[1]; - pwrOffset[9]=(step*3+50)/100+pwrOffsetTmp[1]; - pwrOffset[10]=(step*4+50)/100+pwrOffsetTmp[1]; - pwrOffset[11]=(step*5+50)/100+pwrOffsetTmp[1]; - - pwrOffset[12]=pwrOffsetTmp[2]; - - pwrOffset[13]=(step*7+50)/100+pwrOffsetTmp[1]; - }else{ - mfg_print("No written slot found\r\n"); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -uint8_t mfg_efuse_is_macaddr_slot_empty(uint8_t reload) -{ - uint8_t empty=0; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=1&&EF_Ctrl_Is_MAC_Address_Slot_Empty(0,reload)){ - mfg_print("Empty slot:%d\r\n",0); - empty=1; - }else if(rf_cal_slots>=2&&EF_Ctrl_Is_MAC_Address_Slot_Empty(1,reload)){ - mfg_print("Empty slot:%d\r\n",1); - empty=1; - }else if(rf_cal_slots>=3&&EF_Ctrl_Is_MAC_Address_Slot_Empty(2,reload)){ - mfg_print("Empty slot:%d\r\n",2); - empty=1; - }else{ - mfg_print("No empty slot found\r\n"); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - return empty; -} - -int8_t mfg_efuse_write_macaddr_pre(uint8_t mac[6],uint8_t program) -{ - BL_Err_Type ret=SUCCESS; - uint8_t slot=0xff; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); - -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=1&&EF_Ctrl_Is_MAC_Address_Slot_Empty(0,1)){ - slot=0; - }else if(rf_cal_slots>=2&&EF_Ctrl_Is_MAC_Address_Slot_Empty(1,1)){ - slot=1; - }else if(rf_cal_slots>=3&&EF_Ctrl_Is_MAC_Address_Slot_Empty(2,1)){ - slot=2; - }else{ - mfg_print("No empty slot found\r\n"); - } - - if(slot!=0xff){ - ret=EF_Ctrl_Write_MAC_Address_Opt(slot,mac,program); - mfg_print("Write slot:%d\r\n",slot); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); - -#endif - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -void mfg_efuse_write_macaddr(void) -{ - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - EF_Ctrl_Program_Direct_R0(0,NULL,0); - while(SET==EF_Ctrl_Busy()); - //EF_Ctrl_Program_Direct_R1(0,NULL,0); - //while(SET==EF_Ctrl_Busy()); - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif -} - -int8_t mfg_efuse_read_macaddr(uint8_t mac[6],uint8_t reload) -{ - uint8_t slot=0xff; - BL_Err_Type ret=ERROR; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); - -#if 1 - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(rf_cal_slots>=3&&(!EF_Ctrl_Is_MAC_Address_Slot_Empty(2,reload))){ - slot=2; - }else if(rf_cal_slots>=2&&(!EF_Ctrl_Is_MAC_Address_Slot_Empty(1,reload))){ - slot=1; - }else if(rf_cal_slots>=1&&(!EF_Ctrl_Is_MAC_Address_Slot_Empty(0,reload))){ - slot=0; - } - - if(slot!=0xff){ - mfg_print("Read slot:%d\r\n",slot); - ret=EF_Ctrl_Read_MAC_Address_Opt(slot,mac,reload); - }else{ - mfg_print("No written slot found\r\n"); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); -#endif - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -int8_t mfg_efuse_write_pre(uint32_t addr,uint32_t *data,uint32_t countInword) -{ - BL_Err_Type ret=SUCCESS; - uint8_t hdiv=0,bdiv=0; - - if(addr>128){ - return -1; - } - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); - - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - EF_Ctrl_Write_R0(addr/4,data,countInword); - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); - - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -int8_t mfg_efuse_read(uint32_t addr,uint32_t *data,uint32_t countInword,uint8_t reload) -{ - BL_Err_Type ret=SUCCESS; - uint8_t hdiv=0,bdiv=0; - - if(addr>128){ - return -1; - } - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); - - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - if(reload){ - EF_Ctrl_Read_Direct_R0(addr/4,data,countInword); - }else{ - EF_Ctrl_Read_R0(addr/4,data,countInword); - } - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); - - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} - -int8_t mfg_efuse_program(void) -{ - BL_Err_Type ret=SUCCESS; - uint8_t hdiv=0,bdiv=0; - - bdiv=GLB_Get_BCLK_Div(); - hdiv=GLB_Get_HCLK_Div(); - - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); - - EF_Ctrl_Program_Direct_R0(0,NULL,0); - while(SET==EF_Ctrl_Busy()); - - GLB_Set_System_CLK_Div(hdiv,bdiv); - HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); - - if(ret==SUCCESS){ - return 0; - }else{ - return -1; - } -} +#include "bl602_glb.h" +#include "bl602_mfg_efuse.h" +#include "bl602_ef_ctrl.h" + +static uint8_t rf_cal_slots=3; +extern void main(void); +#define RF_CAL_SLOT_CFG_OFFSET (4*13) +#ifdef BFLB_MCU_SDK +#include "bflb_platform.h" +#define mfg_print MSG +#else +#define mfg_print printf +#endif + +uint8_t mfg_efuse_get_rf_cal_slots(void) +{ +#if 0 + uint8_t *pslot; + pslot=(uint8_t *)((((uint32_t)main)&0xfff00000)+RF_CAL_SLOT_CFG_OFFSET); + if(*pslot!=0){ + rf_cal_slots=*pslot; + } +#endif + return rf_cal_slots; +} + +void mfg_efuse_set_rf_cal_slots(uint8_t slots) +{ + rf_cal_slots=slots; +} + +uint8_t mfg_efuse_is_xtal_capcode_slot_empty(uint8_t reload) +{ + uint8_t empty=0; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=1&&EF_Ctrl_Is_CapCode_Slot_Empty(0,reload)){ + mfg_print("Empty slot:%d\r\n",0); + empty=1; + }else if(rf_cal_slots>=2&&EF_Ctrl_Is_CapCode_Slot_Empty(1,reload)){ + mfg_print("Empty slot:%d\r\n",1); + empty=1; + }else if(rf_cal_slots>=3&&EF_Ctrl_Is_CapCode_Slot_Empty(2,reload)){ + mfg_print("Empty slot:%d\r\n",2); + empty=1; + }else{ + mfg_print("No empty slot found\r\n"); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + return empty; +} + +int8_t mfg_efuse_write_xtal_capcode_pre(uint8_t capcode,uint8_t program) +{ + BL_Err_Type ret=SUCCESS; + uint8_t slot=0xff; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=1&&EF_Ctrl_Is_CapCode_Slot_Empty(0,1)){ + slot=0; + }else if(rf_cal_slots>=2&&EF_Ctrl_Is_CapCode_Slot_Empty(1,1)){ + slot=1; + }else if(rf_cal_slots>=3&&EF_Ctrl_Is_CapCode_Slot_Empty(2,1)){ + slot=2; + }else{ + mfg_print("No empty slot found\r\n"); + } + + if(slot!=0xff){ + ret=EF_Ctrl_Write_CapCode_Opt(slot,capcode,program); + mfg_print("Write slot:%d\r\n",slot); + } + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +void mfg_efuse_write_xtal_capcode(void) +{ + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + EF_Ctrl_Program_Direct_R0(0,NULL,0); + while(SET==EF_Ctrl_Busy()); + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif +} + +int8_t mfg_efuse_read_xtal_capcode(uint8_t *capcode,uint8_t reload) +{ + uint8_t slot=0xff; + BL_Err_Type ret=ERROR; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=3&&(!EF_Ctrl_Is_CapCode_Slot_Empty(2,reload))){ + slot=2; + }else if(rf_cal_slots>=2&&(!EF_Ctrl_Is_CapCode_Slot_Empty(1,reload))){ + slot=1; + }else if(rf_cal_slots>=1&&(!EF_Ctrl_Is_CapCode_Slot_Empty(0,reload))){ + slot=0; + } + + if(slot!=0xff){ + mfg_print("Read slot:%d\r\n",slot); + ret=EF_Ctrl_Read_CapCode_Opt(slot,capcode,reload); + }else{ + mfg_print("No written slot found\r\n"); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +uint8_t mfg_efuse_is_poweroffset_slot_empty(uint8_t reload) +{ + uint8_t empty=0; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=1&&EF_Ctrl_Is_PowerOffset_Slot_Empty(0,reload)){ + mfg_print("Empty slot:%d\r\n",0); + empty=1; + }else if(rf_cal_slots>=2&&EF_Ctrl_Is_PowerOffset_Slot_Empty(1,reload)){ + mfg_print("Empty slot:%d\r\n",1); + empty=1; + }else if(rf_cal_slots>=3&&EF_Ctrl_Is_PowerOffset_Slot_Empty(2,reload)){ + mfg_print("Empty slot:%d\r\n",2); + empty=1; + }else{ + mfg_print("No empty slot found\r\n"); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + return empty; +} + +int8_t mfg_efuse_write_poweroffset_pre(int8_t pwrOffset[14],uint8_t program) +{ + BL_Err_Type ret=SUCCESS; + uint8_t slot=0xff; + int8_t pwrOffsetTmp[3]; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); + +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=1&&EF_Ctrl_Is_PowerOffset_Slot_Empty(0,1)){ + slot=0; + }else if(rf_cal_slots>=2&&EF_Ctrl_Is_PowerOffset_Slot_Empty(1,1)){ + slot=1; + }else if(rf_cal_slots>=3&&EF_Ctrl_Is_PowerOffset_Slot_Empty(2,1)){ + slot=2; + }else{ + mfg_print("No empty slot found\r\n"); + } + + if(slot!=0xff){ + pwrOffsetTmp[0]=pwrOffset[0]; + pwrOffsetTmp[1]=pwrOffset[6]; + pwrOffsetTmp[2]=pwrOffset[12]; + ret=EF_Ctrl_Write_PowerOffset_Opt(slot,pwrOffsetTmp,program); + mfg_print("Write slot:%d\r\n",slot); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +void mfg_efuse_write_poweroffset(void) +{ + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + EF_Ctrl_Program_Direct_R0(0,NULL,0); + while(SET==EF_Ctrl_Busy()); + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif +} + +int8_t mfg_efuse_read_poweroffset(int8_t pwrOffset[14],uint8_t reload) +{ + uint8_t slot=0xff; + BL_Err_Type ret=ERROR; + int8_t pwrOffsetTmp[3]; + + int32_t step=0; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); + +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=3&&(!EF_Ctrl_Is_PowerOffset_Slot_Empty(2,reload))){ + slot=2; + }else if(rf_cal_slots>=2&&(!EF_Ctrl_Is_PowerOffset_Slot_Empty(1,reload))){ + slot=1; + }else if(rf_cal_slots>=1&&(!EF_Ctrl_Is_PowerOffset_Slot_Empty(0,reload))){ + slot=0; + } + + if(slot!=0xff){ + mfg_print("Read slot:%d\r\n",slot); + ret=EF_Ctrl_Read_PowerOffset_Opt(slot,pwrOffsetTmp,reload); + memset(pwrOffset,0,14); + + pwrOffset[0]=pwrOffsetTmp[0]; + + step=(pwrOffsetTmp[1]-pwrOffsetTmp[0])*100/6; + pwrOffset[1]=(step+50)/100+pwrOffsetTmp[0]; + pwrOffset[2]=(step*2+50)/100+pwrOffsetTmp[0]; + pwrOffset[3]=(step*3+50)/100+pwrOffsetTmp[0]; + pwrOffset[4]=(step*4+50)/100+pwrOffsetTmp[0]; + pwrOffset[5]=(step*5+50)/100+pwrOffsetTmp[0]; + + pwrOffset[6]=pwrOffsetTmp[1]; + + step=(pwrOffsetTmp[2]-pwrOffsetTmp[1])*100/6; + pwrOffset[7]=(step+50)/100+pwrOffsetTmp[1]; + pwrOffset[8]=(step*2+50)/100+pwrOffsetTmp[1]; + pwrOffset[9]=(step*3+50)/100+pwrOffsetTmp[1]; + pwrOffset[10]=(step*4+50)/100+pwrOffsetTmp[1]; + pwrOffset[11]=(step*5+50)/100+pwrOffsetTmp[1]; + + pwrOffset[12]=pwrOffsetTmp[2]; + + pwrOffset[13]=(step*7+50)/100+pwrOffsetTmp[1]; + }else{ + mfg_print("No written slot found\r\n"); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +uint8_t mfg_efuse_is_macaddr_slot_empty(uint8_t reload) +{ + uint8_t empty=0; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=1&&EF_Ctrl_Is_MAC_Address_Slot_Empty(0,reload)){ + mfg_print("Empty slot:%d\r\n",0); + empty=1; + }else if(rf_cal_slots>=2&&EF_Ctrl_Is_MAC_Address_Slot_Empty(1,reload)){ + mfg_print("Empty slot:%d\r\n",1); + empty=1; + }else if(rf_cal_slots>=3&&EF_Ctrl_Is_MAC_Address_Slot_Empty(2,reload)){ + mfg_print("Empty slot:%d\r\n",2); + empty=1; + }else{ + mfg_print("No empty slot found\r\n"); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + return empty; +} + +int8_t mfg_efuse_write_macaddr_pre(uint8_t mac[6],uint8_t program) +{ + BL_Err_Type ret=SUCCESS; + uint8_t slot=0xff; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); + +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=1&&EF_Ctrl_Is_MAC_Address_Slot_Empty(0,1)){ + slot=0; + }else if(rf_cal_slots>=2&&EF_Ctrl_Is_MAC_Address_Slot_Empty(1,1)){ + slot=1; + }else if(rf_cal_slots>=3&&EF_Ctrl_Is_MAC_Address_Slot_Empty(2,1)){ + slot=2; + }else{ + mfg_print("No empty slot found\r\n"); + } + + if(slot!=0xff){ + ret=EF_Ctrl_Write_MAC_Address_Opt(slot,mac,program); + mfg_print("Write slot:%d\r\n",slot); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); + +#endif + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +void mfg_efuse_write_macaddr(void) +{ + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + EF_Ctrl_Program_Direct_R0(0,NULL,0); + while(SET==EF_Ctrl_Busy()); + //EF_Ctrl_Program_Direct_R1(0,NULL,0); + //while(SET==EF_Ctrl_Busy()); + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif +} + +int8_t mfg_efuse_read_macaddr(uint8_t mac[6],uint8_t reload) +{ + uint8_t slot=0xff; + BL_Err_Type ret=ERROR; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); + +#if 1 + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(rf_cal_slots>=3&&(!EF_Ctrl_Is_MAC_Address_Slot_Empty(2,reload))){ + slot=2; + }else if(rf_cal_slots>=2&&(!EF_Ctrl_Is_MAC_Address_Slot_Empty(1,reload))){ + slot=1; + }else if(rf_cal_slots>=1&&(!EF_Ctrl_Is_MAC_Address_Slot_Empty(0,reload))){ + slot=0; + } + + if(slot!=0xff){ + mfg_print("Read slot:%d\r\n",slot); + ret=EF_Ctrl_Read_MAC_Address_Opt(slot,mac,reload); + }else{ + mfg_print("No written slot found\r\n"); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); +#endif + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +int8_t mfg_efuse_write_pre(uint32_t addr,uint32_t *data,uint32_t countInword) +{ + BL_Err_Type ret=SUCCESS; + uint8_t hdiv=0,bdiv=0; + + if(addr>128){ + return -1; + } + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); + + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + EF_Ctrl_Write_R0(addr/4,data,countInword); + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); + + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +int8_t mfg_efuse_read(uint32_t addr,uint32_t *data,uint32_t countInword,uint8_t reload) +{ + BL_Err_Type ret=SUCCESS; + uint8_t hdiv=0,bdiv=0; + + if(addr>128){ + return -1; + } + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); + + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + if(reload){ + EF_Ctrl_Read_Direct_R0(addr/4,data,countInword); + }else{ + EF_Ctrl_Read_R0(addr/4,data,countInword); + } + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); + + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} + +int8_t mfg_efuse_program(void) +{ + BL_Err_Type ret=SUCCESS; + uint8_t hdiv=0,bdiv=0; + + bdiv=GLB_Get_BCLK_Div(); + hdiv=GLB_Get_HCLK_Div(); + + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_XTAL); + + EF_Ctrl_Program_Direct_R0(0,NULL,0); + while(SET==EF_Ctrl_Busy()); + + GLB_Set_System_CLK_Div(hdiv,bdiv); + HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); + + if(ret==SUCCESS){ + return 0; + }else{ + return -1; + } +} diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_flash.c b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_flash.c old mode 100755 new mode 100644 index 6bb6ad3f..2926acee --- a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_flash.c +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_flash.c @@ -1,239 +1,239 @@ -#include "bl602_mfg_flash.h" -#include "partition.h" -#include "softcrc.h" - -static rf_para_flash_t rf_para; -static uint32_t rf_para_addr=0; -static SPI_Flash_Cfg_Type *pFlashCfg; - -#ifdef BFLB_MCU_SDK -#include "bflb_platform.h" -#define mfg_print MSG -#else -#define mfg_print printf -#endif -//#define RF_PARA_MAGIC_FLAG 0x41504652 -#define RF_PARA_MAGIC_FLAG 0x41 -#define RF_PARA_VALID_FLAG 0x5A -#define RF_PARA_PART_NAME "rf_para" - - -PtTable_Stuff_Config ptTableStuff[2]; -PtTable_Entry_Config ptEntry={0}; - -/*partiton need this*/ -void main(void) -{ - -} - -static BL_Err_Type PtTable_Flash_Read (uint32_t addr,uint8_t *data, uint32_t len) -{ - XIP_SFlash_Read_Need_Lock(pFlashCfg,addr,data,len); - return SUCCESS; -} - -int8_t mfg_flash_init( SPI_Flash_Cfg_Type *flashCfg) -{ - PtTable_ID_Type activeID; - PtTable_Error_Type ret; - - pFlashCfg=flashCfg; - if(pFlashCfg!=NULL){ - PtTable_Set_Flash_Operation(NULL,NULL,PtTable_Flash_Read); - activeID=PtTable_Get_Active_Partition_Need_Lock(ptTableStuff); - if(PT_TABLE_ID_INVALID==activeID){ - mfg_print("No valid PT\r\n"); - return -1; - } - ret=PtTable_Get_Active_Entries_By_Name(&ptTableStuff[activeID],(uint8_t*)RF_PARA_PART_NAME,&ptEntry); - if(PT_ERROR_SUCCESS==ret){ - rf_para_addr=ptEntry.Address[0]; - mfg_print("RF para flash address=%08x\r\n",(unsigned int)rf_para_addr); - return 0; - }else{ - mfg_print("Not found "RF_PARA_PART_NAME"\r\n"); - return -1; - } - } - return -1; -} - -static int8_t mfg_flash_program(void) -{ - BL_Err_Type ret; - - mfg_print("mfg_flash_write\r\n"); - - __disable_irq(); - ret=XIP_SFlash_Erase_Need_Lock(pFlashCfg,rf_para_addr,rf_para_addr+15); - __enable_irq(); - if(ret!=SUCCESS){ - mfg_print("Flash erase error\r\n"); - return -1; - } - - __disable_irq(); - ret=XIP_SFlash_Write_Need_Lock(pFlashCfg,rf_para_addr,(uint8_t *)&rf_para,sizeof(rf_para)); - __enable_irq(); - if(ret!=SUCCESS){ - mfg_print("Flash write error\r\n"); - return -1; - } - - return 0; -} - -static int8_t mfg_flash_read(void) -{ - BL_Err_Type ret; - - mfg_print("mfg_flash_read\r\n"); - - __disable_irq(); - ret=XIP_SFlash_Read_Need_Lock(pFlashCfg,rf_para_addr,(uint8_t *)&rf_para,sizeof(rf_para)); - __enable_irq(); - if(ret!=SUCCESS){ - mfg_print("Flash write error\r\n"); - return -1; - } - - return 0; -} - -int8_t mfg_flash_write_xtal_capcode_pre(uint8_t capcode,uint8_t program) -{ - rf_para.magic=RF_PARA_MAGIC_FLAG; - rf_para.capcode_valid=RF_PARA_VALID_FLAG; - rf_para.capcode=capcode; - rf_para.crc32=BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8); - - if(program){ - return mfg_flash_program(); - }else{ - return 0; - } -} - -void mfg_flash_write_xtal_capcode(void) -{ - mfg_flash_program(); -} - -int8_t mfg_flash_read_xtal_capcode(uint8_t *capcode,uint8_t reload) -{ - if((reload!=0)&&(mfg_flash_read()!=0)){ - return -1; - } - if(rf_para.magic==RF_PARA_MAGIC_FLAG){ - if(rf_para.crc32==(BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8))){ - if(rf_para.capcode_valid==RF_PARA_VALID_FLAG){ - *capcode=rf_para.capcode; - return 0; - } - } - } - return -1; -} - -int8_t mfg_flash_write_poweroffset_pre(int8_t pwrOffset[14],uint8_t program) -{ - rf_para.magic=RF_PARA_MAGIC_FLAG; - rf_para.poweroffset_valid=RF_PARA_VALID_FLAG; - rf_para.poweroffset[0]=pwrOffset[0]; - rf_para.poweroffset[1]=pwrOffset[6]; - rf_para.poweroffset[2]=pwrOffset[12]; - rf_para.crc32=BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8); - - if(program){ - return mfg_flash_program(); - }else{ - return 0; - } -} - -void mfg_flash_write_poweroffset(void) -{ - mfg_flash_program(); -} - -int8_t mfg_flash_read_poweroffset(int8_t pwrOffset[14],uint8_t reload) -{ - int8_t pwrOffsetTmp[3]; - int32_t step=0; - - if((reload!=0)&&(mfg_flash_read()!=0)){ - return -1; - } - if(rf_para.magic==RF_PARA_MAGIC_FLAG){ - if(rf_para.crc32==(BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8))){ - if(rf_para.poweroffset_valid==RF_PARA_VALID_FLAG){ - memset(pwrOffset,0,14); - pwrOffsetTmp[0]=rf_para.poweroffset[0]; - pwrOffsetTmp[1]=rf_para.poweroffset[1]; - pwrOffsetTmp[2]=rf_para.poweroffset[2]; - - pwrOffset[0]=pwrOffsetTmp[0]; - - step=(pwrOffsetTmp[1]-pwrOffsetTmp[0])*100/6; - pwrOffset[1]=(step+50)/100+pwrOffsetTmp[0]; - pwrOffset[2]=(step*2+50)/100+pwrOffsetTmp[0]; - pwrOffset[3]=(step*3+50)/100+pwrOffsetTmp[0]; - pwrOffset[4]=(step*4+50)/100+pwrOffsetTmp[0]; - pwrOffset[5]=(step*5+50)/100+pwrOffsetTmp[0]; - - pwrOffset[6]=pwrOffsetTmp[1]; - - step=(pwrOffsetTmp[2]-pwrOffsetTmp[1])*100/6; - pwrOffset[7]=(step+50)/100+pwrOffsetTmp[1]; - pwrOffset[8]=(step*2+50)/100+pwrOffsetTmp[1]; - pwrOffset[9]=(step*3+50)/100+pwrOffsetTmp[1]; - pwrOffset[10]=(step*4+50)/100+pwrOffsetTmp[1]; - pwrOffset[11]=(step*5+50)/100+pwrOffsetTmp[1]; - - pwrOffset[12]=pwrOffsetTmp[2]; - - pwrOffset[13]=(step*7+50)/100+pwrOffsetTmp[1]; - return 0; - } - } - } - return -1; -} - -int8_t mfg_flash_write_macaddr_pre(uint8_t mac[6],uint8_t program) -{ - rf_para.magic=RF_PARA_MAGIC_FLAG; - rf_para.mac_valid=RF_PARA_VALID_FLAG; - memcpy(rf_para.mac,mac,6); - rf_para.crc32=BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8); - - if(program){ - return mfg_flash_program(); - }else{ - return 0; - } -} - -void mfg_flash_write_macaddr(void) -{ - mfg_flash_program(); -} - -int8_t mfg_flash_read_macaddr(uint8_t mac[6],uint8_t reload) -{ - if((reload!=0)&&(mfg_flash_read()!=0)){ - mfg_print("mfg_flash_read fail\r\n"); - return -1; - } - if(rf_para.magic==RF_PARA_MAGIC_FLAG){ - if(rf_para.crc32==(BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8))){ - if(rf_para.mac_valid==RF_PARA_VALID_FLAG){ - memcpy(mac,rf_para.mac,6); - return 0; - } - } - } - return -1; -} - +#include "bl602_mfg_flash.h" +#include "partition.h" +#include "softcrc.h" + +static rf_para_flash_t rf_para; +static uint32_t rf_para_addr=0; +static SPI_Flash_Cfg_Type *pFlashCfg; + +#ifdef BFLB_MCU_SDK +#include "bflb_platform.h" +#define mfg_print MSG +#else +#define mfg_print printf +#endif +//#define RF_PARA_MAGIC_FLAG 0x41504652 +#define RF_PARA_MAGIC_FLAG 0x41 +#define RF_PARA_VALID_FLAG 0x5A +#define RF_PARA_PART_NAME "rf_para" + + +PtTable_Stuff_Config ptTableStuff[2]; +PtTable_Entry_Config ptEntry={0}; + +/*partiton need this*/ +void main(void) +{ + +} + +static BL_Err_Type PtTable_Flash_Read (uint32_t addr,uint8_t *data, uint32_t len) +{ + XIP_SFlash_Read_Need_Lock(pFlashCfg,addr,data,len); + return SUCCESS; +} + +int8_t mfg_flash_init( SPI_Flash_Cfg_Type *flashCfg) +{ + PtTable_ID_Type activeID; + PtTable_Error_Type ret; + + pFlashCfg=flashCfg; + if(pFlashCfg!=NULL){ + PtTable_Set_Flash_Operation(NULL,NULL,PtTable_Flash_Read); + activeID=PtTable_Get_Active_Partition_Need_Lock(ptTableStuff); + if(PT_TABLE_ID_INVALID==activeID){ + mfg_print("No valid PT\r\n"); + return -1; + } + ret=PtTable_Get_Active_Entries_By_Name(&ptTableStuff[activeID],(uint8_t*)RF_PARA_PART_NAME,&ptEntry); + if(PT_ERROR_SUCCESS==ret){ + rf_para_addr=ptEntry.Address[0]; + mfg_print("RF para flash address=%08x\r\n",(unsigned int)rf_para_addr); + return 0; + }else{ + mfg_print("Not found "RF_PARA_PART_NAME"\r\n"); + return -1; + } + } + return -1; +} + +static int8_t mfg_flash_program(void) +{ + BL_Err_Type ret; + + mfg_print("mfg_flash_write\r\n"); + + __disable_irq(); + ret=XIP_SFlash_Erase_Need_Lock(pFlashCfg,rf_para_addr,rf_para_addr+15); + __enable_irq(); + if(ret!=SUCCESS){ + mfg_print("Flash erase error\r\n"); + return -1; + } + + __disable_irq(); + ret=XIP_SFlash_Write_Need_Lock(pFlashCfg,rf_para_addr,(uint8_t *)&rf_para,sizeof(rf_para)); + __enable_irq(); + if(ret!=SUCCESS){ + mfg_print("Flash write error\r\n"); + return -1; + } + + return 0; +} + +static int8_t mfg_flash_read(void) +{ + BL_Err_Type ret; + + mfg_print("mfg_flash_read\r\n"); + + __disable_irq(); + ret=XIP_SFlash_Read_Need_Lock(pFlashCfg,rf_para_addr,(uint8_t *)&rf_para,sizeof(rf_para)); + __enable_irq(); + if(ret!=SUCCESS){ + mfg_print("Flash write error\r\n"); + return -1; + } + + return 0; +} + +int8_t mfg_flash_write_xtal_capcode_pre(uint8_t capcode,uint8_t program) +{ + rf_para.magic=RF_PARA_MAGIC_FLAG; + rf_para.capcode_valid=RF_PARA_VALID_FLAG; + rf_para.capcode=capcode; + rf_para.crc32=BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8); + + if(program){ + return mfg_flash_program(); + }else{ + return 0; + } +} + +void mfg_flash_write_xtal_capcode(void) +{ + mfg_flash_program(); +} + +int8_t mfg_flash_read_xtal_capcode(uint8_t *capcode,uint8_t reload) +{ + if((reload!=0)&&(mfg_flash_read()!=0)){ + return -1; + } + if(rf_para.magic==RF_PARA_MAGIC_FLAG){ + if(rf_para.crc32==(BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8))){ + if(rf_para.capcode_valid==RF_PARA_VALID_FLAG){ + *capcode=rf_para.capcode; + return 0; + } + } + } + return -1; +} + +int8_t mfg_flash_write_poweroffset_pre(int8_t pwrOffset[14],uint8_t program) +{ + rf_para.magic=RF_PARA_MAGIC_FLAG; + rf_para.poweroffset_valid=RF_PARA_VALID_FLAG; + rf_para.poweroffset[0]=pwrOffset[0]; + rf_para.poweroffset[1]=pwrOffset[6]; + rf_para.poweroffset[2]=pwrOffset[12]; + rf_para.crc32=BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8); + + if(program){ + return mfg_flash_program(); + }else{ + return 0; + } +} + +void mfg_flash_write_poweroffset(void) +{ + mfg_flash_program(); +} + +int8_t mfg_flash_read_poweroffset(int8_t pwrOffset[14],uint8_t reload) +{ + int8_t pwrOffsetTmp[3]; + int32_t step=0; + + if((reload!=0)&&(mfg_flash_read()!=0)){ + return -1; + } + if(rf_para.magic==RF_PARA_MAGIC_FLAG){ + if(rf_para.crc32==(BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8))){ + if(rf_para.poweroffset_valid==RF_PARA_VALID_FLAG){ + memset(pwrOffset,0,14); + pwrOffsetTmp[0]=rf_para.poweroffset[0]; + pwrOffsetTmp[1]=rf_para.poweroffset[1]; + pwrOffsetTmp[2]=rf_para.poweroffset[2]; + + pwrOffset[0]=pwrOffsetTmp[0]; + + step=(pwrOffsetTmp[1]-pwrOffsetTmp[0])*100/6; + pwrOffset[1]=(step+50)/100+pwrOffsetTmp[0]; + pwrOffset[2]=(step*2+50)/100+pwrOffsetTmp[0]; + pwrOffset[3]=(step*3+50)/100+pwrOffsetTmp[0]; + pwrOffset[4]=(step*4+50)/100+pwrOffsetTmp[0]; + pwrOffset[5]=(step*5+50)/100+pwrOffsetTmp[0]; + + pwrOffset[6]=pwrOffsetTmp[1]; + + step=(pwrOffsetTmp[2]-pwrOffsetTmp[1])*100/6; + pwrOffset[7]=(step+50)/100+pwrOffsetTmp[1]; + pwrOffset[8]=(step*2+50)/100+pwrOffsetTmp[1]; + pwrOffset[9]=(step*3+50)/100+pwrOffsetTmp[1]; + pwrOffset[10]=(step*4+50)/100+pwrOffsetTmp[1]; + pwrOffset[11]=(step*5+50)/100+pwrOffsetTmp[1]; + + pwrOffset[12]=pwrOffsetTmp[2]; + + pwrOffset[13]=(step*7+50)/100+pwrOffsetTmp[1]; + return 0; + } + } + } + return -1; +} + +int8_t mfg_flash_write_macaddr_pre(uint8_t mac[6],uint8_t program) +{ + rf_para.magic=RF_PARA_MAGIC_FLAG; + rf_para.mac_valid=RF_PARA_VALID_FLAG; + memcpy(rf_para.mac,mac,6); + rf_para.crc32=BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8); + + if(program){ + return mfg_flash_program(); + }else{ + return 0; + } +} + +void mfg_flash_write_macaddr(void) +{ + mfg_flash_program(); +} + +int8_t mfg_flash_read_macaddr(uint8_t mac[6],uint8_t reload) +{ + if((reload!=0)&&(mfg_flash_read()!=0)){ + mfg_print("mfg_flash_read fail\r\n"); + return -1; + } + if(rf_para.magic==RF_PARA_MAGIC_FLAG){ + if(rf_para.crc32==(BFLB_Soft_CRC32(&rf_para.capcode_valid,sizeof(rf_para)-8))){ + if(rf_para.mac_valid==RF_PARA_VALID_FLAG){ + memcpy(mac,rf_para.mac,6); + return 0; + } + } + } + return -1; +} + diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_media.c b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_media.c old mode 100755 new mode 100644 index f014a69f..571bbd10 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_media.c +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_media.c @@ -1,122 +1,122 @@ -#include "bl602_mfg_media.h" - -static uint8_t rf_para_on_flash=0; - -int8_t mfg_media_init( SPI_Flash_Cfg_Type *flashCfg) -{ - if(0==mfg_flash_init(flashCfg)){ - rf_para_on_flash=1; - }else{ - rf_para_on_flash=0; - } - return 0; -} - -uint8_t mfg_media_is_xtal_capcode_slot_empty(uint8_t reload) -{ - if(rf_para_on_flash){ - return 1; - }else{ - return mfg_efuse_is_xtal_capcode_slot_empty(reload); - } -} - -int8_t mfg_media_write_xtal_capcode_pre(uint8_t capcode,uint8_t program) -{ - if(rf_para_on_flash){ - return mfg_flash_write_xtal_capcode_pre(capcode,program); - }else{ - return mfg_efuse_write_xtal_capcode_pre(capcode,program); - } -} - -void mfg_media_write_xtal_capcode(void) -{ - if(rf_para_on_flash){ - return mfg_flash_write_xtal_capcode(); - }else{ - return mfg_efuse_write_xtal_capcode(); - } -} - -int8_t mfg_media_read_xtal_capcode(uint8_t *capcode,uint8_t reload) -{ - if(rf_para_on_flash){ - return mfg_flash_read_xtal_capcode(capcode,reload); - }else{ - return mfg_efuse_read_xtal_capcode(capcode,reload); - } -} - -uint8_t mfg_media_is_poweroffset_slot_empty(uint8_t reload) -{ - if(rf_para_on_flash){ - return 1; - }else{ - return mfg_efuse_is_poweroffset_slot_empty(reload); - } -} - -int8_t mfg_media_write_poweroffset_pre(int8_t pwrOffset[14],uint8_t program) -{ - if(rf_para_on_flash){ - return mfg_flash_write_poweroffset_pre(pwrOffset,program); - }else{ - return mfg_efuse_write_poweroffset_pre(pwrOffset,program); - } -} - -void mfg_media_write_poweroffset(void) -{ - if(rf_para_on_flash){ - return mfg_flash_write_poweroffset(); - }else{ - return mfg_efuse_write_poweroffset(); - } -} - -int8_t mfg_media_read_poweroffset(int8_t pwrOffset[14],uint8_t reload) -{ - if(rf_para_on_flash){ - return mfg_flash_read_poweroffset(pwrOffset,reload); - }else{ - return mfg_efuse_read_poweroffset(pwrOffset,reload); - } -} - -uint8_t mfg_media_is_macaddr_slot_empty(uint8_t reload) -{ - if(rf_para_on_flash){ - return 1; - }else{ - return mfg_efuse_is_macaddr_slot_empty(reload); - } -} - -int8_t mfg_media_write_macaddr_pre(uint8_t mac[6],uint8_t program) -{ - if(rf_para_on_flash){ - return mfg_flash_write_macaddr_pre(mac,program); - }else{ - return mfg_efuse_write_macaddr_pre(mac,program); - } -} - -void mfg_media_write_macaddr(void) -{ - if(rf_para_on_flash){ - return mfg_flash_write_macaddr(); - }else{ - return mfg_efuse_write_macaddr(); - } -} - -int8_t mfg_media_read_macaddr(uint8_t mac[6],uint8_t reload) -{ - if(rf_para_on_flash){ - return mfg_flash_read_macaddr(mac,reload); - }else{ - return mfg_efuse_read_macaddr(mac,reload); - } -} - +#include "bl602_mfg_media.h" + +static uint8_t rf_para_on_flash=0; + +int8_t mfg_media_init( SPI_Flash_Cfg_Type *flashCfg) +{ + if(0==mfg_flash_init(flashCfg)){ + rf_para_on_flash=1; + }else{ + rf_para_on_flash=0; + } + return 0; +} + +uint8_t mfg_media_is_xtal_capcode_slot_empty(uint8_t reload) +{ + if(rf_para_on_flash){ + return 1; + }else{ + return mfg_efuse_is_xtal_capcode_slot_empty(reload); + } +} + +int8_t mfg_media_write_xtal_capcode_pre(uint8_t capcode,uint8_t program) +{ + if(rf_para_on_flash){ + return mfg_flash_write_xtal_capcode_pre(capcode,program); + }else{ + return mfg_efuse_write_xtal_capcode_pre(capcode,program); + } +} + +void mfg_media_write_xtal_capcode(void) +{ + if(rf_para_on_flash){ + return mfg_flash_write_xtal_capcode(); + }else{ + return mfg_efuse_write_xtal_capcode(); + } +} + +int8_t mfg_media_read_xtal_capcode(uint8_t *capcode,uint8_t reload) +{ + if(rf_para_on_flash){ + return mfg_flash_read_xtal_capcode(capcode,reload); + }else{ + return mfg_efuse_read_xtal_capcode(capcode,reload); + } +} + +uint8_t mfg_media_is_poweroffset_slot_empty(uint8_t reload) +{ + if(rf_para_on_flash){ + return 1; + }else{ + return mfg_efuse_is_poweroffset_slot_empty(reload); + } +} + +int8_t mfg_media_write_poweroffset_pre(int8_t pwrOffset[14],uint8_t program) +{ + if(rf_para_on_flash){ + return mfg_flash_write_poweroffset_pre(pwrOffset,program); + }else{ + return mfg_efuse_write_poweroffset_pre(pwrOffset,program); + } +} + +void mfg_media_write_poweroffset(void) +{ + if(rf_para_on_flash){ + return mfg_flash_write_poweroffset(); + }else{ + return mfg_efuse_write_poweroffset(); + } +} + +int8_t mfg_media_read_poweroffset(int8_t pwrOffset[14],uint8_t reload) +{ + if(rf_para_on_flash){ + return mfg_flash_read_poweroffset(pwrOffset,reload); + }else{ + return mfg_efuse_read_poweroffset(pwrOffset,reload); + } +} + +uint8_t mfg_media_is_macaddr_slot_empty(uint8_t reload) +{ + if(rf_para_on_flash){ + return 1; + }else{ + return mfg_efuse_is_macaddr_slot_empty(reload); + } +} + +int8_t mfg_media_write_macaddr_pre(uint8_t mac[6],uint8_t program) +{ + if(rf_para_on_flash){ + return mfg_flash_write_macaddr_pre(mac,program); + }else{ + return mfg_efuse_write_macaddr_pre(mac,program); + } +} + +void mfg_media_write_macaddr(void) +{ + if(rf_para_on_flash){ + return mfg_flash_write_macaddr(); + }else{ + return mfg_efuse_write_macaddr(); + } +} + +int8_t mfg_media_read_macaddr(uint8_t mac[6],uint8_t reload) +{ + if(rf_para_on_flash){ + return mfg_flash_read_macaddr(mac,reload); + }else{ + return mfg_efuse_read_macaddr(mac,reload); + } +} + diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_romapi.c b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_romapi.c index e84923a8..dfb1a639 100644 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_romapi.c +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_romapi.c @@ -1,866 +1,866 @@ -#include "bl602_romdriver.h" - - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_MBG(void){ - return RomDriver_AON_Power_On_MBG(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_MBG(void){ - return RomDriver_AON_Power_Off_MBG(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_XTAL(void){ - return RomDriver_AON_Power_On_XTAL(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode(uint8_t capIn,uint8_t capOut){ - return RomDriver_AON_Set_Xtal_CapCode(capIn,capOut); -} - -__ALWAYS_INLINE -uint8_t ATTR_CLOCK_SECTION AON_Get_Xtal_CapCode(void){ - return RomDriver_AON_Get_Xtal_CapCode(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_XTAL(void){ - return RomDriver_AON_Power_Off_XTAL(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_BG(void){ - return RomDriver_AON_Power_On_BG(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_BG(void){ - return RomDriver_AON_Power_Off_BG(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO11_SOC(void){ - return RomDriver_AON_Power_On_LDO11_SOC(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO11_SOC(void){ - return RomDriver_AON_Power_Off_LDO11_SOC(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO15_RF(void){ - return RomDriver_AON_Power_On_LDO15_RF(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO15_RF(void){ - return RomDriver_AON_Power_Off_LDO15_RF(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_On_SFReg(void){ - return RomDriver_AON_Power_On_SFReg(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_SFReg(void){ - return RomDriver_AON_Power_Off_SFReg(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Enter_PDS0(void){ - return RomDriver_AON_LowPower_Enter_PDS0(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Exit_PDS0(void){ - return RomDriver_AON_LowPower_Exit_PDS0(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core,uint32_t cnt){ - return RomDriver_ASM_Delay_Us(core,cnt); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION BL602_Delay_US(uint32_t cnt){ - return RomDriver_BL602_Delay_US(cnt); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION BL602_Delay_MS(uint32_t cnt){ - return RomDriver_BL602_Delay_MS(cnt); -} - -__ALWAYS_INLINE -void* ATTR_TCM_SECTION BL602_MemCpy(void *dst, const void *src, uint32_t n){ - return RomDriver_BL602_MemCpy(dst,src,n); -} - -__ALWAYS_INLINE -uint32_t* ATTR_TCM_SECTION BL602_MemCpy4(uint32_t *dst, const uint32_t *src, uint32_t n){ - return RomDriver_BL602_MemCpy4(dst,src,n); -} - -__ALWAYS_INLINE -void* ATTR_TCM_SECTION BL602_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n){ - return RomDriver_BL602_MemCpy_Fast(pdst,psrc,n); -} - -__ALWAYS_INLINE -void* ATTR_TCM_SECTION BL602_MemSet(void *s, uint8_t c, uint32_t n){ - return RomDriver_BL602_MemSet(s,c,n); -} - -__ALWAYS_INLINE -uint32_t* ATTR_TCM_SECTION BL602_MemSet4(uint32_t *dst, const uint32_t val, uint32_t n){ - return RomDriver_BL602_MemSet4(dst,val,n); -} - -__ALWAYS_INLINE -int ATTR_TCM_SECTION BL602_MemCmp(const void *s1, const void *s2, uint32_t n){ - return RomDriver_BL602_MemCmp(s1,s2,n); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION EF_Ctrl_Sw_AHB_Clk_0(void){ - return RomDriver_EF_Ctrl_Sw_AHB_Clk_0(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION EF_Ctrl_Program_Efuse_0(void){ - return RomDriver_EF_Ctrl_Program_Efuse_0(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION EF_Ctrl_Load_Efuse_R0(void){ - return RomDriver_EF_Ctrl_Load_Efuse_R0(); -} - -__ALWAYS_INLINE -BL_Sts_Type ATTR_TCM_SECTION EF_Ctrl_Busy(void){ - return RomDriver_EF_Ctrl_Busy(); -} - -__ALWAYS_INLINE -BL_Sts_Type ATTR_TCM_SECTION EF_Ctrl_AutoLoad_Done(void){ - return RomDriver_EF_Ctrl_AutoLoad_Done(); -} - -__ALWAYS_INLINE -uint8_t ATTR_CLOCK_SECTION EF_Ctrl_Get_Trim_Parity(uint32_t val,uint8_t len){ - return RomDriver_EF_Ctrl_Get_Trim_Parity(val,len); -} - -__ALWAYS_INLINE -void ATTR_CLOCK_SECTION EF_Ctrl_Read_RC32M_Trim( Efuse_Ana_RC32M_Trim_Type *trim){ - return RomDriver_EF_Ctrl_Read_RC32M_Trim(trim); -} - -__ALWAYS_INLINE -void ATTR_CLOCK_SECTION EF_Ctrl_Read_RC32K_Trim( Efuse_Ana_RC32K_Trim_Type *trim){ - return RomDriver_EF_Ctrl_Read_RC32K_Trim(trim); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION EF_Ctrl_Clear(uint32_t index, uint32_t len){ - return RomDriver_EF_Ctrl_Clear(index,len); -} - -__ALWAYS_INLINE -GLB_ROOT_CLK_Type ATTR_CLOCK_SECTION GLB_Get_Root_CLK_Sel(void){ - return RomDriver_GLB_Get_Root_CLK_Sel(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK_Div(uint8_t hclkDiv,uint8_t bclkDiv){ - return RomDriver_GLB_Set_System_CLK_Div(hclkDiv,bclkDiv); -} - -__ALWAYS_INLINE -uint8_t ATTR_CLOCK_SECTION GLB_Get_BCLK_Div(void){ - return RomDriver_GLB_Get_BCLK_Div(); -} - -__ALWAYS_INLINE -uint8_t ATTR_CLOCK_SECTION GLB_Get_HCLK_Div(void){ - return RomDriver_GLB_Get_HCLK_Div(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION Update_SystemCoreClockWith_XTAL(GLB_PLL_XTAL_Type xtalType){ - return RomDriver_Update_SystemCoreClockWith_XTAL(xtalType); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK(GLB_PLL_XTAL_Type xtalType,GLB_SYS_CLK_Type clkFreq){ - return RomDriver_GLB_Set_System_CLK(xtalType,clkFreq); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION System_Core_Clock_Update_From_RC32M(void){ - return RomDriver_System_Core_Clock_Update_From_RC32M(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_SF_CLK(uint8_t enable,GLB_SFLASH_CLK_Type clkSel,uint8_t div){ - return RomDriver_GLB_Set_SF_CLK(enable,clkSel,div); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_PKA_CLK_Sel(GLB_PKA_CLK_Type clkSel){ - return RomDriver_GLB_Set_PKA_CLK_Sel(clkSel); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_SW_System_Reset(void){ - return RomDriver_GLB_SW_System_Reset(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_SW_CPU_Reset(void){ - return RomDriver_GLB_SW_CPU_Reset(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_SW_POR_Reset(void){ - return RomDriver_GLB_SW_POR_Reset(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_Flash(void){ - return RomDriver_GLB_Select_Internal_Flash(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_Select_External_Flash(void){ - return RomDriver_GLB_Select_External_Flash(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_Deswap_Flash_Pin(void){ - return RomDriver_GLB_Deswap_Flash_Pin(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_Pin(void){ - return RomDriver_GLB_Swap_Flash_Pin(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Init(GLB_GPIO_Cfg_Type *cfg){ - return RomDriver_GLB_GPIO_Init(cfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Enable(GLB_GPIO_Type gpioPin){ - return RomDriver_GLB_GPIO_OUTPUT_Enable(gpioPin); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Disable(GLB_GPIO_Type gpioPin){ - return RomDriver_GLB_GPIO_OUTPUT_Disable(gpioPin); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin){ - return RomDriver_GLB_GPIO_Set_HZ(gpioPin); -} - -__ALWAYS_INLINE -uint8_t ATTR_TCM_SECTION GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin){ - return RomDriver_GLB_GPIO_Get_Fun(gpioPin); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION HBN_Mode_Enter(HBN_APP_CFG_Type *cfg){ - return RomDriver_HBN_Mode_Enter(cfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION HBN_Power_Down_Flash(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_HBN_Power_Down_Flash(flashCfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION HBN_Enable(uint8_t aGPIOIeCfg,HBN_LDO_LEVEL_Type ldoLevel,HBN_LEVEL_Type hbnLevel){ - return RomDriver_HBN_Enable(aGPIOIeCfg,ldoLevel,hbnLevel); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_Reset(void){ - return RomDriver_HBN_Reset(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Aon_Vout(HBN_LDO_LEVEL_Type ldoLevel){ - return RomDriver_HBN_Set_Ldo11_Aon_Vout(ldoLevel); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Rt_Vout(HBN_LDO_LEVEL_Type ldoLevel){ - return RomDriver_HBN_Set_Ldo11_Rt_Vout(ldoLevel); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Soc_Vout(HBN_LDO_LEVEL_Type ldoLevel){ - return RomDriver_HBN_Set_Ldo11_Soc_Vout(ldoLevel); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION HBN_32K_Sel(HBN_32K_CLK_Type clkType){ - return RomDriver_HBN_32K_Sel(clkType); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk){ - return RomDriver_HBN_Set_ROOT_CLK_Sel(rootClk); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_Xtal_32K(void){ - return RomDriver_HBN_Power_On_Xtal_32K(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_Xtal_32K(void){ - return RomDriver_HBN_Power_Off_Xtal_32K(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_RC32K(void){ - return RomDriver_HBN_Power_On_RC32K(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_RC32K(void){ - return RomDriver_HBN_Power_Off_RC32K(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION HBN_Trim_RC32K(void){ - return RomDriver_HBN_Trim_RC32K(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_Hw_Pu_Pd_Cfg(uint8_t enable){ - return RomDriver_HBN_Hw_Pu_Pd_Cfg(enable); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_Pin_WakeUp_Mask(uint8_t maskVal){ - return RomDriver_HBN_Pin_WakeUp_Mask(maskVal); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_GPIO7_Dbg_Pull_Cfg(BL_Fun_Type pupdEn,BL_Fun_Type iesmtEn,BL_Fun_Type dlyEn,uint8_t dlySec){ - return RomDriver_HBN_GPIO7_Dbg_Pull_Cfg(pupdEn,iesmtEn,dlyEn,dlySec); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION HBN_Set_Embedded_Flash_Pullup(uint8_t enable){ - return RomDriver_HBN_Set_Embedded_Flash_Pullup(enable); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION L1C_Set_Wrap(BL_Fun_Type wrap){ - return RomDriver_L1C_Set_Wrap(wrap); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION L1C_Set_Way_Disable(uint8_t disableVal){ - return RomDriver_L1C_Set_Way_Disable(disableVal); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION L1C_IROM_2T_Access_Set(uint8_t enable){ - return RomDriver_L1C_IROM_2T_Access_Set(enable); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION PDS_Reset(void){ - return RomDriver_PDS_Reset(); -} - -#if 0 -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION PDS_Enable(PDS_CTL_Type *cfg,PDS_CTL4_Type *cfg4,uint32_t pdsSleepCnt){ - return RomDriver_PDS_Enable(cfg,cfg4,pdsSleepCnt); -} -#endif - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION PDS_Force_Config(PDS_CTL2_Type *cfg2,PDS_CTL3_Type *cfg3){ - return RomDriver_PDS_Force_Config(cfg2,cfg3); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION PDS_RAM_Config(PDS_RAM_CFG_Type *ramCfg){ - return RomDriver_PDS_RAM_Config(ramCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION PDS_Default_Level_Config(PDS_DEFAULT_LV_CFG_Type *defaultLvCfg,PDS_RAM_CFG_Type *ramCfg,uint32_t pdsSleepCnt){ - return RomDriver_PDS_Default_Level_Config(defaultLvCfg,ramCfg,pdsSleepCnt); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Trim_RC32M(void){ - return RomDriver_PDS_Trim_RC32M(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_RC32M_As_PLL_Ref(void){ - return RomDriver_PDS_Select_RC32M_As_PLL_Ref(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_XTAL_As_PLL_Ref(void){ - return RomDriver_PDS_Select_XTAL_As_PLL_Ref(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType){ - return RomDriver_PDS_Power_On_PLL(xtalType); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_All_Clks(void){ - return RomDriver_PDS_Enable_PLL_All_Clks(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_All_Clks(void){ - return RomDriver_PDS_Disable_PLL_All_Clks(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk){ - return RomDriver_PDS_Enable_PLL_Clk(pllClk); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk){ - return RomDriver_PDS_Disable_PLL_Clk(pllClk); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_Off_PLL(void){ - return RomDriver_PDS_Power_Off_PLL(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SEC_Eng_Turn_On_Sec_Ring(void){ - return RomDriver_SEC_Eng_Turn_On_Sec_Ring(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SEC_Eng_Turn_Off_Sec_Ring(void){ - return RomDriver_SEC_Eng_Turn_Off_Sec_Ring(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_Init(const SF_Ctrl_Cfg_Type *pSfCtrlCfg){ - return RomDriver_SFlash_Init(pSfCtrlCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_SetSPIMode(SF_Ctrl_Mode_Type mode){ - return RomDriver_SFlash_SetSPIMode(mode); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg(SPI_Flash_Cfg_Type *flashCfg,uint8_t regIndex,uint8_t *regValue,uint8_t regLen){ - return RomDriver_SFlash_Read_Reg(flashCfg,regIndex,regValue,regLen); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg(SPI_Flash_Cfg_Type *flashCfg,uint8_t regIndex,uint8_t *regValue,uint8_t regLen){ - return RomDriver_SFlash_Write_Reg(flashCfg,regIndex,regValue,regLen); -} - -__ALWAYS_INLINE -BL_Sts_Type ATTR_TCM_SECTION SFlash_Busy(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Busy(flashCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Enable(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Write_Enable(flashCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Qspi_Enable(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Qspi_Enable(flashCfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_Volatile_Reg_Write_Enable(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Volatile_Reg_Write_Enable(flashCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Chip_Erase(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Chip_Erase(flashCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Sector_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t secNum){ - return RomDriver_SFlash_Sector_Erase(flashCfg,secNum); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Blk32_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t blkNum){ - return RomDriver_SFlash_Blk32_Erase(flashCfg,blkNum); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Blk64_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t blkNum){ - return RomDriver_SFlash_Blk64_Erase(flashCfg,blkNum); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t startaddr,uint32_t endaddr){ - return RomDriver_SFlash_Erase(flashCfg,startaddr,endaddr); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Program(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint32_t addr,uint8_t *data, uint32_t len){ - return RomDriver_SFlash_Program(flashCfg,ioMode,addr,data,len); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_GetUniqueId(uint8_t *data,uint8_t idLen){ - return RomDriver_SFlash_GetUniqueId(data,idLen); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_GetJedecId(SPI_Flash_Cfg_Type *flashCfg,uint8_t *data){ - return RomDriver_SFlash_GetJedecId(flashCfg,data); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_GetDeviceId(uint8_t *data){ - return RomDriver_SFlash_GetDeviceId(data); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_Powerdown(void){ - return RomDriver_SFlash_Powerdown(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_Releae_Powerdown(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Releae_Powerdown(flashCfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_SetBurstWrap(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_SetBurstWrap(flashCfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_DisableBurstWrap(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_DisableBurstWrap(flashCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Software_Reset(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Software_Reset(flashCfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_Reset_Continue_Read(SPI_Flash_Cfg_Type *flashCfg){ - return RomDriver_SFlash_Reset_Continue_Read(flashCfg); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Set_IDbus_Cfg(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead,uint32_t addr,uint32_t len){ - return RomDriver_SFlash_Set_IDbus_Cfg(flashCfg,ioMode,contRead,addr,len); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_IDbus_Read_Enable(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead){ - return RomDriver_SFlash_IDbus_Read_Enable(flashCfg,ioMode,contRead); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Enable_Set(uint8_t wayDisable){ - return RomDriver_SFlash_Cache_Enable_Set(wayDisable); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Flush(void){ - return RomDriver_SFlash_Cache_Flush(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Read_Enable(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead,uint8_t wayDisable){ - return RomDriver_SFlash_Cache_Read_Enable(flashCfg,ioMode,contRead,wayDisable); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_Cache_Hit_Count_Get(uint32_t *hitCountLow,uint32_t *hitCountHigh){ - return RomDriver_SFlash_Cache_Hit_Count_Get(hitCountLow,hitCountHigh); -} - -__ALWAYS_INLINE -uint32_t ATTR_TCM_SECTION SFlash_Cache_Miss_Count_Get(void){ - return RomDriver_SFlash_Cache_Miss_Count_Get(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SFlash_Cache_Read_Disable(void){ - return RomDriver_SFlash_Cache_Read_Disable(); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Read(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead,uint32_t addr,uint8_t *data, uint32_t len){ - return RomDriver_SFlash_Read(flashCfg,ioMode,contRead,addr,data,len); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg,uint8_t readRegCmd,uint8_t *regValue,uint8_t regLen){ - return RomDriver_SFlash_Read_Reg_With_Cmd(flashCfg,readRegCmd,regValue,regLen); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg,uint8_t writeRegCmd,uint8_t *regValue,uint8_t regLen){ - return RomDriver_SFlash_Write_Reg_With_Cmd(flashCfg,writeRegCmd,regValue,regLen); -} - -#if 0 -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SFlash_Restore_From_Powerdown(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t flashContRead){ - return RomDriver_SFlash_Restore_From_Powerdown(pFlashCfg,flashContRead); -} -#endif - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin){ - return RomDriver_SF_Cfg_Init_Ext_Flash_Gpio(extFlashPin); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Cfg_Init_Internal_Flash_Gpio(void){ - return RomDriver_SF_Cfg_Init_Internal_Flash_Gpio(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin){ - return RomDriver_SF_Cfg_Deinit_Ext_Flash_Gpio(extFlashPin); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Cfg_Restore_GPIO17_Fun(uint8_t fun){ - return RomDriver_SF_Cfg_Restore_GPIO17_Fun(fun); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID,SPI_Flash_Cfg_Type * pFlashCfg){ - return RomDriver_SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID,pFlashCfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg,uint8_t restoreDefault){ - return RomDriver_SF_Cfg_Init_Flash_Gpio(flashPinCfg,restoreDefault); -} - -__ALWAYS_INLINE -uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify(uint8_t callFromFlash,uint32_t autoScan,uint32_t flashPinCfg,uint8_t restoreDefault,SPI_Flash_Cfg_Type * pFlashCfg){ - return RomDriver_SF_Cfg_Flash_Identify(callFromFlash,autoScan,flashPinCfg,restoreDefault,pFlashCfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg){ - return RomDriver_SF_Ctrl_Enable(cfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Sel sel){ - return RomDriver_SF_Ctrl_Select_Pad(sel); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner){ - return RomDriver_SF_Ctrl_Set_Owner(owner); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Disable(void){ - return RomDriver_SF_Ctrl_Disable(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_BE(void){ - return RomDriver_SF_Ctrl_AES_Enable_BE(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_LE(void){ - return RomDriver_SF_Ctrl_AES_Enable_LE(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Region(uint8_t region,uint8_t enable,uint8_t hwKey,uint32_t startAddr,uint32_t endAddr,uint8_t locked){ - return RomDriver_SF_Ctrl_AES_Set_Region(region,enable,hwKey,startAddr,endAddr,locked); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key(uint8_t region,uint8_t *key, SF_Ctrl_AES_Key_Type keyType){ - return RomDriver_SF_Ctrl_AES_Set_Key(region,key,keyType); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key_BE(uint8_t region,uint8_t *key, SF_Ctrl_AES_Key_Type keyType){ - return RomDriver_SF_Ctrl_AES_Set_Key_BE(region,key,keyType); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV(uint8_t region,uint8_t *iv,uint32_t addrOffset){ - return RomDriver_SF_Ctrl_AES_Set_IV(region,iv,addrOffset); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV_BE(uint8_t region,uint8_t *iv,uint32_t addrOffset){ - return RomDriver_SF_Ctrl_AES_Set_IV_BE(region,iv,addrOffset); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Enable(void){ - return RomDriver_SF_Ctrl_AES_Enable(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_AES_Disable(void){ - return RomDriver_SF_Ctrl_AES_Disable(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset){ - return RomDriver_SF_Ctrl_Set_Flash_Image_Offset(addrOffset); -} - -__ALWAYS_INLINE -uint32_t ATTR_TCM_SECTION SF_Ctrl_Get_Flash_Image_Offset(void){ - return RomDriver_SF_Ctrl_Get_Flash_Image_Offset(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType){ - return RomDriver_SF_Ctrl_Select_Clock(sahbType); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg){ - return RomDriver_SF_Ctrl_SendCmd(cfg); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg,uint8_t cmdValid){ - return RomDriver_SF_Ctrl_Icache_Set(cfg,cmdValid); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Icache2_Set(SF_Ctrl_Cmd_Cfg_Type *cfg,uint8_t cmdValid){ - return RomDriver_SF_Ctrl_Icache2_Set(cfg,cmdValid); -} - -__ALWAYS_INLINE -BL_Sts_Type ATTR_TCM_SECTION SF_Ctrl_GetBusyState(void){ - return RomDriver_SF_Ctrl_GetBusyState(); -} - -__ALWAYS_INLINE -uint8_t ATTR_TCM_SECTION SF_Ctrl_Is_AES_Enable(void){ - return RomDriver_SF_Ctrl_Is_AES_Enable(); -} - -__ALWAYS_INLINE -uint8_t ATTR_TCM_SECTION SF_Ctrl_Get_Clock_Delay(void){ - return RomDriver_SF_Ctrl_Get_Clock_Delay(); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION SF_Ctrl_Set_Clock_Delay(uint8_t delay){ - return RomDriver_SF_Ctrl_Set_Clock_Delay(delay); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t *offset){ - return RomDriver_XIP_SFlash_State_Save(pFlashCfg,offset); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t offset){ - return RomDriver_XIP_SFlash_State_Restore(pFlashCfg,offset); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t startaddr,uint32_t endaddr){ - return RomDriver_XIP_SFlash_Erase_Need_Lock(pFlashCfg,startaddr,endaddr); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr,uint8_t *data, uint32_t len){ - return RomDriver_XIP_SFlash_Write_Need_Lock(pFlashCfg,addr,data,len); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr,uint8_t *data, uint32_t len){ - return RomDriver_XIP_SFlash_Read_Need_Lock(pFlashCfg,addr,data,len); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t *data){ - return RomDriver_XIP_SFlash_GetJedecId_Need_Lock(pFlashCfg,data); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t *data){ - return RomDriver_XIP_SFlash_GetDeviceId_Need_Lock(pFlashCfg,data); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t *data,uint8_t idLen){ - return RomDriver_XIP_SFlash_GetUniqueId_Need_Lock(pFlashCfg,data,idLen); -} - -__ALWAYS_INLINE -BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr,uint8_t *data, uint32_t len){ - return RomDriver_XIP_SFlash_Read_Via_Cache_Need_Lock(addr,data,len); -} - -__ALWAYS_INLINE -int ATTR_TCM_SECTION XIP_SFlash_Read_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr, uint8_t *dst, int len){ - return RomDriver_XIP_SFlash_Read_With_Lock(pFlashCfg,addr,dst,len); -} - -__ALWAYS_INLINE -int ATTR_TCM_SECTION XIP_SFlash_Write_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr, uint8_t *src, int len){ - return RomDriver_XIP_SFlash_Write_With_Lock(pFlashCfg,addr,src,len); -} - -__ALWAYS_INLINE -int ATTR_TCM_SECTION XIP_SFlash_Erase_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr, int len){ - return RomDriver_XIP_SFlash_Erase_With_Lock(pFlashCfg,addr,len); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION XIP_SFlash_Opt_Enter(uint8_t *aesEnable){ - return RomDriver_XIP_SFlash_Opt_Enter(aesEnable); -} - -__ALWAYS_INLINE -void ATTR_TCM_SECTION XIP_SFlash_Opt_Exit(uint8_t aesEnable){ - return RomDriver_XIP_SFlash_Opt_Exit(aesEnable); -} - -__ALWAYS_INLINE -uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32(void *dataIn, uint32_t len){ - return RomDriver_BFLB_Soft_CRC32(dataIn,len); +#include "bl602_romdriver.h" + + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_MBG(void){ + return RomDriver_AON_Power_On_MBG(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_MBG(void){ + return RomDriver_AON_Power_Off_MBG(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION AON_Power_On_XTAL(void){ + return RomDriver_AON_Power_On_XTAL(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION AON_Set_Xtal_CapCode(uint8_t capIn,uint8_t capOut){ + return RomDriver_AON_Set_Xtal_CapCode(capIn,capOut); +} + +__ALWAYS_INLINE +uint8_t ATTR_CLOCK_SECTION AON_Get_Xtal_CapCode(void){ + return RomDriver_AON_Get_Xtal_CapCode(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION AON_Power_Off_XTAL(void){ + return RomDriver_AON_Power_Off_XTAL(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_BG(void){ + return RomDriver_AON_Power_On_BG(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_BG(void){ + return RomDriver_AON_Power_Off_BG(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO11_SOC(void){ + return RomDriver_AON_Power_On_LDO11_SOC(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO11_SOC(void){ + return RomDriver_AON_Power_Off_LDO11_SOC(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_LDO15_RF(void){ + return RomDriver_AON_Power_On_LDO15_RF(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_LDO15_RF(void){ + return RomDriver_AON_Power_Off_LDO15_RF(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_On_SFReg(void){ + return RomDriver_AON_Power_On_SFReg(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_Power_Off_SFReg(void){ + return RomDriver_AON_Power_Off_SFReg(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Enter_PDS0(void){ + return RomDriver_AON_LowPower_Enter_PDS0(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION AON_LowPower_Exit_PDS0(void){ + return RomDriver_AON_LowPower_Exit_PDS0(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION ASM_Delay_Us(uint32_t core,uint32_t cnt){ + return RomDriver_ASM_Delay_Us(core,cnt); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION BL602_Delay_US(uint32_t cnt){ + return RomDriver_BL602_Delay_US(cnt); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION BL602_Delay_MS(uint32_t cnt){ + return RomDriver_BL602_Delay_MS(cnt); +} + +__ALWAYS_INLINE +void* ATTR_TCM_SECTION BL602_MemCpy(void *dst, const void *src, uint32_t n){ + return RomDriver_BL602_MemCpy(dst,src,n); +} + +__ALWAYS_INLINE +uint32_t* ATTR_TCM_SECTION BL602_MemCpy4(uint32_t *dst, const uint32_t *src, uint32_t n){ + return RomDriver_BL602_MemCpy4(dst,src,n); +} + +__ALWAYS_INLINE +void* ATTR_TCM_SECTION BL602_MemCpy_Fast(void *pdst, const void *psrc, uint32_t n){ + return RomDriver_BL602_MemCpy_Fast(pdst,psrc,n); +} + +__ALWAYS_INLINE +void* ATTR_TCM_SECTION BL602_MemSet(void *s, uint8_t c, uint32_t n){ + return RomDriver_BL602_MemSet(s,c,n); +} + +__ALWAYS_INLINE +uint32_t* ATTR_TCM_SECTION BL602_MemSet4(uint32_t *dst, const uint32_t val, uint32_t n){ + return RomDriver_BL602_MemSet4(dst,val,n); +} + +__ALWAYS_INLINE +int ATTR_TCM_SECTION BL602_MemCmp(const void *s1, const void *s2, uint32_t n){ + return RomDriver_BL602_MemCmp(s1,s2,n); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION EF_Ctrl_Sw_AHB_Clk_0(void){ + return RomDriver_EF_Ctrl_Sw_AHB_Clk_0(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION EF_Ctrl_Program_Efuse_0(void){ + return RomDriver_EF_Ctrl_Program_Efuse_0(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION EF_Ctrl_Load_Efuse_R0(void){ + return RomDriver_EF_Ctrl_Load_Efuse_R0(); +} + +__ALWAYS_INLINE +BL_Sts_Type ATTR_TCM_SECTION EF_Ctrl_Busy(void){ + return RomDriver_EF_Ctrl_Busy(); +} + +__ALWAYS_INLINE +BL_Sts_Type ATTR_TCM_SECTION EF_Ctrl_AutoLoad_Done(void){ + return RomDriver_EF_Ctrl_AutoLoad_Done(); +} + +__ALWAYS_INLINE +uint8_t ATTR_CLOCK_SECTION EF_Ctrl_Get_Trim_Parity(uint32_t val,uint8_t len){ + return RomDriver_EF_Ctrl_Get_Trim_Parity(val,len); +} + +__ALWAYS_INLINE +void ATTR_CLOCK_SECTION EF_Ctrl_Read_RC32M_Trim( Efuse_Ana_RC32M_Trim_Type *trim){ + return RomDriver_EF_Ctrl_Read_RC32M_Trim(trim); +} + +__ALWAYS_INLINE +void ATTR_CLOCK_SECTION EF_Ctrl_Read_RC32K_Trim( Efuse_Ana_RC32K_Trim_Type *trim){ + return RomDriver_EF_Ctrl_Read_RC32K_Trim(trim); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION EF_Ctrl_Clear(uint32_t index, uint32_t len){ + return RomDriver_EF_Ctrl_Clear(index,len); +} + +__ALWAYS_INLINE +GLB_ROOT_CLK_Type ATTR_CLOCK_SECTION GLB_Get_Root_CLK_Sel(void){ + return RomDriver_GLB_Get_Root_CLK_Sel(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK_Div(uint8_t hclkDiv,uint8_t bclkDiv){ + return RomDriver_GLB_Set_System_CLK_Div(hclkDiv,bclkDiv); +} + +__ALWAYS_INLINE +uint8_t ATTR_CLOCK_SECTION GLB_Get_BCLK_Div(void){ + return RomDriver_GLB_Get_BCLK_Div(); +} + +__ALWAYS_INLINE +uint8_t ATTR_CLOCK_SECTION GLB_Get_HCLK_Div(void){ + return RomDriver_GLB_Get_HCLK_Div(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION Update_SystemCoreClockWith_XTAL(GLB_PLL_XTAL_Type xtalType){ + return RomDriver_Update_SystemCoreClockWith_XTAL(xtalType); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_System_CLK(GLB_PLL_XTAL_Type xtalType,GLB_SYS_CLK_Type clkFreq){ + return RomDriver_GLB_Set_System_CLK(xtalType,clkFreq); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION System_Core_Clock_Update_From_RC32M(void){ + return RomDriver_System_Core_Clock_Update_From_RC32M(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_SF_CLK(uint8_t enable,GLB_SFLASH_CLK_Type clkSel,uint8_t div){ + return RomDriver_GLB_Set_SF_CLK(enable,clkSel,div); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION GLB_Set_PKA_CLK_Sel(GLB_PKA_CLK_Type clkSel){ + return RomDriver_GLB_Set_PKA_CLK_Sel(clkSel); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_SW_System_Reset(void){ + return RomDriver_GLB_SW_System_Reset(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_SW_CPU_Reset(void){ + return RomDriver_GLB_SW_CPU_Reset(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_SW_POR_Reset(void){ + return RomDriver_GLB_SW_POR_Reset(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_Select_Internal_Flash(void){ + return RomDriver_GLB_Select_Internal_Flash(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_Select_External_Flash(void){ + return RomDriver_GLB_Select_External_Flash(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_Deswap_Flash_Pin(void){ + return RomDriver_GLB_Deswap_Flash_Pin(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_Swap_Flash_Pin(void){ + return RomDriver_GLB_Swap_Flash_Pin(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Init(GLB_GPIO_Cfg_Type *cfg){ + return RomDriver_GLB_GPIO_Init(cfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Enable(GLB_GPIO_Type gpioPin){ + return RomDriver_GLB_GPIO_OUTPUT_Enable(gpioPin); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_OUTPUT_Disable(GLB_GPIO_Type gpioPin){ + return RomDriver_GLB_GPIO_OUTPUT_Disable(gpioPin); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION GLB_GPIO_Set_HZ(GLB_GPIO_Type gpioPin){ + return RomDriver_GLB_GPIO_Set_HZ(gpioPin); +} + +__ALWAYS_INLINE +uint8_t ATTR_TCM_SECTION GLB_GPIO_Get_Fun(GLB_GPIO_Type gpioPin){ + return RomDriver_GLB_GPIO_Get_Fun(gpioPin); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION HBN_Mode_Enter(HBN_APP_CFG_Type *cfg){ + return RomDriver_HBN_Mode_Enter(cfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION HBN_Power_Down_Flash(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_HBN_Power_Down_Flash(flashCfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION HBN_Enable(uint8_t aGPIOIeCfg,HBN_LDO_LEVEL_Type ldoLevel,HBN_LEVEL_Type hbnLevel){ + return RomDriver_HBN_Enable(aGPIOIeCfg,ldoLevel,hbnLevel); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_Reset(void){ + return RomDriver_HBN_Reset(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Aon_Vout(HBN_LDO_LEVEL_Type ldoLevel){ + return RomDriver_HBN_Set_Ldo11_Aon_Vout(ldoLevel); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Rt_Vout(HBN_LDO_LEVEL_Type ldoLevel){ + return RomDriver_HBN_Set_Ldo11_Rt_Vout(ldoLevel); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Ldo11_Soc_Vout(HBN_LDO_LEVEL_Type ldoLevel){ + return RomDriver_HBN_Set_Ldo11_Soc_Vout(ldoLevel); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION HBN_32K_Sel(HBN_32K_CLK_Type clkType){ + return RomDriver_HBN_32K_Sel(clkType); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_Type rootClk){ + return RomDriver_HBN_Set_ROOT_CLK_Sel(rootClk); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_Xtal_32K(void){ + return RomDriver_HBN_Power_On_Xtal_32K(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_Xtal_32K(void){ + return RomDriver_HBN_Power_Off_Xtal_32K(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_On_RC32K(void){ + return RomDriver_HBN_Power_On_RC32K(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION HBN_Power_Off_RC32K(void){ + return RomDriver_HBN_Power_Off_RC32K(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION HBN_Trim_RC32K(void){ + return RomDriver_HBN_Trim_RC32K(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_Hw_Pu_Pd_Cfg(uint8_t enable){ + return RomDriver_HBN_Hw_Pu_Pd_Cfg(enable); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_Pin_WakeUp_Mask(uint8_t maskVal){ + return RomDriver_HBN_Pin_WakeUp_Mask(maskVal); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_GPIO7_Dbg_Pull_Cfg(BL_Fun_Type pupdEn,BL_Fun_Type iesmtEn,BL_Fun_Type dlyEn,uint8_t dlySec){ + return RomDriver_HBN_GPIO7_Dbg_Pull_Cfg(pupdEn,iesmtEn,dlyEn,dlySec); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION HBN_Set_Embedded_Flash_Pullup(uint8_t enable){ + return RomDriver_HBN_Set_Embedded_Flash_Pullup(enable); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION L1C_Set_Wrap(BL_Fun_Type wrap){ + return RomDriver_L1C_Set_Wrap(wrap); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION L1C_Set_Way_Disable(uint8_t disableVal){ + return RomDriver_L1C_Set_Way_Disable(disableVal); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION L1C_IROM_2T_Access_Set(uint8_t enable){ + return RomDriver_L1C_IROM_2T_Access_Set(enable); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION PDS_Reset(void){ + return RomDriver_PDS_Reset(); +} + +#if 0 +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION PDS_Enable(PDS_CTL_Type *cfg,PDS_CTL4_Type *cfg4,uint32_t pdsSleepCnt){ + return RomDriver_PDS_Enable(cfg,cfg4,pdsSleepCnt); +} +#endif + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION PDS_Force_Config(PDS_CTL2_Type *cfg2,PDS_CTL3_Type *cfg3){ + return RomDriver_PDS_Force_Config(cfg2,cfg3); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION PDS_RAM_Config(PDS_RAM_CFG_Type *ramCfg){ + return RomDriver_PDS_RAM_Config(ramCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION PDS_Default_Level_Config(PDS_DEFAULT_LV_CFG_Type *defaultLvCfg,PDS_RAM_CFG_Type *ramCfg,uint32_t pdsSleepCnt){ + return RomDriver_PDS_Default_Level_Config(defaultLvCfg,ramCfg,pdsSleepCnt); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Trim_RC32M(void){ + return RomDriver_PDS_Trim_RC32M(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_RC32M_As_PLL_Ref(void){ + return RomDriver_PDS_Select_RC32M_As_PLL_Ref(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Select_XTAL_As_PLL_Ref(void){ + return RomDriver_PDS_Select_XTAL_As_PLL_Ref(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_On_PLL(PDS_PLL_XTAL_Type xtalType){ + return RomDriver_PDS_Power_On_PLL(xtalType); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_All_Clks(void){ + return RomDriver_PDS_Enable_PLL_All_Clks(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_All_Clks(void){ + return RomDriver_PDS_Disable_PLL_All_Clks(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Enable_PLL_Clk(PDS_PLL_CLK_Type pllClk){ + return RomDriver_PDS_Enable_PLL_Clk(pllClk); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Disable_PLL_Clk(PDS_PLL_CLK_Type pllClk){ + return RomDriver_PDS_Disable_PLL_Clk(pllClk); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_CLOCK_SECTION PDS_Power_Off_PLL(void){ + return RomDriver_PDS_Power_Off_PLL(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SEC_Eng_Turn_On_Sec_Ring(void){ + return RomDriver_SEC_Eng_Turn_On_Sec_Ring(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SEC_Eng_Turn_Off_Sec_Ring(void){ + return RomDriver_SEC_Eng_Turn_Off_Sec_Ring(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_Init(const SF_Ctrl_Cfg_Type *pSfCtrlCfg){ + return RomDriver_SFlash_Init(pSfCtrlCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_SetSPIMode(SF_Ctrl_Mode_Type mode){ + return RomDriver_SFlash_SetSPIMode(mode); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg(SPI_Flash_Cfg_Type *flashCfg,uint8_t regIndex,uint8_t *regValue,uint8_t regLen){ + return RomDriver_SFlash_Read_Reg(flashCfg,regIndex,regValue,regLen); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg(SPI_Flash_Cfg_Type *flashCfg,uint8_t regIndex,uint8_t *regValue,uint8_t regLen){ + return RomDriver_SFlash_Write_Reg(flashCfg,regIndex,regValue,regLen); +} + +__ALWAYS_INLINE +BL_Sts_Type ATTR_TCM_SECTION SFlash_Busy(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Busy(flashCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Enable(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Write_Enable(flashCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Qspi_Enable(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Qspi_Enable(flashCfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_Volatile_Reg_Write_Enable(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Volatile_Reg_Write_Enable(flashCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Chip_Erase(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Chip_Erase(flashCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Sector_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t secNum){ + return RomDriver_SFlash_Sector_Erase(flashCfg,secNum); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Blk32_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t blkNum){ + return RomDriver_SFlash_Blk32_Erase(flashCfg,blkNum); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Blk64_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t blkNum){ + return RomDriver_SFlash_Blk64_Erase(flashCfg,blkNum); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Erase(SPI_Flash_Cfg_Type *flashCfg,uint32_t startaddr,uint32_t endaddr){ + return RomDriver_SFlash_Erase(flashCfg,startaddr,endaddr); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Program(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint32_t addr,uint8_t *data, uint32_t len){ + return RomDriver_SFlash_Program(flashCfg,ioMode,addr,data,len); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_GetUniqueId(uint8_t *data,uint8_t idLen){ + return RomDriver_SFlash_GetUniqueId(data,idLen); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_GetJedecId(SPI_Flash_Cfg_Type *flashCfg,uint8_t *data){ + return RomDriver_SFlash_GetJedecId(flashCfg,data); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_GetDeviceId(uint8_t *data){ + return RomDriver_SFlash_GetDeviceId(data); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_Powerdown(void){ + return RomDriver_SFlash_Powerdown(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_Releae_Powerdown(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Releae_Powerdown(flashCfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_SetBurstWrap(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_SetBurstWrap(flashCfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_DisableBurstWrap(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_DisableBurstWrap(flashCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Software_Reset(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Software_Reset(flashCfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_Reset_Continue_Read(SPI_Flash_Cfg_Type *flashCfg){ + return RomDriver_SFlash_Reset_Continue_Read(flashCfg); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Set_IDbus_Cfg(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead,uint32_t addr,uint32_t len){ + return RomDriver_SFlash_Set_IDbus_Cfg(flashCfg,ioMode,contRead,addr,len); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_IDbus_Read_Enable(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead){ + return RomDriver_SFlash_IDbus_Read_Enable(flashCfg,ioMode,contRead); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Enable_Set(uint8_t wayDisable){ + return RomDriver_SFlash_Cache_Enable_Set(wayDisable); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Flush(void){ + return RomDriver_SFlash_Cache_Flush(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Read_Enable(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead,uint8_t wayDisable){ + return RomDriver_SFlash_Cache_Read_Enable(flashCfg,ioMode,contRead,wayDisable); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_Cache_Hit_Count_Get(uint32_t *hitCountLow,uint32_t *hitCountHigh){ + return RomDriver_SFlash_Cache_Hit_Count_Get(hitCountLow,hitCountHigh); +} + +__ALWAYS_INLINE +uint32_t ATTR_TCM_SECTION SFlash_Cache_Miss_Count_Get(void){ + return RomDriver_SFlash_Cache_Miss_Count_Get(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SFlash_Cache_Read_Disable(void){ + return RomDriver_SFlash_Cache_Read_Disable(); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Read(SPI_Flash_Cfg_Type *flashCfg,SF_Ctrl_IO_Type ioMode,uint8_t contRead,uint32_t addr,uint8_t *data, uint32_t len){ + return RomDriver_SFlash_Read(flashCfg,ioMode,contRead,addr,data,len); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg,uint8_t readRegCmd,uint8_t *regValue,uint8_t regLen){ + return RomDriver_SFlash_Read_Reg_With_Cmd(flashCfg,readRegCmd,regValue,regLen); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg,uint8_t writeRegCmd,uint8_t *regValue,uint8_t regLen){ + return RomDriver_SFlash_Write_Reg_With_Cmd(flashCfg,writeRegCmd,regValue,regLen); +} + +#if 0 +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SFlash_Restore_From_Powerdown(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t flashContRead){ + return RomDriver_SFlash_Restore_From_Powerdown(pFlashCfg,flashContRead); +} +#endif + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Cfg_Init_Ext_Flash_Gpio(uint8_t extFlashPin){ + return RomDriver_SF_Cfg_Init_Ext_Flash_Gpio(extFlashPin); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Cfg_Init_Internal_Flash_Gpio(void){ + return RomDriver_SF_Cfg_Init_Internal_Flash_Gpio(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Cfg_Deinit_Ext_Flash_Gpio(uint8_t extFlashPin){ + return RomDriver_SF_Cfg_Deinit_Ext_Flash_Gpio(extFlashPin); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Cfg_Restore_GPIO17_Fun(uint8_t fun){ + return RomDriver_SF_Cfg_Restore_GPIO17_Fun(fun); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID,SPI_Flash_Cfg_Type * pFlashCfg){ + return RomDriver_SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID,pFlashCfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Cfg_Init_Flash_Gpio(uint8_t flashPinCfg,uint8_t restoreDefault){ + return RomDriver_SF_Cfg_Init_Flash_Gpio(flashPinCfg,restoreDefault); +} + +__ALWAYS_INLINE +uint32_t ATTR_TCM_SECTION SF_Cfg_Flash_Identify(uint8_t callFromFlash,uint32_t autoScan,uint32_t flashPinCfg,uint8_t restoreDefault,SPI_Flash_Cfg_Type * pFlashCfg){ + return RomDriver_SF_Cfg_Flash_Identify(callFromFlash,autoScan,flashPinCfg,restoreDefault,pFlashCfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Enable(const SF_Ctrl_Cfg_Type *cfg){ + return RomDriver_SF_Ctrl_Enable(cfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Select_Pad(SF_Ctrl_Pad_Sel sel){ + return RomDriver_SF_Ctrl_Select_Pad(sel); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Set_Owner(SF_Ctrl_Owner_Type owner){ + return RomDriver_SF_Ctrl_Set_Owner(owner); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Disable(void){ + return RomDriver_SF_Ctrl_Disable(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_BE(void){ + return RomDriver_SF_Ctrl_AES_Enable_BE(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable_LE(void){ + return RomDriver_SF_Ctrl_AES_Enable_LE(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Region(uint8_t region,uint8_t enable,uint8_t hwKey,uint32_t startAddr,uint32_t endAddr,uint8_t locked){ + return RomDriver_SF_Ctrl_AES_Set_Region(region,enable,hwKey,startAddr,endAddr,locked); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key(uint8_t region,uint8_t *key, SF_Ctrl_AES_Key_Type keyType){ + return RomDriver_SF_Ctrl_AES_Set_Key(region,key,keyType); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key_BE(uint8_t region,uint8_t *key, SF_Ctrl_AES_Key_Type keyType){ + return RomDriver_SF_Ctrl_AES_Set_Key_BE(region,key,keyType); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV(uint8_t region,uint8_t *iv,uint32_t addrOffset){ + return RomDriver_SF_Ctrl_AES_Set_IV(region,iv,addrOffset); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV_BE(uint8_t region,uint8_t *iv,uint32_t addrOffset){ + return RomDriver_SF_Ctrl_AES_Set_IV_BE(region,iv,addrOffset); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Enable(void){ + return RomDriver_SF_Ctrl_AES_Enable(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_AES_Disable(void){ + return RomDriver_SF_Ctrl_AES_Disable(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Set_Flash_Image_Offset(uint32_t addrOffset){ + return RomDriver_SF_Ctrl_Set_Flash_Image_Offset(addrOffset); +} + +__ALWAYS_INLINE +uint32_t ATTR_TCM_SECTION SF_Ctrl_Get_Flash_Image_Offset(void){ + return RomDriver_SF_Ctrl_Get_Flash_Image_Offset(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Select_Clock(SF_Ctrl_Sahb_Type sahbType){ + return RomDriver_SF_Ctrl_Select_Clock(sahbType); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_SendCmd(SF_Ctrl_Cmd_Cfg_Type *cfg){ + return RomDriver_SF_Ctrl_SendCmd(cfg); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Icache_Set(SF_Ctrl_Cmd_Cfg_Type *cfg,uint8_t cmdValid){ + return RomDriver_SF_Ctrl_Icache_Set(cfg,cmdValid); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Icache2_Set(SF_Ctrl_Cmd_Cfg_Type *cfg,uint8_t cmdValid){ + return RomDriver_SF_Ctrl_Icache2_Set(cfg,cmdValid); +} + +__ALWAYS_INLINE +BL_Sts_Type ATTR_TCM_SECTION SF_Ctrl_GetBusyState(void){ + return RomDriver_SF_Ctrl_GetBusyState(); +} + +__ALWAYS_INLINE +uint8_t ATTR_TCM_SECTION SF_Ctrl_Is_AES_Enable(void){ + return RomDriver_SF_Ctrl_Is_AES_Enable(); +} + +__ALWAYS_INLINE +uint8_t ATTR_TCM_SECTION SF_Ctrl_Get_Clock_Delay(void){ + return RomDriver_SF_Ctrl_Get_Clock_Delay(); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION SF_Ctrl_Set_Clock_Delay(uint8_t delay){ + return RomDriver_SF_Ctrl_Set_Clock_Delay(delay); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Save(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t *offset){ + return RomDriver_XIP_SFlash_State_Save(pFlashCfg,offset); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_State_Restore(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t offset){ + return RomDriver_XIP_SFlash_State_Restore(pFlashCfg,offset); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Erase_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t startaddr,uint32_t endaddr){ + return RomDriver_XIP_SFlash_Erase_Need_Lock(pFlashCfg,startaddr,endaddr); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Write_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr,uint8_t *data, uint32_t len){ + return RomDriver_XIP_SFlash_Write_Need_Lock(pFlashCfg,addr,data,len); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr,uint8_t *data, uint32_t len){ + return RomDriver_XIP_SFlash_Read_Need_Lock(pFlashCfg,addr,data,len); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetJedecId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t *data){ + return RomDriver_XIP_SFlash_GetJedecId_Need_Lock(pFlashCfg,data); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetDeviceId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t *data){ + return RomDriver_XIP_SFlash_GetDeviceId_Need_Lock(pFlashCfg,data); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_GetUniqueId_Need_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t *data,uint8_t idLen){ + return RomDriver_XIP_SFlash_GetUniqueId_Need_Lock(pFlashCfg,data,idLen); +} + +__ALWAYS_INLINE +BL_Err_Type ATTR_TCM_SECTION XIP_SFlash_Read_Via_Cache_Need_Lock(uint32_t addr,uint8_t *data, uint32_t len){ + return RomDriver_XIP_SFlash_Read_Via_Cache_Need_Lock(addr,data,len); +} + +__ALWAYS_INLINE +int ATTR_TCM_SECTION XIP_SFlash_Read_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr, uint8_t *dst, int len){ + return RomDriver_XIP_SFlash_Read_With_Lock(pFlashCfg,addr,dst,len); +} + +__ALWAYS_INLINE +int ATTR_TCM_SECTION XIP_SFlash_Write_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr, uint8_t *src, int len){ + return RomDriver_XIP_SFlash_Write_With_Lock(pFlashCfg,addr,src,len); +} + +__ALWAYS_INLINE +int ATTR_TCM_SECTION XIP_SFlash_Erase_With_Lock(SPI_Flash_Cfg_Type *pFlashCfg,uint32_t addr, int len){ + return RomDriver_XIP_SFlash_Erase_With_Lock(pFlashCfg,addr,len); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION XIP_SFlash_Opt_Enter(uint8_t *aesEnable){ + return RomDriver_XIP_SFlash_Opt_Enter(aesEnable); +} + +__ALWAYS_INLINE +void ATTR_TCM_SECTION XIP_SFlash_Opt_Exit(uint8_t aesEnable){ + return RomDriver_XIP_SFlash_Opt_Exit(aesEnable); +} + +__ALWAYS_INLINE +uint32_t ATTR_TCM_SECTION BFLB_Soft_CRC32(void *dataIn, uint32_t len){ + return RomDriver_BFLB_Soft_CRC32(dataIn,len); } \ No newline at end of file diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sdu.c b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sdu.c index cced4c80..b09f8f46 100644 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sdu.c +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sdu.c @@ -1,76 +1,76 @@ -#include "bl602_sdu.h" - -volatile pHidSdio_RegMap_t SdioFuncReg[] = -{ - (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE), -#if NUM_FUNC == 2 - (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE+BL_SDIO_CCR_FUNC_OFFSET) -#elif NUM_FUNC == 3 - (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE+BL_SDIO_CCR_FUNC_OFFSET), - (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE+(2 * BL_SDIO_CCR_FUNC_OFFSET)) -#endif -}; - -/* if flag_mport = 0, then it supports mport - * flag_mport = 1, then mport disabled - */ -uint8_t flag_mport[NUM_FUNC] = -{ - 0, -#if NUM_FUNC == 2 - 1 -#elif NUM_FUNC == 3 - 1,1 -#endif -}; - -void sdio_GEN_CARD2HOST_INT(uint32_t port_id, uint16_t value) -{ - /* We do not want to generate Download rdy for command port - * only. Currently there is a condition where if we generate - * download ready for command, followed by a download - * ready for data, the download ready for data would be gated - * by the SDIO controller. To avoid this we do not generate - * a download ready for command. Download ready is only generated for data. - */ - /* - if (!flag_mport[port_id] && - (value & SDIO_CCR_CS_DnLdRdy) && (prev_WrBitMap[port_id] == 0x01)) - { - value &= ~SDIO_CCR_CS_DnLdRdy; - if (!value) - { - return; - } - } - */ - SdioFuncReg[port_id]->CardToHostEvent = value; -} - - -uint32_t sdio_ioctl(uint32_t port_id, SDIO_CMD_TYPE cmd, void *arg) -{ - switch(cmd) - { - case IOCTL_HID_GET_BLOCK_SIZE: - { - if (port_id == FUNC_WIFI) - { - uint32_t blockSize = BL_REGS8(SDIO_FN1_BLK_SIZE_0); - - blockSize |= ((BL_REGS8(SDIO_FN1_BLK_SIZE_1) & - SDIO_FN1_BLK_SIZE_1_MASK ) << 8); - - if(blockSize == 0) - { - blockSize = 512; - } - return(blockSize); - } - break; - } - default: - break; - } - return 0; -} +#include "bl602_sdu.h" + +volatile pHidSdio_RegMap_t SdioFuncReg[] = +{ + (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE), +#if NUM_FUNC == 2 + (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE+BL_SDIO_CCR_FUNC_OFFSET) +#elif NUM_FUNC == 3 + (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE+BL_SDIO_CCR_FUNC_OFFSET), + (pHidSdio_RegMap_t)(BL_SDIO_CCR_BASE+(2 * BL_SDIO_CCR_FUNC_OFFSET)) +#endif +}; + +/* if flag_mport = 0, then it supports mport + * flag_mport = 1, then mport disabled + */ +uint8_t flag_mport[NUM_FUNC] = +{ + 0, +#if NUM_FUNC == 2 + 1 +#elif NUM_FUNC == 3 + 1,1 +#endif +}; + +void sdio_GEN_CARD2HOST_INT(uint32_t port_id, uint16_t value) +{ + /* We do not want to generate Download rdy for command port + * only. Currently there is a condition where if we generate + * download ready for command, followed by a download + * ready for data, the download ready for data would be gated + * by the SDIO controller. To avoid this we do not generate + * a download ready for command. Download ready is only generated for data. + */ + /* + if (!flag_mport[port_id] && + (value & SDIO_CCR_CS_DnLdRdy) && (prev_WrBitMap[port_id] == 0x01)) + { + value &= ~SDIO_CCR_CS_DnLdRdy; + if (!value) + { + return; + } + } + */ + SdioFuncReg[port_id]->CardToHostEvent = value; +} + + +uint32_t sdio_ioctl(uint32_t port_id, SDIO_CMD_TYPE cmd, void *arg) +{ + switch(cmd) + { + case IOCTL_HID_GET_BLOCK_SIZE: + { + if (port_id == FUNC_WIFI) + { + uint32_t blockSize = BL_REGS8(SDIO_FN1_BLK_SIZE_0); + + blockSize |= ((BL_REGS8(SDIO_FN1_BLK_SIZE_1) & + SDIO_FN1_BLK_SIZE_1_MASK ) << 8); + + if(blockSize == 0) + { + blockSize = 512; + } + return(blockSize); + } + break; + } + default: + break; + } + return 0; +} diff --git a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_ctrl.c b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_ctrl.c index c800c2e1..f087d114 100644 --- a/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_ctrl.c +++ b/components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_ctrl.c @@ -446,10 +446,10 @@ void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key(uint8_t region,uint8_t *key, SF_Ctrl_A } tmpVal=SF_CTRL_SF_AES_KEY_7_OFFSET; while(i--){ - BL_WR_WORD(regionRegBase+tmpVal,__REV(BL_RDWD_FRM_BYTEP(key))); - key+=4; - tmpVal-=4; - } + BL_WR_WORD(regionRegBase+tmpVal,__REV(BL_RDWD_FRM_BYTEP(key))); + key+=4; + tmpVal-=4; + } } } @@ -528,10 +528,10 @@ void ATTR_TCM_SECTION SF_Ctrl_AES_Set_Key_BE(uint8_t region,uint8_t *key, SF_Ctr } tmpVal=SF_CTRL_SF_AES_KEY_0_OFFSET; while(i--){ - BL_WR_WORD(regionRegBase+tmpVal,BL_RDWD_FRM_BYTEP(key)); - key+=4; - tmpVal+=4; - } + BL_WR_WORD(regionRegBase+tmpVal,BL_RDWD_FRM_BYTEP(key)); + key+=4; + tmpVal+=4; + } } } @@ -555,10 +555,10 @@ void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV(uint8_t region,uint8_t *iv,uint32_t add if(iv!=NULL){ tmpVal=SF_CTRL_SF_AES_IV_W3_OFFSET; while(i--){ - BL_WR_WORD(regionRegBase+tmpVal,__REV(BL_RDWD_FRM_BYTEP(iv))); - iv+=4; - tmpVal-=4; - } + BL_WR_WORD(regionRegBase+tmpVal,__REV(BL_RDWD_FRM_BYTEP(iv))); + iv+=4; + tmpVal-=4; + } /* BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W3,__REV(BL_RDWD_FRM_BYTEP(iv))); iv+=4; @@ -592,10 +592,10 @@ void ATTR_TCM_SECTION SF_Ctrl_AES_Set_IV_BE(uint8_t region,uint8_t *iv,uint32_t if(iv!=NULL){ tmpVal=SF_CTRL_SF_AES_IV_W0_OFFSET; while(i--){ - BL_WR_WORD(regionRegBase+tmpVal,BL_RDWD_FRM_BYTEP(iv)); - iv+=4; - tmpVal+=4; - } + BL_WR_WORD(regionRegBase+tmpVal,BL_RDWD_FRM_BYTEP(iv)); + iv+=4; + tmpVal+=4; + } /* BL_WR_REG(regionRegBase,SF_CTRL_SF_AES_IV_W0,BL_RDWD_FRM_BYTEP(iv)); iv+=4; diff --git a/components/bl602/bl602_std/bouffalo.mk b/components/bl602/bl602_std/bouffalo.mk index 248226aa..976e8c8b 100755 --- a/components/bl602/bl602_std/bouffalo.mk +++ b/components/bl602/bl602_std/bouffalo.mk @@ -14,10 +14,10 @@ COMPONENT_ADD_INCLUDEDIRS += bl602_std/StdDriver/Inc \ bl602_std/Common/ring_buffer \ ## not be exported to project level -COMPONENT_PRIV_INCLUDEDIRS := +COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src COMPONENT_SRCS := bl602_std/StdDriver/Src/bl602_uart.c \ bl602_std/StdDriver/Src/bl602_adc.c \ bl602_std/StdDriver/Src/bl602_sec_eng.c \ @@ -53,7 +53,7 @@ COMPONENT_SRCS := bl602_std/StdDriver/Src/bl602_uart.c \ bl602_std/Common/platform_print/platform_gpio.c \ bl602_std/Common/ring_buffer/ring_buffer.c \ bl602_std/RISCV/Device/Bouffalo/BL602/Startup/interrupt.c - + ifeq ($(CONFIG_BL602_USE_ROM_DRIVER),0) COMPONENT_SRCS += bl602_std/StdDriver/Src/bl602_sf_ctrl.c \ bl602_std/StdDriver/Src/bl602_sflash.c \ @@ -61,7 +61,7 @@ COMPONENT_SRCS += bl602_std/StdDriver/Src/bl602_sf_ctrl.c \ bl602_std/StdDriver/Src/bl602_xip_sflash.c \ bl602_std/StdDriver/Src/bl602_sf_cfg.c \ bl602_std/StdDriver/Src/bl602_sf_cfg_ext.c \ - + else COMPONENT_SRCS += bl602_std/StdDriver/Src/bl602_romapi.c \ bl602_std/StdDriver/Src/bl602_sflash_ext.c \ @@ -70,7 +70,7 @@ COMPONENT_SRCS += bl602_std/StdDriver/Src/bl602_romapi.c \ endif ifeq ($(CONFIG_BL602_USE_BSP_PARTITION),1) -COMPONENT_SRCS += bl602_std/Common/partition/partition.c +COMPONENT_SRCS += bl602_std/Common/partition/partition.c endif ifeq ($(CONFIG_BL602_USE_BSP_STARTUP),1) diff --git a/components/bl602/bl602_wifi/include/bl60x_fw_api.h b/components/bl602/bl602_wifi/include/bl60x_fw_api.h old mode 100755 new mode 100644 diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_defs.h b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_defs.h index 928dde25..e077fc87 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_defs.h +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_defs.h @@ -171,29 +171,29 @@ struct bl_dbginfo { }; struct net_device_stats { - unsigned long rx_packets; - unsigned long tx_packets; - unsigned long rx_bytes; - unsigned long tx_bytes; - unsigned long rx_errors; - unsigned long tx_errors; - unsigned long rx_dropped; - unsigned long tx_dropped; - unsigned long multicast; - unsigned long collisions; - unsigned long rx_length_errors; - unsigned long rx_over_errors; - unsigned long rx_crc_errors; - unsigned long rx_frame_errors; - unsigned long rx_fifo_errors; - unsigned long rx_missed_errors; - unsigned long tx_aborted_errors; - unsigned long tx_carrier_errors; - unsigned long tx_fifo_errors; - unsigned long tx_heartbeat_errors; - unsigned long tx_window_errors; - unsigned long rx_compressed; - unsigned long tx_compressed; + unsigned long rx_packets; + unsigned long tx_packets; + unsigned long rx_bytes; + unsigned long tx_bytes; + unsigned long rx_errors; + unsigned long tx_errors; + unsigned long rx_dropped; + unsigned long tx_dropped; + unsigned long multicast; + unsigned long collisions; + unsigned long rx_length_errors; + unsigned long rx_over_errors; + unsigned long rx_crc_errors; + unsigned long rx_frame_errors; + unsigned long rx_fifo_errors; + unsigned long rx_missed_errors; + unsigned long tx_aborted_errors; + unsigned long tx_carrier_errors; + unsigned long tx_fifo_errors; + unsigned long tx_heartbeat_errors; + unsigned long tx_window_errors; + unsigned long rx_compressed; + unsigned long tx_compressed; }; /* diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_main.c b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_main.c index 51fa7409..bf4eedf9 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_main.c +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_main.c @@ -518,9 +518,9 @@ err_out: /** * @scan: Request to do a scan. If returning zero, the scan request is given - * the driver, and will be valid until passed to cfg80211_scan_done(). - * For scan results, call cfg80211_inform_bss(); you can call this outside - * the scan/scan_done bracket too. + * the driver, and will be valid until passed to cfg80211_scan_done(). + * For scan results, call cfg80211_inform_bss(); you can call this outside + * the scan/scan_done bracket too. */ int bl_cfg80211_scan(struct bl_hw *bl_hw) { diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_rx.c b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_rx.c index ffbc8b56..df594055 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_rx.c +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_rx.c @@ -492,9 +492,9 @@ static int find_ie_ds(uint8_t *buffer, int len, uint8_t *result) extern uint32_t mac_vsie_find(uint32_t addr, uint16_t buflen, uint8_t const *oui, uint8_t ouilen); extern uint32_t mac_ie_find(uint32_t addr, uint16_t buflen, uint8_t ie_id); extern unsigned char process_rsn_ie(uint8_t *rsn_ie, Cipher_t *mcstCipher, - Cipher_t *ucstCipher, bool *is_pmf_required); + Cipher_t *ucstCipher, bool *is_pmf_required); extern unsigned char process_wpa_ie(uint8_t *wpa_ie, Cipher_t *mcstCipher, - Cipher_t *ucstCipher); + Cipher_t *ucstCipher); static uint8_t co_read8p(uint32_t addr) { return (*(uint8_t *)addr); diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_utils.c b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_utils.c index a7965037..8db7b625 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_utils.c +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/bl_utils.c @@ -151,7 +151,7 @@ static void bl_rx_mgmt(uint32_t *skb, struct hw_rxhdr *hw_rxhdr, int len) #endif (void)counter; - if (ieee80211_is_beacon(mgmt->frame_control)) { + if (ieee80211_is_beacon(mgmt->frame_control)) { #if 0 os_printf("[RX] %04X BCN Received, freq %u, rssi %d\r\n", mgmt->frame_control, diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/cfg80211.h b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/cfg80211.h index 85673bb5..53562f74 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/cfg80211.h +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/cfg80211.h @@ -44,19 +44,19 @@ */ enum ieee80211_channel_flags { - IEEE80211_CHAN_DISABLED = 1<<0, - IEEE80211_CHAN_NO_IR = 1<<1, - /* hole at 1<<2 */ - IEEE80211_CHAN_RADAR = 1<<3, - IEEE80211_CHAN_NO_HT40PLUS = 1<<4, - IEEE80211_CHAN_NO_HT40MINUS = 1<<5, - IEEE80211_CHAN_NO_OFDM = 1<<6, - IEEE80211_CHAN_NO_80MHZ = 1<<7, - IEEE80211_CHAN_NO_160MHZ = 1<<8, - IEEE80211_CHAN_INDOOR_ONLY = 1<<9, - IEEE80211_CHAN_IR_CONCURRENT = 1<<10, - IEEE80211_CHAN_NO_20MHZ = 1<<11, - IEEE80211_CHAN_NO_10MHZ = 1<<12, + IEEE80211_CHAN_DISABLED = 1<<0, + IEEE80211_CHAN_NO_IR = 1<<1, + /* hole at 1<<2 */ + IEEE80211_CHAN_RADAR = 1<<3, + IEEE80211_CHAN_NO_HT40PLUS = 1<<4, + IEEE80211_CHAN_NO_HT40MINUS = 1<<5, + IEEE80211_CHAN_NO_OFDM = 1<<6, + IEEE80211_CHAN_NO_80MHZ = 1<<7, + IEEE80211_CHAN_NO_160MHZ = 1<<8, + IEEE80211_CHAN_INDOOR_ONLY = 1<<9, + IEEE80211_CHAN_IR_CONCURRENT = 1<<10, + IEEE80211_CHAN_NO_20MHZ = 1<<11, + IEEE80211_CHAN_NO_10MHZ = 1<<12, }; /** @@ -69,35 +69,35 @@ enum ieee80211_channel_flags { * @hw_value: hardware-specific value for the channel * @flags: channel flags from &enum ieee80211_channel_flags. * @orig_flags: channel flags at registration time, used by regulatory - * code to support devices with additional restrictions + * code to support devices with additional restrictions * @band: band this channel belongs to. * @max_antenna_gain: maximum antenna gain in dBi * @max_power: maximum transmission power (in dBm) * @max_reg_power: maximum regulatory transmission power (in dBm) * @beacon_found: helper to regulatory code to indicate when a beacon - * has been found on this channel. Use regulatory_hint_found_beacon() - * to enable this, this is useful only on 5 GHz band. + * has been found on this channel. Use regulatory_hint_found_beacon() + * to enable this, this is useful only on 5 GHz band. * @orig_mag: internal use * @orig_mpwr: internal use * @dfs_state: current state of this channel. Only relevant if radar is required - * on this channel. + * on this channel. * @dfs_state_entered: timestamp (jiffies) when the dfs state was entered. * @dfs_cac_ms: DFS CAC time in milliseconds, this is valid for DFS channels. */ struct ieee80211_channel { - enum nl80211_band band; - u16 center_freq; - u16 hw_value; - u32 flags; - int max_antenna_gain; - int max_power; - int max_reg_power; - bool beacon_found; - u32 orig_flags; - int orig_mag, orig_mpwr; - enum nl80211_dfs_state dfs_state; - unsigned long dfs_state_entered; - unsigned int dfs_cac_ms; + enum nl80211_band band; + u16 center_freq; + u16 hw_value; + u32 flags; + int max_antenna_gain; + int max_power; + int max_reg_power; + bool beacon_found; + u32 orig_flags; + int orig_mag, orig_mpwr; + enum nl80211_dfs_state dfs_state; + unsigned long dfs_state_entered; + unsigned int dfs_cac_ms; }; struct ieee80211_dot_d { @@ -119,11 +119,11 @@ struct ieee80211_dot_d { * @mcs: Supported MCS rates */ struct ieee80211_sta_ht_cap { - u16 cap; /* use IEEE80211_HT_CAP_ */ - bool ht_supported; - u8 ampdu_factor; - u8 ampdu_density; - struct ieee80211_mcs_info mcs; + u16 cap; /* use IEEE80211_HT_CAP_ */ + bool ht_supported; + u8 ampdu_factor; + u8 ampdu_density; + struct ieee80211_mcs_info mcs; }; /* @@ -135,69 +135,69 @@ struct ieee80211_sta_ht_cap { * enum wiphy_flags - wiphy capability flags * * @WIPHY_FLAG_NETNS_OK: if not set, do not allow changing the netns of this - * wiphy at all + * wiphy at all * @WIPHY_FLAG_PS_ON_BY_DEFAULT: if set to true, powersave will be enabled - * by default -- this flag will be set depending on the kernel's default - * on wiphy_new(), but can be changed by the driver if it has a good - * reason to override the default + * by default -- this flag will be set depending on the kernel's default + * on wiphy_new(), but can be changed by the driver if it has a good + * reason to override the default * @WIPHY_FLAG_4ADDR_AP: supports 4addr mode even on AP (with a single station - * on a VLAN interface) + * on a VLAN interface) * @WIPHY_FLAG_4ADDR_STATION: supports 4addr mode even as a station * @WIPHY_FLAG_CONTROL_PORT_PROTOCOL: This device supports setting the - * control port protocol ethertype. The device also honours the - * control_port_no_encrypt flag. + * control port protocol ethertype. The device also honours the + * control_port_no_encrypt flag. * @WIPHY_FLAG_IBSS_RSN: The device supports IBSS RSN. * @WIPHY_FLAG_MESH_AUTH: The device supports mesh authentication by routing - * auth frames to userspace. See @NL80211_MESH_SETUP_USERSPACE_AUTH. + * auth frames to userspace. See @NL80211_MESH_SETUP_USERSPACE_AUTH. * @WIPHY_FLAG_SUPPORTS_SCHED_SCAN: The device supports scheduled scans. * @WIPHY_FLAG_SUPPORTS_FW_ROAM: The device supports roaming feature in the - * firmware. + * firmware. * @WIPHY_FLAG_AP_UAPSD: The device supports uapsd on AP. * @WIPHY_FLAG_SUPPORTS_TDLS: The device supports TDLS (802.11z) operation. * @WIPHY_FLAG_TDLS_EXTERNAL_SETUP: The device does not handle TDLS (802.11z) - * link setup/discovery operations internally. Setup, discovery and - * teardown packets should be sent through the @NL80211_CMD_TDLS_MGMT - * command. When this flag is not set, @NL80211_CMD_TDLS_OPER should be - * used for asking the driver/firmware to perform a TDLS operation. + * link setup/discovery operations internally. Setup, discovery and + * teardown packets should be sent through the @NL80211_CMD_TDLS_MGMT + * command. When this flag is not set, @NL80211_CMD_TDLS_OPER should be + * used for asking the driver/firmware to perform a TDLS operation. * @WIPHY_FLAG_HAVE_AP_SME: device integrates AP SME * @WIPHY_FLAG_REPORTS_OBSS: the device will report beacons from other BSSes - * when there are virtual interfaces in AP mode by calling - * cfg80211_report_obss_beacon(). + * when there are virtual interfaces in AP mode by calling + * cfg80211_report_obss_beacon(). * @WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD: When operating as an AP, the device - * responds to probe-requests in hardware. + * responds to probe-requests in hardware. * @WIPHY_FLAG_OFFCHAN_TX: Device supports direct off-channel TX. * @WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL: Device supports remain-on-channel call. * @WIPHY_FLAG_SUPPORTS_5_10_MHZ: Device supports 5 MHz and 10 MHz channels. * @WIPHY_FLAG_HAS_CHANNEL_SWITCH: Device supports channel switch in - * beaconing mode (AP, IBSS, Mesh, ...). + * beaconing mode (AP, IBSS, Mesh, ...). * @WIPHY_FLAG_HAS_STATIC_WEP: The device supports static WEP key installation - * before connection. + * before connection. */ enum wiphy_flags { - /* use hole at 0 */ - /* use hole at 1 */ - /* use hole at 2 */ - WIPHY_FLAG_NETNS_OK = BIT(3), - WIPHY_FLAG_PS_ON_BY_DEFAULT = BIT(4), - WIPHY_FLAG_4ADDR_AP = BIT(5), - WIPHY_FLAG_4ADDR_STATION = BIT(6), - WIPHY_FLAG_CONTROL_PORT_PROTOCOL = BIT(7), - WIPHY_FLAG_IBSS_RSN = BIT(8), - WIPHY_FLAG_MESH_AUTH = BIT(10), - WIPHY_FLAG_SUPPORTS_SCHED_SCAN = BIT(11), - /* use hole at 12 */ - WIPHY_FLAG_SUPPORTS_FW_ROAM = BIT(13), - WIPHY_FLAG_AP_UAPSD = BIT(14), - WIPHY_FLAG_SUPPORTS_TDLS = BIT(15), - WIPHY_FLAG_TDLS_EXTERNAL_SETUP = BIT(16), - WIPHY_FLAG_HAVE_AP_SME = BIT(17), - WIPHY_FLAG_REPORTS_OBSS = BIT(18), - WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD = BIT(19), - WIPHY_FLAG_OFFCHAN_TX = BIT(20), - WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL = BIT(21), - WIPHY_FLAG_SUPPORTS_5_10_MHZ = BIT(22), - WIPHY_FLAG_HAS_CHANNEL_SWITCH = BIT(23), - WIPHY_FLAG_HAS_STATIC_WEP = BIT(24), + /* use hole at 0 */ + /* use hole at 1 */ + /* use hole at 2 */ + WIPHY_FLAG_NETNS_OK = BIT(3), + WIPHY_FLAG_PS_ON_BY_DEFAULT = BIT(4), + WIPHY_FLAG_4ADDR_AP = BIT(5), + WIPHY_FLAG_4ADDR_STATION = BIT(6), + WIPHY_FLAG_CONTROL_PORT_PROTOCOL = BIT(7), + WIPHY_FLAG_IBSS_RSN = BIT(8), + WIPHY_FLAG_MESH_AUTH = BIT(10), + WIPHY_FLAG_SUPPORTS_SCHED_SCAN = BIT(11), + /* use hole at 12 */ + WIPHY_FLAG_SUPPORTS_FW_ROAM = BIT(13), + WIPHY_FLAG_AP_UAPSD = BIT(14), + WIPHY_FLAG_SUPPORTS_TDLS = BIT(15), + WIPHY_FLAG_TDLS_EXTERNAL_SETUP = BIT(16), + WIPHY_FLAG_HAVE_AP_SME = BIT(17), + WIPHY_FLAG_REPORTS_OBSS = BIT(18), + WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD = BIT(19), + WIPHY_FLAG_OFFCHAN_TX = BIT(20), + WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL = BIT(21), + WIPHY_FLAG_SUPPORTS_5_10_MHZ = BIT(22), + WIPHY_FLAG_HAS_CHANNEL_SWITCH = BIT(23), + WIPHY_FLAG_HAS_STATIC_WEP = BIT(24), }; /** @@ -209,51 +209,51 @@ enum wiphy_flags { * @key_len: length of key material * @cipher: cipher suite selector * @seq: sequence counter (IV/PN) for TKIP and CCMP keys, only used - * with the get_key() callback, must be in little endian, - * length given by @seq_len. + * with the get_key() callback, must be in little endian, + * length given by @seq_len. * @seq_len: length of @seq. */ struct key_params { - const u8 *key; - const u8 *seq; - int key_len; - int seq_len; - u32 cipher; + const u8 *key; + const u8 *seq; + int key_len; + int seq_len; + u32 cipher; }; /** * struct cfg80211_crypto_settings - Crypto settings * @wpa_versions: indicates which, if any, WPA versions are enabled - * (from enum nl80211_wpa_versions) + * (from enum nl80211_wpa_versions) * @cipher_group: group key cipher suite (or 0 if unset) * @n_ciphers_pairwise: number of AP supported unicast ciphers * @ciphers_pairwise: unicast key cipher suites * @n_akm_suites: number of AKM suites * @akm_suites: AKM suites * @control_port: Whether user space controls IEEE 802.1X port, i.e., - * sets/clears %NL80211_STA_FLAG_AUTHORIZED. If true, the driver is - * required to assume that the port is unauthorized until authorized by - * user space. Otherwise, port is marked authorized by default. + * sets/clears %NL80211_STA_FLAG_AUTHORIZED. If true, the driver is + * required to assume that the port is unauthorized until authorized by + * user space. Otherwise, port is marked authorized by default. * @control_port_ethertype: the control port protocol that should be - * allowed through even on unauthorized ports + * allowed through even on unauthorized ports * @control_port_no_encrypt: TRUE to prevent encryption of control port - * protocol frames. + * protocol frames. * @wep_keys: static WEP keys, if not NULL points to an array of - * CFG80211_MAX_WEP_KEYS WEP keys + * CFG80211_MAX_WEP_KEYS WEP keys * @wep_tx_key: key index (0..3) of the default TX static WEP key */ struct cfg80211_crypto_settings { - u32 wpa_versions; - u32 cipher_group; - int n_ciphers_pairwise; - u32 ciphers_pairwise[NL80211_MAX_NR_CIPHER_SUITES]; - int n_akm_suites; - u32 akm_suites[NL80211_MAX_NR_AKM_SUITES]; - bool control_port; - __be16 control_port_ethertype; - bool control_port_no_encrypt; - struct key_params *wep_keys; - int wep_tx_key; + u32 wpa_versions; + u32 cipher_group; + int n_ciphers_pairwise; + u32 ciphers_pairwise[NL80211_MAX_NR_CIPHER_SUITES]; + int n_akm_suites; + u32 akm_suites[NL80211_MAX_NR_AKM_SUITES]; + bool control_port; + __be16 control_port_ethertype; + bool control_port_no_encrypt; + struct key_params *wep_keys; + int wep_tx_key; }; /** @@ -263,8 +263,8 @@ struct cfg80211_crypto_settings { * @delta: value of RSSI level adjustment. */ struct cfg80211_bss_select_adjust { - enum nl80211_band band; - s8 delta; + enum nl80211_band band; + s8 delta; }; /** @@ -276,11 +276,11 @@ struct cfg80211_bss_select_adjust { * @adjust: parameters for %NL80211_BSS_SELECT_ATTR_RSSI_ADJUST. */ struct cfg80211_bss_selection { - enum nl80211_bss_select_attr behaviour; - union { - enum nl80211_band band_pref; - struct cfg80211_bss_select_adjust adjust; - } param; + enum nl80211_bss_select_attr behaviour; + union { + enum nl80211_band band_pref; + struct cfg80211_bss_select_adjust adjust; + } param; }; /** @@ -290,15 +290,15 @@ struct cfg80211_bss_selection { * authentication and association. * * @channel: The channel to use or %NULL if not specified (auto-select based - * on scan results) + * on scan results) * @channel_hint: The channel of the recommended BSS for initial connection or - * %NULL if not specified + * %NULL if not specified * @bssid: The AP BSSID or %NULL if not specified (auto-select based on scan - * results) + * results) * @bssid_hint: The recommended AP BSSID for initial connection to the BSS or - * %NULL if not specified. Unlike the @bssid parameter, the driver is - * allowed to ignore this @bssid_hint if it has knowledge of a better BSS - * to use. + * %NULL if not specified. Unlike the @bssid parameter, the driver is + * allowed to ignore this @bssid_hint if it has knowledge of a better BSS + * to use. * @ssid: SSID * @ssid_len: Length of ssid in octets * @auth_type: Authentication type (algorithm) @@ -312,45 +312,45 @@ struct cfg80211_bss_selection { * @key: WEP key for shared key authentication * @flags: See &enum cfg80211_assoc_req_flags * @bg_scan_period: Background scan period in seconds - * or -1 to indicate that default value is to be used. + * or -1 to indicate that default value is to be used. * @ht_capa: HT Capabilities over-rides. Values set in ht_capa_mask - * will be used in ht_capa. Un-supported values will be ignored. + * will be used in ht_capa. Un-supported values will be ignored. * @ht_capa_mask: The bits of ht_capa which are to be used. * @vht_capa: VHT Capability overrides * @vht_capa_mask: The bits of vht_capa which are to be used. * @pbss: if set, connect to a PCP instead of AP. Valid for DMG - * networks. + * networks. * @bss_select: criteria to be used for BSS selection. * @prev_bssid: previous BSSID, if not %NULL use reassociate frame. This is used - * to indicate a request to reassociate within the ESS instead of a request - * do the initial association with the ESS. When included, this is set to - * the BSSID of the current association, i.e., to the value that is - * included in the Current AP address field of the Reassociation Request - * frame. + * to indicate a request to reassociate within the ESS instead of a request + * do the initial association with the ESS. When included, this is set to + * the BSSID of the current association, i.e., to the value that is + * included in the Current AP address field of the Reassociation Request + * frame. */ struct cfg80211_connect_params { - struct ieee80211_channel channel; - struct ieee80211_channel *channel_hint; - const u8 *bssid; - const u8 *bssid_hint; - const u8 *ssid; - size_t ssid_len; - enum nl80211_auth_type auth_type; - const u8 *ie; - size_t ie_len; - bool privacy; - enum nl80211_mfp mfp; - struct cfg80211_crypto_settings crypto; - const u8 *key; + struct ieee80211_channel channel; + struct ieee80211_channel *channel_hint; + const u8 *bssid; + const u8 *bssid_hint; + const u8 *ssid; + size_t ssid_len; + enum nl80211_auth_type auth_type; + const u8 *ie; + size_t ie_len; + bool privacy; + enum nl80211_mfp mfp; + struct cfg80211_crypto_settings crypto; + const u8 *key; const u8 *pmk; - u8 key_len, pmk_len, key_idx; - u32 flags; - int bg_scan_period; - struct ieee80211_ht_cap ht_capa; - struct ieee80211_ht_cap ht_capa_mask; - bool pbss; - struct cfg80211_bss_selection bss_select; - const u8 *prev_bssid; + u8 key_len, pmk_len, key_idx; + u32 flags; + int bg_scan_period; + struct ieee80211_ht_cap ht_capa; + struct ieee80211_ht_cap ht_capa_mask; + bool pbss; + struct cfg80211_bss_selection bss_select; + const u8 *prev_bssid; }; #endif diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/ieee80211.h b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/ieee80211.h index af1ce4a8..01ff3e30 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/ieee80211.h +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/ieee80211.h @@ -56,87 +56,87 @@ #define FCS_LEN 4 -#define IEEE80211_FCTL_VERS 0x0003 -#define IEEE80211_FCTL_FTYPE 0x000c -#define IEEE80211_FCTL_STYPE 0x00f0 -#define IEEE80211_FCTL_TODS 0x0100 -#define IEEE80211_FCTL_FROMDS 0x0200 -#define IEEE80211_FCTL_MOREFRAGS 0x0400 -#define IEEE80211_FCTL_RETRY 0x0800 -#define IEEE80211_FCTL_PM 0x1000 -#define IEEE80211_FCTL_MOREDATA 0x2000 -#define IEEE80211_FCTL_PROTECTED 0x4000 -#define IEEE80211_FCTL_ORDER 0x8000 -#define IEEE80211_FCTL_CTL_EXT 0x0f00 +#define IEEE80211_FCTL_VERS 0x0003 +#define IEEE80211_FCTL_FTYPE 0x000c +#define IEEE80211_FCTL_STYPE 0x00f0 +#define IEEE80211_FCTL_TODS 0x0100 +#define IEEE80211_FCTL_FROMDS 0x0200 +#define IEEE80211_FCTL_MOREFRAGS 0x0400 +#define IEEE80211_FCTL_RETRY 0x0800 +#define IEEE80211_FCTL_PM 0x1000 +#define IEEE80211_FCTL_MOREDATA 0x2000 +#define IEEE80211_FCTL_PROTECTED 0x4000 +#define IEEE80211_FCTL_ORDER 0x8000 +#define IEEE80211_FCTL_CTL_EXT 0x0f00 -#define IEEE80211_SCTL_FRAG 0x000F -#define IEEE80211_SCTL_SEQ 0xFFF0 +#define IEEE80211_SCTL_FRAG 0x000F +#define IEEE80211_SCTL_SEQ 0xFFF0 -#define IEEE80211_FTYPE_MGMT 0x0000 -#define IEEE80211_FTYPE_CTL 0x0004 -#define IEEE80211_FTYPE_DATA 0x0008 -#define IEEE80211_FTYPE_EXT 0x000c +#define IEEE80211_FTYPE_MGMT 0x0000 +#define IEEE80211_FTYPE_CTL 0x0004 +#define IEEE80211_FTYPE_DATA 0x0008 +#define IEEE80211_FTYPE_EXT 0x000c /* management */ -#define IEEE80211_STYPE_ASSOC_REQ 0x0000 -#define IEEE80211_STYPE_ASSOC_RESP 0x0010 -#define IEEE80211_STYPE_REASSOC_REQ 0x0020 -#define IEEE80211_STYPE_REASSOC_RESP 0x0030 -#define IEEE80211_STYPE_PROBE_REQ 0x0040 -#define IEEE80211_STYPE_PROBE_RESP 0x0050 -#define IEEE80211_STYPE_BEACON 0x0080 -#define IEEE80211_STYPE_ATIM 0x0090 -#define IEEE80211_STYPE_DISASSOC 0x00A0 -#define IEEE80211_STYPE_AUTH 0x00B0 -#define IEEE80211_STYPE_DEAUTH 0x00C0 -#define IEEE80211_STYPE_ACTION 0x00D0 +#define IEEE80211_STYPE_ASSOC_REQ 0x0000 +#define IEEE80211_STYPE_ASSOC_RESP 0x0010 +#define IEEE80211_STYPE_REASSOC_REQ 0x0020 +#define IEEE80211_STYPE_REASSOC_RESP 0x0030 +#define IEEE80211_STYPE_PROBE_REQ 0x0040 +#define IEEE80211_STYPE_PROBE_RESP 0x0050 +#define IEEE80211_STYPE_BEACON 0x0080 +#define IEEE80211_STYPE_ATIM 0x0090 +#define IEEE80211_STYPE_DISASSOC 0x00A0 +#define IEEE80211_STYPE_AUTH 0x00B0 +#define IEEE80211_STYPE_DEAUTH 0x00C0 +#define IEEE80211_STYPE_ACTION 0x00D0 /* control */ -#define IEEE80211_STYPE_CTL_EXT 0x0060 -#define IEEE80211_STYPE_BACK_REQ 0x0080 -#define IEEE80211_STYPE_BACK 0x0090 -#define IEEE80211_STYPE_PSPOLL 0x00A0 -#define IEEE80211_STYPE_RTS 0x00B0 -#define IEEE80211_STYPE_CTS 0x00C0 -#define IEEE80211_STYPE_ACK 0x00D0 -#define IEEE80211_STYPE_CFEND 0x00E0 -#define IEEE80211_STYPE_CFENDACK 0x00F0 +#define IEEE80211_STYPE_CTL_EXT 0x0060 +#define IEEE80211_STYPE_BACK_REQ 0x0080 +#define IEEE80211_STYPE_BACK 0x0090 +#define IEEE80211_STYPE_PSPOLL 0x00A0 +#define IEEE80211_STYPE_RTS 0x00B0 +#define IEEE80211_STYPE_CTS 0x00C0 +#define IEEE80211_STYPE_ACK 0x00D0 +#define IEEE80211_STYPE_CFEND 0x00E0 +#define IEEE80211_STYPE_CFENDACK 0x00F0 /* data */ -#define IEEE80211_STYPE_DATA 0x0000 -#define IEEE80211_STYPE_DATA_CFACK 0x0010 -#define IEEE80211_STYPE_DATA_CFPOLL 0x0020 -#define IEEE80211_STYPE_DATA_CFACKPOLL 0x0030 -#define IEEE80211_STYPE_NULLFUNC 0x0040 -#define IEEE80211_STYPE_CFACK 0x0050 -#define IEEE80211_STYPE_CFPOLL 0x0060 -#define IEEE80211_STYPE_CFACKPOLL 0x0070 -#define IEEE80211_STYPE_QOS_DATA 0x0080 -#define IEEE80211_STYPE_QOS_DATA_CFACK 0x0090 -#define IEEE80211_STYPE_QOS_DATA_CFPOLL 0x00A0 -#define IEEE80211_STYPE_QOS_DATA_CFACKPOLL 0x00B0 -#define IEEE80211_STYPE_QOS_NULLFUNC 0x00C0 -#define IEEE80211_STYPE_QOS_CFACK 0x00D0 -#define IEEE80211_STYPE_QOS_CFPOLL 0x00E0 -#define IEEE80211_STYPE_QOS_CFACKPOLL 0x00F0 +#define IEEE80211_STYPE_DATA 0x0000 +#define IEEE80211_STYPE_DATA_CFACK 0x0010 +#define IEEE80211_STYPE_DATA_CFPOLL 0x0020 +#define IEEE80211_STYPE_DATA_CFACKPOLL 0x0030 +#define IEEE80211_STYPE_NULLFUNC 0x0040 +#define IEEE80211_STYPE_CFACK 0x0050 +#define IEEE80211_STYPE_CFPOLL 0x0060 +#define IEEE80211_STYPE_CFACKPOLL 0x0070 +#define IEEE80211_STYPE_QOS_DATA 0x0080 +#define IEEE80211_STYPE_QOS_DATA_CFACK 0x0090 +#define IEEE80211_STYPE_QOS_DATA_CFPOLL 0x00A0 +#define IEEE80211_STYPE_QOS_DATA_CFACKPOLL 0x00B0 +#define IEEE80211_STYPE_QOS_NULLFUNC 0x00C0 +#define IEEE80211_STYPE_QOS_CFACK 0x00D0 +#define IEEE80211_STYPE_QOS_CFPOLL 0x00E0 +#define IEEE80211_STYPE_QOS_CFACKPOLL 0x00F0 /* extension, added by 802.11ad */ -#define IEEE80211_STYPE_DMG_BEACON 0x0000 +#define IEEE80211_STYPE_DMG_BEACON 0x0000 /* control extension - for IEEE80211_FTYPE_CTL | IEEE80211_STYPE_CTL_EXT */ -#define IEEE80211_CTL_EXT_POLL 0x2000 -#define IEEE80211_CTL_EXT_SPR 0x3000 -#define IEEE80211_CTL_EXT_GRANT 0x4000 -#define IEEE80211_CTL_EXT_DMG_CTS 0x5000 -#define IEEE80211_CTL_EXT_DMG_DTS 0x6000 -#define IEEE80211_CTL_EXT_SSW 0x8000 -#define IEEE80211_CTL_EXT_SSW_FBACK 0x9000 -#define IEEE80211_CTL_EXT_SSW_ACK 0xa000 +#define IEEE80211_CTL_EXT_POLL 0x2000 +#define IEEE80211_CTL_EXT_SPR 0x3000 +#define IEEE80211_CTL_EXT_GRANT 0x4000 +#define IEEE80211_CTL_EXT_DMG_CTS 0x5000 +#define IEEE80211_CTL_EXT_DMG_DTS 0x6000 +#define IEEE80211_CTL_EXT_SSW 0x8000 +#define IEEE80211_CTL_EXT_SSW_FBACK 0x9000 +#define IEEE80211_CTL_EXT_SSW_ACK 0xa000 -#define IEEE80211_SN_MASK ((IEEE80211_SCTL_SEQ) >> 4) -#define IEEE80211_MAX_SN IEEE80211_SN_MASK -#define IEEE80211_SN_MODULO (IEEE80211_MAX_SN + 1) +#define IEEE80211_SN_MASK ((IEEE80211_SCTL_SEQ) >> 4) +#define IEEE80211_MAX_SN IEEE80211_SN_MASK +#define IEEE80211_SN_MODULO (IEEE80211_MAX_SN + 1) /* 802.11n HT capabilities masks (for cap_info) */ @@ -174,19 +174,19 @@ #define IEEE80211_HT_MCS_MASK_LEN 10 /* cipher suite selectors */ -#define WLAN_CIPHER_SUITE_USE_GROUP 0x000FAC00 -#define WLAN_CIPHER_SUITE_WEP40 0x000FAC01 -#define WLAN_CIPHER_SUITE_TKIP 0x000FAC02 -/* reserved: 0x000FAC03 */ -#define WLAN_CIPHER_SUITE_CCMP 0x000FAC04 -#define WLAN_CIPHER_SUITE_WEP104 0x000FAC05 -#define WLAN_CIPHER_SUITE_AES_CMAC 0x000FAC06 -#define WLAN_CIPHER_SUITE_GCMP 0x000FAC08 -#define WLAN_CIPHER_SUITE_GCMP_256 0x000FAC09 -#define WLAN_CIPHER_SUITE_CCMP_256 0x000FAC0A -#define WLAN_CIPHER_SUITE_BIP_GMAC_128 0x000FAC0B -#define WLAN_CIPHER_SUITE_BIP_GMAC_256 0x000FAC0C -#define WLAN_CIPHER_SUITE_BIP_CMAC_256 0x000FAC0D +#define WLAN_CIPHER_SUITE_USE_GROUP 0x000FAC00 +#define WLAN_CIPHER_SUITE_WEP40 0x000FAC01 +#define WLAN_CIPHER_SUITE_TKIP 0x000FAC02 +/* reserved: 0x000FAC03 */ +#define WLAN_CIPHER_SUITE_CCMP 0x000FAC04 +#define WLAN_CIPHER_SUITE_WEP104 0x000FAC05 +#define WLAN_CIPHER_SUITE_AES_CMAC 0x000FAC06 +#define WLAN_CIPHER_SUITE_GCMP 0x000FAC08 +#define WLAN_CIPHER_SUITE_GCMP_256 0x000FAC09 +#define WLAN_CIPHER_SUITE_CCMP_256 0x000FAC0A +#define WLAN_CIPHER_SUITE_BIP_GMAC_128 0x000FAC0B +#define WLAN_CIPHER_SUITE_BIP_GMAC_256 0x000FAC0C +#define WLAN_CIPHER_SUITE_BIP_CMAC_256 0x000FAC0D #define WLAN_CAPABILITY_BSS (1<<0) #define WLAN_CAPABILITY_IBSS (1<<1) @@ -200,76 +200,76 @@ /* Reason codes */ enum ieee80211_reasoncode { - WLAN_REASON_UNSPECIFIED = 1, - WLAN_REASON_PREV_AUTH_NOT_VALID = 2, - WLAN_REASON_DEAUTH_LEAVING = 3, - WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY = 4, - WLAN_REASON_DISASSOC_AP_BUSY = 5, - WLAN_REASON_CLASS2_FRAME_FROM_NONAUTH_STA = 6, - WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA = 7, - WLAN_REASON_DISASSOC_STA_HAS_LEFT = 8, - WLAN_REASON_STA_REQ_ASSOC_WITHOUT_AUTH = 9, - /* 802.11h */ - WLAN_REASON_DISASSOC_BAD_POWER = 10, - WLAN_REASON_DISASSOC_BAD_SUPP_CHAN = 11, - /* 802.11i */ - WLAN_REASON_INVALID_IE = 13, - WLAN_REASON_MIC_FAILURE = 14, - WLAN_REASON_4WAY_HANDSHAKE_TIMEOUT = 15, - WLAN_REASON_GROUP_KEY_HANDSHAKE_TIMEOUT = 16, - WLAN_REASON_IE_DIFFERENT = 17, - WLAN_REASON_INVALID_GROUP_CIPHER = 18, - WLAN_REASON_INVALID_PAIRWISE_CIPHER = 19, - WLAN_REASON_INVALID_AKMP = 20, - WLAN_REASON_UNSUPP_RSN_VERSION = 21, - WLAN_REASON_INVALID_RSN_IE_CAP = 22, - WLAN_REASON_IEEE8021X_FAILED = 23, - WLAN_REASON_CIPHER_SUITE_REJECTED = 24, - /* TDLS (802.11z) */ - WLAN_REASON_TDLS_TEARDOWN_UNREACHABLE = 25, - WLAN_REASON_TDLS_TEARDOWN_UNSPECIFIED = 26, - /* 802.11e */ - WLAN_REASON_DISASSOC_UNSPECIFIED_QOS = 32, - WLAN_REASON_DISASSOC_QAP_NO_BANDWIDTH = 33, - WLAN_REASON_DISASSOC_LOW_ACK = 34, - WLAN_REASON_DISASSOC_QAP_EXCEED_TXOP = 35, - WLAN_REASON_QSTA_LEAVE_QBSS = 36, - WLAN_REASON_QSTA_NOT_USE = 37, - WLAN_REASON_QSTA_REQUIRE_SETUP = 38, - WLAN_REASON_QSTA_TIMEOUT = 39, - WLAN_REASON_QSTA_CIPHER_NOT_SUPP = 45, - /* 802.11s */ - WLAN_REASON_MESH_PEER_CANCELED = 52, - WLAN_REASON_MESH_MAX_PEERS = 53, - WLAN_REASON_MESH_CONFIG = 54, - WLAN_REASON_MESH_CLOSE = 55, - WLAN_REASON_MESH_MAX_RETRIES = 56, - WLAN_REASON_MESH_CONFIRM_TIMEOUT = 57, - WLAN_REASON_MESH_INVALID_GTK = 58, - WLAN_REASON_MESH_INCONSISTENT_PARAM = 59, - WLAN_REASON_MESH_INVALID_SECURITY = 60, - WLAN_REASON_MESH_PATH_ERROR = 61, - WLAN_REASON_MESH_PATH_NOFORWARD = 62, - WLAN_REASON_MESH_PATH_DEST_UNREACHABLE = 63, - WLAN_REASON_MAC_EXISTS_IN_MBSS = 64, - WLAN_REASON_MESH_CHAN_REGULATORY = 65, - WLAN_REASON_MESH_CHAN = 66, + WLAN_REASON_UNSPECIFIED = 1, + WLAN_REASON_PREV_AUTH_NOT_VALID = 2, + WLAN_REASON_DEAUTH_LEAVING = 3, + WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY = 4, + WLAN_REASON_DISASSOC_AP_BUSY = 5, + WLAN_REASON_CLASS2_FRAME_FROM_NONAUTH_STA = 6, + WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA = 7, + WLAN_REASON_DISASSOC_STA_HAS_LEFT = 8, + WLAN_REASON_STA_REQ_ASSOC_WITHOUT_AUTH = 9, + /* 802.11h */ + WLAN_REASON_DISASSOC_BAD_POWER = 10, + WLAN_REASON_DISASSOC_BAD_SUPP_CHAN = 11, + /* 802.11i */ + WLAN_REASON_INVALID_IE = 13, + WLAN_REASON_MIC_FAILURE = 14, + WLAN_REASON_4WAY_HANDSHAKE_TIMEOUT = 15, + WLAN_REASON_GROUP_KEY_HANDSHAKE_TIMEOUT = 16, + WLAN_REASON_IE_DIFFERENT = 17, + WLAN_REASON_INVALID_GROUP_CIPHER = 18, + WLAN_REASON_INVALID_PAIRWISE_CIPHER = 19, + WLAN_REASON_INVALID_AKMP = 20, + WLAN_REASON_UNSUPP_RSN_VERSION = 21, + WLAN_REASON_INVALID_RSN_IE_CAP = 22, + WLAN_REASON_IEEE8021X_FAILED = 23, + WLAN_REASON_CIPHER_SUITE_REJECTED = 24, + /* TDLS (802.11z) */ + WLAN_REASON_TDLS_TEARDOWN_UNREACHABLE = 25, + WLAN_REASON_TDLS_TEARDOWN_UNSPECIFIED = 26, + /* 802.11e */ + WLAN_REASON_DISASSOC_UNSPECIFIED_QOS = 32, + WLAN_REASON_DISASSOC_QAP_NO_BANDWIDTH = 33, + WLAN_REASON_DISASSOC_LOW_ACK = 34, + WLAN_REASON_DISASSOC_QAP_EXCEED_TXOP = 35, + WLAN_REASON_QSTA_LEAVE_QBSS = 36, + WLAN_REASON_QSTA_NOT_USE = 37, + WLAN_REASON_QSTA_REQUIRE_SETUP = 38, + WLAN_REASON_QSTA_TIMEOUT = 39, + WLAN_REASON_QSTA_CIPHER_NOT_SUPP = 45, + /* 802.11s */ + WLAN_REASON_MESH_PEER_CANCELED = 52, + WLAN_REASON_MESH_MAX_PEERS = 53, + WLAN_REASON_MESH_CONFIG = 54, + WLAN_REASON_MESH_CLOSE = 55, + WLAN_REASON_MESH_MAX_RETRIES = 56, + WLAN_REASON_MESH_CONFIRM_TIMEOUT = 57, + WLAN_REASON_MESH_INVALID_GTK = 58, + WLAN_REASON_MESH_INCONSISTENT_PARAM = 59, + WLAN_REASON_MESH_INVALID_SECURITY = 60, + WLAN_REASON_MESH_PATH_ERROR = 61, + WLAN_REASON_MESH_PATH_NOFORWARD = 62, + WLAN_REASON_MESH_PATH_DEST_UNREACHABLE = 63, + WLAN_REASON_MAC_EXISTS_IN_MBSS = 64, + WLAN_REASON_MESH_CHAN_REGULATORY = 65, + WLAN_REASON_MESH_CHAN = 66, }; /** * struct ieee80211_mcs_info - MCS information * @rx_mask: RX mask * @rx_highest: highest supported RX rate. If set represents - * the highest supported RX data rate in units of 1 Mbps. - * If this field is 0 this value should not be used to - * consider the highest RX data rate supported. + * the highest supported RX data rate in units of 1 Mbps. + * If this field is 0 this value should not be used to + * consider the highest RX data rate supported. * @tx_params: TX parameters */ struct ieee80211_mcs_info { - u8 rx_mask[IEEE80211_HT_MCS_MASK_LEN]; - __le16 rx_highest; - u8 tx_params; - u8 reserved[3]; + u8 rx_mask[IEEE80211_HT_MCS_MASK_LEN]; + __le16 rx_highest; + u8 tx_params; + u8 reserved[3]; }; /** @@ -279,177 +279,177 @@ struct ieee80211_mcs_info { * described in 802.11n D5.0 7.3.2.57 */ struct ieee80211_ht_cap { - __le16 cap_info; - u8 ampdu_params_info; + __le16 cap_info; + u8 ampdu_params_info; - /* 16 bytes MCS information */ - struct ieee80211_mcs_info mcs; + /* 16 bytes MCS information */ + struct ieee80211_mcs_info mcs; - __le16 extended_ht_cap_info; - __le32 tx_BF_cap_info; - u8 antenna_selection_info; + __le16 extended_ht_cap_info; + __le32 tx_BF_cap_info; + u8 antenna_selection_info; }; struct ieee80211_mgmt { - __le16 frame_control; - __le16 duration; - u8 da[6]; - u8 sa[6]; - u8 bssid[6]; - __le16 seq_ctrl; - union { - struct { - __le16 auth_alg; - __le16 auth_transaction; - __le16 status_code; - /* possibly followed by Challenge text */ - u8 variable[0]; - } __attribute__((__packed__)) auth; - struct { - __le16 reason_code; - } __attribute__((__packed__)) deauth; - struct { - __le16 capab_info; - __le16 listen_interval; - /* followed by SSID and Supported rates */ - u8 variable[0]; - } __attribute__((__packed__)) assoc_req; - struct { - __le16 capab_info; - __le16 status_code; - __le16 aid; - /* followed by Supported rates */ - u8 variable[0]; - } __attribute__((__packed__)) assoc_resp, reassoc_resp; - struct { - __le16 capab_info; - __le16 listen_interval; - u8 current_ap[6]; - /* followed by SSID and Supported rates */ - u8 variable[0]; - } __attribute__((__packed__)) reassoc_req; - struct { - __le16 reason_code; - } __attribute__((__packed__)) disassoc; - struct { - __le64 timestamp; - __le16 beacon_int; - __le16 capab_info; - /* followed by some of SSID, Supported rates, - * FH Params, DS Params, CF Params, IBSS Params, TIM */ - u8 variable[0]; - } __attribute__((__packed__)) beacon; - struct { - /* only variable items: SSID, Supported rates */ - u8 variable[0]; - } __attribute__((__packed__)) probe_req; - struct { - __le64 timestamp; - __le16 beacon_int; - __le16 capab_info; - /* followed by some of SSID, Supported rates, - * FH Params, DS Params, CF Params, IBSS Params */ - u8 variable[0]; - } __attribute__((__packed__)) probe_resp; - struct { - u8 category; - union { - struct { - u8 action_code; - u8 dialog_token; - u8 status_code; - u8 variable[0]; - } __attribute__((__packed__)) wme_action; - struct{ - u8 action_code; - u8 variable[0]; - } __attribute__((__packed__)) chan_switch; - struct{ - u8 action_code; - //struct ieee80211_ext_chansw_ie data; - u8 variable[0]; - } __attribute__((__packed__)) ext_chan_switch; - struct{ - u8 action_code; - u8 dialog_token; - u8 element_id; - u8 length; - //struct ieee80211_msrment_ie msr_elem; - } __attribute__((__packed__)) measurement; - struct{ - u8 action_code; - u8 dialog_token; - __le16 capab; - __le16 timeout; - __le16 start_seq_num; - } __attribute__((__packed__)) addba_req; - struct{ - u8 action_code; - u8 dialog_token; - __le16 status; - __le16 capab; - __le16 timeout; - } __attribute__((__packed__)) addba_resp; - struct{ - u8 action_code; - __le16 params; - __le16 reason_code; - } __attribute__((__packed__)) delba; - struct { - u8 action_code; - u8 variable[0]; - } __attribute__((__packed__)) self_prot; - struct{ - u8 action_code; - u8 variable[0]; - } __attribute__((__packed__)) mesh_action; - struct { - u8 action; - u8 trans_id[WLAN_SA_QUERY_TR_ID_LEN]; - } __attribute__((__packed__)) sa_query; - struct { - u8 action; - u8 smps_control; - } __attribute__((__packed__)) ht_smps; - struct { - u8 action_code; - u8 chanwidth; - } __attribute__((__packed__)) ht_notify_cw; - struct { - u8 action_code; - u8 dialog_token; - __le16 capability; - u8 variable[0]; - } __attribute__((__packed__)) tdls_discover_resp; - struct { - u8 action_code; - u8 operating_mode; - } __attribute__((__packed__)) vht_opmode_notif; - struct { - u8 action_code; - u8 membership[WLAN_MEMBERSHIP_LEN]; - u8 position[WLAN_USER_POSITION_LEN]; - } __attribute__((__packed__)) vht_group_notif; - struct { - u8 action_code; - u8 dialog_token; - u8 tpc_elem_id; - u8 tpc_elem_length; - //struct ieee80211_tpc_report_ie tpc; - } __attribute__((__packed__)) tpc_report; - struct { - u8 action_code; - u8 dialog_token; - u8 follow_up; - u8 tod[6]; - u8 toa[6]; - __le16 tod_error; - __le16 toa_error; - u8 variable[0]; - } __attribute__((__packed__)) ftm; - } u; - } __attribute__((__packed__)) action; - } u; + __le16 frame_control; + __le16 duration; + u8 da[6]; + u8 sa[6]; + u8 bssid[6]; + __le16 seq_ctrl; + union { + struct { + __le16 auth_alg; + __le16 auth_transaction; + __le16 status_code; + /* possibly followed by Challenge text */ + u8 variable[0]; + } __attribute__((__packed__)) auth; + struct { + __le16 reason_code; + } __attribute__((__packed__)) deauth; + struct { + __le16 capab_info; + __le16 listen_interval; + /* followed by SSID and Supported rates */ + u8 variable[0]; + } __attribute__((__packed__)) assoc_req; + struct { + __le16 capab_info; + __le16 status_code; + __le16 aid; + /* followed by Supported rates */ + u8 variable[0]; + } __attribute__((__packed__)) assoc_resp, reassoc_resp; + struct { + __le16 capab_info; + __le16 listen_interval; + u8 current_ap[6]; + /* followed by SSID and Supported rates */ + u8 variable[0]; + } __attribute__((__packed__)) reassoc_req; + struct { + __le16 reason_code; + } __attribute__((__packed__)) disassoc; + struct { + __le64 timestamp; + __le16 beacon_int; + __le16 capab_info; + /* followed by some of SSID, Supported rates, + * FH Params, DS Params, CF Params, IBSS Params, TIM */ + u8 variable[0]; + } __attribute__((__packed__)) beacon; + struct { + /* only variable items: SSID, Supported rates */ + u8 variable[0]; + } __attribute__((__packed__)) probe_req; + struct { + __le64 timestamp; + __le16 beacon_int; + __le16 capab_info; + /* followed by some of SSID, Supported rates, + * FH Params, DS Params, CF Params, IBSS Params */ + u8 variable[0]; + } __attribute__((__packed__)) probe_resp; + struct { + u8 category; + union { + struct { + u8 action_code; + u8 dialog_token; + u8 status_code; + u8 variable[0]; + } __attribute__((__packed__)) wme_action; + struct{ + u8 action_code; + u8 variable[0]; + } __attribute__((__packed__)) chan_switch; + struct{ + u8 action_code; + //struct ieee80211_ext_chansw_ie data; + u8 variable[0]; + } __attribute__((__packed__)) ext_chan_switch; + struct{ + u8 action_code; + u8 dialog_token; + u8 element_id; + u8 length; + //struct ieee80211_msrment_ie msr_elem; + } __attribute__((__packed__)) measurement; + struct{ + u8 action_code; + u8 dialog_token; + __le16 capab; + __le16 timeout; + __le16 start_seq_num; + } __attribute__((__packed__)) addba_req; + struct{ + u8 action_code; + u8 dialog_token; + __le16 status; + __le16 capab; + __le16 timeout; + } __attribute__((__packed__)) addba_resp; + struct{ + u8 action_code; + __le16 params; + __le16 reason_code; + } __attribute__((__packed__)) delba; + struct { + u8 action_code; + u8 variable[0]; + } __attribute__((__packed__)) self_prot; + struct{ + u8 action_code; + u8 variable[0]; + } __attribute__((__packed__)) mesh_action; + struct { + u8 action; + u8 trans_id[WLAN_SA_QUERY_TR_ID_LEN]; + } __attribute__((__packed__)) sa_query; + struct { + u8 action; + u8 smps_control; + } __attribute__((__packed__)) ht_smps; + struct { + u8 action_code; + u8 chanwidth; + } __attribute__((__packed__)) ht_notify_cw; + struct { + u8 action_code; + u8 dialog_token; + __le16 capability; + u8 variable[0]; + } __attribute__((__packed__)) tdls_discover_resp; + struct { + u8 action_code; + u8 operating_mode; + } __attribute__((__packed__)) vht_opmode_notif; + struct { + u8 action_code; + u8 membership[WLAN_MEMBERSHIP_LEN]; + u8 position[WLAN_USER_POSITION_LEN]; + } __attribute__((__packed__)) vht_group_notif; + struct { + u8 action_code; + u8 dialog_token; + u8 tpc_elem_id; + u8 tpc_elem_length; + //struct ieee80211_tpc_report_ie tpc; + } __attribute__((__packed__)) tpc_report; + struct { + u8 action_code; + u8 dialog_token; + u8 follow_up; + u8 tod[6]; + u8 toa[6]; + __le16 tod_error; + __le16 toa_error; + u8 variable[0]; + } __attribute__((__packed__)) ftm; + } u; + } __attribute__((__packed__)) action; + } u; } __attribute__((packed, aligned(2))); /** @@ -458,8 +458,8 @@ struct ieee80211_mgmt { */ static inline bool ieee80211_is_beacon(__le16 fc) { - return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == - cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_BEACON); + return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == + cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_BEACON); } /** @@ -468,8 +468,8 @@ static inline bool ieee80211_is_beacon(__le16 fc) */ static inline bool ieee80211_is_deauth(__le16 fc) { - return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == - cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_DEAUTH); + return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == + cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_DEAUTH); } /** @@ -478,8 +478,8 @@ static inline bool ieee80211_is_deauth(__le16 fc) */ static inline bool ieee80211_is_disassoc(__le16 fc) { - return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == - cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_DISASSOC); + return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == + cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_DISASSOC); } /** @@ -488,8 +488,8 @@ static inline bool ieee80211_is_disassoc(__le16 fc) */ static inline bool ieee80211_is_action(__le16 fc) { - return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == - cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_ACTION); + return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == + cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_ACTION); } /** @@ -508,8 +508,8 @@ static inline int ieee80211_is_probe_resp(__le16 fc) */ static inline bool ieee80211_is_probe_req(__le16 fc) { - return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == - cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_PROBE_REQ); + return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_FCTL_STYPE)) == + cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_PROBE_REQ); } /** @@ -518,8 +518,8 @@ static inline bool ieee80211_is_probe_req(__le16 fc) */ static inline bool ieee80211_is_data(__le16 fc) { - return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE)) == - cpu_to_le16(IEEE80211_FTYPE_DATA); + return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE)) == + cpu_to_le16(IEEE80211_FTYPE_DATA); } /** @@ -528,12 +528,12 @@ static inline bool ieee80211_is_data(__le16 fc) */ static inline bool ieee80211_is_data_qos(__le16 fc) { - /* - * mask with QOS_DATA rather than IEEE80211_FCTL_STYPE as we just need - * to check the one bit - */ - return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_STYPE_QOS_DATA)) == - cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_QOS_DATA); + /* + * mask with QOS_DATA rather than IEEE80211_FCTL_STYPE as we just need + * to check the one bit + */ + return (fc & cpu_to_le16(IEEE80211_FCTL_FTYPE | IEEE80211_STYPE_QOS_DATA)) == + cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_QOS_DATA); } #endif diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/list.h b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/list.h index 81f576c8..0db974b8 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/list.h +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/list.h @@ -80,16 +80,16 @@ * using the generic single-entry routines. */ struct list_head { - struct list_head *next, *prev; + struct list_head *next, *prev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) \ - struct list_head name = LIST_HEAD_INIT(name) + struct list_head name = LIST_HEAD_INIT(name) #define INIT_LIST_HEAD(ptr) do { \ - (ptr)->next = (ptr); (ptr)->prev = (ptr); \ + (ptr)->next = (ptr); (ptr)->prev = (ptr); \ } while (0) /* @@ -99,13 +99,13 @@ struct list_head { * the prev/next entries already! */ static inline void __list_add(struct list_head *new, - struct list_head *prev, - struct list_head *next) + struct list_head *prev, + struct list_head *next) { - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; } /** @@ -118,7 +118,7 @@ static inline void __list_add(struct list_head *new, */ static inline void list_add(struct list_head *new, struct list_head *head) { - __list_add(new, head, head->next); + __list_add(new, head, head->next); } /** @@ -131,7 +131,7 @@ static inline void list_add(struct list_head *new, struct list_head *head) */ static inline void list_add_tail(struct list_head *new, struct list_head *head) { - __list_add(new, head->prev, head); + __list_add(new, head->prev, head); } @@ -144,8 +144,8 @@ static inline void list_add_tail(struct list_head *new, struct list_head *head) */ static inline void __list_del(struct list_head * prev, struct list_head * next) { - next->prev = prev; - prev->next = next; + next->prev = prev; + prev->next = next; } /** @@ -156,9 +156,9 @@ static inline void __list_del(struct list_head * prev, struct list_head * next) */ static inline void list_del(struct list_head *entry) { - __list_del(entry->prev, entry->next); - entry->next = LIST_POISON1; - entry->prev = LIST_POISON2; + __list_del(entry->prev, entry->next); + entry->next = LIST_POISON1; + entry->prev = LIST_POISON2; } @@ -169,8 +169,8 @@ static inline void list_del(struct list_head *entry) */ static inline void list_del_init(struct list_head *entry) { - __list_del(entry->prev, entry->next); - INIT_LIST_HEAD(entry); + __list_del(entry->prev, entry->next); + INIT_LIST_HEAD(entry); } /** @@ -190,7 +190,7 @@ static inline void list_move(struct list_head *list, struct list_head *head) * @head: the head that will follow our entry */ static inline void list_move_tail(struct list_head *list, - struct list_head *head) + struct list_head *head) { __list_del(list->prev, list->next); list_add_tail(list, head); @@ -202,21 +202,21 @@ static inline void list_move_tail(struct list_head *list, */ static inline int list_empty(const struct list_head *head) { - return head->next == head; + return head->next == head; } static inline void __list_splice(struct list_head *list, - struct list_head *head) + struct list_head *head) { - struct list_head *first = list->next; - struct list_head *last = list->prev; - struct list_head *at = head->next; + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->next; - first->prev = head; - head->next = first; + first->prev = head; + head->next = first; - last->next = at; - at->prev = last; + last->next = at; + at->prev = last; } /** @@ -226,8 +226,8 @@ static inline void __list_splice(struct list_head *list, */ static inline void list_splice(struct list_head *list, struct list_head *head) { - if (!list_empty(list)) - __list_splice(list, head); + if (!list_empty(list)) + __list_splice(list, head); } /** @@ -238,37 +238,37 @@ static inline void list_splice(struct list_head *list, struct list_head *head) * The list at @list is reinitialised */ static inline void list_splice_init(struct list_head *list, - struct list_head *head) + struct list_head *head) { - if (!list_empty(list)) { - __list_splice(list, head); - INIT_LIST_HEAD(list); - } + if (!list_empty(list)) { + __list_splice(list, head); + INIT_LIST_HEAD(list); + } } /** * list_entry - get the struct for this entry - * @ptr: the &struct list_head pointer. - * @type: the type of the struct this is embedded in. - * @member: the name of the list_struct within the struct. + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. */ #define list_entry(ptr, type, member) \ - container_of(ptr, type, member) + container_of(ptr, type, member) /** - * list_for_each - iterate over a list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. + * list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. */ #define list_for_each(pos, head) \ - for (pos = (head)->next; pos != (head); \ + for (pos = (head)->next; pos != (head); \ pos = pos->next) /** - * __list_for_each - iterate over a list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. + * __list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. * * This variant differs from list_for_each() in that it's the * simplest possible list iteration code, no prefetching is done. @@ -276,111 +276,111 @@ static inline void list_splice_init(struct list_head *list, * or 1 entry) most of the time. */ #define __list_for_each(pos, head) \ - for (pos = (head)->next; pos != (head); pos = pos->next) + for (pos = (head)->next; pos != (head); pos = pos->next) /** - * list_for_each_prev - iterate over a list backwards - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. + * list_for_each_prev - iterate over a list backwards + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. */ #define list_for_each_prev(pos, head) \ - for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \ - pos = pos->prev) + for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \ + pos = pos->prev) /** - * list_for_each_safe - iterate over a list safe against removal of list entry - * @pos: the &struct list_head to use as a loop counter. - * @n: another &struct list_head to use as temporary storage - * @head: the head for your list. + * list_for_each_safe - iterate over a list safe against removal of list entry + * @pos: the &struct list_head to use as a loop counter. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. */ #define list_for_each_safe(pos, n, head) \ - for (pos = (head)->next, n = pos->next; pos != (head); \ - pos = n, n = pos->next) + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) /** - * list_for_each_entry - iterate over list of given type - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. */ -#define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, typeof(*pos), member)) +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) /** * list_for_each_entry_reverse - iterate backwards over list of given type. - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. */ -#define list_for_each_entry_reverse(pos, head, member) \ - for (pos = list_entry((head)->prev, typeof(*pos), member); \ - &pos->member != (head); \ - pos = list_entry(pos->member.prev, typeof(*pos), member)) +#define list_for_each_entry_reverse(pos, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.prev, typeof(*pos), member)) /** * list_prepare_entry - prepare a pos entry for use as a start point in - * list_for_each_entry_continue - * @pos: the type * to use as a start point - * @head: the head of the list - * @member: the name of the list_struct within the struct. + * list_for_each_entry_continue + * @pos: the type * to use as a start point + * @head: the head of the list + * @member: the name of the list_struct within the struct. */ #define list_prepare_entry(pos, head, member) \ - ((pos) ? : list_entry(head, typeof(*pos), member)) + ((pos) ? : list_entry(head, typeof(*pos), member)) /** - * list_for_each_entry_continue - iterate over list of given type - * continuing after existing point - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. + * list_for_each_entry_continue - iterate over list of given type + * continuing after existing point + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. */ -#define list_for_each_entry_continue(pos, head, member) \ - for (pos = list_entry(pos->member.next, typeof(*pos), member); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, typeof(*pos), member)) +#define list_for_each_entry_continue(pos, head, member) \ + for (pos = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) /** * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry - * @pos: the type * to use as a loop counter. - * @n: another type * to use as temporary storage - * @head: the head for your list. - * @member: the name of the list_struct within the struct. + * @pos: the type * to use as a loop counter. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. */ -#define list_for_each_entry_safe(pos, n, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - n = list_entry(pos->member.next, typeof(*pos), member); \ - &pos->member != (head); \ - pos = n, n = list_entry(n->member.next, typeof(*n), member)) +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) /** - * list_for_each_entry_safe_continue - iterate over list of given type - * continuing after existing point safe against removal of list entry - * @pos: the type * to use as a loop counter. - * @n: another type * to use as temporary storage - * @head: the head for your list. - * @member: the name of the list_struct within the struct. + * list_for_each_entry_safe_continue - iterate over list of given type + * continuing after existing point safe against removal of list entry + * @pos: the type * to use as a loop counter. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. */ -#define list_for_each_entry_safe_continue(pos, n, head, member) \ - for (pos = list_entry(pos->member.next, typeof(*pos), member), \ - n = list_entry(pos->member.next, typeof(*pos), member); \ - &pos->member != (head); \ - pos = n, n = list_entry(n->member.next, typeof(*n), member)) +#define list_for_each_entry_safe_continue(pos, n, head, member) \ + for (pos = list_entry(pos->member.next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) /** * list_for_each_entry_safe_reverse - iterate backwards over list of given type safe against - * removal of list entry - * @pos: the type * to use as a loop counter. - * @n: another type * to use as temporary storage - * @head: the head for your list. - * @member: the name of the list_struct within the struct. + * removal of list entry + * @pos: the type * to use as a loop counter. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. */ -#define list_for_each_entry_safe_reverse(pos, n, head, member) \ - for (pos = list_entry((head)->prev, typeof(*pos), member), \ - n = list_entry(pos->member.prev, typeof(*pos), member); \ - &pos->member != (head); \ - pos = n, n = list_entry(n->member.prev, typeof(*n), member)) +#define list_for_each_entry_safe_reverse(pos, n, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member), \ + n = list_entry(pos->member.prev, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.prev, typeof(*n), member)) @@ -393,11 +393,11 @@ static inline void list_splice_init(struct list_head *list, */ struct hlist_head { - struct hlist_node *first; + struct hlist_node *first; }; struct hlist_node { - struct hlist_node *next, **pprev; + struct hlist_node *next, **pprev; }; #define HLIST_HEAD_INIT { .first = NULL } @@ -407,70 +407,70 @@ struct hlist_node { static inline int hlist_unhashed(const struct hlist_node *h) { - return !h->pprev; + return !h->pprev; } static inline int hlist_empty(const struct hlist_head *h) { - return !h->first; + return !h->first; } static inline void __hlist_del(struct hlist_node *n) { - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next) - next->pprev = pprev; + struct hlist_node *next = n->next; + struct hlist_node **pprev = n->pprev; + *pprev = next; + if (next) + next->pprev = pprev; } static inline void hlist_del(struct hlist_node *n) { - __hlist_del(n); - n->next = LIST_POISON1; - n->pprev = LIST_POISON2; + __hlist_del(n); + n->next = LIST_POISON1; + n->pprev = LIST_POISON2; } static inline void hlist_del_init(struct hlist_node *n) { - if (n->pprev) { - __hlist_del(n); - INIT_HLIST_NODE(n); - } + if (n->pprev) { + __hlist_del(n); + INIT_HLIST_NODE(n); + } } static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) { - struct hlist_node *first = h->first; - n->next = first; - if (first) - first->pprev = &n->next; - h->first = n; - n->pprev = &h->first; + struct hlist_node *first = h->first; + n->next = first; + if (first) + first->pprev = &n->next; + h->first = n; + n->pprev = &h->first; } /* next must be != NULL */ static inline void hlist_add_before(struct hlist_node *n, - struct hlist_node *next) + struct hlist_node *next) { - n->pprev = next->pprev; - n->next = next; - next->pprev = &n->next; - *(n->pprev) = n; + n->pprev = next->pprev; + n->next = next; + next->pprev = &n->next; + *(n->pprev) = n; } static inline void hlist_add_after(struct hlist_node *n, - struct hlist_node *next) + struct hlist_node *next) { - next->next = n->next; - n->next = next; - next->pprev = &n->next; + next->next = n->next; + n->next = next; + next->pprev = &n->next; - if(next->next) - next->next->pprev = &next->next; + if(next->next) + next->next->pprev = &next->next; } @@ -478,62 +478,62 @@ static inline void hlist_add_after(struct hlist_node *n, #define hlist_entry(ptr, type, member) container_of(ptr,type,member) #define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \ - pos = pos->next) + for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \ + pos = pos->next) #define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \ - pos = n) + for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \ + pos = n) /** - * hlist_for_each_entry - iterate over list of given type - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @head: the head for your list. - * @member: the name of the hlist_node within the struct. + * hlist_for_each_entry - iterate over list of given type + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @head: the head for your list. + * @member: the name of the hlist_node within the struct. */ -#define hlist_for_each_entry(tpos, pos, head, member) \ - for (pos = (head)->first; \ - pos && ({ prefetch(pos->next); 1;}) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = pos->next) +#define hlist_for_each_entry(tpos, pos, head, member) \ + for (pos = (head)->first; \ + pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) /** * hlist_for_each_entry_continue - iterate over a hlist continuing after existing point - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @member: the name of the hlist_node within the struct. + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @member: the name of the hlist_node within the struct. */ -#define hlist_for_each_entry_continue(tpos, pos, member) \ - for (pos = (pos)->next; \ - pos && ({ prefetch(pos->next); 1;}) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = pos->next) +#define hlist_for_each_entry_continue(tpos, pos, member) \ + for (pos = (pos)->next; \ + pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) /** * hlist_for_each_entry_from - iterate over a hlist continuing from existing point - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @member: the name of the hlist_node within the struct. + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @member: the name of the hlist_node within the struct. */ -#define hlist_for_each_entry_from(tpos, pos, member) \ - for (; pos && ({ prefetch(pos->next); 1;}) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = pos->next) +#define hlist_for_each_entry_from(tpos, pos, member) \ + for (; pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) /** * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @n: another &struct hlist_node to use as temporary storage - * @head: the head for your list. - * @member: the name of the hlist_node within the struct. + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @n: another &struct hlist_node to use as temporary storage + * @head: the head for your list. + * @member: the name of the hlist_node within the struct. */ -#define hlist_for_each_entry_safe(tpos, pos, n, head, member) \ - for (pos = (head)->first; \ - pos && ({ n = pos->next; 1; }) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = n) +#define hlist_for_each_entry_safe(tpos, pos, n, head, member) \ + for (pos = (head)->first; \ + pos && ({ n = pos->next; 1; }) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = n) #endif diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/lmac_msg.h b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/lmac_msg.h index 3e48a361..a728a05a 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/lmac_msg.h +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/lmac_msg.h @@ -1701,7 +1701,7 @@ struct me_traffic_ind_req struct me_rc_stats_req { /// Index of the station for which the RC statistics are requested - u8_l sta_idx; + u8_l sta_idx; }; /// Structure containing the structure of a retry chain step diff --git a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/nl80211.h b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/nl80211.h index 601f6ef5..23f6a5c3 100644 --- a/components/bl602/bl602_wifidrv/bl60x_wifi_driver/nl80211.h +++ b/components/bl602/bl602_wifidrv/bl60x_wifi_driver/nl80211.h @@ -30,8 +30,8 @@ #ifndef __NL80211_H__ #define __NL80211_H__ -#define NL80211_MAX_NR_CIPHER_SUITES 5 -#define NL80211_MAX_NR_AKM_SUITES 2 +#define NL80211_MAX_NR_CIPHER_SUITES 5 +#define NL80211_MAX_NR_AKM_SUITES 2 /** @@ -44,14 +44,14 @@ */ enum nl80211_bss_select_attr { - __NL80211_BSS_SELECT_ATTR_INVALID, - NL80211_BSS_SELECT_ATTR_RSSI, - NL80211_BSS_SELECT_ATTR_BAND_PREF, - NL80211_BSS_SELECT_ATTR_RSSI_ADJUST, + __NL80211_BSS_SELECT_ATTR_INVALID, + NL80211_BSS_SELECT_ATTR_RSSI, + NL80211_BSS_SELECT_ATTR_BAND_PREF, + NL80211_BSS_SELECT_ATTR_RSSI_ADJUST, - /* keep last */ - __NL80211_BSS_SELECT_ATTR_AFTER_LAST, - NL80211_BSS_SELECT_ATTR_MAX = __NL80211_BSS_SELECT_ATTR_AFTER_LAST - 1 + /* keep last */ + __NL80211_BSS_SELECT_ATTR_AFTER_LAST, + NL80211_BSS_SELECT_ATTR_MAX = __NL80211_BSS_SELECT_ATTR_AFTER_LAST - 1 }; /** @@ -68,23 +68,23 @@ enum nl80211_bss_select_attr { * @__NL80211_AUTHTYPE_NUM: internal * @NL80211_AUTHTYPE_MAX: maximum valid auth algorithm * @NL80211_AUTHTYPE_AUTOMATIC: determine automatically (if necessary by - * trying multiple times); this is invalid in netlink -- leave out - * the attribute for this on CONNECT commands. + * trying multiple times); this is invalid in netlink -- leave out + * the attribute for this on CONNECT commands. */ enum nl80211_auth_type { - NL80211_AUTHTYPE_OPEN_SYSTEM, - NL80211_AUTHTYPE_SHARED_KEY, - NL80211_AUTHTYPE_FT, - NL80211_AUTHTYPE_NETWORK_EAP, - NL80211_AUTHTYPE_SAE, - NL80211_AUTHTYPE_FILS_SK, - NL80211_AUTHTYPE_FILS_SK_PFS, - NL80211_AUTHTYPE_FILS_PK, + NL80211_AUTHTYPE_OPEN_SYSTEM, + NL80211_AUTHTYPE_SHARED_KEY, + NL80211_AUTHTYPE_FT, + NL80211_AUTHTYPE_NETWORK_EAP, + NL80211_AUTHTYPE_SAE, + NL80211_AUTHTYPE_FILS_SK, + NL80211_AUTHTYPE_FILS_SK_PFS, + NL80211_AUTHTYPE_FILS_PK, - /* keep last */ - __NL80211_AUTHTYPE_NUM, - NL80211_AUTHTYPE_MAX = __NL80211_AUTHTYPE_NUM - 1, - NL80211_AUTHTYPE_AUTOMATIC + /* keep last */ + __NL80211_AUTHTYPE_NUM, + NL80211_AUTHTYPE_MAX = __NL80211_AUTHTYPE_NUM - 1, + NL80211_AUTHTYPE_AUTOMATIC }; /** @@ -93,15 +93,15 @@ enum nl80211_auth_type { * Channel states used by the DFS code. * * @NL80211_DFS_USABLE: The channel can be used, but channel availability - * check (CAC) must be performed before using it for AP or IBSS. + * check (CAC) must be performed before using it for AP or IBSS. * @NL80211_DFS_UNAVAILABLE: A radar has been detected on this channel, it - * is therefore marked as not available. + * is therefore marked as not available. * @NL80211_DFS_AVAILABLE: The channel has been CAC checked and is available. */ enum nl80211_dfs_state { - NL80211_DFS_USABLE, - NL80211_DFS_UNAVAILABLE, - NL80211_DFS_AVAILABLE, + NL80211_DFS_USABLE, + NL80211_DFS_UNAVAILABLE, + NL80211_DFS_AVAILABLE, }; /** @@ -110,14 +110,14 @@ enum nl80211_dfs_state { * @NL80211_BAND_5GHZ: around 5 GHz band (4.9 - 5.7 GHz) * @NL80211_BAND_60GHZ: around 60 GHz band (58.32 - 64.80 GHz) * @NUM_NL80211_BANDS: number of bands, avoid using this in userspace - * since newer kernel versions may support more bands + * since newer kernel versions may support more bands */ enum nl80211_band { - NL80211_BAND_2GHZ, - NL80211_BAND_5GHZ, - NL80211_BAND_60GHZ, + NL80211_BAND_2GHZ, + NL80211_BAND_5GHZ, + NL80211_BAND_60GHZ, - NUM_NL80211_BANDS, + NUM_NL80211_BANDS, }; /** @@ -128,19 +128,19 @@ enum nl80211_band { * @NL80211_IFTYPE_STATION: managed BSS member * @NL80211_IFTYPE_AP: access point * @NL80211_IFTYPE_AP_VLAN: VLAN interface for access points; VLAN interfaces - * are a bit special in that they must always be tied to a pre-existing - * AP type interface. + * are a bit special in that they must always be tied to a pre-existing + * AP type interface. * @NL80211_IFTYPE_WDS: wireless distribution interface * @NL80211_IFTYPE_MONITOR: monitor interface receiving all frames * @NL80211_IFTYPE_MESH_POINT: mesh point * @NL80211_IFTYPE_P2P_CLIENT: P2P client * @NL80211_IFTYPE_P2P_GO: P2P group owner * @NL80211_IFTYPE_P2P_DEVICE: P2P device interface type, this is not a netdev - * and therefore can't be created in the normal ways, use the - * %NL80211_CMD_START_P2P_DEVICE and %NL80211_CMD_STOP_P2P_DEVICE - * commands to create and destroy one + * and therefore can't be created in the normal ways, use the + * %NL80211_CMD_START_P2P_DEVICE and %NL80211_CMD_STOP_P2P_DEVICE + * commands to create and destroy one * @NL80211_IF_TYPE_OCB: Outside Context of a BSS - * This mode corresponds to the MIB variable dot11OCBActivated=true + * This mode corresponds to the MIB variable dot11OCBActivated=true * @NL80211_IFTYPE_NAN: NAN device interface type (not a netdev) * @NL80211_IFTYPE_MAX: highest interface type number currently defined * @NUM_NL80211_IFTYPES: number of defined interface types @@ -150,23 +150,23 @@ enum nl80211_band { * */ enum nl80211_iftype { - NL80211_IFTYPE_UNSPECIFIED, - NL80211_IFTYPE_ADHOC, - NL80211_IFTYPE_STATION, - NL80211_IFTYPE_AP, - NL80211_IFTYPE_AP_VLAN, - NL80211_IFTYPE_WDS, - NL80211_IFTYPE_MONITOR, - NL80211_IFTYPE_MESH_POINT, - NL80211_IFTYPE_P2P_CLIENT, - NL80211_IFTYPE_P2P_GO, - NL80211_IFTYPE_P2P_DEVICE, - NL80211_IFTYPE_OCB, - NL80211_IFTYPE_NAN, + NL80211_IFTYPE_UNSPECIFIED, + NL80211_IFTYPE_ADHOC, + NL80211_IFTYPE_STATION, + NL80211_IFTYPE_AP, + NL80211_IFTYPE_AP_VLAN, + NL80211_IFTYPE_WDS, + NL80211_IFTYPE_MONITOR, + NL80211_IFTYPE_MESH_POINT, + NL80211_IFTYPE_P2P_CLIENT, + NL80211_IFTYPE_P2P_GO, + NL80211_IFTYPE_P2P_DEVICE, + NL80211_IFTYPE_OCB, + NL80211_IFTYPE_NAN, - /* keep last */ - NUM_NL80211_IFTYPES, - NL80211_IFTYPE_MAX = NUM_NL80211_IFTYPES - 1 + /* keep last */ + NUM_NL80211_IFTYPES, + NL80211_IFTYPE_MAX = NUM_NL80211_IFTYPES - 1 }; /** @@ -175,8 +175,8 @@ enum nl80211_iftype { * @NL80211_MFP_REQUIRED: Management frame protection required */ enum nl80211_mfp { - NL80211_MFP_NO, - NL80211_MFP_REQUIRED, + NL80211_MFP_NO, + NL80211_MFP_REQUIRED, }; #endif diff --git a/components/bl602/bl602_wifidrv/bouffalo.mk b/components/bl602/bl602_wifidrv/bouffalo.mk index 847b32ca..f4cc9b97 100644 --- a/components/bl602/bl602_wifidrv/bouffalo.mk +++ b/components/bl602/bl602_wifidrv/bouffalo.mk @@ -2,11 +2,11 @@ # ## These include paths would be exported to project level COMPONENT_ADD_INCLUDEDIRS += bl60x_wifi_driver/include - -## not be exported to project level -COMPONENT_PRIV_INCLUDEDIRS := bl60x_wifi_driver -## This component's src +## not be exported to project level +COMPONENT_PRIV_INCLUDEDIRS := bl60x_wifi_driver + +## This component's src COMPONENT_SRCS := bl60x_wifi_driver/ipc_host.c \ bl60x_wifi_driver/os_hal.c \ bl60x_wifi_driver/bl_apis.c \ @@ -30,7 +30,7 @@ COMPONENT_SRCS := bl60x_wifi_driver/ipc_host.c \ bl60x_wifi_driver/wifi_mgmr_profile.c \ bl60x_wifi_driver/wifi_netif.c \ bl60x_wifi_driver/wifi_mgmr_event.c - + COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) COMPONENT_SRCDIRS := bl60x_wifi_driver @@ -43,4 +43,4 @@ endif ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/bl602/freertos_riscv/bouffalo.mk b/components/bl602/freertos_riscv/bouffalo.mk index 5f5b764a..ec2833ed 100644 --- a/components/bl602/freertos_riscv/bouffalo.mk +++ b/components/bl602/freertos_riscv/bouffalo.mk @@ -3,9 +3,9 @@ # COMPONENT_ADD_INCLUDEDIRS += config portable/GCC/RISC-V portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions -COMPONENT_OBJS := +COMPONENT_OBJS := -COMPONENT_SRCDIRS := +COMPONENT_SRCDIRS := OPT_FLAG_G := $(findstring -Og, $(CFLAGS)) ifeq ($(strip $(OPT_FLAG_G)),-Og) diff --git a/components/bl602/freertos_riscv/config/FreeRTOS.h b/components/bl602/freertos_riscv/config/FreeRTOS.h index 9d09d91a..a3796364 100644 --- a/components/bl602/freertos_riscv/config/FreeRTOS.h +++ b/components/bl602/freertos_riscv/config/FreeRTOS.h @@ -63,12 +63,12 @@ extern "C" { /* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ #ifndef configUSE_NEWLIB_REENTRANT - #define configUSE_NEWLIB_REENTRANT 0 + #define configUSE_NEWLIB_REENTRANT 0 #endif /* Required if struct _reent is used. */ #if ( configUSE_NEWLIB_REENTRANT == 1 ) - #include + #include #endif /* * Check all the required application specific macros have been defined. @@ -77,479 +77,479 @@ extern "C" { */ #ifndef configMINIMAL_STACK_SIZE - #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. + #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. #endif #ifndef configMAX_PRIORITIES - #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. #endif #if configMAX_PRIORITIES < 1 - #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. + #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. #endif #ifndef configUSE_PREEMPTION - #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_IDLE_HOOK - #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_TICK_HOOK - #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_16_BIT_TICKS - #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_CO_ROUTINES - #define configUSE_CO_ROUTINES 0 + #define configUSE_CO_ROUTINES 0 #endif #ifndef INCLUDE_vTaskPrioritySet - #define INCLUDE_vTaskPrioritySet 0 + #define INCLUDE_vTaskPrioritySet 0 #endif #ifndef INCLUDE_uxTaskPriorityGet - #define INCLUDE_uxTaskPriorityGet 0 + #define INCLUDE_uxTaskPriorityGet 0 #endif #ifndef INCLUDE_vTaskDelete - #define INCLUDE_vTaskDelete 0 + #define INCLUDE_vTaskDelete 0 #endif #ifndef INCLUDE_vTaskSuspend - #define INCLUDE_vTaskSuspend 0 + #define INCLUDE_vTaskSuspend 0 #endif #ifndef INCLUDE_vTaskDelayUntil - #define INCLUDE_vTaskDelayUntil 0 + #define INCLUDE_vTaskDelayUntil 0 #endif #ifndef INCLUDE_vTaskDelay - #define INCLUDE_vTaskDelay 0 + #define INCLUDE_vTaskDelay 0 #endif #ifndef INCLUDE_xTaskGetIdleTaskHandle - #define INCLUDE_xTaskGetIdleTaskHandle 0 + #define INCLUDE_xTaskGetIdleTaskHandle 0 #endif #ifndef INCLUDE_xTaskAbortDelay - #define INCLUDE_xTaskAbortDelay 0 + #define INCLUDE_xTaskAbortDelay 0 #endif #ifndef INCLUDE_xQueueGetMutexHolder - #define INCLUDE_xQueueGetMutexHolder 0 + #define INCLUDE_xQueueGetMutexHolder 0 #endif #ifndef INCLUDE_xSemaphoreGetMutexHolder - #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder + #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder #endif #ifndef INCLUDE_xTaskGetHandle - #define INCLUDE_xTaskGetHandle 0 + #define INCLUDE_xTaskGetHandle 0 #endif #ifndef INCLUDE_uxTaskGetStackHighWaterMark - #define INCLUDE_uxTaskGetStackHighWaterMark 0 + #define INCLUDE_uxTaskGetStackHighWaterMark 0 #endif #ifndef INCLUDE_uxTaskGetStackHighWaterMark2 - #define INCLUDE_uxTaskGetStackHighWaterMark2 0 + #define INCLUDE_uxTaskGetStackHighWaterMark2 0 #endif #ifndef INCLUDE_eTaskGetState - #define INCLUDE_eTaskGetState 0 + #define INCLUDE_eTaskGetState 0 #endif #ifndef INCLUDE_xTaskResumeFromISR - #define INCLUDE_xTaskResumeFromISR 1 + #define INCLUDE_xTaskResumeFromISR 1 #endif #ifndef INCLUDE_xTimerPendFunctionCall - #define INCLUDE_xTimerPendFunctionCall 0 + #define INCLUDE_xTimerPendFunctionCall 0 #endif #ifndef INCLUDE_xTaskGetSchedulerState - #define INCLUDE_xTaskGetSchedulerState 0 + #define INCLUDE_xTaskGetSchedulerState 0 #endif #ifndef INCLUDE_xTaskGetCurrentTaskHandle - #define INCLUDE_xTaskGetCurrentTaskHandle 0 + #define INCLUDE_xTaskGetCurrentTaskHandle 0 #endif #if configUSE_CO_ROUTINES != 0 - #ifndef configMAX_CO_ROUTINE_PRIORITIES - #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. - #endif + #ifndef configMAX_CO_ROUTINE_PRIORITIES + #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. + #endif #endif #ifndef configUSE_DAEMON_TASK_STARTUP_HOOK - #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 + #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 #endif #ifndef configUSE_APPLICATION_TASK_TAG - #define configUSE_APPLICATION_TASK_TAG 0 + #define configUSE_APPLICATION_TASK_TAG 0 #endif #ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS - #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 + #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 #endif #ifndef configUSE_RECURSIVE_MUTEXES - #define configUSE_RECURSIVE_MUTEXES 0 + #define configUSE_RECURSIVE_MUTEXES 0 #endif #ifndef configUSE_MUTEXES - #define configUSE_MUTEXES 0 + #define configUSE_MUTEXES 0 #endif #ifndef configUSE_TIMERS - #define configUSE_TIMERS 0 + #define configUSE_TIMERS 0 #endif #ifndef configUSE_COUNTING_SEMAPHORES - #define configUSE_COUNTING_SEMAPHORES 0 + #define configUSE_COUNTING_SEMAPHORES 0 #endif #ifndef configUSE_ALTERNATIVE_API - #define configUSE_ALTERNATIVE_API 0 + #define configUSE_ALTERNATIVE_API 0 #endif #ifndef portCRITICAL_NESTING_IN_TCB - #define portCRITICAL_NESTING_IN_TCB 0 + #define portCRITICAL_NESTING_IN_TCB 0 #endif #ifndef configMAX_TASK_NAME_LEN - #define configMAX_TASK_NAME_LEN 16 + #define configMAX_TASK_NAME_LEN 16 #endif #ifndef configIDLE_SHOULD_YIELD - #define configIDLE_SHOULD_YIELD 1 + #define configIDLE_SHOULD_YIELD 1 #endif #if configMAX_TASK_NAME_LEN < 1 - #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h + #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h #endif #ifndef configASSERT - #define configASSERT( x ) - #define configASSERT_DEFINED 0 + #define configASSERT( x ) + #define configASSERT_DEFINED 0 #else - #define configASSERT_DEFINED 1 + #define configASSERT_DEFINED 1 #endif #ifndef portMEMORY_BARRIER - #define portMEMORY_BARRIER() + #define portMEMORY_BARRIER() #endif /* The timers module relies on xTaskGetSchedulerState(). */ #if configUSE_TIMERS == 1 - #ifndef configTIMER_TASK_PRIORITY - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. - #endif /* configTIMER_TASK_PRIORITY */ + #ifndef configTIMER_TASK_PRIORITY + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. + #endif /* configTIMER_TASK_PRIORITY */ - #ifndef configTIMER_QUEUE_LENGTH - #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. - #endif /* configTIMER_QUEUE_LENGTH */ + #ifndef configTIMER_QUEUE_LENGTH + #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. + #endif /* configTIMER_QUEUE_LENGTH */ - #ifndef configTIMER_TASK_STACK_DEPTH - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. - #endif /* configTIMER_TASK_STACK_DEPTH */ + #ifndef configTIMER_TASK_STACK_DEPTH + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. + #endif /* configTIMER_TASK_STACK_DEPTH */ #endif /* configUSE_TIMERS */ #ifndef portSET_INTERRUPT_MASK_FROM_ISR - #define portSET_INTERRUPT_MASK_FROM_ISR() 0 + #define portSET_INTERRUPT_MASK_FROM_ISR() 0 #endif #ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR - #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue + #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue #endif #ifndef portCLEAN_UP_TCB - #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB + #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef portPRE_TASK_DELETE_HOOK - #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) + #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) #endif #ifndef portSETUP_TCB - #define portSETUP_TCB( pxTCB ) ( void ) pxTCB + #define portSETUP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef configQUEUE_REGISTRY_SIZE - #define configQUEUE_REGISTRY_SIZE 0U + #define configQUEUE_REGISTRY_SIZE 0U #endif #if ( configQUEUE_REGISTRY_SIZE < 1 ) - #define vQueueAddToRegistry( xQueue, pcName ) - #define vQueueUnregisterQueue( xQueue ) - #define pcQueueGetName( xQueue ) + #define vQueueAddToRegistry( xQueue, pcName ) + #define vQueueUnregisterQueue( xQueue ) + #define pcQueueGetName( xQueue ) #endif #ifndef portPOINTER_SIZE_TYPE - #define portPOINTER_SIZE_TYPE uint32_t + #define portPOINTER_SIZE_TYPE uint32_t #endif /* Remove any unused trace macros. */ #ifndef traceSTART - /* Used to perform any necessary initialisation - for example, open a file - into which trace is to be written. */ - #define traceSTART() + /* Used to perform any necessary initialisation - for example, open a file + into which trace is to be written. */ + #define traceSTART() #endif #ifndef traceEND - /* Use to close a trace, for example close a file into which trace has been - written. */ - #define traceEND() + /* Use to close a trace, for example close a file into which trace has been + written. */ + #define traceEND() #endif #ifndef traceTASK_SWITCHED_IN - /* Called after a task has been selected to run. pxCurrentTCB holds a pointer - to the task control block of the selected task. */ - #define traceTASK_SWITCHED_IN() + /* Called after a task has been selected to run. pxCurrentTCB holds a pointer + to the task control block of the selected task. */ + #define traceTASK_SWITCHED_IN() #endif #ifndef traceINCREASE_TICK_COUNT - /* Called before stepping the tick count after waking from tickless idle - sleep. */ - #define traceINCREASE_TICK_COUNT( x ) + /* Called before stepping the tick count after waking from tickless idle + sleep. */ + #define traceINCREASE_TICK_COUNT( x ) #endif #ifndef traceLOW_POWER_IDLE_BEGIN - /* Called immediately before entering tickless idle. */ - #define traceLOW_POWER_IDLE_BEGIN() + /* Called immediately before entering tickless idle. */ + #define traceLOW_POWER_IDLE_BEGIN() #endif -#ifndef traceLOW_POWER_IDLE_END - /* Called when returning to the Idle task after a tickless idle. */ - #define traceLOW_POWER_IDLE_END() +#ifndef traceLOW_POWER_IDLE_END + /* Called when returning to the Idle task after a tickless idle. */ + #define traceLOW_POWER_IDLE_END() #endif #ifndef traceTASK_SWITCHED_OUT - /* Called before a task has been selected to run. pxCurrentTCB holds a pointer - to the task control block of the task being switched out. */ - #define traceTASK_SWITCHED_OUT() + /* Called before a task has been selected to run. pxCurrentTCB holds a pointer + to the task control block of the task being switched out. */ + #define traceTASK_SWITCHED_OUT() #endif #ifndef traceTASK_PRIORITY_INHERIT - /* Called when a task attempts to take a mutex that is already held by a - lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task - that holds the mutex. uxInheritedPriority is the priority the mutex holder - will inherit (the priority of the task that is attempting to obtain the - muted. */ - #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) + /* Called when a task attempts to take a mutex that is already held by a + lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task + that holds the mutex. uxInheritedPriority is the priority the mutex holder + will inherit (the priority of the task that is attempting to obtain the + muted. */ + #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) #endif #ifndef traceTASK_PRIORITY_DISINHERIT - /* Called when a task releases a mutex, the holding of which had resulted in - the task inheriting the priority of a higher priority task. - pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the - mutex. uxOriginalPriority is the task's configured (base) priority. */ - #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) + /* Called when a task releases a mutex, the holding of which had resulted in + the task inheriting the priority of a higher priority task. + pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the + mutex. uxOriginalPriority is the task's configured (base) priority. */ + #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) #endif #ifndef traceBLOCKING_ON_QUEUE_RECEIVE - /* Task is about to block because it cannot read from a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the read was attempted. pxCurrentTCB points to the TCB of the - task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) + /* Task is about to block because it cannot read from a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the read was attempted. pxCurrentTCB points to the TCB of the + task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) #endif #ifndef traceBLOCKING_ON_QUEUE_PEEK - /* Task is about to block because it cannot read from a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the read was attempted. pxCurrentTCB points to the TCB of the - task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) + /* Task is about to block because it cannot read from a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the read was attempted. pxCurrentTCB points to the TCB of the + task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) #endif #ifndef traceBLOCKING_ON_QUEUE_SEND - /* Task is about to block because it cannot write to a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the write was attempted. pxCurrentTCB points to the TCB of the - task that attempted the write. */ - #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) + /* Task is about to block because it cannot write to a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the write was attempted. pxCurrentTCB points to the TCB of the + task that attempted the write. */ + #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) #endif #ifndef configCHECK_FOR_STACK_OVERFLOW - #define configCHECK_FOR_STACK_OVERFLOW 0 + #define configCHECK_FOR_STACK_OVERFLOW 0 #endif #ifndef configRECORD_STACK_HIGH_ADDRESS - #define configRECORD_STACK_HIGH_ADDRESS 0 + #define configRECORD_STACK_HIGH_ADDRESS 0 #endif #ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H - #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 + #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 #endif /* The following event macros are embedded in the kernel API calls. */ #ifndef traceMOVED_TASK_TO_READY_STATE - #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) + #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) #endif #ifndef tracePOST_MOVED_TASK_TO_READY_STATE - #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) + #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) #endif #ifndef traceQUEUE_CREATE - #define traceQUEUE_CREATE( pxNewQueue ) + #define traceQUEUE_CREATE( pxNewQueue ) #endif #ifndef traceQUEUE_CREATE_FAILED - #define traceQUEUE_CREATE_FAILED( ucQueueType ) + #define traceQUEUE_CREATE_FAILED( ucQueueType ) #endif #ifndef traceCREATE_MUTEX - #define traceCREATE_MUTEX( pxNewQueue ) + #define traceCREATE_MUTEX( pxNewQueue ) #endif #ifndef traceCREATE_MUTEX_FAILED - #define traceCREATE_MUTEX_FAILED() + #define traceCREATE_MUTEX_FAILED() #endif #ifndef traceGIVE_MUTEX_RECURSIVE - #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) + #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceGIVE_MUTEX_RECURSIVE_FAILED - #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) + #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE - #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) + #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE_FAILED - #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) + #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceCREATE_COUNTING_SEMAPHORE - #define traceCREATE_COUNTING_SEMAPHORE() + #define traceCREATE_COUNTING_SEMAPHORE() #endif #ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED - #define traceCREATE_COUNTING_SEMAPHORE_FAILED() + #define traceCREATE_COUNTING_SEMAPHORE_FAILED() #endif #ifndef traceQUEUE_SEND - #define traceQUEUE_SEND( pxQueue ) + #define traceQUEUE_SEND( pxQueue ) #endif #ifndef traceQUEUE_SEND_FAILED - #define traceQUEUE_SEND_FAILED( pxQueue ) + #define traceQUEUE_SEND_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE - #define traceQUEUE_RECEIVE( pxQueue ) + #define traceQUEUE_RECEIVE( pxQueue ) #endif #ifndef traceQUEUE_PEEK - #define traceQUEUE_PEEK( pxQueue ) + #define traceQUEUE_PEEK( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FAILED - #define traceQUEUE_PEEK_FAILED( pxQueue ) + #define traceQUEUE_PEEK_FAILED( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR - #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) + #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FAILED - #define traceQUEUE_RECEIVE_FAILED( pxQueue ) + #define traceQUEUE_RECEIVE_FAILED( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR - #define traceQUEUE_SEND_FROM_ISR( pxQueue ) + #define traceQUEUE_SEND_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR_FAILED - #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) + #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR - #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) + #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED - #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) + #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR_FAILED - #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) + #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_DELETE - #define traceQUEUE_DELETE( pxQueue ) + #define traceQUEUE_DELETE( pxQueue ) #endif #ifndef traceTASK_CREATE - #define traceTASK_CREATE( pxNewTCB ) + #define traceTASK_CREATE( pxNewTCB ) #endif #ifndef traceTASK_CREATE_FAILED - #define traceTASK_CREATE_FAILED() + #define traceTASK_CREATE_FAILED() #endif #ifndef traceTASK_DELETE - #define traceTASK_DELETE( pxTaskToDelete ) + #define traceTASK_DELETE( pxTaskToDelete ) #endif #ifndef traceTASK_DELAY_UNTIL - #define traceTASK_DELAY_UNTIL( x ) + #define traceTASK_DELAY_UNTIL( x ) #endif #ifndef traceTASK_DELAY - #define traceTASK_DELAY() + #define traceTASK_DELAY() #endif #ifndef traceTASK_PRIORITY_SET - #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) + #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) #endif #ifndef traceTASK_SUSPEND - #define traceTASK_SUSPEND( pxTaskToSuspend ) + #define traceTASK_SUSPEND( pxTaskToSuspend ) #endif #ifndef traceTASK_RESUME - #define traceTASK_RESUME( pxTaskToResume ) + #define traceTASK_RESUME( pxTaskToResume ) #endif #ifndef traceTASK_RESUME_FROM_ISR - #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) + #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) #endif #ifndef traceTASK_INCREMENT_TICK - #define traceTASK_INCREMENT_TICK( xTickCount ) + #define traceTASK_INCREMENT_TICK( xTickCount ) #endif #ifndef traceTIMER_CREATE - #define traceTIMER_CREATE( pxNewTimer ) + #define traceTIMER_CREATE( pxNewTimer ) #endif #ifndef traceTIMER_CREATE_FAILED - #define traceTIMER_CREATE_FAILED() + #define traceTIMER_CREATE_FAILED() #endif #ifndef traceTIMER_COMMAND_SEND - #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) + #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) #endif #ifndef traceTIMER_EXPIRED - #define traceTIMER_EXPIRED( pxTimer ) + #define traceTIMER_EXPIRED( pxTimer ) #endif #ifndef traceTIMER_COMMAND_RECEIVED - #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) + #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) #endif #ifndef traceMALLOC @@ -561,397 +561,397 @@ extern "C" { #endif #ifndef traceEVENT_GROUP_CREATE - #define traceEVENT_GROUP_CREATE( xEventGroup ) + #define traceEVENT_GROUP_CREATE( xEventGroup ) #endif #ifndef traceEVENT_GROUP_CREATE_FAILED - #define traceEVENT_GROUP_CREATE_FAILED() + #define traceEVENT_GROUP_CREATE_FAILED() #endif #ifndef traceEVENT_GROUP_SYNC_BLOCK - #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) + #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_SYNC_END - #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred + #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK - #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) + #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_WAIT_BITS_END - #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred + #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_CLEAR_BITS - #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) + #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR - #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) + #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_SET_BITS - #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) + #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR - #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) + #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_DELETE - #define traceEVENT_GROUP_DELETE( xEventGroup ) + #define traceEVENT_GROUP_DELETE( xEventGroup ) #endif #ifndef tracePEND_FUNC_CALL - #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) + #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef tracePEND_FUNC_CALL_FROM_ISR - #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) + #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef traceQUEUE_REGISTRY_ADD - #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) + #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) #endif #ifndef traceTASK_NOTIFY_TAKE_BLOCK - #define traceTASK_NOTIFY_TAKE_BLOCK() + #define traceTASK_NOTIFY_TAKE_BLOCK() #endif #ifndef traceTASK_NOTIFY_TAKE - #define traceTASK_NOTIFY_TAKE() + #define traceTASK_NOTIFY_TAKE() #endif #ifndef traceTASK_NOTIFY_WAIT_BLOCK - #define traceTASK_NOTIFY_WAIT_BLOCK() + #define traceTASK_NOTIFY_WAIT_BLOCK() #endif #ifndef traceTASK_NOTIFY_WAIT - #define traceTASK_NOTIFY_WAIT() + #define traceTASK_NOTIFY_WAIT() #endif #ifndef traceTASK_NOTIFY - #define traceTASK_NOTIFY() + #define traceTASK_NOTIFY() #endif #ifndef traceTASK_NOTIFY_FROM_ISR - #define traceTASK_NOTIFY_FROM_ISR() + #define traceTASK_NOTIFY_FROM_ISR() #endif #ifndef traceTASK_NOTIFY_GIVE_FROM_ISR - #define traceTASK_NOTIFY_GIVE_FROM_ISR() + #define traceTASK_NOTIFY_GIVE_FROM_ISR() #endif #ifndef traceSTREAM_BUFFER_CREATE_FAILED - #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) + #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED - #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) + #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_CREATE - #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) + #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_DELETE - #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) + #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RESET - #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) + #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) #endif #ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND - #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) + #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_SEND - #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) + #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) #endif #ifndef traceSTREAM_BUFFER_SEND_FAILED - #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) + #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_SEND_FROM_ISR - #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) + #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) #endif #ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE - #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) + #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE - #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) + #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE_FAILED - #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) + #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR - #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) + #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) #endif #ifndef configGENERATE_RUN_TIME_STATS - #define configGENERATE_RUN_TIME_STATS 0 + #define configGENERATE_RUN_TIME_STATS 0 #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) - #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. - #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ + #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. + #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ - #ifndef portGET_RUN_TIME_COUNTER_VALUE - #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE - #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. - #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ - #endif /* portGET_RUN_TIME_COUNTER_VALUE */ + #ifndef portGET_RUN_TIME_COUNTER_VALUE + #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE + #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. + #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ + #endif /* portGET_RUN_TIME_COUNTER_VALUE */ #endif /* configGENERATE_RUN_TIME_STATS */ #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() + #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() #endif #ifndef configUSE_MALLOC_FAILED_HOOK - #define configUSE_MALLOC_FAILED_HOOK 0 + #define configUSE_MALLOC_FAILED_HOOK 0 #endif #ifndef portPRIVILEGE_BIT - #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) + #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) #endif #ifndef portYIELD_WITHIN_API - #define portYIELD_WITHIN_API portYIELD + #define portYIELD_WITHIN_API portYIELD #endif #ifndef portSUPPRESS_TICKS_AND_SLEEP - #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) + #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) #endif #ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP - #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 + #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 #endif #if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 - #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 + #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 #endif #ifndef configUSE_TICKLESS_IDLE - #define configUSE_TICKLESS_IDLE 0 + #define configUSE_TICKLESS_IDLE 0 #endif #ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING - #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) + #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) #endif #ifndef configPRE_SLEEP_PROCESSING - #define configPRE_SLEEP_PROCESSING( x ) + #define configPRE_SLEEP_PROCESSING( x ) #endif #ifndef configPOST_SLEEP_PROCESSING - #define configPOST_SLEEP_PROCESSING( x ) + #define configPOST_SLEEP_PROCESSING( x ) #endif #ifndef configUSE_QUEUE_SETS - #define configUSE_QUEUE_SETS 0 + #define configUSE_QUEUE_SETS 0 #endif #ifndef portTASK_USES_FLOATING_POINT - #define portTASK_USES_FLOATING_POINT() + #define portTASK_USES_FLOATING_POINT() #endif #ifndef portALLOCATE_SECURE_CONTEXT - #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) + #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) #endif #ifndef portDONT_DISCARD - #define portDONT_DISCARD + #define portDONT_DISCARD #endif #ifndef configUSE_TIME_SLICING - #define configUSE_TIME_SLICING 1 + #define configUSE_TIME_SLICING 1 #endif #ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS - #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 + #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 #endif #ifndef configUSE_STATS_FORMATTING_FUNCTIONS - #define configUSE_STATS_FORMATTING_FUNCTIONS 0 + #define configUSE_STATS_FORMATTING_FUNCTIONS 0 #endif #ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID - #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() + #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() #endif #ifndef configUSE_TRACE_FACILITY - #define configUSE_TRACE_FACILITY 0 + #define configUSE_TRACE_FACILITY 0 #endif #ifndef mtCOVERAGE_TEST_MARKER - #define mtCOVERAGE_TEST_MARKER() + #define mtCOVERAGE_TEST_MARKER() #endif #ifndef mtCOVERAGE_TEST_DELAY - #define mtCOVERAGE_TEST_DELAY() + #define mtCOVERAGE_TEST_DELAY() #endif #ifndef portASSERT_IF_IN_ISR - #define portASSERT_IF_IN_ISR() + #define portASSERT_IF_IN_ISR() #endif #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 #endif #ifndef configAPPLICATION_ALLOCATED_HEAP - #define configAPPLICATION_ALLOCATED_HEAP 0 + #define configAPPLICATION_ALLOCATED_HEAP 0 #endif #ifndef configUSE_TASK_NOTIFICATIONS - #define configUSE_TASK_NOTIFICATIONS 1 + #define configUSE_TASK_NOTIFICATIONS 1 #endif #ifndef configUSE_POSIX_ERRNO - #define configUSE_POSIX_ERRNO 0 + #define configUSE_POSIX_ERRNO 0 #endif #ifndef portTICK_TYPE_IS_ATOMIC - #define portTICK_TYPE_IS_ATOMIC 0 + #define portTICK_TYPE_IS_ATOMIC 0 #endif #ifndef configSUPPORT_STATIC_ALLOCATION - /* Defaults to 0 for backward compatibility. */ - #define configSUPPORT_STATIC_ALLOCATION 0 + /* Defaults to 0 for backward compatibility. */ + #define configSUPPORT_STATIC_ALLOCATION 0 #endif #ifndef configSUPPORT_DYNAMIC_ALLOCATION - /* Defaults to 1 for backward compatibility. */ - #define configSUPPORT_DYNAMIC_ALLOCATION 1 + /* Defaults to 1 for backward compatibility. */ + #define configSUPPORT_DYNAMIC_ALLOCATION 1 #endif #ifndef configSTACK_DEPTH_TYPE - /* Defaults to uint16_t for backward compatibility, but can be overridden - in FreeRTOSConfig.h if uint16_t is too restrictive. */ - #define configSTACK_DEPTH_TYPE uint16_t + /* Defaults to uint16_t for backward compatibility, but can be overridden + in FreeRTOSConfig.h if uint16_t is too restrictive. */ + #define configSTACK_DEPTH_TYPE uint16_t #endif #ifndef configMESSAGE_BUFFER_LENGTH_TYPE - /* Defaults to size_t for backward compatibility, but can be overridden - in FreeRTOSConfig.h if lengths will always be less than the number of bytes - in a size_t. */ - #define configMESSAGE_BUFFER_LENGTH_TYPE size_t + /* Defaults to size_t for backward compatibility, but can be overridden + in FreeRTOSConfig.h if lengths will always be less than the number of bytes + in a size_t. */ + #define configMESSAGE_BUFFER_LENGTH_TYPE size_t #endif /* Sanity check the configuration. */ #if( configUSE_TICKLESS_IDLE != 0 ) - #if( INCLUDE_vTaskSuspend != 1 ) - #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 - #endif /* INCLUDE_vTaskSuspend */ + #if( INCLUDE_vTaskSuspend != 1 ) + #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 + #endif /* INCLUDE_vTaskSuspend */ #endif /* configUSE_TICKLESS_IDLE */ #if( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) - #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. + #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. #endif #if( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) - #error configUSE_MUTEXES must be set to 1 to use recursive mutexes + #error configUSE_MUTEXES must be set to 1 to use recursive mutexes #endif #ifndef configINITIAL_TICK_COUNT - #define configINITIAL_TICK_COUNT 0 + #define configINITIAL_TICK_COUNT 0 #endif #if( portTICK_TYPE_IS_ATOMIC == 0 ) - /* Either variables of tick type cannot be read atomically, or - portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when - the tick count is returned to the standard critical section macros. */ - #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) + /* Either variables of tick type cannot be read atomically, or + portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when + the tick count is returned to the standard critical section macros. */ + #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) #else - /* The tick type can be read atomically, so critical sections used when the - tick count is returned can be defined away. */ - #define portTICK_TYPE_ENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x + /* The tick type can be read atomically, so critical sections used when the + tick count is returned can be defined away. */ + #define portTICK_TYPE_ENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x #endif /* Definitions to allow backward compatibility with FreeRTOS versions prior to V8 if desired. */ #ifndef configENABLE_BACKWARD_COMPATIBILITY - #define configENABLE_BACKWARD_COMPATIBILITY 1 + #define configENABLE_BACKWARD_COMPATIBILITY 1 #endif #ifndef configPRINTF - /* configPRINTF() was not defined, so define it away to nothing. To use - configPRINTF() then define it as follows (where MyPrintFunction() is - provided by the application writer): + /* configPRINTF() was not defined, so define it away to nothing. To use + configPRINTF() then define it as follows (where MyPrintFunction() is + provided by the application writer): - void MyPrintFunction(const char *pcFormat, ... ); - #define configPRINTF( X ) MyPrintFunction X + void MyPrintFunction(const char *pcFormat, ... ); + #define configPRINTF( X ) MyPrintFunction X - Then call like a standard printf() function, but placing brackets around - all parameters so they are passed as a single parameter. For example: - configPRINTF( ("Value = %d", MyVariable) ); */ - #define configPRINTF( X ) + Then call like a standard printf() function, but placing brackets around + all parameters so they are passed as a single parameter. For example: + configPRINTF( ("Value = %d", MyVariable) ); */ + #define configPRINTF( X ) #endif #ifndef configMAX - /* The application writer has not provided their own MAX macro, so define - the following generic implementation. */ - #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) + /* The application writer has not provided their own MAX macro, so define + the following generic implementation. */ + #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) #endif #ifndef configMIN - /* The application writer has not provided their own MAX macro, so define - the following generic implementation. */ - #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) + /* The application writer has not provided their own MAX macro, so define + the following generic implementation. */ + #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) #endif #if configENABLE_BACKWARD_COMPATIBILITY == 1 - #define eTaskStateGet eTaskGetState - #define portTickType TickType_t - #define xTaskHandle TaskHandle_t - #define xQueueHandle QueueHandle_t - #define xSemaphoreHandle SemaphoreHandle_t - #define xQueueSetHandle QueueSetHandle_t - #define xQueueSetMemberHandle QueueSetMemberHandle_t - #define xTimeOutType TimeOut_t - #define xMemoryRegion MemoryRegion_t - #define xTaskParameters TaskParameters_t - #define xTaskStatusType TaskStatus_t - #define xTimerHandle TimerHandle_t - #define xCoRoutineHandle CoRoutineHandle_t - #define pdTASK_HOOK_CODE TaskHookFunction_t - #define portTICK_RATE_MS portTICK_PERIOD_MS - #define pcTaskGetTaskName pcTaskGetName - #define pcTimerGetTimerName pcTimerGetName - #define pcQueueGetQueueName pcQueueGetName - #define vTaskGetTaskInfo vTaskGetInfo + #define eTaskStateGet eTaskGetState + #define portTickType TickType_t + #define xTaskHandle TaskHandle_t + #define xQueueHandle QueueHandle_t + #define xSemaphoreHandle SemaphoreHandle_t + #define xQueueSetHandle QueueSetHandle_t + #define xQueueSetMemberHandle QueueSetMemberHandle_t + #define xTimeOutType TimeOut_t + #define xMemoryRegion MemoryRegion_t + #define xTaskParameters TaskParameters_t + #define xTaskStatusType TaskStatus_t + #define xTimerHandle TimerHandle_t + #define xCoRoutineHandle CoRoutineHandle_t + #define pdTASK_HOOK_CODE TaskHookFunction_t + #define portTICK_RATE_MS portTICK_PERIOD_MS + #define pcTaskGetTaskName pcTaskGetName + #define pcTimerGetTimerName pcTimerGetName + #define pcQueueGetQueueName pcQueueGetName + #define vTaskGetTaskInfo vTaskGetInfo - /* Backward compatibility within the scheduler code only - these definitions - are not really required but are included for completeness. */ - #define tmrTIMER_CALLBACK TimerCallbackFunction_t - #define pdTASK_CODE TaskFunction_t - #define xListItem ListItem_t - #define xList List_t + /* Backward compatibility within the scheduler code only - these definitions + are not really required but are included for completeness. */ + #define tmrTIMER_CALLBACK TimerCallbackFunction_t + #define pdTASK_CODE TaskFunction_t + #define xListItem ListItem_t + #define xList List_t - /* For libraries that break the list data hiding, and access list structure - members directly (which is not supposed to be done). */ - #define pxContainer pvContainer + /* For libraries that break the list data hiding, and access list structure + members directly (which is not supposed to be done). */ + #define pxContainer pvContainer #endif /* configENABLE_BACKWARD_COMPATIBILITY */ #if( configUSE_ALTERNATIVE_API != 0 ) - #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 + #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 #endif /* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even @@ -959,31 +959,31 @@ if floating point hardware is otherwise supported by the FreeRTOS port in use. This constant is not supported by all FreeRTOS ports that include floating point support. */ #ifndef configUSE_TASK_FPU_SUPPORT - #define configUSE_TASK_FPU_SUPPORT 1 + #define configUSE_TASK_FPU_SUPPORT 1 #endif /* Set configENABLE_MPU to 1 to enable MPU support and 0 to disable it. This is currently used in ARMv8M ports. */ #ifndef configENABLE_MPU - #define configENABLE_MPU 0 + #define configENABLE_MPU 0 #endif /* Set configENABLE_FPU to 1 to enable FPU support and 0 to disable it. This is currently used in ARMv8M ports. */ #ifndef configENABLE_FPU - #define configENABLE_FPU 1 + #define configENABLE_FPU 1 #endif /* Set configENABLE_TRUSTZONE to 1 enable TrustZone support and 0 to disable it. This is currently used in ARMv8M ports. */ #ifndef configENABLE_TRUSTZONE - #define configENABLE_TRUSTZONE 1 + #define configENABLE_TRUSTZONE 1 #endif /* Set configRUN_FREERTOS_SECURE_ONLY to 1 to run the FreeRTOS ARMv8M port on the Secure Side only. */ #ifndef configRUN_FREERTOS_SECURE_ONLY - #define configRUN_FREERTOS_SECURE_ONLY 0 + #define configRUN_FREERTOS_SECURE_ONLY 0 #endif /* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using @@ -1028,8 +1028,8 @@ the Secure Side only. */ * | | | | xTaskCreateRestrictedStatic | | | | * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ */ -#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ - ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) +#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ + ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) /* * In line with software engineering best practice, FreeRTOS implements a strict @@ -1043,40 +1043,40 @@ the Secure Side only. */ */ struct xSTATIC_LIST_ITEM { - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - TickType_t xDummy2; - void *pvDummy3[ 4 ]; - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy4; - #endif + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void *pvDummy3[ 4 ]; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy4; + #endif }; typedef struct xSTATIC_LIST_ITEM StaticListItem_t; /* See the comments above the struct xSTATIC_LIST_ITEM definition. */ struct xSTATIC_MINI_LIST_ITEM { - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - TickType_t xDummy2; - void *pvDummy3[ 2 ]; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void *pvDummy3[ 2 ]; }; typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; /* See the comments above the struct xSTATIC_LIST_ITEM definition. */ typedef struct xSTATIC_LIST { - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - UBaseType_t uxDummy2; - void *pvDummy3; - StaticMiniListItem_t xDummy4; - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy5; - #endif + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + UBaseType_t uxDummy2; + void *pvDummy3; + StaticMiniListItem_t xDummy4; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy5; + #endif } StaticList_t; /* @@ -1094,52 +1094,52 @@ typedef struct xSTATIC_LIST */ typedef struct xSTATIC_TCB { - void *pxDummy1; - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xDummy2; - #endif - StaticListItem_t xDummy3[ 2 ]; - UBaseType_t uxDummy5; - void *pxDummy6; - uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - void *pxDummy8; - #endif - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxDummy9; - #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy10[ 2 ]; - #endif - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxDummy12[ 2 ]; - #endif - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - void *pxDummy14; - #endif - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void *pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulDummy16; - #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - struct _reent xDummy17; - #endif - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - uint32_t ulDummy18; - uint8_t ucDummy19; - #endif - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - uint8_t uxDummy20; - #endif + void *pxDummy1; + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xDummy2; + #endif + StaticListItem_t xDummy3[ 2 ]; + UBaseType_t uxDummy5; + void *pxDummy6; + uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + void *pxDummy8; + #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxDummy9; + #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy10[ 2 ]; + #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxDummy12[ 2 ]; + #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + void *pxDummy14; + #endif + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void *pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + uint32_t ulDummy16; + #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + struct _reent xDummy17; + #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + uint32_t ulDummy18; + uint8_t ucDummy19; + #endif + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + uint8_t uxDummy20; + #endif - #if( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDummy21; - #endif - #if ( configUSE_POSIX_ERRNO == 1 ) - int iDummy22; - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDummy21; + #endif + #if ( configUSE_POSIX_ERRNO == 1 ) + int iDummy22; + #endif } StaticTask_t; /* @@ -1158,30 +1158,30 @@ typedef struct xSTATIC_TCB */ typedef struct xSTATIC_QUEUE { - void *pvDummy1[ 3 ]; + void *pvDummy1[ 3 ]; - union - { - void *pvDummy2; - UBaseType_t uxDummy2; - } u; + union + { + void *pvDummy2; + UBaseType_t uxDummy2; + } u; - StaticList_t xDummy3[ 2 ]; - UBaseType_t uxDummy4[ 3 ]; - uint8_t ucDummy5[ 2 ]; + StaticList_t xDummy3[ 2 ]; + UBaseType_t uxDummy4[ 3 ]; + uint8_t ucDummy5[ 2 ]; - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy6; - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy6; + #endif - #if ( configUSE_QUEUE_SETS == 1 ) - void *pvDummy7; - #endif + #if ( configUSE_QUEUE_SETS == 1 ) + void *pvDummy7; + #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy8; - uint8_t ucDummy9; - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy8; + uint8_t ucDummy9; + #endif } StaticQueue_t; typedef StaticQueue_t StaticSemaphore_t; @@ -1202,16 +1202,16 @@ typedef StaticQueue_t StaticSemaphore_t; */ typedef struct xSTATIC_EVENT_GROUP { - TickType_t xDummy1; - StaticList_t xDummy2; + TickType_t xDummy1; + StaticList_t xDummy2; - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy3; - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy3; + #endif - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy4; - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy4; + #endif } StaticEventGroup_t; @@ -1231,15 +1231,15 @@ typedef struct xSTATIC_EVENT_GROUP */ typedef struct xSTATIC_TIMER { - void *pvDummy1; - StaticListItem_t xDummy2; - TickType_t xDummy3; - void *pvDummy5; - TaskFunction_t pvDummy6; - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy7; - #endif - uint8_t ucDummy8; + void *pvDummy1; + StaticListItem_t xDummy2; + TickType_t xDummy3; + void *pvDummy5; + TaskFunction_t pvDummy6; + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy7; + #endif + uint8_t ucDummy8; } StaticTimer_t; @@ -1259,12 +1259,12 @@ typedef struct xSTATIC_TIMER */ typedef struct xSTATIC_STREAM_BUFFER { - size_t uxDummy1[ 4 ]; - void * pvDummy2[ 3 ]; - uint8_t ucDummy3; - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy4; - #endif + size_t uxDummy1[ 4 ]; + void * pvDummy2[ 3 ]; + uint8_t ucDummy3; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy4; + #endif } StaticStreamBuffer_t; /* Message buffers are built on stream buffers. */ diff --git a/components/bl602/freertos_riscv/config/FreeRTOSConfig.h b/components/bl602/freertos_riscv/config/FreeRTOSConfig.h index dee41349..7d36aead 100644 --- a/components/bl602/freertos_riscv/config/FreeRTOSConfig.h +++ b/components/bl602/freertos_riscv/config/FreeRTOSConfig.h @@ -87,57 +87,57 @@ #define configSUPPORT_STATIC_ALLOCATION 1 -#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR -#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) -#define configUSE_PREEMPTION 1 -#define configUSE_IDLE_HOOK 1 -#define configUSE_TICK_HOOK 0 -#define configCPU_CLOCK_HZ ( 2000000 ) /*QEMU*/ -#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) -#define configMAX_PRIORITIES ( 32 ) -#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 70 ) -#define configTOTAL_HEAP_SIZE ( ( size_t ) 14100 ) -#define configMAX_TASK_NAME_LEN ( 16 ) -#define configUSE_TRACE_FACILITY 1 +#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR +#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 0 +#define configCPU_CLOCK_HZ ( 2000000 ) /*QEMU*/ +#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) +#define configMAX_PRIORITIES ( 32 ) +#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 70 ) +#define configTOTAL_HEAP_SIZE ( ( size_t ) 14100 ) +#define configMAX_TASK_NAME_LEN ( 16 ) +#define configUSE_TRACE_FACILITY 1 #define configUSE_STATS_FORMATTING_FUNCTIONS 1 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_MUTEXES 1 -#define configQUEUE_REGISTRY_SIZE 8 -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_MALLOC_FAILED_HOOK 1 -#define configUSE_APPLICATION_TASK_TAG 0 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 0 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 /* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 +#define configUSE_CO_ROUTINES 0 #define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) /* Software timer definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) -#define configTIMER_QUEUE_LENGTH 4 -#define configTIMER_TASK_STACK_DEPTH ( 400 ) +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH ( 400 ) /* Task priorities. Allow these to be overridden. */ #ifndef uartPRIMARY_PRIORITY - #define uartPRIMARY_PRIORITY ( configMAX_PRIORITIES - 3 ) + #define uartPRIMARY_PRIORITY ( configMAX_PRIORITIES - 3 ) #endif /* Set the following definitions to 1 to include the API function, or zero to exclude the API function. */ -#define INCLUDE_vTaskPrioritySet 1 -#define INCLUDE_uxTaskPriorityGet 1 -#define INCLUDE_vTaskDelete 1 -#define INCLUDE_vTaskCleanUpResources 1 -#define INCLUDE_vTaskSuspend 1 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_eTaskGetState 1 -#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 #define INCLUDE_uxTaskGetStackHighWaterMark 1 /* Normal assert() semantics without relying on the provision of an assert.h diff --git a/components/bl602/freertos_riscv/config/StackMacros.h b/components/bl602/freertos_riscv/config/StackMacros.h index 3ed8b22d..d3e79464 100644 --- a/components/bl602/freertos_riscv/config/StackMacros.h +++ b/components/bl602/freertos_riscv/config/StackMacros.h @@ -29,7 +29,7 @@ #define STACK_MACROS_H #ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ - #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. + #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. #endif /* @@ -50,81 +50,81 @@ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + /* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + /* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ - const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ - \ - if( ( pulStack[ 0 ] != ulCheckValue ) || \ - ( pulStack[ 1 ] != ulCheckValue ) || \ - ( pulStack[ 2 ] != ulCheckValue ) || \ - ( pulStack[ 3 ] != ulCheckValue ) ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ + const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ + \ + if( ( pulStack[ 0 ] != ulCheckValue ) || \ + ( pulStack[ 1 ] != ulCheckValue ) || \ + ( pulStack[ 2 ] != ulCheckValue ) || \ + ( pulStack[ 3 ] != ulCheckValue ) ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ - static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ - \ - \ - pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ - \ - /* Has the extremity of the task stack ever been written over? */ \ - if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ + static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ + \ + \ + pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ + \ + /* Has the extremity of the task stack ever been written over? */ \ + if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ /* Remove stack overflow macro if not being used. */ #ifndef taskCHECK_FOR_STACK_OVERFLOW - #define taskCHECK_FOR_STACK_OVERFLOW() + #define taskCHECK_FOR_STACK_OVERFLOW() #endif diff --git a/components/bl602/freertos_riscv/config/croutine.h b/components/bl602/freertos_riscv/config/croutine.h index 8b3b41b9..8de53088 100644 --- a/components/bl602/freertos_riscv/config/croutine.h +++ b/components/bl602/freertos_riscv/config/croutine.h @@ -29,7 +29,7 @@ #define CO_ROUTINE_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include croutine.h" + #error "include FreeRTOS.h must appear in source files before include croutine.h" #endif #include "list.h" @@ -48,12 +48,12 @@ typedef void (*crCOROUTINE_CODE)( CoRoutineHandle_t, UBaseType_t ); typedef struct corCoRoutineControlBlock { - crCOROUTINE_CODE pxCoRoutineFunction; - ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ - ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ - UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ - UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ - uint16_t uxState; /*< Used internally by the co-routine implementation. */ + crCOROUTINE_CODE pxCoRoutineFunction; + ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ + ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ + UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ + UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ + uint16_t uxState; /*< Used internally by the co-routine implementation. */ } CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ /** @@ -153,7 +153,7 @@ BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPri // The rest of the idle task will execute between co-routine calls. void vApplicationIdleHook( void ) { - vCoRoutineSchedule(); + vCoRoutineSchedule(); } // Alternatively, if you do not require any other part of the idle task to @@ -287,12 +287,12 @@ void vCoRoutineSchedule( void ); * \defgroup crDELAY crDELAY * \ingroup Tasks */ -#define crDELAY( xHandle, xTicksToDelay ) \ - if( ( xTicksToDelay ) > 0 ) \ - { \ - vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ - } \ - crSET_STATE0( ( xHandle ) ); +#define crDELAY( xHandle, xTicksToDelay ) \ + if( ( xTicksToDelay ) > 0 ) \ + { \ + vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ + } \ + crSET_STATE0( ( xHandle ) ); /** *
@@ -377,19 +377,19 @@ void vCoRoutineSchedule( void );
  * \defgroup crQUEUE_SEND crQUEUE_SEND
  * \ingroup Tasks
  */
-#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult )			\
-{																						\
-	*( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) );	\
-	if( *( pxResult ) == errQUEUE_BLOCKED )												\
-	{																					\
-		crSET_STATE0( ( xHandle ) );													\
-		*pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 );					\
-	}																					\
-	if( *pxResult == errQUEUE_YIELD )													\
-	{																					\
-		crSET_STATE1( ( xHandle ) );													\
-		*pxResult = pdPASS;																\
-	}																					\
+#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult )         \
+{                                                                                       \
+    *( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) );   \
+    if( *( pxResult ) == errQUEUE_BLOCKED )                                             \
+    {                                                                                   \
+        crSET_STATE0( ( xHandle ) );                                                    \
+        *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 );                  \
+    }                                                                                   \
+    if( *pxResult == errQUEUE_YIELD )                                                   \
+    {                                                                                   \
+        crSET_STATE1( ( xHandle ) );                                                    \
+        *pxResult = pdPASS;                                                             \
+    }                                                                                   \
 }
 
 /**
@@ -469,19 +469,19 @@ void vCoRoutineSchedule( void );
  * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE
  * \ingroup Tasks
  */
-#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult )			\
-{																						\
-	*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) );		\
-	if( *( pxResult ) == errQUEUE_BLOCKED ) 											\
-	{																					\
-		crSET_STATE0( ( xHandle ) );													\
-		*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 );				\
-	}																					\
-	if( *( pxResult ) == errQUEUE_YIELD )												\
-	{																					\
-		crSET_STATE1( ( xHandle ) );													\
-		*( pxResult ) = pdPASS;															\
-	}																					\
+#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult )           \
+{                                                                                       \
+    *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) );     \
+    if( *( pxResult ) == errQUEUE_BLOCKED )                                             \
+    {                                                                                   \
+        crSET_STATE0( ( xHandle ) );                                                    \
+        *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 );                \
+    }                                                                                   \
+    if( *( pxResult ) == errQUEUE_YIELD )                                               \
+    {                                                                                   \
+        crSET_STATE1( ( xHandle ) );                                                    \
+        *( pxResult ) = pdPASS;                                                         \
+    }                                                                                   \
 }
 
 /**
@@ -645,25 +645,25 @@ void vCoRoutineSchedule( void );
          {
              // The character was successfully posted to the queue.
          }
-		 else
-		 {
-			// Could not post the character to the queue.
-		 }
+         else
+         {
+            // Could not post the character to the queue.
+         }
 
          // Enable the UART Tx interrupt to cause an interrupt in this
-		 // hypothetical UART.  The interrupt will obtain the character
-		 // from the queue and send it.
-		 ENABLE_RX_INTERRUPT();
+         // hypothetical UART.  The interrupt will obtain the character
+         // from the queue and send it.
+         ENABLE_RX_INTERRUPT();
 
-		 // Increment to the next character then block for a fixed period.
-		 // cCharToTx will maintain its value across the delay as it is
-		 // declared static.
-		 cCharToTx++;
-		 if( cCharToTx > 'x' )
-		 {
-			cCharToTx = 'a';
-		 }
-		 crDELAY( 100 );
+         // Increment to the next character then block for a fixed period.
+         // cCharToTx will maintain its value across the delay as it is
+         // declared static.
+         cCharToTx++;
+         if( cCharToTx > 'x' )
+         {
+            cCharToTx = 'a';
+         }
+         crDELAY( 100 );
      }
 
      // All co-routines must end with a call to crEND().
@@ -679,13 +679,13 @@ void vCoRoutineSchedule( void );
      while( UART_TX_REG_EMPTY() )
      {
          // Are there any characters in the queue waiting to be sent?
-		 // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
-		 // is woken by the post - ensuring that only a single co-routine is
-		 // woken no matter how many times we go around this loop.
+         // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
+         // is woken by the post - ensuring that only a single co-routine is
+         // woken no matter how many times we go around this loop.
          if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
-		 {
-			 SEND_CHARACTER( cCharToTx );
-		 }
+         {
+             SEND_CHARACTER( cCharToTx );
+         }
      }
  }
* \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR diff --git a/components/bl602/freertos_riscv/config/deprecated_definitions.h b/components/bl602/freertos_riscv/config/deprecated_definitions.h index 9cece988..20e6efee 100644 --- a/components/bl602/freertos_riscv/config/deprecated_definitions.h +++ b/components/bl602/freertos_riscv/config/deprecated_definitions.h @@ -39,149 +39,149 @@ definitions below remain in the code for backward compatibility only. New projects should not use them. */ #ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT - #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" - typedef void ( __interrupt __far *pxISR )(); + #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" + typedef void ( __interrupt __far *pxISR )(); #endif #ifdef OPEN_WATCOM_FLASH_LITE_186_PORT - #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" - typedef void ( __interrupt __far *pxISR )(); + #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" + typedef void ( __interrupt __far *pxISR )(); #endif #ifdef GCC_MEGA_AVR - #include "../portable/GCC/ATMega323/portmacro.h" + #include "../portable/GCC/ATMega323/portmacro.h" #endif #ifdef IAR_MEGA_AVR - #include "../portable/IAR/ATMega323/portmacro.h" + #include "../portable/IAR/ATMega323/portmacro.h" #endif #ifdef MPLAB_PIC24_PORT - #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" #endif #ifdef MPLAB_DSPIC_PORT - #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" #endif #ifdef MPLAB_PIC18F_PORT - #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" + #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" #endif #ifdef MPLAB_PIC32MX_PORT - #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" + #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" #endif #ifdef _FEDPICC - #include "libFreeRTOS/Include/portmacro.h" + #include "libFreeRTOS/Include/portmacro.h" #endif #ifdef SDCC_CYGNAL - #include "../../Source/portable/SDCC/Cygnal/portmacro.h" + #include "../../Source/portable/SDCC/Cygnal/portmacro.h" #endif #ifdef GCC_ARM7 - #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" + #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" #endif #ifdef GCC_ARM7_ECLIPSE - #include "portmacro.h" + #include "portmacro.h" #endif #ifdef ROWLEY_LPC23xx - #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" + #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" #endif #ifdef IAR_MSP430 - #include "..\..\Source\portable\IAR\MSP430\portmacro.h" + #include "..\..\Source\portable\IAR\MSP430\portmacro.h" #endif #ifdef GCC_MSP430 - #include "../../Source/portable/GCC/MSP430F449/portmacro.h" + #include "../../Source/portable/GCC/MSP430F449/portmacro.h" #endif #ifdef ROWLEY_MSP430 - #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" + #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" #endif #ifdef ARM7_LPC21xx_KEIL_RVDS - #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" + #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" #endif #ifdef SAM7_GCC - #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" + #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" #endif #ifdef SAM7_IAR - #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" + #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" #endif #ifdef SAM9XE_IAR - #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" + #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" #endif #ifdef LPC2000_IAR - #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" + #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" #endif #ifdef STR71X_IAR - #include "..\..\Source\portable\IAR\STR71x\portmacro.h" + #include "..\..\Source\portable\IAR\STR71x\portmacro.h" #endif #ifdef STR75X_IAR - #include "..\..\Source\portable\IAR\STR75x\portmacro.h" + #include "..\..\Source\portable\IAR\STR75x\portmacro.h" #endif #ifdef STR75X_GCC - #include "..\..\Source\portable\GCC\STR75x\portmacro.h" + #include "..\..\Source\portable\GCC\STR75x\portmacro.h" #endif #ifdef STR91X_IAR - #include "..\..\Source\portable\IAR\STR91x\portmacro.h" + #include "..\..\Source\portable\IAR\STR91x\portmacro.h" #endif #ifdef GCC_H8S - #include "../../Source/portable/GCC/H8S2329/portmacro.h" + #include "../../Source/portable/GCC/H8S2329/portmacro.h" #endif #ifdef GCC_AT91FR40008 - #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" + #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" #endif #ifdef RVDS_ARMCM3_LM3S102 - #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" + #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" #endif #ifdef GCC_ARMCM3_LM3S102 - #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" #endif #ifdef GCC_ARMCM3 - #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" #endif #ifdef IAR_ARM_CM3 - #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" #endif #ifdef IAR_ARMCM3_LM - #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" #endif #ifdef HCS12_CODE_WARRIOR - #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" + #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" #endif #ifdef MICROBLAZE_GCC - #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" + #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" #endif #ifdef TERN_EE - #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" + #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" #endif #ifdef GCC_HCS12 - #include "../../Source/portable/GCC/HCS12/portmacro.h" + #include "../../Source/portable/GCC/HCS12/portmacro.h" #endif #ifdef GCC_MCF5235 @@ -189,90 +189,90 @@ projects should not use them. */ #endif #ifdef COLDFIRE_V2_GCC - #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" + #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" #endif #ifdef COLDFIRE_V2_CODEWARRIOR - #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" + #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" #endif #ifdef GCC_PPC405 - #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" + #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" #endif #ifdef GCC_PPC440 - #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" + #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" #endif #ifdef _16FX_SOFTUNE - #include "..\..\Source\portable\Softune\MB96340\portmacro.h" + #include "..\..\Source\portable\Softune\MB96340\portmacro.h" #endif #ifdef BCC_INDUSTRIAL_PC_PORT - /* A short file name has to be used in place of the normal - FreeRTOSConfig.h when using the Borland compiler. */ - #include "frconfig.h" - #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" + /* A short file name has to be used in place of the normal + FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef BCC_FLASH_LITE_186_PORT - /* A short file name has to be used in place of the normal - FreeRTOSConfig.h when using the Borland compiler. */ - #include "frconfig.h" - #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" + /* A short file name has to be used in place of the normal + FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef __GNUC__ #ifdef __AVR32_AVR32A__ - #include "portmacro.h" + #include "portmacro.h" #endif #endif #ifdef __ICCAVR32__ #ifdef __CORE__ #if __CORE__ == __AVR32A__ - #include "portmacro.h" + #include "portmacro.h" #endif #endif #endif #ifdef __91467D - #include "portmacro.h" + #include "portmacro.h" #endif #ifdef __96340 - #include "portmacro.h" + #include "portmacro.h" #endif #ifdef __IAR_V850ES_Fx3__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx3__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx3_L__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx2__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Hx2__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_78K0R_Kx3__ - #include "../../Source/portable/IAR/78K0R/portmacro.h" + #include "../../Source/portable/IAR/78K0R/portmacro.h" #endif #ifdef __IAR_78K0R_Kx3L__ - #include "../../Source/portable/IAR/78K0R/portmacro.h" + #include "../../Source/portable/IAR/78K0R/portmacro.h" #endif #endif /* DEPRECATED_DEFINITIONS_H */ diff --git a/components/bl602/freertos_riscv/config/event_groups.h b/components/bl602/freertos_riscv/config/event_groups.h index 1f38bdb7..056152b4 100644 --- a/components/bl602/freertos_riscv/config/event_groups.h +++ b/components/bl602/freertos_riscv/config/event_groups.h @@ -29,7 +29,7 @@ #define EVENT_GROUPS_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" + #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" #endif /* FreeRTOS includes. */ @@ -123,28 +123,28 @@ typedef TickType_t EventBits_t; * * Example usage:
-	// Declare a variable to hold the created event group.
-	EventGroupHandle_t xCreatedEventGroup;
+    // Declare a variable to hold the created event group.
+    EventGroupHandle_t xCreatedEventGroup;
 
-	// Attempt to create the event group.
-	xCreatedEventGroup = xEventGroupCreate();
+    // Attempt to create the event group.
+    xCreatedEventGroup = xEventGroupCreate();
 
-	// Was the event group created successfully?
-	if( xCreatedEventGroup == NULL )
-	{
-		// The event group was not created because there was insufficient
-		// FreeRTOS heap available.
-	}
-	else
-	{
-		// The event group was created.
-	}
+    // Was the event group created successfully?
+    if( xCreatedEventGroup == NULL )
+    {
+        // The event group was not created because there was insufficient
+        // FreeRTOS heap available.
+    }
+    else
+    {
+        // The event group was created.
+    }
    
* \defgroup xEventGroupCreate xEventGroupCreate * \ingroup EventGroup */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION; + EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION; #endif /** @@ -182,32 +182,32 @@ typedef TickType_t EventBits_t; * * Example usage:
-	// StaticEventGroup_t is a publicly accessible structure that has the same
-	// size and alignment requirements as the real event group structure.  It is
-	// provided as a mechanism for applications to know the size of the event
-	// group (which is dependent on the architecture and configuration file
-	// settings) without breaking the strict data hiding policy by exposing the
-	// real event group internals.  This StaticEventGroup_t variable is passed
-	// into the xSemaphoreCreateEventGroupStatic() function and is used to store
-	// the event group's data structures
-	StaticEventGroup_t xEventGroupBuffer;
+    // StaticEventGroup_t is a publicly accessible structure that has the same
+    // size and alignment requirements as the real event group structure.  It is
+    // provided as a mechanism for applications to know the size of the event
+    // group (which is dependent on the architecture and configuration file
+    // settings) without breaking the strict data hiding policy by exposing the
+    // real event group internals.  This StaticEventGroup_t variable is passed
+    // into the xSemaphoreCreateEventGroupStatic() function and is used to store
+    // the event group's data structures
+    StaticEventGroup_t xEventGroupBuffer;
 
-	// Create the event group without dynamically allocating any memory.
-	xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer );
+    // Create the event group without dynamically allocating any memory.
+    xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer );
    
*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION; + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION; #endif /** * event_groups.h *
-	EventBits_t xEventGroupWaitBits( 	EventGroupHandle_t xEventGroup,
-										const EventBits_t uxBitsToWaitFor,
-										const BaseType_t xClearOnExit,
-										const BaseType_t xWaitForAllBits,
-										const TickType_t xTicksToWait );
+    EventBits_t xEventGroupWaitBits(    EventGroupHandle_t xEventGroup,
+                                        const EventBits_t uxBitsToWaitFor,
+                                        const BaseType_t xClearOnExit,
+                                        const BaseType_t xWaitForAllBits,
+                                        const TickType_t xTicksToWait );
  
* * [Potentially] block to wait for one or more bits to be set within a @@ -253,40 +253,40 @@ typedef TickType_t EventBits_t; * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    void aFunction( EventGroupHandle_t xEventGroup )
    {
    EventBits_t uxBits;
    const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
 
-		// Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
-		// the event group.  Clear the bits before exiting.
-		uxBits = xEventGroupWaitBits(
-					xEventGroup,	// The event group being tested.
-					BIT_0 | BIT_4,	// The bits within the event group to wait for.
-					pdTRUE,			// BIT_0 and BIT_4 should be cleared before returning.
-					pdFALSE,		// Don't wait for both bits, either bit will do.
-					xTicksToWait );	// Wait a maximum of 100ms for either bit to be set.
+        // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
+        // the event group.  Clear the bits before exiting.
+        uxBits = xEventGroupWaitBits(
+                    xEventGroup,    // The event group being tested.
+                    BIT_0 | BIT_4,  // The bits within the event group to wait for.
+                    pdTRUE,         // BIT_0 and BIT_4 should be cleared before returning.
+                    pdFALSE,        // Don't wait for both bits, either bit will do.
+                    xTicksToWait ); // Wait a maximum of 100ms for either bit to be set.
 
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// xEventGroupWaitBits() returned because both bits were set.
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// xEventGroupWaitBits() returned because just BIT_0 was set.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// xEventGroupWaitBits() returned because just BIT_4 was set.
-		}
-		else
-		{
-			// xEventGroupWaitBits() returned because xTicksToWait ticks passed
-			// without either BIT_0 or BIT_4 becoming set.
-		}
+        if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+        {
+            // xEventGroupWaitBits() returned because both bits were set.
+        }
+        else if( ( uxBits & BIT_0 ) != 0 )
+        {
+            // xEventGroupWaitBits() returned because just BIT_0 was set.
+        }
+        else if( ( uxBits & BIT_4 ) != 0 )
+        {
+            // xEventGroupWaitBits() returned because just BIT_4 was set.
+        }
+        else
+        {
+            // xEventGroupWaitBits() returned because xTicksToWait ticks passed
+            // without either BIT_0 or BIT_4 becoming set.
+        }
    }
    
* \defgroup xEventGroupWaitBits xEventGroupWaitBits @@ -297,7 +297,7 @@ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits /** * event_groups.h *
-	EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
+    EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
  
* * Clear bits within an event group. This function cannot be called from an @@ -313,37 +313,37 @@ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    void aFunction( EventGroupHandle_t xEventGroup )
    {
    EventBits_t uxBits;
 
-		// Clear bit 0 and bit 4 in xEventGroup.
-		uxBits = xEventGroupClearBits(
-								xEventGroup,	// The event group being updated.
-								BIT_0 | BIT_4 );// The bits being cleared.
+        // Clear bit 0 and bit 4 in xEventGroup.
+        uxBits = xEventGroupClearBits(
+                                xEventGroup,    // The event group being updated.
+                                BIT_0 | BIT_4 );// The bits being cleared.
 
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// Both bit 0 and bit 4 were set before xEventGroupClearBits() was
-			// called.  Both will now be clear (not set).
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// Bit 0 was set before xEventGroupClearBits() was called.  It will
-			// now be clear.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// Bit 4 was set before xEventGroupClearBits() was called.  It will
-			// now be clear.
-		}
-		else
-		{
-			// Neither bit 0 nor bit 4 were set in the first place.
-		}
+        if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+        {
+            // Both bit 0 and bit 4 were set before xEventGroupClearBits() was
+            // called.  Both will now be clear (not set).
+        }
+        else if( ( uxBits & BIT_0 ) != 0 )
+        {
+            // Bit 0 was set before xEventGroupClearBits() was called.  It will
+            // now be clear.
+        }
+        else if( ( uxBits & BIT_4 ) != 0 )
+        {
+            // Bit 4 was set before xEventGroupClearBits() was called.  It will
+            // now be clear.
+        }
+        else
+        {
+            // Neither bit 0 nor bit 4 were set in the first place.
+        }
    }
    
* \defgroup xEventGroupClearBits xEventGroupClearBits @@ -354,7 +354,7 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit /** * event_groups.h *
-	BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+    BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
  
* * A version of xEventGroupClearBits() that can be called from an interrupt. @@ -381,8 +381,8 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    // An event group which it is assumed has already been created by a call to
    // xEventGroupCreate().
@@ -390,30 +390,30 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit
 
    void anInterruptHandler( void )
    {
-		// Clear bit 0 and bit 4 in xEventGroup.
-		xResult = xEventGroupClearBitsFromISR(
-							xEventGroup,	 // The event group being updated.
-							BIT_0 | BIT_4 ); // The bits being set.
+        // Clear bit 0 and bit 4 in xEventGroup.
+        xResult = xEventGroupClearBitsFromISR(
+                            xEventGroup,     // The event group being updated.
+                            BIT_0 | BIT_4 ); // The bits being set.
 
-		if( xResult == pdPASS )
-		{
-			// The message was posted successfully.
-		}
+        if( xResult == pdPASS )
+        {
+            // The message was posted successfully.
+        }
   }
    
* \defgroup xEventGroupClearBitsFromISR xEventGroupClearBitsFromISR * \ingroup EventGroup */ #if( configUSE_TRACE_FACILITY == 1 ) - BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; #else - #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) + #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) #endif /** * event_groups.h *
-	EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+    EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
  
* * Set bits within an event group. @@ -441,42 +441,42 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    void aFunction( EventGroupHandle_t xEventGroup )
    {
    EventBits_t uxBits;
 
-		// Set bit 0 and bit 4 in xEventGroup.
-		uxBits = xEventGroupSetBits(
-							xEventGroup,	// The event group being updated.
-							BIT_0 | BIT_4 );// The bits being set.
+        // Set bit 0 and bit 4 in xEventGroup.
+        uxBits = xEventGroupSetBits(
+                            xEventGroup,    // The event group being updated.
+                            BIT_0 | BIT_4 );// The bits being set.
 
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// Both bit 0 and bit 4 remained set when the function returned.
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// Bit 0 remained set when the function returned, but bit 4 was
-			// cleared.  It might be that bit 4 was cleared automatically as a
-			// task that was waiting for bit 4 was removed from the Blocked
-			// state.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// Bit 4 remained set when the function returned, but bit 0 was
-			// cleared.  It might be that bit 0 was cleared automatically as a
-			// task that was waiting for bit 0 was removed from the Blocked
-			// state.
-		}
-		else
-		{
-			// Neither bit 0 nor bit 4 remained set.  It might be that a task
-			// was waiting for both of the bits to be set, and the bits were
-			// cleared as the task left the Blocked state.
-		}
+        if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+        {
+            // Both bit 0 and bit 4 remained set when the function returned.
+        }
+        else if( ( uxBits & BIT_0 ) != 0 )
+        {
+            // Bit 0 remained set when the function returned, but bit 4 was
+            // cleared.  It might be that bit 4 was cleared automatically as a
+            // task that was waiting for bit 4 was removed from the Blocked
+            // state.
+        }
+        else if( ( uxBits & BIT_4 ) != 0 )
+        {
+            // Bit 4 remained set when the function returned, but bit 0 was
+            // cleared.  It might be that bit 0 was cleared automatically as a
+            // task that was waiting for bit 0 was removed from the Blocked
+            // state.
+        }
+        else
+        {
+            // Neither bit 0 nor bit 4 remained set.  It might be that a task
+            // was waiting for both of the bits to be set, and the bits were
+            // cleared as the task left the Blocked state.
+        }
    }
    
* \defgroup xEventGroupSetBits xEventGroupSetBits @@ -487,7 +487,7 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_ /** * event_groups.h *
-	BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
+    BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
  
* * A version of xEventGroupSetBits() that can be called from an interrupt. @@ -522,8 +522,8 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_ * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    // An event group which it is assumed has already been created by a call to
    // xEventGroupCreate().
@@ -533,42 +533,42 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_
    {
    BaseType_t xHigherPriorityTaskWoken, xResult;
 
-		// xHigherPriorityTaskWoken must be initialised to pdFALSE.
-		xHigherPriorityTaskWoken = pdFALSE;
+        // xHigherPriorityTaskWoken must be initialised to pdFALSE.
+        xHigherPriorityTaskWoken = pdFALSE;
 
-		// Set bit 0 and bit 4 in xEventGroup.
-		xResult = xEventGroupSetBitsFromISR(
-							xEventGroup,	// The event group being updated.
-							BIT_0 | BIT_4   // The bits being set.
-							&xHigherPriorityTaskWoken );
+        // Set bit 0 and bit 4 in xEventGroup.
+        xResult = xEventGroupSetBitsFromISR(
+                            xEventGroup,    // The event group being updated.
+                            BIT_0 | BIT_4   // The bits being set.
+                            &xHigherPriorityTaskWoken );
 
-		// Was the message posted successfully?
-		if( xResult == pdPASS )
-		{
-			// If xHigherPriorityTaskWoken is now set to pdTRUE then a context
-			// switch should be requested.  The macro used is port specific and
-			// will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
-			// refer to the documentation page for the port being used.
-			portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
-		}
+        // Was the message posted successfully?
+        if( xResult == pdPASS )
+        {
+            // If xHigherPriorityTaskWoken is now set to pdTRUE then a context
+            // switch should be requested.  The macro used is port specific and
+            // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
+            // refer to the documentation page for the port being used.
+            portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
+        }
   }
    
* \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR * \ingroup EventGroup */ #if( configUSE_TRACE_FACILITY == 1 ) - BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; #else - #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) + #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) #endif /** * event_groups.h *
-	EventBits_t xEventGroupSync(	EventGroupHandle_t xEventGroup,
-									const EventBits_t uxBitsToSet,
-									const EventBits_t uxBitsToWaitFor,
-									TickType_t xTicksToWait );
+    EventBits_t xEventGroupSync(    EventGroupHandle_t xEventGroup,
+                                    const EventBits_t uxBitsToSet,
+                                    const EventBits_t uxBitsToWaitFor,
+                                    TickType_t xTicksToWait );
  
* * Atomically set bits within an event group, then wait for a combination of @@ -610,9 +610,9 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_ * Example usage:
  // Bits used by the three tasks.
- #define TASK_0_BIT		( 1 << 0 )
- #define TASK_1_BIT		( 1 << 1 )
- #define TASK_2_BIT		( 1 << 2 )
+ #define TASK_0_BIT     ( 1 << 0 )
+ #define TASK_1_BIT     ( 1 << 1 )
+ #define TASK_2_BIT     ( 1 << 2 )
 
  #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
 
@@ -625,61 +625,61 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_
  EventBits_t uxReturn;
  TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
 
-	 for( ;; )
-	 {
-		// Perform task functionality here.
+     for( ;; )
+     {
+        // Perform task functionality here.
 
-		// Set bit 0 in the event flag to note this task has reached the
-		// sync point.  The other two tasks will set the other two bits defined
-		// by ALL_SYNC_BITS.  All three tasks have reached the synchronisation
-		// point when all the ALL_SYNC_BITS are set.  Wait a maximum of 100ms
-		// for this to happen.
-		uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
+        // Set bit 0 in the event flag to note this task has reached the
+        // sync point.  The other two tasks will set the other two bits defined
+        // by ALL_SYNC_BITS.  All three tasks have reached the synchronisation
+        // point when all the ALL_SYNC_BITS are set.  Wait a maximum of 100ms
+        // for this to happen.
+        uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
 
-		if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
-		{
-			// All three tasks reached the synchronisation point before the call
-			// to xEventGroupSync() timed out.
-		}
-	}
+        if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
+        {
+            // All three tasks reached the synchronisation point before the call
+            // to xEventGroupSync() timed out.
+        }
+    }
  }
 
  void vTask1( void *pvParameters )
  {
-	 for( ;; )
-	 {
-		// Perform task functionality here.
+     for( ;; )
+     {
+        // Perform task functionality here.
 
-		// Set bit 1 in the event flag to note this task has reached the
-		// synchronisation point.  The other two tasks will set the other two
-		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
-		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
-		// indefinitely for this to happen.
-		xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+        // Set bit 1 in the event flag to note this task has reached the
+        // synchronisation point.  The other two tasks will set the other two
+        // bits defined by ALL_SYNC_BITS.  All three tasks have reached the
+        // synchronisation point when all the ALL_SYNC_BITS are set.  Wait
+        // indefinitely for this to happen.
+        xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
 
-		// xEventGroupSync() was called with an indefinite block time, so
-		// this task will only reach here if the syncrhonisation was made by all
-		// three tasks, so there is no need to test the return value.
-	 }
+        // xEventGroupSync() was called with an indefinite block time, so
+        // this task will only reach here if the syncrhonisation was made by all
+        // three tasks, so there is no need to test the return value.
+     }
  }
 
  void vTask2( void *pvParameters )
  {
-	 for( ;; )
-	 {
-		// Perform task functionality here.
+     for( ;; )
+     {
+        // Perform task functionality here.
 
-		// Set bit 2 in the event flag to note this task has reached the
-		// synchronisation point.  The other two tasks will set the other two
-		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
-		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
-		// indefinitely for this to happen.
-		xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+        // Set bit 2 in the event flag to note this task has reached the
+        // synchronisation point.  The other two tasks will set the other two
+        // bits defined by ALL_SYNC_BITS.  All three tasks have reached the
+        // synchronisation point when all the ALL_SYNC_BITS are set.  Wait
+        // indefinitely for this to happen.
+        xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
 
-		// xEventGroupSync() was called with an indefinite block time, so
-		// this task will only reach here if the syncrhonisation was made by all
-		// three tasks, so there is no need to test the return value.
-	}
+        // xEventGroupSync() was called with an indefinite block time, so
+        // this task will only reach here if the syncrhonisation was made by all
+        // three tasks, so there is no need to test the return value.
+    }
  }
 
  
@@ -692,7 +692,7 @@ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t u /** * event_groups.h *
-	EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
+    EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
  
* * Returns the current value of the bits in an event group. This function @@ -710,7 +710,7 @@ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t u /** * event_groups.h *
-	EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
+    EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
  
* * A version of xEventGroupGetBits() that can be called from an ISR. @@ -727,7 +727,7 @@ EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEG /** * event_groups.h *
-	void xEventGroupDelete( EventGroupHandle_t xEventGroup );
+    void xEventGroupDelete( EventGroupHandle_t xEventGroup );
  
* * Delete an event group that was previously created by a call to @@ -744,8 +744,8 @@ void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToCl #if (configUSE_TRACE_FACILITY == 1) - UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) PRIVILEGED_FUNCTION; - void vEventGroupSetNumber( void* xEventGroup, UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) PRIVILEGED_FUNCTION; + void vEventGroupSetNumber( void* xEventGroup, UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; #endif #ifdef __cplusplus diff --git a/components/bl602/freertos_riscv/config/list.h b/components/bl602/freertos_riscv/config/list.h index 2fb6775f..fe90782a 100644 --- a/components/bl602/freertos_riscv/config/list.h +++ b/components/bl602/freertos_riscv/config/list.h @@ -54,7 +54,7 @@ */ #ifndef INC_FREERTOS_H - #error FreeRTOS.h must be included before list.h + #error FreeRTOS.h must be included before list.h #endif #ifndef LIST_H @@ -89,7 +89,7 @@ * "#define configLIST_VOLATILE volatile" */ #ifndef configLIST_VOLATILE - #define configLIST_VOLATILE + #define configLIST_VOLATILE #endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ #ifdef __cplusplus @@ -102,34 +102,34 @@ the application. These may catch the list data structures being overwritten in memory. They will not catch data errors caused by incorrect configuration or use of FreeRTOS.*/ #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) - /* Define the macros to do nothing. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) - #define listTEST_LIST_INTEGRITY( pxList ) + /* Define the macros to do nothing. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) + #define listTEST_LIST_INTEGRITY( pxList ) #else - /* Define macros that add new members into the list structures. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; + /* Define macros that add new members into the list structures. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; - /* Define macros that set the new structure members to known values. */ - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + /* Define macros that set the new structure members to known values. */ + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - /* Define macros that will assert if one of the structure members does not - contain its expected value. */ - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) - #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + /* Define macros that will assert if one of the structure members does not + contain its expected value. */ + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) #endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ @@ -139,22 +139,22 @@ use of FreeRTOS.*/ struct xLIST; struct xLIST_ITEM { - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ - struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ - void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ - struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ - listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ + struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ + void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ + struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ + listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ }; -typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ +typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ struct xMINI_LIST_ITEM { - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; - struct xLIST_ITEM * configLIST_VOLATILE pxNext; - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; + struct xLIST_ITEM * configLIST_VOLATILE pxNext; + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; }; typedef struct xMINI_LIST_ITEM MiniListItem_t; @@ -163,11 +163,11 @@ typedef struct xMINI_LIST_ITEM MiniListItem_t; */ typedef struct xLIST { - listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - volatile UBaseType_t uxNumberOfItems; - ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ - MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ - listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + volatile UBaseType_t uxNumberOfItems; + ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ + MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ + listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ } List_t; /* @@ -177,7 +177,7 @@ typedef struct xLIST * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER * \ingroup LinkedList */ -#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) +#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) /* * Access macro to get the owner of a list item. The owner of a list item @@ -186,7 +186,7 @@ typedef struct xLIST * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER * \ingroup LinkedList */ -#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) +#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) /* * Access macro to set the value of the list item. In most cases the value is @@ -195,7 +195,7 @@ typedef struct xLIST * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE * \ingroup LinkedList */ -#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) +#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) /* * Access macro to retrieve the value of the list item. The value can @@ -205,7 +205,7 @@ typedef struct xLIST * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE * \ingroup LinkedList */ -#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) +#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) /* * Access macro to retrieve the value of the list item at the head of a given @@ -214,7 +214,7 @@ typedef struct xLIST * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE * \ingroup LinkedList */ -#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) +#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) /* * Return the list item at the head of the list. @@ -222,7 +222,7 @@ typedef struct xLIST * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY * \ingroup LinkedList */ -#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) +#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) /* * Return the list item at the head of the list. @@ -230,7 +230,7 @@ typedef struct xLIST * \page listGET_NEXT listGET_NEXT * \ingroup LinkedList */ -#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) +#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) /* * Return the list item that marks the end of the list @@ -238,7 +238,7 @@ typedef struct xLIST * \page listGET_END_MARKER listGET_END_MARKER * \ingroup LinkedList */ -#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) +#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) /* * Access macro to determine if a list contains any items. The macro will @@ -247,12 +247,12 @@ typedef struct xLIST * \page listLIST_IS_EMPTY listLIST_IS_EMPTY * \ingroup LinkedList */ -#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) +#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) /* * Access macro to return the number of items in the list. */ -#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) +#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) /* * Access function to obtain the owner of the next entry in a list. @@ -274,17 +274,17 @@ typedef struct xLIST * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY * \ingroup LinkedList */ -#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ -{ \ -List_t * const pxConstList = ( pxList ); \ - /* Increment the index to the next item and return the item, ensuring */ \ - /* we don't return the marker used at the end of the list. */ \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ - { \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - } \ - ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ +#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ +{ \ +List_t * const pxConstList = ( pxList ); \ + /* Increment the index to the next item and return the item, ensuring */ \ + /* we don't return the marker used at the end of the list. */ \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ + { \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + } \ + ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ } diff --git a/components/bl602/freertos_riscv/config/message_buffer.h b/components/bl602/freertos_riscv/config/message_buffer.h index 88f38d25..04b6efec 100644 --- a/components/bl602/freertos_riscv/config/message_buffer.h +++ b/components/bl602/freertos_riscv/config/message_buffer.h @@ -795,4 +795,4 @@ BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xStreamB } /* extern "C" */ #endif -#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ +#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/components/bl602/freertos_riscv/config/mpu_wrappers.h b/components/bl602/freertos_riscv/config/mpu_wrappers.h index 711393f6..a4e19741 100644 --- a/components/bl602/freertos_riscv/config/mpu_wrappers.h +++ b/components/bl602/freertos_riscv/config/mpu_wrappers.h @@ -32,152 +32,152 @@ only for ports that are using the MPU. */ #ifdef portUSING_MPU_WRAPPERS - /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is - included from queue.c or task.c to prevent it from having an effect within - those files. */ - #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is + included from queue.c or task.c to prevent it from having an effect within + those files. */ + #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE - /* - * Map standard (non MPU) API functions to equivalents that start - * "MPU_". This will cause the application code to call the MPU_ - * version, which wraps the non-MPU version with privilege promoting - * then demoting code, so the kernel code always runs will full - * privileges. - */ + /* + * Map standard (non MPU) API functions to equivalents that start + * "MPU_". This will cause the application code to call the MPU_ + * version, which wraps the non-MPU version with privilege promoting + * then demoting code, so the kernel code always runs will full + * privileges. + */ - /* Map standard tasks.h API functions to the MPU equivalents. */ - #define xTaskCreate MPU_xTaskCreate - #define xTaskCreateStatic MPU_xTaskCreateStatic - #define xTaskCreateRestricted MPU_xTaskCreateRestricted - #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions - #define vTaskDelete MPU_vTaskDelete - #define vTaskDelay MPU_vTaskDelay - #define vTaskDelayUntil MPU_vTaskDelayUntil - #define xTaskAbortDelay MPU_xTaskAbortDelay - #define uxTaskPriorityGet MPU_uxTaskPriorityGet - #define eTaskGetState MPU_eTaskGetState - #define vTaskGetInfo MPU_vTaskGetInfo - #define vTaskPrioritySet MPU_vTaskPrioritySet - #define vTaskSuspend MPU_vTaskSuspend - #define vTaskResume MPU_vTaskResume - #define vTaskSuspendAll MPU_vTaskSuspendAll - #define xTaskResumeAll MPU_xTaskResumeAll - #define xTaskGetTickCount MPU_xTaskGetTickCount - #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks - #define pcTaskGetName MPU_pcTaskGetName - #define xTaskGetHandle MPU_xTaskGetHandle - #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark - #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 - #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag - #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag - #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer - #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer - #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook - #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle - #define uxTaskGetSystemState MPU_uxTaskGetSystemState - #define vTaskList MPU_vTaskList - #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats - #define xTaskGetIdleRunTimeCounter MPU_xTaskGetIdleRunTimeCounter - #define xTaskGenericNotify MPU_xTaskGenericNotify - #define xTaskNotifyWait MPU_xTaskNotifyWait - #define ulTaskNotifyTake MPU_ulTaskNotifyTake - #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear + /* Map standard tasks.h API functions to the MPU equivalents. */ + #define xTaskCreate MPU_xTaskCreate + #define xTaskCreateStatic MPU_xTaskCreateStatic + #define xTaskCreateRestricted MPU_xTaskCreateRestricted + #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions + #define vTaskDelete MPU_vTaskDelete + #define vTaskDelay MPU_vTaskDelay + #define vTaskDelayUntil MPU_vTaskDelayUntil + #define xTaskAbortDelay MPU_xTaskAbortDelay + #define uxTaskPriorityGet MPU_uxTaskPriorityGet + #define eTaskGetState MPU_eTaskGetState + #define vTaskGetInfo MPU_vTaskGetInfo + #define vTaskPrioritySet MPU_vTaskPrioritySet + #define vTaskSuspend MPU_vTaskSuspend + #define vTaskResume MPU_vTaskResume + #define vTaskSuspendAll MPU_vTaskSuspendAll + #define xTaskResumeAll MPU_xTaskResumeAll + #define xTaskGetTickCount MPU_xTaskGetTickCount + #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks + #define pcTaskGetName MPU_pcTaskGetName + #define xTaskGetHandle MPU_xTaskGetHandle + #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark + #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 + #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag + #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag + #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer + #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer + #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook + #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle + #define uxTaskGetSystemState MPU_uxTaskGetSystemState + #define vTaskList MPU_vTaskList + #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats + #define xTaskGetIdleRunTimeCounter MPU_xTaskGetIdleRunTimeCounter + #define xTaskGenericNotify MPU_xTaskGenericNotify + #define xTaskNotifyWait MPU_xTaskNotifyWait + #define ulTaskNotifyTake MPU_ulTaskNotifyTake + #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear - #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle - #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState - #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut - #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState + #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle + #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState + #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut + #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState - /* Map standard queue.h API functions to the MPU equivalents. */ - #define xQueueGenericSend MPU_xQueueGenericSend - #define xQueueReceive MPU_xQueueReceive - #define xQueuePeek MPU_xQueuePeek - #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake - #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting - #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable - #define vQueueDelete MPU_vQueueDelete - #define xQueueCreateMutex MPU_xQueueCreateMutex - #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic - #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore - #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic - #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder - #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive - #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive - #define xQueueGenericCreate MPU_xQueueGenericCreate - #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic - #define xQueueCreateSet MPU_xQueueCreateSet - #define xQueueAddToSet MPU_xQueueAddToSet - #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet - #define xQueueSelectFromSet MPU_xQueueSelectFromSet - #define xQueueGenericReset MPU_xQueueGenericReset + /* Map standard queue.h API functions to the MPU equivalents. */ + #define xQueueGenericSend MPU_xQueueGenericSend + #define xQueueReceive MPU_xQueueReceive + #define xQueuePeek MPU_xQueuePeek + #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake + #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting + #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable + #define vQueueDelete MPU_vQueueDelete + #define xQueueCreateMutex MPU_xQueueCreateMutex + #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic + #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore + #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic + #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder + #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive + #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive + #define xQueueGenericCreate MPU_xQueueGenericCreate + #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic + #define xQueueCreateSet MPU_xQueueCreateSet + #define xQueueAddToSet MPU_xQueueAddToSet + #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet + #define xQueueSelectFromSet MPU_xQueueSelectFromSet + #define xQueueGenericReset MPU_xQueueGenericReset - #if( configQUEUE_REGISTRY_SIZE > 0 ) - #define vQueueAddToRegistry MPU_vQueueAddToRegistry - #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue - #define pcQueueGetName MPU_pcQueueGetName - #endif + #if( configQUEUE_REGISTRY_SIZE > 0 ) + #define vQueueAddToRegistry MPU_vQueueAddToRegistry + #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue + #define pcQueueGetName MPU_pcQueueGetName + #endif - /* Map standard timer.h API functions to the MPU equivalents. */ - #define xTimerCreate MPU_xTimerCreate - #define xTimerCreateStatic MPU_xTimerCreateStatic - #define pvTimerGetTimerID MPU_pvTimerGetTimerID - #define vTimerSetTimerID MPU_vTimerSetTimerID - #define xTimerIsTimerActive MPU_xTimerIsTimerActive - #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle - #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall - #define pcTimerGetName MPU_pcTimerGetName - #define vTimerSetReloadMode MPU_vTimerSetReloadMode - #define xTimerGetPeriod MPU_xTimerGetPeriod - #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime - #define xTimerGenericCommand MPU_xTimerGenericCommand + /* Map standard timer.h API functions to the MPU equivalents. */ + #define xTimerCreate MPU_xTimerCreate + #define xTimerCreateStatic MPU_xTimerCreateStatic + #define pvTimerGetTimerID MPU_pvTimerGetTimerID + #define vTimerSetTimerID MPU_vTimerSetTimerID + #define xTimerIsTimerActive MPU_xTimerIsTimerActive + #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle + #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall + #define pcTimerGetName MPU_pcTimerGetName + #define vTimerSetReloadMode MPU_vTimerSetReloadMode + #define xTimerGetPeriod MPU_xTimerGetPeriod + #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime + #define xTimerGenericCommand MPU_xTimerGenericCommand - /* Map standard event_group.h API functions to the MPU equivalents. */ - #define xEventGroupCreate MPU_xEventGroupCreate - #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic - #define xEventGroupWaitBits MPU_xEventGroupWaitBits - #define xEventGroupClearBits MPU_xEventGroupClearBits - #define xEventGroupSetBits MPU_xEventGroupSetBits - #define xEventGroupSync MPU_xEventGroupSync - #define vEventGroupDelete MPU_vEventGroupDelete + /* Map standard event_group.h API functions to the MPU equivalents. */ + #define xEventGroupCreate MPU_xEventGroupCreate + #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic + #define xEventGroupWaitBits MPU_xEventGroupWaitBits + #define xEventGroupClearBits MPU_xEventGroupClearBits + #define xEventGroupSetBits MPU_xEventGroupSetBits + #define xEventGroupSync MPU_xEventGroupSync + #define vEventGroupDelete MPU_vEventGroupDelete - /* Map standard message/stream_buffer.h API functions to the MPU - equivalents. */ - #define xStreamBufferSend MPU_xStreamBufferSend - #define xStreamBufferReceive MPU_xStreamBufferReceive - #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes - #define vStreamBufferDelete MPU_vStreamBufferDelete - #define xStreamBufferIsFull MPU_xStreamBufferIsFull - #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty - #define xStreamBufferReset MPU_xStreamBufferReset - #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable - #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable - #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel - #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate - #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic + /* Map standard message/stream_buffer.h API functions to the MPU + equivalents. */ + #define xStreamBufferSend MPU_xStreamBufferSend + #define xStreamBufferReceive MPU_xStreamBufferReceive + #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes + #define vStreamBufferDelete MPU_vStreamBufferDelete + #define xStreamBufferIsFull MPU_xStreamBufferIsFull + #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty + #define xStreamBufferReset MPU_xStreamBufferReset + #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable + #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable + #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel + #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate + #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic - /* Remove the privileged function macro, but keep the PRIVILEGED_DATA - macro so applications can place data in privileged access sections - (useful when using statically allocated objects). */ - #define PRIVILEGED_FUNCTION - #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) - #define FREERTOS_SYSTEM_CALL + /* Remove the privileged function macro, but keep the PRIVILEGED_DATA + macro so applications can place data in privileged access sections + (useful when using statically allocated objects). */ + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL - #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ - /* Ensure API functions go in the privileged execution section. */ - #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) - #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) - #define FREERTOS_SYSTEM_CALL __attribute__((section( "freertos_system_calls"))) + /* Ensure API functions go in the privileged execution section. */ + #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL __attribute__((section( "freertos_system_calls"))) - #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ #else /* portUSING_MPU_WRAPPERS */ - #define PRIVILEGED_FUNCTION - #define PRIVILEGED_DATA - #define FREERTOS_SYSTEM_CALL - #define portUSING_MPU_WRAPPERS 0 + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA + #define FREERTOS_SYSTEM_CALL + #define portUSING_MPU_WRAPPERS 0 #endif /* portUSING_MPU_WRAPPERS */ diff --git a/components/bl602/freertos_riscv/config/portable.h b/components/bl602/freertos_riscv/config/portable.h index 59e81694..a6e65b0d 100644 --- a/components/bl602/freertos_riscv/config/portable.h +++ b/components/bl602/freertos_riscv/config/portable.h @@ -49,47 +49,47 @@ did not result in a portmacro.h header file being included - and it should be included here. In this case the path to the correct portmacro.h header file must be set in the compiler's include path. */ #ifndef portENTER_CRITICAL - #include "portmacro.h" + #include "portmacro.h" #endif #if portBYTE_ALIGNMENT == 32 - #define portBYTE_ALIGNMENT_MASK ( 0x001f ) + #define portBYTE_ALIGNMENT_MASK ( 0x001f ) #endif #if portBYTE_ALIGNMENT == 16 - #define portBYTE_ALIGNMENT_MASK ( 0x000f ) + #define portBYTE_ALIGNMENT_MASK ( 0x000f ) #endif #if portBYTE_ALIGNMENT == 8 - #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) #endif #if portBYTE_ALIGNMENT == 4 - #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) #endif #if portBYTE_ALIGNMENT == 2 - #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) #endif #if portBYTE_ALIGNMENT == 1 - #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) #endif #ifndef portBYTE_ALIGNMENT_MASK - #error "Invalid portBYTE_ALIGNMENT definition" + #error "Invalid portBYTE_ALIGNMENT definition" #endif #ifndef portNUM_CONFIGURABLE_REGIONS - #define portNUM_CONFIGURABLE_REGIONS 1 + #define portNUM_CONFIGURABLE_REGIONS 1 #endif #ifndef portHAS_STACK_OVERFLOW_CHECKING - #define portHAS_STACK_OVERFLOW_CHECKING 0 + #define portHAS_STACK_OVERFLOW_CHECKING 0 #endif #ifndef portARCH_NAME - #define portARCH_NAME NULL + #define portARCH_NAME NULL #endif #ifdef __cplusplus @@ -105,24 +105,24 @@ extern "C" { * */ #if( portUSING_MPU_WRAPPERS == 1 ) - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; - #else - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; - #endif + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #endif #else - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; - #else - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; - #endif + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #endif #endif /* Used by heap_5.c. */ typedef struct HeapRegion { - uint8_t *pucStartAddress; - size_t xSizeInBytes; + uint8_t *pucStartAddress; + size_t xSizeInBytes; } HeapRegion_t; /* @@ -169,8 +169,8 @@ void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; * contained in xRegions. */ #if( portUSING_MPU_WRAPPERS == 1 ) - struct xMEMORY_REGION; - void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; + struct xMEMORY_REGION; + void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; #endif #ifdef __cplusplus diff --git a/components/bl602/freertos_riscv/config/projdefs.h b/components/bl602/freertos_riscv/config/projdefs.h index e0458619..d33f145b 100644 --- a/components/bl602/freertos_riscv/config/projdefs.h +++ b/components/bl602/freertos_riscv/config/projdefs.h @@ -38,84 +38,84 @@ typedef void (*TaskFunction_t)( void * ); overridden by a macro of the same name defined in FreeRTOSConfig.h in case the definition here is not suitable for your application. */ #ifndef pdMS_TO_TICKS - #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) + #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) #endif -#define pdFALSE ( ( BaseType_t ) 0 ) -#define pdTRUE ( ( BaseType_t ) 1 ) +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) -#define pdPASS ( pdTRUE ) -#define pdFAIL ( pdFALSE ) -#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) -#define errQUEUE_FULL ( ( BaseType_t ) 0 ) +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) +#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) +#define errQUEUE_FULL ( ( BaseType_t ) 0 ) /* FreeRTOS error definitions. */ -#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) -#define errQUEUE_BLOCKED ( -4 ) -#define errQUEUE_YIELD ( -5 ) +#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) +#define errQUEUE_BLOCKED ( -4 ) +#define errQUEUE_YIELD ( -5 ) /* Macros used for basic data corruption checks. */ #ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES - #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 + #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 #endif #if( configUSE_16_BIT_TICKS == 1 ) - #define pdINTEGRITY_CHECK_VALUE 0x5a5a + #define pdINTEGRITY_CHECK_VALUE 0x5a5a #else - #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL #endif /* The following errno values are used by FreeRTOS+ components, not FreeRTOS itself. */ -#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ -#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ -#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ -#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ -#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ -#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ -#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ -#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ -#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ -#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ -#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ -#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ -#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ -#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ -#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ -#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ -#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ -#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ -#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ -#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ -#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ -#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ -#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ -#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ -#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ -#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ -#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ -#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ -#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ -#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ -#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ -#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ -#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ -#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ -#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ -#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ -#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ -#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ -#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ +#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ +#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ +#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ +#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ +#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ +#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ +#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ +#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ +#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ +#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ +#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ +#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ +#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ +#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ +#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ +#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ +#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ +#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ +#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ +#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ +#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ +#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ +#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ +#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ +#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ +#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ +#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ +#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ +#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ +#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ +#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ +#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ +#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ +#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ +#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ +#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ +#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ +#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ +#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ /* The following endian values are used by FreeRTOS+ components, not FreeRTOS itself. */ -#define pdFREERTOS_LITTLE_ENDIAN 0 -#define pdFREERTOS_BIG_ENDIAN 1 +#define pdFREERTOS_LITTLE_ENDIAN 0 +#define pdFREERTOS_BIG_ENDIAN 1 /* Re-defining endian values for generic naming. */ -#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN -#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN +#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN +#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN #endif /* PROJDEFS_H */ diff --git a/components/bl602/freertos_riscv/config/queue.h b/components/bl602/freertos_riscv/config/queue.h index 3b9da937..2ce0415c 100644 --- a/components/bl602/freertos_riscv/config/queue.h +++ b/components/bl602/freertos_riscv/config/queue.h @@ -30,7 +30,7 @@ #define QUEUE_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include queue.h" + #error "include FreeRTOS.h" must appear in source files before "include queue.h" #endif #ifdef __cplusplus @@ -62,25 +62,25 @@ typedef struct QueueDefinition * QueueSetHandle_t; typedef struct QueueDefinition * QueueSetMemberHandle_t; /* For internal use only. */ -#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) -#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) -#define queueOVERWRITE ( ( BaseType_t ) 2 ) +#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) +#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) +#define queueOVERWRITE ( ( BaseType_t ) 2 ) /* For internal use only. These definitions *must* match those in queue.c. */ -#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) -#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) -#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) -#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) -#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) -#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) +#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) +#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) +#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) +#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) /** * queue. h *
  QueueHandle_t xQueueCreate(
-							  UBaseType_t uxQueueLength,
-							  UBaseType_t uxItemSize
-						  );
+                              UBaseType_t uxQueueLength,
+                              UBaseType_t uxItemSize
+                          );
  * 
* * Creates a new queue instance, and returns a handle by which the new queue @@ -113,48 +113,48 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  };
 
  void vATask( void *pvParameters )
  {
  QueueHandle_t xQueue1, xQueue2;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
-	if( xQueue1 == 0 )
-	{
-		// Queue was not created and must not be used.
-	}
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    if( xQueue1 == 0 )
+    {
+        // Queue was not created and must not be used.
+    }
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue2 == 0 )
-	{
-		// Queue was not created and must not be used.
-	}
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    if( xQueue2 == 0 )
+    {
+        // Queue was not created and must not be used.
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueCreate xQueueCreate * \ingroup QueueManagement */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) + #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) #endif /** * queue. h *
  QueueHandle_t xQueueCreateStatic(
-							  UBaseType_t uxQueueLength,
-							  UBaseType_t uxItemSize,
-							  uint8_t *pucQueueStorageBuffer,
-							  StaticQueue_t *pxQueueBuffer
-						  );
+                              UBaseType_t uxQueueLength,
+                              UBaseType_t uxItemSize,
+                              uint8_t *pucQueueStorageBuffer,
+                              StaticQueue_t *pxQueueBuffer
+                          );
  * 
* * Creates a new queue instance, and returns a handle by which the new queue @@ -195,8 +195,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  };
 
  #define QUEUE_LENGTH 10
@@ -213,33 +213,33 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  {
  QueueHandle_t xQueue1;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold.
-							ITEM_SIZE	  // The size of each item in the queue
-							&( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue.
-							&xQueueBuffer ); // The buffer that will hold the queue structure.
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold.
+                            ITEM_SIZE     // The size of each item in the queue
+                            &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue.
+                            &xQueueBuffer ); // The buffer that will hold the queue structure.
 
-	// The queue is guaranteed to be created successfully as no dynamic memory
-	// allocation is used.  Therefore xQueue1 is now a handle to a valid queue.
+    // The queue is guaranteed to be created successfully as no dynamic memory
+    // allocation is used.  Therefore xQueue1 is now a handle to a valid queue.
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueCreateStatic xQueueCreateStatic * \ingroup QueueManagement */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) + #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * queue. h *
  BaseType_t xQueueSendToToFront(
-								   QueueHandle_t	xQueue,
-								   const void		*pvItemToQueue,
-								   TickType_t		xTicksToWait
-							   );
+                                   QueueHandle_t    xQueue,
+                                   const void       *pvItemToQueue,
+                                   TickType_t       xTicksToWait
+                               );
  * 
* * Post an item to the front of a queue. The item is queued by copy, not by @@ -266,8 +266,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -277,34 +277,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -316,10 +316,10 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueSendToBack(
-								   QueueHandle_t	xQueue,
-								   const void		*pvItemToQueue,
-								   TickType_t		xTicksToWait
-							   );
+                                   QueueHandle_t    xQueue,
+                                   const void       *pvItemToQueue,
+                                   TickType_t       xTicksToWait
+                               );
  * 
* * This is a macro that calls xQueueGenericSend(). @@ -348,8 +348,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -359,34 +359,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -398,10 +398,10 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueSend(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue,
-							  TickType_t xTicksToWait
-						 );
+                              QueueHandle_t xQueue,
+                              const void * pvItemToQueue,
+                              TickType_t xTicksToWait
+                         );
  * 
* * This is a macro that calls xQueueGenericSend(). It is included for @@ -432,8 +432,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -443,34 +443,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -482,9 +482,9 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueOverwrite(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue
-						 );
+                              QueueHandle_t xQueue,
+                              const void * pvItemToQueue
+                         );
  * 
* * Only for use with queues that have a length of one - so the queue is either @@ -516,44 +516,44 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; QueueHandle_t xQueue; uint32_t ulVarToSend, ulValReceived; - // Create a queue to hold one uint32_t value. It is strongly - // recommended *not* to use xQueueOverwrite() on queues that can - // contain more than one value, and doing so will trigger an assertion - // if configASSERT() is defined. - xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + // Create a queue to hold one uint32_t value. It is strongly + // recommended *not* to use xQueueOverwrite() on queues that can + // contain more than one value, and doing so will trigger an assertion + // if configASSERT() is defined. + xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); - // Write the value 10 to the queue using xQueueOverwrite(). - ulVarToSend = 10; - xQueueOverwrite( xQueue, &ulVarToSend ); + // Write the value 10 to the queue using xQueueOverwrite(). + ulVarToSend = 10; + xQueueOverwrite( xQueue, &ulVarToSend ); - // Peeking the queue should now return 10, but leave the value 10 in - // the queue. A block time of zero is used as it is known that the - // queue holds a value. - ulValReceived = 0; - xQueuePeek( xQueue, &ulValReceived, 0 ); + // Peeking the queue should now return 10, but leave the value 10 in + // the queue. A block time of zero is used as it is known that the + // queue holds a value. + ulValReceived = 0; + xQueuePeek( xQueue, &ulValReceived, 0 ); - if( ulValReceived != 10 ) - { - // Error unless the item was removed by a different task. - } + if( ulValReceived != 10 ) + { + // Error unless the item was removed by a different task. + } - // The queue is still full. Use xQueueOverwrite() to overwrite the - // value held in the queue with 100. - ulVarToSend = 100; - xQueueOverwrite( xQueue, &ulVarToSend ); + // The queue is still full. Use xQueueOverwrite() to overwrite the + // value held in the queue with 100. + ulVarToSend = 100; + xQueueOverwrite( xQueue, &ulVarToSend ); - // This time read from the queue, leaving the queue empty once more. - // A block time of 0 is used again. - xQueueReceive( xQueue, &ulValReceived, 0 ); + // This time read from the queue, leaving the queue empty once more. + // A block time of 0 is used again. + xQueueReceive( xQueue, &ulValReceived, 0 ); - // The value read should be the last value written, even though the - // queue was already full when the value was written. - if( ulValReceived != 100 ) - { - // Error! - } + // The value read should be the last value written, even though the + // queue was already full when the value was written. + if( ulValReceived != 100 ) + { + // Error! + } - // ... + // ... } * \defgroup xQueueOverwrite xQueueOverwrite @@ -566,11 +566,11 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueGenericSend(
-									QueueHandle_t xQueue,
-									const void * pvItemToQueue,
-									TickType_t xTicksToWait
-									BaseType_t xCopyPosition
-								);
+                                    QueueHandle_t xQueue,
+                                    const void * pvItemToQueue,
+                                    TickType_t xTicksToWait
+                                    BaseType_t xCopyPosition
+                                );
  * 
* * It is preferred that the macros xQueueSend(), xQueueSendToFront() and @@ -603,8 +603,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -614,34 +614,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -653,10 +653,10 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ * queue. h *
  BaseType_t xQueuePeek(
-							 QueueHandle_t xQueue,
-							 void * const pvBuffer,
-							 TickType_t xTicksToWait
-						 );
+ QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait + ); * * Receive an item from a queue without removing the item from the queue. * The item is received by copy so a buffer of adequate size must be @@ -678,7 +678,7 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ * * @param xTicksToWait The maximum amount of time the task should block * waiting for an item to receive should the queue be empty at the time - * of the call. The time is defined in tick periods so the constant + * of the call. The time is defined in tick periods so the constant * portTICK_PERIOD_MS should be used to convert to real time if this is required. * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue * is empty. @@ -690,8 +690,8 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  QueueHandle_t xQueue;
@@ -701,22 +701,22 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ
  {
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue == 0 )
-	{
-		// Failed to create the queue.
-	}
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    if( xQueue == 0 )
+    {
+        // Failed to create the queue.
+    }
 
-	// ...
+    // ...
 
-	// Send a pointer to a struct AMessage object.  Don't block if the
-	// queue is already full.
-	pxMessage = & xMessage;
-	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    // Send a pointer to a struct AMessage object.  Don't block if the
+    // queue is already full.
+    pxMessage = & xMessage;
+    xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
 
  // Task to peek the data from the queue.
@@ -724,18 +724,18 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ
  {
  struct AMessage *pxRxedMessage;
 
-	if( xQueue != 0 )
-	{
-		// Peek a message on the created queue.  Block for 10 ticks if a
-		// message is not immediately available.
-		if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
-		{
-			// pcRxedMessage now points to the struct AMessage variable posted
-			// by vATask, but the item still remains on the queue.
-		}
-	}
+    if( xQueue != 0 )
+    {
+        // Peek a message on the created queue.  Block for 10 ticks if a
+        // message is not immediately available.
+        if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+        {
+            // pcRxedMessage now points to the struct AMessage variable posted
+            // by vATask, but the item still remains on the queue.
+        }
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueuePeek xQueuePeek @@ -747,9 +747,9 @@ BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t x * queue. h *
  BaseType_t xQueuePeekFromISR(
-									QueueHandle_t xQueue,
-									void *pvBuffer,
-								);
+ QueueHandle_t xQueue, + void *pvBuffer, + ); * * A version of xQueuePeek() that can be called from an interrupt service * routine (ISR). @@ -780,10 +780,10 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV * queue. h *
  BaseType_t xQueueReceive(
-								 QueueHandle_t xQueue,
-								 void *pvBuffer,
-								 TickType_t xTicksToWait
-							);
+ QueueHandle_t xQueue, + void *pvBuffer, + TickType_t xTicksToWait + ); * * Receive an item from a queue. The item is received by copy so a buffer of * adequate size must be provided. The number of bytes copied into the buffer @@ -802,7 +802,7 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV * * @param xTicksToWait The maximum amount of time the task should block * waiting for an item to receive should the queue be empty at the time - * of the call. xQueueReceive() will return immediately if xTicksToWait + * of the call. xQueueReceive() will return immediately if xTicksToWait * is zero and the queue is empty. The time is defined in tick periods so the * constant portTICK_PERIOD_MS should be used to convert to real time if this is * required. @@ -814,8 +814,8 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  QueueHandle_t xQueue;
@@ -825,22 +825,22 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV
  {
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue == 0 )
-	{
-		// Failed to create the queue.
-	}
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    if( xQueue == 0 )
+    {
+        // Failed to create the queue.
+    }
 
-	// ...
+    // ...
 
-	// Send a pointer to a struct AMessage object.  Don't block if the
-	// queue is already full.
-	pxMessage = & xMessage;
-	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    // Send a pointer to a struct AMessage object.  Don't block if the
+    // queue is already full.
+    pxMessage = & xMessage;
+    xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
 
  // Task to receive from the queue.
@@ -848,18 +848,18 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV
  {
  struct AMessage *pxRxedMessage;
 
-	if( xQueue != 0 )
-	{
-		// Receive a message on the created queue.  Block for 10 ticks if a
-		// message is not immediately available.
-		if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
-		{
-			// pcRxedMessage now points to the struct AMessage variable posted
-			// by vATask.
-		}
-	}
+    if( xQueue != 0 )
+    {
+        // Receive a message on the created queue.  Block for 10 ticks if a
+        // message is not immediately available.
+        if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+        {
+            // pcRxedMessage now points to the struct AMessage variable posted
+            // by vATask.
+        }
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueReceive xQueueReceive @@ -917,10 +917,10 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * queue. h *
  BaseType_t xQueueSendToFrontFromISR(
-										 QueueHandle_t xQueue,
-										 const void *pvItemToQueue,
-										 BaseType_t *pxHigherPriorityTaskWoken
-									  );
+                                         QueueHandle_t xQueue,
+                                         const void *pvItemToQueue,
+                                         BaseType_t *pxHigherPriorityTaskWoken
+                                      );
  
* * This is a macro that calls xQueueGenericSendFromISR(). @@ -956,25 +956,25 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; char cIn; BaseType_t xHigherPrioritTaskWoken; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWoken = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post the byte. - xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + // Post the byte. + xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. - if( xHigherPriorityTaskWoken ) - { - taskYIELD (); - } + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + taskYIELD (); + } } * @@ -988,10 +988,10 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * queue. h *
  BaseType_t xQueueSendToBackFromISR(
-										 QueueHandle_t xQueue,
-										 const void *pvItemToQueue,
-										 BaseType_t *pxHigherPriorityTaskWoken
-									  );
+                                         QueueHandle_t xQueue,
+                                         const void *pvItemToQueue,
+                                         BaseType_t *pxHigherPriorityTaskWoken
+                                      );
  
* * This is a macro that calls xQueueGenericSendFromISR(). @@ -1027,25 +1027,25 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; char cIn; BaseType_t xHigherPriorityTaskWoken; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWoken = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post the byte. - xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + // Post the byte. + xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. - if( xHigherPriorityTaskWoken ) - { - taskYIELD (); - } + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + taskYIELD (); + } } * @@ -1058,10 +1058,10 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * queue. h *
  BaseType_t xQueueOverwriteFromISR(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue,
-							  BaseType_t *pxHigherPriorityTaskWoken
-						 );
+                              QueueHandle_t xQueue,
+                              const void * pvItemToQueue,
+                              BaseType_t *pxHigherPriorityTaskWoken
+                         );
  * 
* * A version of xQueueOverwrite() that can be used in an interrupt service @@ -1099,11 +1099,11 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; void vFunction( void *pvParameters ) { - // Create a queue to hold one uint32_t value. It is strongly - // recommended *not* to use xQueueOverwriteFromISR() on queues that can - // contain more than one value, and doing so will trigger an assertion - // if configASSERT() is defined. - xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + // Create a queue to hold one uint32_t value. It is strongly + // recommended *not* to use xQueueOverwriteFromISR() on queues that can + // contain more than one value, and doing so will trigger an assertion + // if configASSERT() is defined. + xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); } void vAnInterruptHandler( void ) @@ -1112,28 +1112,28 @@ void vAnInterruptHandler( void ) BaseType_t xHigherPriorityTaskWoken = pdFALSE; uint32_t ulVarToSend, ulValReceived; - // Write the value 10 to the queue using xQueueOverwriteFromISR(). - ulVarToSend = 10; - xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + // Write the value 10 to the queue using xQueueOverwriteFromISR(). + ulVarToSend = 10; + xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); - // The queue is full, but calling xQueueOverwriteFromISR() again will still - // pass because the value held in the queue will be overwritten with the - // new value. - ulVarToSend = 100; - xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + // The queue is full, but calling xQueueOverwriteFromISR() again will still + // pass because the value held in the queue will be overwritten with the + // new value. + ulVarToSend = 100; + xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); - // Reading from the queue will now return 100. + // Reading from the queue will now return 100. - // ... + // ... - if( xHigherPrioritytaskWoken == pdTRUE ) - { - // Writing to the queue caused a task to unblock and the unblocked task - // has a priority higher than or equal to the priority of the currently - // executing task (the task this interrupt interrupted). Perform a context - // switch so this interrupt returns directly to the unblocked task. - portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. - } + if( xHigherPrioritytaskWoken == pdTRUE ) + { + // Writing to the queue caused a task to unblock and the unblocked task + // has a priority higher than or equal to the priority of the currently + // executing task (the task this interrupt interrupted). Perform a context + // switch so this interrupt returns directly to the unblocked task. + portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. + } } * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR @@ -1145,10 +1145,10 @@ uint32_t ulVarToSend, ulValReceived; * queue. h *
  BaseType_t xQueueSendFromISR(
-									 QueueHandle_t xQueue,
-									 const void *pvItemToQueue,
-									 BaseType_t *pxHigherPriorityTaskWoken
-								);
+                                     QueueHandle_t xQueue,
+                                     const void *pvItemToQueue,
+                                     BaseType_t *pxHigherPriorityTaskWoken
+                                );
  
* * This is a macro that calls xQueueGenericSendFromISR(). It is included @@ -1187,26 +1187,26 @@ uint32_t ulVarToSend, ulValReceived; char cIn; BaseType_t xHigherPriorityTaskWoken; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWoken = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post the byte. - xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + // Post the byte. + xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. - if( xHigherPriorityTaskWoken ) - { - // Actual macro used here is port specific. - portYIELD_FROM_ISR (); - } + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + // Actual macro used here is port specific. + portYIELD_FROM_ISR (); + } } * @@ -1219,11 +1219,11 @@ uint32_t ulVarToSend, ulValReceived; * queue. h *
  BaseType_t xQueueGenericSendFromISR(
-										   QueueHandle_t		xQueue,
-										   const	void	*pvItemToQueue,
-										   BaseType_t	*pxHigherPriorityTaskWoken,
-										   BaseType_t	xCopyPosition
-									   );
+                                           QueueHandle_t        xQueue,
+                                           const    void    *pvItemToQueue,
+                                           BaseType_t   *pxHigherPriorityTaskWoken,
+                                           BaseType_t   xCopyPosition
+                                       );
  
* * It is preferred that the macros xQueueSendFromISR(), @@ -1266,26 +1266,26 @@ uint32_t ulVarToSend, ulValReceived; char cIn; BaseType_t xHigherPriorityTaskWokenByPost; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWokenByPost = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWokenByPost = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post each byte. - xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); + // Post each byte. + xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. Note that the - // name of the yield function required is port specific. - if( xHigherPriorityTaskWokenByPost ) - { - taskYIELD_YIELD_FROM_ISR(); - } + // Now the buffer is empty we can switch context if necessary. Note that the + // name of the yield function required is port specific. + if( xHigherPriorityTaskWokenByPost ) + { + taskYIELD_YIELD_FROM_ISR(); + } } * @@ -1299,10 +1299,10 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherP * queue. h *
  BaseType_t xQueueReceiveFromISR(
-									   QueueHandle_t	xQueue,
-									   void	*pvBuffer,
-									   BaseType_t *pxTaskWoken
-								   );
+                                       QueueHandle_t    xQueue,
+                                       void *pvBuffer,
+                                       BaseType_t *pxTaskWoken
+                                   );
  * 
* * Receive an item from a queue. It is safe to use this function from within an @@ -1333,27 +1333,27 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherP char cValueToPost; const TickType_t xTicksToWait = ( TickType_t )0xff; - // Create a queue capable of containing 10 characters. - xQueue = xQueueCreate( 10, sizeof( char ) ); - if( xQueue == 0 ) - { - // Failed to create the queue. - } + // Create a queue capable of containing 10 characters. + xQueue = xQueueCreate( 10, sizeof( char ) ); + if( xQueue == 0 ) + { + // Failed to create the queue. + } - // ... + // ... - // Post some characters that will be used within an ISR. If the queue - // is full then this task will block for xTicksToWait ticks. - cValueToPost = 'a'; - xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); - cValueToPost = 'b'; - xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + // Post some characters that will be used within an ISR. If the queue + // is full then this task will block for xTicksToWait ticks. + cValueToPost = 'a'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + cValueToPost = 'b'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); - // ... keep posting characters ... this task may block when the queue - // becomes full. + // ... keep posting characters ... this task may block when the queue + // becomes full. - cValueToPost = 'c'; - xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + cValueToPost = 'c'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); } // ISR that outputs all the characters received on the queue. @@ -1362,21 +1362,21 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherP BaseType_t xTaskWokenByReceive = pdFALSE; char cRxedChar; - while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) - { - // A character was received. Output the character now. - vOutputCharacter( cRxedChar ); + while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) + { + // A character was received. Output the character now. + vOutputCharacter( cRxedChar ); - // If removing the character from the queue woke the task that was - // posting onto the queue cTaskWokenByReceive will have been set to - // pdTRUE. No matter how many times this loop iterates only one - // task will be woken. - } + // If removing the character from the queue woke the task that was + // posting onto the queue cTaskWokenByReceive will have been set to + // pdTRUE. No matter how many times this loop iterates only one + // task will be woken. + } - if( cTaskWokenByPost != ( char ) pdFALSE; - { - taskYIELD (); - } + if( cTaskWokenByPost != ( char ) pdFALSE; + { + taskYIELD (); + } } * \defgroup xQueueReceiveFromISR xQueueReceiveFromISR @@ -1455,7 +1455,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * preferably in ROM/Flash), not on the stack. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ #endif /* @@ -1469,7 +1469,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * @param xQueue The handle of the queue being removed from the registry. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; #endif /* @@ -1484,7 +1484,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * returned. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) - const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ #endif /* @@ -1493,7 +1493,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * RTOS objects that use the queue structure as their base. */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; #endif /* @@ -1502,7 +1502,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * RTOS objects that use the queue structure as their base. */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; #endif /* diff --git a/components/bl602/freertos_riscv/config/semphr.h b/components/bl602/freertos_riscv/config/semphr.h index 2c106eac..db258aef 100644 --- a/components/bl602/freertos_riscv/config/semphr.h +++ b/components/bl602/freertos_riscv/config/semphr.h @@ -29,16 +29,16 @@ #define SEMAPHORE_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include semphr.h" + #error "include FreeRTOS.h" must appear in source files before "include semphr.h" #endif #include "queue.h" typedef QueueHandle_t SemaphoreHandle_t; -#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) -#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) -#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) +#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) +#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) +#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) /** @@ -91,14 +91,14 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define vSemaphoreCreateBinary( xSemaphore ) \ - { \ - ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ - if( ( xSemaphore ) != NULL ) \ - { \ - ( void ) xSemaphoreGive( ( xSemaphore ) ); \ - } \ - } + #define vSemaphoreCreateBinary( xSemaphore ) \ + { \ + ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ + if( ( xSemaphore ) != NULL ) \ + { \ + ( void ) xSemaphoreGive( ( xSemaphore ) ); \ + } \ + } #endif /** @@ -159,7 +159,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) + #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) #endif /** @@ -218,7 +218,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) + #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) #endif /* configSUPPORT_STATIC_ALLOCATION */ /** @@ -286,7 +286,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \defgroup xSemaphoreTake xSemaphoreTake * \ingroup Semaphores */ -#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) +#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) /** * semphr. h @@ -380,7 +380,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) + #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) #endif /** @@ -444,7 +444,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \defgroup xSemaphoreGive xSemaphoreGive * \ingroup Semaphores */ -#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) +#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) /** * semphr. h @@ -498,24 +498,24 @@ typedef QueueHandle_t SemaphoreHandle_t; // ... // For some reason due to the nature of the code further calls to - // xSemaphoreTakeRecursive() are made on the same mutex. In real - // code these would not be just sequential calls as this would make - // no sense. Instead the calls are likely to be buried inside - // a more complex call structure. + // xSemaphoreTakeRecursive() are made on the same mutex. In real + // code these would not be just sequential calls as this would make + // no sense. Instead the calls are likely to be buried inside + // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be - // available to another task until it has also been given back - // three times. Again it is unlikely that real code would have - // these calls sequentially, it would be more likely that the calls - // to xSemaphoreGiveRecursive() would be called as a call stack - // unwound. This is just for demonstrative purposes. + // available to another task until it has also been given back + // three times. Again it is unlikely that real code would have + // these calls sequentially, it would be more likely that the calls + // to xSemaphoreGiveRecursive() would be called as a call stack + // unwound. This is just for demonstrative purposes. + xSemaphoreGiveRecursive( xMutex ); + xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); - xSemaphoreGiveRecursive( xMutex ); - xSemaphoreGiveRecursive( xMutex ); - // Now the mutex can be taken by other tasks. + // Now the mutex can be taken by other tasks. } else { @@ -529,7 +529,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) + #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) #endif /** @@ -562,7 +562,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * Example usage:
  \#define LONG_TIME 0xffff
- \#define TICKS_TO_WAIT	10
+ \#define TICKS_TO_WAIT 10
  SemaphoreHandle_t xSemaphore = NULL;
 
  // Repetitive task.
@@ -583,7 +583,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
             // We have finished our task.  Return to the top of the loop where
             // we will block on the semaphore until it is time to execute
             // again.  Note when using the semaphore for synchronisation with an
-			// ISR in this manner there is no need to 'give' the semaphore back.
+            // ISR in this manner there is no need to 'give' the semaphore back.
         }
     }
  }
@@ -599,7 +599,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
     // ... Do other time functions.
 
     // Is it time for vATask () to run?
-	xHigherPriorityTaskWoken = pdFALSE;
+    xHigherPriorityTaskWoken = pdFALSE;
     ucLocalTickCount++;
     if( ucLocalTickCount >= TICKS_TO_WAIT )
     {
@@ -621,7 +621,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR
  * \ingroup Semaphores
  */
-#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken )	xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) )
+#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken )  xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) )
 
 /**
  * semphr. h
@@ -655,7 +655,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * @return pdTRUE if the semaphore was successfully taken, otherwise
  * pdFALSE
  */
-#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken )	xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) )
+#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken )  xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) )
 
 /**
  * semphr. h
@@ -713,7 +713,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )
+    #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )
 #endif
 
 /**
@@ -774,7 +774,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
  #if( configSUPPORT_STATIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) )
+    #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) )
 #endif /* configSUPPORT_STATIC_ALLOCATION */
 
 
@@ -842,7 +842,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) )
-	#define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
+    #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
 #endif
 
 /**
@@ -915,7 +915,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) )
-	#define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore )
+    #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore )
 #endif /* configSUPPORT_STATIC_ALLOCATION */
 
 /**
@@ -995,7 +995,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )
+    #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )
 #endif
 
 /**
@@ -1080,7 +1080,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) )
+    #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) )
 #endif /* configSUPPORT_STATIC_ALLOCATION */
 
 /**
diff --git a/components/bl602/freertos_riscv/config/stack_macros.h b/components/bl602/freertos_riscv/config/stack_macros.h
index 18406bbf..60a95370 100644
--- a/components/bl602/freertos_riscv/config/stack_macros.h
+++ b/components/bl602/freertos_riscv/config/stack_macros.h
@@ -46,81 +46,81 @@
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) )
 
-	/* Only the current stack state is to be checked. */
-	#define taskCHECK_FOR_STACK_OVERFLOW()																\
-	{																									\
-		/* Is the currently saved stack pointer within the stack limit? */								\
-		if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack )										\
-		{																								\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
-		}																								\
-	}
+    /* Only the current stack state is to be checked. */
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                              \
+    {                                                                                                   \
+        /* Is the currently saved stack pointer within the stack limit? */                              \
+        if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack )                                       \
+        {                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );   \
+        }                                                                                               \
+    }
 
 #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
 /*-----------------------------------------------------------*/
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) )
 
-	/* Only the current stack state is to be checked. */
-	#define taskCHECK_FOR_STACK_OVERFLOW()																\
-	{																									\
-																										\
-		/* Is the currently saved stack pointer within the stack limit? */								\
-		if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack )									\
-		{																								\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
-		}																								\
-	}
+    /* Only the current stack state is to be checked. */
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                              \
+    {                                                                                                   \
+                                                                                                        \
+        /* Is the currently saved stack pointer within the stack limit? */                              \
+        if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack )                                  \
+        {                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );   \
+        }                                                                                               \
+    }
 
 #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
 /*-----------------------------------------------------------*/
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) )
 
-	#define taskCHECK_FOR_STACK_OVERFLOW()																\
-	{																									\
-		const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack;							\
-		const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5;											\
-																										\
-		if( ( pulStack[ 0 ] != ulCheckValue ) ||														\
-			( pulStack[ 1 ] != ulCheckValue ) ||														\
-			( pulStack[ 2 ] != ulCheckValue ) ||														\
-			( pulStack[ 3 ] != ulCheckValue ) )															\
-		{																								\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
-		}																								\
-	}
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                              \
+    {                                                                                                   \
+        const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack;                         \
+        const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5;                                          \
+                                                                                                        \
+        if( ( pulStack[ 0 ] != ulCheckValue ) ||                                                        \
+            ( pulStack[ 1 ] != ulCheckValue ) ||                                                        \
+            ( pulStack[ 2 ] != ulCheckValue ) ||                                                        \
+            ( pulStack[ 3 ] != ulCheckValue ) )                                                         \
+        {                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );   \
+        }                                                                                               \
+    }
 
 #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
 /*-----------------------------------------------------------*/
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) )
 
-	#define taskCHECK_FOR_STACK_OVERFLOW()																								\
-	{																																	\
-	int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack;																		\
-	static const uint8_t ucExpectedStackBytes[] = {	tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE };	\
-																																		\
-																																		\
-		pcEndOfStack -= sizeof( ucExpectedStackBytes );																					\
-																																		\
-		/* Has the extremity of the task stack ever been written over? */																\
-		if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 )					\
-		{																																\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );									\
-		}																																\
-	}
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                                                              \
+    {                                                                                                                                   \
+    int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack;                                                                     \
+    static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE };   \
+                                                                                                                                        \
+                                                                                                                                        \
+        pcEndOfStack -= sizeof( ucExpectedStackBytes );                                                                                 \
+                                                                                                                                        \
+        /* Has the extremity of the task stack ever been written over? */                                                               \
+        if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 )                   \
+        {                                                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );                                   \
+        }                                                                                                                               \
+    }
 
 #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
 /*-----------------------------------------------------------*/
 
 /* Remove stack overflow macro if not being used. */
 #ifndef taskCHECK_FOR_STACK_OVERFLOW
-	#define taskCHECK_FOR_STACK_OVERFLOW()
+    #define taskCHECK_FOR_STACK_OVERFLOW()
 #endif
 
 
diff --git a/components/bl602/freertos_riscv/config/stream_buffer.h b/components/bl602/freertos_riscv/config/stream_buffer.h
index 0f00119e..2dd7e7fe 100644
--- a/components/bl602/freertos_riscv/config/stream_buffer.h
+++ b/components/bl602/freertos_riscv/config/stream_buffer.h
@@ -306,9 +306,9 @@ const TickType_t x100ms = pdMS_TO_TICKS( 100 );
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
-						  const void *pvTxData,
-						  size_t xDataLengthBytes,
-						  TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+                          const void *pvTxData,
+                          size_t xDataLengthBytes,
+                          TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -407,9 +407,9 @@ BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
-								 const void *pvTxData,
-								 size_t xDataLengthBytes,
-								 BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+                                 const void *pvTxData,
+                                 size_t xDataLengthBytes,
+                                 BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -496,9 +496,9 @@ const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
-							 void *pvRxData,
-							 size_t xBufferLengthBytes,
-							 TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+                             void *pvRxData,
+                             size_t xBufferLengthBytes,
+                             TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -582,9 +582,9 @@ BaseType_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
-									void *pvRxData,
-									size_t xBufferLengthBytes,
-									BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+                                    void *pvRxData,
+                                    size_t xBufferLengthBytes,
+                                    BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -831,25 +831,25 @@ BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuf
 
 /* Functions below here are not part of the public API. */
 StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,
-												 size_t xTriggerLevelBytes,
-												 BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION;
+                                                 size_t xTriggerLevelBytes,
+                                                 BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION;
 
 StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes,
-													   size_t xTriggerLevelBytes,
-													   BaseType_t xIsMessageBuffer,
-													   uint8_t * const pucStreamBufferStorageArea,
-													   StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION;
+                                                       size_t xTriggerLevelBytes,
+                                                       BaseType_t xIsMessageBuffer,
+                                                       uint8_t * const pucStreamBufferStorageArea,
+                                                       StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION;
 
 size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
 
 #if( configUSE_TRACE_FACILITY == 1 )
-	void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION;
-	UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
-	uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
+    void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION;
+    UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
+    uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
 #endif
 
 #if defined( __cplusplus )
 }
 #endif
 
-#endif	/* !defined( STREAM_BUFFER_H ) */
+#endif  /* !defined( STREAM_BUFFER_H ) */
diff --git a/components/bl602/freertos_riscv/config/task.h b/components/bl602/freertos_riscv/config/task.h
index 37305461..eff6b9e2 100644
--- a/components/bl602/freertos_riscv/config/task.h
+++ b/components/bl602/freertos_riscv/config/task.h
@@ -30,7 +30,7 @@
 #define INC_TASK_H
 
 #ifndef INC_FREERTOS_H
-	#error "include FreeRTOS.h must appear in source files before include task.h"
+    #error "include FreeRTOS.h must appear in source files before include task.h"
 #endif
 
 #include "list.h"
@@ -50,11 +50,11 @@ extern "C" {
 
 /* MPU region parameters passed in ulParameters
  * of MemoryRegion_t struct. */
-#define tskMPU_REGION_READ_ONLY			( 1UL << 0UL )
-#define tskMPU_REGION_READ_WRITE		( 1UL << 1UL )
-#define tskMPU_REGION_EXECUTE_NEVER		( 1UL << 2UL )
-#define tskMPU_REGION_NORMAL_MEMORY		( 1UL << 3UL )
-#define tskMPU_REGION_DEVICE_MEMORY		( 1UL << 4UL )
+#define tskMPU_REGION_READ_ONLY         ( 1UL << 0UL )
+#define tskMPU_REGION_READ_WRITE        ( 1UL << 1UL )
+#define tskMPU_REGION_EXECUTE_NEVER     ( 1UL << 2UL )
+#define tskMPU_REGION_NORMAL_MEMORY     ( 1UL << 3UL )
+#define tskMPU_REGION_DEVICE_MEMORY     ( 1UL << 4UL )
 
 /**
  * task. h
@@ -78,22 +78,22 @@ typedef BaseType_t (*TaskHookFunction_t)( void * );
 /* Task states returned by eTaskGetState. */
 typedef enum
 {
-	eRunning = 0,	/* A task is querying the state of itself, so must be running. */
-	eReady,			/* The task being queried is in a read or pending ready list. */
-	eBlocked,		/* The task being queried is in the Blocked state. */
-	eSuspended,		/* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
-	eDeleted,		/* The task being queried has been deleted, but its TCB has not yet been freed. */
-	eInvalid		/* Used as an 'invalid state' value. */
+    eRunning = 0,   /* A task is querying the state of itself, so must be running. */
+    eReady,         /* The task being queried is in a read or pending ready list. */
+    eBlocked,       /* The task being queried is in the Blocked state. */
+    eSuspended,     /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
+    eDeleted,       /* The task being queried has been deleted, but its TCB has not yet been freed. */
+    eInvalid        /* Used as an 'invalid state' value. */
 } eTaskState;
 
 /* Actions that can be performed when vTaskNotify() is called. */
 typedef enum
 {
-	eNoAction = 0,				/* Notify the task without updating its notify value. */
-	eSetBits,					/* Set bits in the task's notification value. */
-	eIncrement,					/* Increment the task's notification value. */
-	eSetValueWithOverwrite,		/* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */
-	eSetValueWithoutOverwrite	/* Set the task's notification value if the previous value has been read by the task. */
+    eNoAction = 0,              /* Notify the task without updating its notify value. */
+    eSetBits,                   /* Set bits in the task's notification value. */
+    eIncrement,                 /* Increment the task's notification value. */
+    eSetValueWithOverwrite,     /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */
+    eSetValueWithoutOverwrite   /* Set the task's notification value if the previous value has been read by the task. */
 } eNotifyAction;
 
 /*
@@ -101,8 +101,8 @@ typedef enum
  */
 typedef struct xTIME_OUT
 {
-	BaseType_t xOverflowCount;
-	TickType_t xTimeOnEntering;
+    BaseType_t xOverflowCount;
+    TickType_t xTimeOnEntering;
 } TimeOut_t;
 
 /*
@@ -110,9 +110,9 @@ typedef struct xTIME_OUT
  */
 typedef struct xMEMORY_REGION
 {
-	void *pvBaseAddress;
-	uint32_t ulLengthInBytes;
-	uint32_t ulParameters;
+    void *pvBaseAddress;
+    uint32_t ulLengthInBytes;
+    uint32_t ulParameters;
 } MemoryRegion_t;
 
 /*
@@ -120,39 +120,39 @@ typedef struct xMEMORY_REGION
  */
 typedef struct xTASK_PARAMETERS
 {
-	TaskFunction_t pvTaskCode;
-	const char * const pcName;	/*lint !e971 Unqualified char types are allowed for strings and single characters only. */
-	configSTACK_DEPTH_TYPE usStackDepth;
-	void *pvParameters;
-	UBaseType_t uxPriority;
-	StackType_t *puxStackBuffer;
-	MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
-	#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
-		StaticTask_t * const pxTaskBuffer;
-	#endif
+    TaskFunction_t pvTaskCode;
+    const char * const pcName;  /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+    configSTACK_DEPTH_TYPE usStackDepth;
+    void *pvParameters;
+    UBaseType_t uxPriority;
+    StackType_t *puxStackBuffer;
+    MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
+    #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
+        StaticTask_t * const pxTaskBuffer;
+    #endif
 } TaskParameters_t;
 
 /* Used with the uxTaskGetSystemState() function to return the state of each task
 in the system. */
 typedef struct xTASK_STATUS
 {
-	TaskHandle_t xHandle;			/* The handle of the task to which the rest of the information in the structure relates. */
-	const char *pcTaskName;			/* A pointer to the task's name.  This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
-	UBaseType_t xTaskNumber;		/* A number unique to the task. */
-	eTaskState eCurrentState;		/* The state in which the task existed when the structure was populated. */
-	UBaseType_t uxCurrentPriority;	/* The priority at which the task was running (may be inherited) when the structure was populated. */
-	UBaseType_t uxBasePriority;		/* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex.  Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */
-	uint32_t ulRunTimeCounter;		/* The total run time allocated to the task so far, as defined by the run time stats clock.  See http://www.freertos.org/rtos-run-time-stats.html.  Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */
-	StackType_t *pxStackBase;		/* Points to the lowest address of the task's stack area. */
-	configSTACK_DEPTH_TYPE usStackHighWaterMark;	/* The minimum amount of stack space that has remained for the task since the task was created.  The closer this value is to zero the closer the task has come to overflowing its stack. */
+    TaskHandle_t xHandle;           /* The handle of the task to which the rest of the information in the structure relates. */
+    const char *pcTaskName;         /* A pointer to the task's name.  This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+    UBaseType_t xTaskNumber;        /* A number unique to the task. */
+    eTaskState eCurrentState;       /* The state in which the task existed when the structure was populated. */
+    UBaseType_t uxCurrentPriority;  /* The priority at which the task was running (may be inherited) when the structure was populated. */
+    UBaseType_t uxBasePriority;     /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex.  Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */
+    uint32_t ulRunTimeCounter;      /* The total run time allocated to the task so far, as defined by the run time stats clock.  See http://www.freertos.org/rtos-run-time-stats.html.  Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */
+    StackType_t *pxStackBase;       /* Points to the lowest address of the task's stack area. */
+    configSTACK_DEPTH_TYPE usStackHighWaterMark;    /* The minimum amount of stack space that has remained for the task since the task was created.  The closer this value is to zero the closer the task has come to overflowing its stack. */
 } TaskStatus_t;
 
 /* Possible return values for eTaskConfirmSleepModeStatus(). */
 typedef enum
 {
-	eAbortSleep = 0,		/* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */
-	eStandardSleep,			/* Enter a sleep mode that will not last any longer than the expected idle time. */
-	eNoTasksWaitingTimeout	/* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */
+    eAbortSleep = 0,        /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */
+    eStandardSleep,         /* Enter a sleep mode that will not last any longer than the expected idle time. */
+    eNoTasksWaitingTimeout  /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */
 } eSleepModeStatus;
 
 /**
@@ -160,7 +160,7 @@ typedef enum
  *
  * \ingroup TaskUtils
  */
-#define tskIDLE_PRIORITY			( ( UBaseType_t ) 0U )
+#define tskIDLE_PRIORITY            ( ( UBaseType_t ) 0U )
 
 /**
  * task. h
@@ -170,7 +170,7 @@ typedef enum
  * \defgroup taskYIELD taskYIELD
  * \ingroup SchedulerControl
  */
-#define taskYIELD()					portYIELD()
+#define taskYIELD()                 portYIELD()
 
 /**
  * task. h
@@ -184,7 +184,7 @@ typedef enum
  * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL
  * \ingroup SchedulerControl
  */
-#define taskENTER_CRITICAL()		portENTER_CRITICAL()
+#define taskENTER_CRITICAL()        portENTER_CRITICAL()
 #define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR()
 
 /**
@@ -199,7 +199,7 @@ typedef enum
  * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL
  * \ingroup SchedulerControl
  */
-#define taskEXIT_CRITICAL()			portEXIT_CRITICAL()
+#define taskEXIT_CRITICAL()         portEXIT_CRITICAL()
 #define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x )
 /**
  * task. h
@@ -209,7 +209,7 @@ typedef enum
  * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS
  * \ingroup SchedulerControl
  */
-#define taskDISABLE_INTERRUPTS()	portDISABLE_INTERRUPTS()
+#define taskDISABLE_INTERRUPTS()    portDISABLE_INTERRUPTS()
 
 /**
  * task. h
@@ -219,14 +219,14 @@ typedef enum
  * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS
  * \ingroup SchedulerControl
  */
-#define taskENABLE_INTERRUPTS()		portENABLE_INTERRUPTS()
+#define taskENABLE_INTERRUPTS()     portENABLE_INTERRUPTS()
 
 /* Definitions returned by xTaskGetSchedulerState().  taskSCHEDULER_SUSPENDED is
 0 to generate more optimal code when configASSERT() is defined as the constant
 is used in assert() statements. */
-#define taskSCHEDULER_SUSPENDED		( ( BaseType_t ) 0 )
-#define taskSCHEDULER_NOT_STARTED	( ( BaseType_t ) 1 )
-#define taskSCHEDULER_RUNNING		( ( BaseType_t ) 2 )
+#define taskSCHEDULER_SUSPENDED     ( ( BaseType_t ) 0 )
+#define taskSCHEDULER_NOT_STARTED   ( ( BaseType_t ) 1 )
+#define taskSCHEDULER_RUNNING       ( ( BaseType_t ) 2 )
 
 
 /*-----------------------------------------------------------
@@ -237,13 +237,13 @@ is used in assert() statements. */
  * task. h
  *
  BaseType_t xTaskCreate(
-							  TaskFunction_t pvTaskCode,
-							  const char * const pcName,
-							  configSTACK_DEPTH_TYPE usStackDepth,
-							  void *pvParameters,
-							  UBaseType_t uxPriority,
-							  TaskHandle_t *pvCreatedTask
-						  );
+ TaskFunction_t pvTaskCode, + const char * const pcName, + configSTACK_DEPTH_TYPE usStackDepth, + void *pvParameters, + UBaseType_t uxPriority, + TaskHandle_t *pvCreatedTask + );
* * Create a new task and add it to the list of tasks that are ready to run. * @@ -297,10 +297,10 @@ is used in assert() statements. */ // Task to be created. void vTaskCode( void * pvParameters ) { - for( ;; ) - { - // Task code goes here. - } + for( ;; ) + { + // Task code goes here. + } } // Function that creates a task. @@ -309,17 +309,17 @@ is used in assert() statements. */ static uint8_t ucParameterToPass; TaskHandle_t xHandle = NULL; - // Create the task, storing the handle. Note that the passed parameter ucParameterToPass - // must exist for the lifetime of the task, so in this case is declared static. If it was just an - // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time - // the new task attempts to access it. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); + // Create the task, storing the handle. Note that the passed parameter ucParameterToPass + // must exist for the lifetime of the task, so in this case is declared static. If it was just an + // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time + // the new task attempts to access it. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); configASSERT( xHandle ); - // Use the handle to delete the task. + // Use the handle to delete the task. if( xHandle != NULL ) { - vTaskDelete( xHandle ); + vTaskDelete( xHandle ); } } @@ -327,24 +327,24 @@ is used in assert() statements. */ * \ingroup Tasks */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; #endif /** * task. h *
  TaskHandle_t xTaskCreateStatic( TaskFunction_t pvTaskCode,
-								 const char * const pcName,
-								 uint32_t ulStackDepth,
-								 void *pvParameters,
-								 UBaseType_t uxPriority,
-								 StackType_t *pxStackBuffer,
-								 StaticTask_t *pxTaskBuffer );
+ const char * const pcName, + uint32_t ulStackDepth, + void *pvParameters, + UBaseType_t uxPriority, + StackType_t *pxStackBuffer, + StaticTask_t *pxTaskBuffer ); * * Create a new task and add it to the list of tasks that are ready to run. * @@ -443,13 +443,13 @@ is used in assert() statements. */ * \ingroup Tasks */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; #endif /* configSUPPORT_STATIC_ALLOCATION */ /** @@ -485,47 +485,47 @@ is used in assert() statements. */ // Create an TaskParameters_t structure that defines the task to be created. static const TaskParameters_t xCheckTaskParameters = { - vATask, // pvTaskCode - the function that implements the task. - "ATask", // pcName - just a text name for the task to assist debugging. - 100, // usStackDepth - the stack size DEFINED IN WORDS. - NULL, // pvParameters - passed into the task function as the function parameters. - ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. - cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + vATask, // pvTaskCode - the function that implements the task. + "ATask", // pcName - just a text name for the task to assist debugging. + 100, // usStackDepth - the stack size DEFINED IN WORDS. + NULL, // pvParameters - passed into the task function as the function parameters. + ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. - // xRegions - Allocate up to three separate memory regions for access by - // the task, with appropriate access permissions. Different processors have - // different memory alignment requirements - refer to the FreeRTOS documentation - // for full information. - { - // Base address Length Parameters - { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, - { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, - { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } - } + // xRegions - Allocate up to three separate memory regions for access by + // the task, with appropriate access permissions. Different processors have + // different memory alignment requirements - refer to the FreeRTOS documentation + // for full information. + { + // Base address Length Parameters + { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + } }; int main( void ) { TaskHandle_t xHandle; - // Create a task from the const structure defined above. The task handle - // is requested (the second parameter is not NULL) but in this case just for - // demonstration purposes as its not actually used. - xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + // Create a task from the const structure defined above. The task handle + // is requested (the second parameter is not NULL) but in this case just for + // demonstration purposes as its not actually used. + xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); - // Start the scheduler. - vTaskStartScheduler(); + // Start the scheduler. + vTaskStartScheduler(); - // Will only get here if there was insufficient memory to create the idle - // and/or timer task. - for( ;; ); + // Will only get here if there was insufficient memory to create the idle + // and/or timer task. + for( ;; ); } * \defgroup xTaskCreateRestricted xTaskCreateRestricted * \ingroup Tasks */ #if( portUSING_MPU_WRAPPERS == 1 ) - BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; #endif /** @@ -571,49 +571,49 @@ TaskHandle_t xHandle; static PRIVILEGED_DATA StaticTask_t xTaskBuffer; static const TaskParameters_t xCheckTaskParameters = { - vATask, // pvTaskCode - the function that implements the task. - "ATask", // pcName - just a text name for the task to assist debugging. - 100, // usStackDepth - the stack size DEFINED IN WORDS. - NULL, // pvParameters - passed into the task function as the function parameters. - ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. - cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + vATask, // pvTaskCode - the function that implements the task. + "ATask", // pcName - just a text name for the task to assist debugging. + 100, // usStackDepth - the stack size DEFINED IN WORDS. + NULL, // pvParameters - passed into the task function as the function parameters. + ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. - // xRegions - Allocate up to three separate memory regions for access by - // the task, with appropriate access permissions. Different processors have - // different memory alignment requirements - refer to the FreeRTOS documentation - // for full information. - { - // Base address Length Parameters - { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, - { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, - { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } - } + // xRegions - Allocate up to three separate memory regions for access by + // the task, with appropriate access permissions. Different processors have + // different memory alignment requirements - refer to the FreeRTOS documentation + // for full information. + { + // Base address Length Parameters + { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + } - &xTaskBuffer; // Holds the task's data structure. + &xTaskBuffer; // Holds the task's data structure. }; int main( void ) { TaskHandle_t xHandle; - // Create a task from the const structure defined above. The task handle - // is requested (the second parameter is not NULL) but in this case just for - // demonstration purposes as its not actually used. - xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + // Create a task from the const structure defined above. The task handle + // is requested (the second parameter is not NULL) but in this case just for + // demonstration purposes as its not actually used. + xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); - // Start the scheduler. - vTaskStartScheduler(); + // Start the scheduler. + vTaskStartScheduler(); - // Will only get here if there was insufficient memory to create the idle - // and/or timer task. - for( ;; ); + // Will only get here if there was insufficient memory to create the idle + // and/or timer task. + for( ;; ); } * \defgroup xTaskCreateRestrictedStatic xTaskCreateRestrictedStatic * \ingroup Tasks */ #if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; #endif /** @@ -638,25 +638,25 @@ TaskHandle_t xHandle; // unused so set to zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = { - // Base address Length Parameters - { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, - { 0, 0, 0 }, - { 0, 0, 0 } + // Base address Length Parameters + { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, + { 0, 0, 0 }, + { 0, 0, 0 } }; void vATask( void *pvParameters ) { - // This task was created such that it has access to certain regions of - // memory as defined by the MPU configuration. At some point it is - // desired that these MPU regions are replaced with that defined in the - // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() - // for this purpose. NULL is used as the task handle to indicate that this - // function should modify the MPU regions of the calling task. - vTaskAllocateMPURegions( NULL, xAltRegions ); + // This task was created such that it has access to certain regions of + // memory as defined by the MPU configuration. At some point it is + // desired that these MPU regions are replaced with that defined in the + // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() + // for this purpose. NULL is used as the task handle to indicate that this + // function should modify the MPU regions of the calling task. + vTaskAllocateMPURegions( NULL, xAltRegions ); - // Now the task can continue its function, but from this point on can only - // access its stack and the ucOneKByte array (unless any other statically - // defined or shared regions have been declared elsewhere). + // Now the task can continue its function, but from this point on can only + // access its stack and the ucOneKByte array (unless any other statically + // defined or shared regions have been declared elsewhere). } * \defgroup xTaskCreateRestricted xTaskCreateRestricted @@ -693,11 +693,11 @@ void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const p { TaskHandle_t xHandle; - // Create the task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create the task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // Use the handle to delete the task. - vTaskDelete( xHandle ); + // Use the handle to delete the task. + vTaskDelete( xHandle ); } * \defgroup vTaskDelete vTaskDelete @@ -744,12 +744,12 @@ void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; // Block for 500ms. const TickType_t xDelay = 500 / portTICK_PERIOD_MS; - for( ;; ) - { - // Simply toggle the LED every 500ms, blocking between each toggle. - vToggleLED(); - vTaskDelay( xDelay ); - } + for( ;; ) + { + // Simply toggle the LED every 500ms, blocking between each toggle. + vToggleLED(); + vTaskDelay( xDelay ); + } } * \defgroup vTaskDelay vTaskDelay @@ -800,15 +800,15 @@ void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; TickType_t xLastWakeTime; const TickType_t xFrequency = 10; - // Initialise the xLastWakeTime variable with the current time. - xLastWakeTime = xTaskGetTickCount (); - for( ;; ) - { - // Wait for the next cycle. - vTaskDelayUntil( &xLastWakeTime, xFrequency ); + // Initialise the xLastWakeTime variable with the current time. + xLastWakeTime = xTaskGetTickCount (); + for( ;; ) + { + // Wait for the next cycle. + vTaskDelayUntil( &xLastWakeTime, xFrequency ); - // Perform action here. - } + // Perform action here. + } } * \defgroup vTaskDelayUntil vTaskDelayUntil @@ -861,26 +861,26 @@ BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to obtain the priority of the created task. - // It was created with tskIDLE_PRIORITY, but may have changed - // it itself. - if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) - { - // The task has changed it's priority. - } + // Use the handle to obtain the priority of the created task. + // It was created with tskIDLE_PRIORITY, but may have changed + // it itself. + if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) + { + // The task has changed it's priority. + } - // ... + // ... - // Is our priority higher than the created task? - if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) - { - // Our priority (obtained using NULL handle) is higher. - } + // Is our priority higher than the created task? + if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) + { + // Our priority (obtained using NULL handle) is higher. + } } * \defgroup uxTaskPriorityGet uxTaskPriorityGet @@ -993,18 +993,18 @@ void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xG { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to raise the priority of the created task. - vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); + // Use the handle to raise the priority of the created task. + vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); - // ... + // ... - // Use a NULL handle to raise our priority to the same value. - vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); + // Use a NULL handle to raise our priority to the same value. + vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); } * \defgroup vTaskPrioritySet vTaskPrioritySet @@ -1035,27 +1035,27 @@ void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGE { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to suspend the created task. - vTaskSuspend( xHandle ); + // Use the handle to suspend the created task. + vTaskSuspend( xHandle ); - // ... + // ... - // The created task will not run during this period, unless - // another task calls vTaskResume( xHandle ). + // The created task will not run during this period, unless + // another task calls vTaskResume( xHandle ). - //... + //... - // Suspend ourselves. - vTaskSuspend( NULL ); + // Suspend ourselves. + vTaskSuspend( NULL ); - // We cannot get here unless another task calls vTaskResume - // with our handle as the parameter. + // We cannot get here unless another task calls vTaskResume + // with our handle as the parameter. } * \defgroup vTaskSuspend vTaskSuspend @@ -1084,27 +1084,27 @@ void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to suspend the created task. - vTaskSuspend( xHandle ); + // Use the handle to suspend the created task. + vTaskSuspend( xHandle ); - // ... + // ... - // The created task will not run during this period, unless - // another task calls vTaskResume( xHandle ). + // The created task will not run during this period, unless + // another task calls vTaskResume( xHandle ). - //... + //... - // Resume the suspended task ourselves. - vTaskResume( xHandle ); + // Resume the suspended task ourselves. + vTaskResume( xHandle ); - // The created task will once again get microcontroller processing - // time in accordance with its priority within the system. + // The created task will once again get microcontroller processing + // time in accordance with its priority within the system. } * \defgroup vTaskResume vTaskResume @@ -1159,13 +1159,13 @@ BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
  void vAFunction( void )
  {
-	 // Create at least one task before starting the kernel.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+     // Create at least one task before starting the kernel.
+     xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
 
-	 // Start the real time kernel with preemption.
-	 vTaskStartScheduler ();
+     // Start the real time kernel with preemption.
+     vTaskStartScheduler ();
 
-	 // Will not get here unless a task calls vTaskEndScheduler ()
+     // Will not get here unless a task calls vTaskEndScheduler ()
  }
    
* @@ -1201,27 +1201,27 @@ void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;
  void vTaskCode( void * pvParameters )
  {
-	 for( ;; )
-	 {
-		 // Task code goes here.
+     for( ;; )
+     {
+         // Task code goes here.
 
-		 // At some point we want to end the real time kernel processing
-		 // so call ...
-		 vTaskEndScheduler ();
-	 }
+         // At some point we want to end the real time kernel processing
+         // so call ...
+         vTaskEndScheduler ();
+     }
  }
 
  void vAFunction( void )
  {
-	 // Create at least one task before starting the kernel.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+     // Create at least one task before starting the kernel.
+     xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
 
-	 // Start the real time kernel with preemption.
-	 vTaskStartScheduler ();
+     // Start the real time kernel with preemption.
+     vTaskStartScheduler ();
 
-	 // Will only get here when the vTaskCode () task has called
-	 // vTaskEndScheduler ().  When we get here we are back to single task
-	 // execution.
+     // Will only get here when the vTaskCode () task has called
+     // vTaskEndScheduler ().  When we get here we are back to single task
+     // execution.
  }
    
* @@ -1249,31 +1249,31 @@ void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;
  void vTask1( void * pvParameters )
  {
-	 for( ;; )
-	 {
-		 // Task code goes here.
+     for( ;; )
+     {
+         // Task code goes here.
 
-		 // ...
+         // ...
 
-		 // At some point the task wants to perform a long operation during
-		 // which it does not want to get swapped out.  It cannot use
-		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
-		 // operation may cause interrupts to be missed - including the
-		 // ticks.
+         // At some point the task wants to perform a long operation during
+         // which it does not want to get swapped out.  It cannot use
+         // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+         // operation may cause interrupts to be missed - including the
+         // ticks.
 
-		 // Prevent the real time kernel swapping out the task.
-		 vTaskSuspendAll ();
+         // Prevent the real time kernel swapping out the task.
+         vTaskSuspendAll ();
 
-		 // Perform the operation here.  There is no need to use critical
-		 // sections as we have all the microcontroller processing time.
-		 // During this time interrupts will still operate and the kernel
-		 // tick count will be maintained.
+         // Perform the operation here.  There is no need to use critical
+         // sections as we have all the microcontroller processing time.
+         // During this time interrupts will still operate and the kernel
+         // tick count will be maintained.
 
-		 // ...
+         // ...
 
-		 // The operation is complete.  Restart the kernel.
-		 xTaskResumeAll ();
-	 }
+         // The operation is complete.  Restart the kernel.
+         xTaskResumeAll ();
+     }
  }
    
* \defgroup vTaskSuspendAll vTaskSuspendAll @@ -1292,42 +1292,42 @@ void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; * that were previously suspended by a call to vTaskSuspend(). * * @return If resuming the scheduler caused a context switch then pdTRUE is - * returned, otherwise pdFALSE is returned. + * returned, otherwise pdFALSE is returned. * * Example usage:
  void vTask1( void * pvParameters )
  {
-	 for( ;; )
-	 {
-		 // Task code goes here.
+     for( ;; )
+     {
+         // Task code goes here.
 
-		 // ...
+         // ...
 
-		 // At some point the task wants to perform a long operation during
-		 // which it does not want to get swapped out.  It cannot use
-		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
-		 // operation may cause interrupts to be missed - including the
-		 // ticks.
+         // At some point the task wants to perform a long operation during
+         // which it does not want to get swapped out.  It cannot use
+         // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+         // operation may cause interrupts to be missed - including the
+         // ticks.
 
-		 // Prevent the real time kernel swapping out the task.
-		 vTaskSuspendAll ();
+         // Prevent the real time kernel swapping out the task.
+         vTaskSuspendAll ();
 
-		 // Perform the operation here.  There is no need to use critical
-		 // sections as we have all the microcontroller processing time.
-		 // During this time interrupts will still operate and the real
-		 // time kernel tick count will be maintained.
+         // Perform the operation here.  There is no need to use critical
+         // sections as we have all the microcontroller processing time.
+         // During this time interrupts will still operate and the real
+         // time kernel tick count will be maintained.
 
-		 // ...
+         // ...
 
-		 // The operation is complete.  Restart the kernel.  We want to force
-		 // a context switch - but there is no point if resuming the scheduler
-		 // caused a context switch already.
-		 if( !xTaskResumeAll () )
-		 {
-			  taskYIELD ();
-		 }
-	 }
+         // The operation is complete.  Restart the kernel.  We want to force
+         // a context switch - but there is no point if resuming the scheduler
+         // caused a context switch already.
+         if( !xTaskResumeAll () )
+         {
+              taskYIELD ();
+         }
+     }
  }
    
* \defgroup xTaskResumeAll xTaskResumeAll @@ -1471,47 +1471,47 @@ fixed by simply guarding against the inclusion of these two prototypes unless they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration constant. */ #ifdef configUSE_APPLICATION_TASK_TAG - #if configUSE_APPLICATION_TASK_TAG == 1 - /** - * task.h - *
void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );
- * - * Sets pxHookFunction to be the task hook function used by the task xTask. - * Passing xTask as NULL has the effect of setting the calling tasks hook - * function. - */ - void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; + #if configUSE_APPLICATION_TASK_TAG == 1 + /** + * task.h + *
void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );
+ * + * Sets pxHookFunction to be the task hook function used by the task xTask. + * Passing xTask as NULL has the effect of setting the calling tasks hook + * function. + */ + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; - /** - * task.h - *
void xTaskGetApplicationTaskTag( TaskHandle_t xTask );
- * - * Returns the pxHookFunction value assigned to the task xTask. Do not - * call from an interrupt service routine - call - * xTaskGetApplicationTaskTagFromISR() instead. - */ - TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + /** + * task.h + *
void xTaskGetApplicationTaskTag( TaskHandle_t xTask );
+ * + * Returns the pxHookFunction value assigned to the task xTask. Do not + * call from an interrupt service routine - call + * xTaskGetApplicationTaskTagFromISR() instead. + */ + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - /** - * task.h - *
void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask );
- * - * Returns the pxHookFunction value assigned to the task xTask. Can - * be called from an interrupt service routine. - */ - TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ + /** + * task.h + *
void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask );
+ * + * Returns the pxHookFunction value assigned to the task xTask. Can + * be called from an interrupt service routine. + */ + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ #endif /* ifdef configUSE_APPLICATION_TASK_TAG */ #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - /* Each task contains an array of pointers that is dimensioned by the - configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The - kernel does not use the pointers itself, so the application writer can use - the pointers for any purpose they wish. The following two functions are - used to set and query a pointer respectively. */ - void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION; - void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION; + /* Each task contains an array of pointers that is dimensioned by the + configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The + kernel does not use the pointers itself, so the application writer can use + the pointers for any purpose they wish. The following two functions are + used to set and query a pointer respectively. */ + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION; + void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION; #endif @@ -1574,65 +1574,65 @@ TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; * Example usage:
     // This example demonstrates how a human readable table of run time stats
-	// information is generated from raw data provided by uxTaskGetSystemState().
-	// The human readable table is written to pcWriteBuffer
-	void vTaskGetRunTimeStats( char *pcWriteBuffer )
-	{
-	TaskStatus_t *pxTaskStatusArray;
-	volatile UBaseType_t uxArraySize, x;
-	uint32_t ulTotalRunTime, ulStatsAsPercentage;
+    // information is generated from raw data provided by uxTaskGetSystemState().
+    // The human readable table is written to pcWriteBuffer
+    void vTaskGetRunTimeStats( char *pcWriteBuffer )
+    {
+    TaskStatus_t *pxTaskStatusArray;
+    volatile UBaseType_t uxArraySize, x;
+    uint32_t ulTotalRunTime, ulStatsAsPercentage;
 
-		// Make sure the write buffer does not contain a string.
-		*pcWriteBuffer = 0x00;
+        // Make sure the write buffer does not contain a string.
+        *pcWriteBuffer = 0x00;
 
-		// Take a snapshot of the number of tasks in case it changes while this
-		// function is executing.
-		uxArraySize = uxTaskGetNumberOfTasks();
+        // Take a snapshot of the number of tasks in case it changes while this
+        // function is executing.
+        uxArraySize = uxTaskGetNumberOfTasks();
 
-		// Allocate a TaskStatus_t structure for each task.  An array could be
-		// allocated statically at compile time.
-		pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
+        // Allocate a TaskStatus_t structure for each task.  An array could be
+        // allocated statically at compile time.
+        pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
 
-		if( pxTaskStatusArray != NULL )
-		{
-			// Generate raw status information about each task.
-			uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
+        if( pxTaskStatusArray != NULL )
+        {
+            // Generate raw status information about each task.
+            uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
 
-			// For percentage calculations.
-			ulTotalRunTime /= 100UL;
+            // For percentage calculations.
+            ulTotalRunTime /= 100UL;
 
-			// Avoid divide by zero errors.
-			if( ulTotalRunTime > 0 )
-			{
-				// For each populated position in the pxTaskStatusArray array,
-				// format the raw data as human readable ASCII data
-				for( x = 0; x < uxArraySize; x++ )
-				{
-					// What percentage of the total run time has the task used?
-					// This will always be rounded down to the nearest integer.
-					// ulTotalRunTimeDiv100 has already been divided by 100.
-					ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
+            // Avoid divide by zero errors.
+            if( ulTotalRunTime > 0 )
+            {
+                // For each populated position in the pxTaskStatusArray array,
+                // format the raw data as human readable ASCII data
+                for( x = 0; x < uxArraySize; x++ )
+                {
+                    // What percentage of the total run time has the task used?
+                    // This will always be rounded down to the nearest integer.
+                    // ulTotalRunTimeDiv100 has already been divided by 100.
+                    ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
 
-					if( ulStatsAsPercentage > 0UL )
-					{
-						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
-					}
-					else
-					{
-						// If the percentage is zero here then the task has
-						// consumed less than 1% of the total run time.
-						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
-					}
+                    if( ulStatsAsPercentage > 0UL )
+                    {
+                        sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
+                    }
+                    else
+                    {
+                        // If the percentage is zero here then the task has
+                        // consumed less than 1% of the total run time.
+                        sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
+                    }
 
-					pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
-				}
-			}
+                    pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
+                }
+            }
 
-			// The array is no longer needed, free the memory it consumes.
-			vPortFree( pxTaskStatusArray );
-		}
-	}
-	
+ // The array is no longer needed, free the memory it consumes. + vPortFree( pxTaskStatusArray ); + } + } + */ UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) PRIVILEGED_FUNCTION; diff --git a/components/bl602/freertos_riscv/config/timers.h b/components/bl602/freertos_riscv/config/timers.h index cb721797..67a238c3 100644 --- a/components/bl602/freertos_riscv/config/timers.h +++ b/components/bl602/freertos_riscv/config/timers.h @@ -30,7 +30,7 @@ #define TIMERS_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include timers.h" + #error "include FreeRTOS.h must appear in source files before include timers.h" #endif /*lint -save -e537 This headers are only multiply included if the application code @@ -51,20 +51,20 @@ be used solely through the macros that make up the public software timer API, as defined below. The commands that are sent from interrupts must use the highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task or interrupt version of the queue send function should be used. */ -#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) -#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) -#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) -#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) -#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) -#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) -#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) -#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) +#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) +#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) +#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) +#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) +#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) +#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) +#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) +#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) -#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) -#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) -#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) -#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) -#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) +#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) +#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) +#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) /** @@ -88,11 +88,11 @@ typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer ); typedef void (*PendedFunction_t)( void *, uint32_t ); /** - * TimerHandle_t xTimerCreate( const char * const pcTimerName, - * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, - * void * pvTimerID, - * TimerCallbackFunction_t pxCallbackFunction ); + * TimerHandle_t xTimerCreate( const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction ); * * Creates a new software timer instance, and returns a handle by which the * created software timer can be referenced. @@ -135,7 +135,7 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * * @param pxCallbackFunction The function to call when the timer expires. * Callback functions must have the prototype defined by TimerCallbackFunction_t, - * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * which is "void vCallbackFunction( TimerHandle_t xTimer );". * * @return If the timer is successfully created then a handle to the newly * created timer is returned. If the timer cannot be created (because either @@ -161,8 +161,8 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * int32_t lArrayIndex; * const int32_t xMaxExpiryCountBeforeStopping = 10; * - * // Optionally do something if the pxTimer parameter is NULL. - * configASSERT( pxTimer ); + * // Optionally do something if the pxTimer parameter is NULL. + * configASSERT( pxTimer ); * * // Which timer expired? * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); @@ -225,20 +225,20 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * @endverbatim */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; #endif /** * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, - * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, - * void * pvTimerID, - * TimerCallbackFunction_t pxCallbackFunction, - * StaticTimer_t *pxTimerBuffer ); + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction, + * StaticTimer_t *pxTimerBuffer ); * * Creates a new software timer instance, and returns a handle by which the * created software timer can be referenced. @@ -355,12 +355,12 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * @endverbatim */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t *pxTimerBuffer ) PRIVILEGED_FUNCTION; + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t *pxTimerBuffer ) PRIVILEGED_FUNCTION; #endif /* configSUPPORT_STATIC_ALLOCATION */ /** @@ -546,9 +546,9 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerStop( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) /** - * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, - * TickType_t xNewPeriod, - * TickType_t xTicksToWait ); + * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * TickType_t xTicksToWait ); * * Timer functionality is provided by a timer service/daemon task. Many of the * public FreeRTOS timer API functions send commands to the timer service task @@ -788,8 +788,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerReset( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) /** - * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerStart() that can be called from an interrupt service * routine. @@ -874,8 +874,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) /** - * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerStop() that can be called from an interrupt service * routine. @@ -938,8 +938,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; /** * BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, - * TickType_t xNewPeriod, - * BaseType_t *pxHigherPriorityTaskWoken ); + * TickType_t xNewPeriod, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerChangePeriod() that can be called from an interrupt * service routine. @@ -1010,8 +1010,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) /** - * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerReset() that can be called from an interrupt service * routine. @@ -1146,42 +1146,42 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; * Example usage: * @verbatim * - * // The callback function that will execute in the context of the daemon task. + * // The callback function that will execute in the context of the daemon task. * // Note callback functions must all use this same prototype. * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) - * { - * BaseType_t xInterfaceToService; + * { + * BaseType_t xInterfaceToService; * - * // The interface that requires servicing is passed in the second + * // The interface that requires servicing is passed in the second * // parameter. The first parameter is not used in this case. - * xInterfaceToService = ( BaseType_t ) ulParameter2; + * xInterfaceToService = ( BaseType_t ) ulParameter2; * - * // ...Perform the processing here... - * } + * // ...Perform the processing here... + * } * - * // An ISR that receives data packets from multiple interfaces + * // An ISR that receives data packets from multiple interfaces * void vAnISR( void ) - * { - * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; + * { + * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; * - * // Query the hardware to determine which interface needs processing. - * xInterfaceToService = prvCheckInterfaces(); + * // Query the hardware to determine which interface needs processing. + * xInterfaceToService = prvCheckInterfaces(); * * // The actual processing is to be deferred to a task. Request the * // vProcessInterface() callback function is executed, passing in the - * // number of the interface that needs processing. The interface to - * // service is passed in the second parameter. The first parameter is - * // not used in this case. - * xHigherPriorityTaskWoken = pdFALSE; - * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); + * // number of the interface that needs processing. The interface to + * // service is passed in the second parameter. The first parameter is + * // not used in this case. + * xHigherPriorityTaskWoken = pdFALSE; + * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); * - * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context - * // switch should be requested. The macro used is port specific and will - * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to - * // the documentation page for the port being used. - * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and will + * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to + * // the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); * - * } + * } * @endverbatim */ BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; @@ -1282,8 +1282,8 @@ BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; #if( configUSE_TRACE_FACILITY == 1 ) - void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; - UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; #endif #ifdef __cplusplus diff --git a/components/bl602/freertos_riscv/croutine.c b/components/bl602/freertos_riscv/croutine.c index 56c8ac29..07df1cd8 100644 --- a/components/bl602/freertos_riscv/croutine.c +++ b/components/bl602/freertos_riscv/croutine.c @@ -37,17 +37,17 @@ * than file scope. */ #ifdef portREMOVE_STATIC_QUALIFIER - #define static + #define static #endif /* Lists for ready and blocked co-routines. --------------------*/ -static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ -static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ -static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ -static List_t * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */ -static List_t * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ -static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ +static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ +static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ +static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ +static List_t * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */ +static List_t * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ +static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ /* Other file private variables. --------------------------------*/ CRCB_t * pxCurrentCoRoutine = NULL; @@ -55,7 +55,7 @@ static UBaseType_t uxTopCoRoutineReadyPriority = 0; static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; /* The initial state of the co-routine when it is created. */ -#define corINITIAL_STATE ( 0 ) +#define corINITIAL_STATE ( 0 ) /* * Place the co-routine represented by pxCRCB into the appropriate ready queue @@ -64,13 +64,13 @@ static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; * This macro accesses the co-routine ready lists and therefore must not be * used from within an ISR. */ -#define prvAddCoRoutineToReadyQueue( pxCRCB ) \ -{ \ - if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ - { \ - uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ - } \ - vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ +#define prvAddCoRoutineToReadyQueue( pxCRCB ) \ +{ \ + if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ + { \ + uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ + } \ + vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ } /* @@ -104,55 +104,55 @@ BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPri BaseType_t xReturn; CRCB_t *pxCoRoutine; - /* Allocate the memory that will store the co-routine control block. */ - pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); - if( pxCoRoutine ) - { - /* If pxCurrentCoRoutine is NULL then this is the first co-routine to - be created and the co-routine data structures need initialising. */ - if( pxCurrentCoRoutine == NULL ) - { - pxCurrentCoRoutine = pxCoRoutine; - prvInitialiseCoRoutineLists(); - } + /* Allocate the memory that will store the co-routine control block. */ + pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); + if( pxCoRoutine ) + { + /* If pxCurrentCoRoutine is NULL then this is the first co-routine to + be created and the co-routine data structures need initialising. */ + if( pxCurrentCoRoutine == NULL ) + { + pxCurrentCoRoutine = pxCoRoutine; + prvInitialiseCoRoutineLists(); + } - /* Check the priority is within limits. */ - if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) - { - uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; - } + /* Check the priority is within limits. */ + if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) + { + uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; + } - /* Fill out the co-routine control block from the function parameters. */ - pxCoRoutine->uxState = corINITIAL_STATE; - pxCoRoutine->uxPriority = uxPriority; - pxCoRoutine->uxIndex = uxIndex; - pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; + /* Fill out the co-routine control block from the function parameters. */ + pxCoRoutine->uxState = corINITIAL_STATE; + pxCoRoutine->uxPriority = uxPriority; + pxCoRoutine->uxIndex = uxIndex; + pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; - /* Initialise all the other co-routine control block parameters. */ - vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); - vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); + /* Initialise all the other co-routine control block parameters. */ + vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); + vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); - /* Set the co-routine control block as a link back from the ListItem_t. - This is so we can get back to the containing CRCB from a generic item - in a list. */ - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); + /* Set the co-routine control block as a link back from the ListItem_t. + This is so we can get back to the containing CRCB from a generic item + in a list. */ + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); - /* Now the co-routine has been initialised it can be added to the ready - list at the correct priority. */ - prvAddCoRoutineToReadyQueue( pxCoRoutine ); + /* Now the co-routine has been initialised it can be added to the ready + list at the correct priority. */ + prvAddCoRoutineToReadyQueue( pxCoRoutine ); - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -160,60 +160,60 @@ void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList ) { TickType_t xTimeToWake; - /* Calculate the time to wake - this may overflow but this is - not a problem. */ - xTimeToWake = xCoRoutineTickCount + xTicksToDelay; + /* Calculate the time to wake - this may overflow but this is + not a problem. */ + xTimeToWake = xCoRoutineTickCount + xTicksToDelay; - /* We must remove ourselves from the ready list before adding - ourselves to the blocked list as the same list item is used for - both lists. */ - ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + /* We must remove ourselves from the ready list before adding + ourselves to the blocked list as the same list item is used for + both lists. */ + ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); - if( xTimeToWake < xCoRoutineTickCount ) - { - /* Wake time has overflowed. Place this item in the - overflow list. */ - vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } - else - { - /* The wake time has not overflowed, so we can use the - current block list. */ - vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } + if( xTimeToWake < xCoRoutineTickCount ) + { + /* Wake time has overflowed. Place this item in the + overflow list. */ + vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + else + { + /* The wake time has not overflowed, so we can use the + current block list. */ + vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } - if( pxEventList ) - { - /* Also add the co-routine to an event list. If this is done then the - function must be called with interrupts disabled. */ - vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); - } + if( pxEventList ) + { + /* Also add the co-routine to an event list. If this is done then the + function must be called with interrupts disabled. */ + vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); + } } /*-----------------------------------------------------------*/ static void prvCheckPendingReadyList( void ) { - /* Are there any co-routines waiting to get moved to the ready list? These - are co-routines that have been readied by an ISR. The ISR cannot access - the ready lists itself. */ - while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) - { - CRCB_t *pxUnblockedCRCB; + /* Are there any co-routines waiting to get moved to the ready list? These + are co-routines that have been readied by an ISR. The ISR cannot access + the ready lists itself. */ + while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) + { + CRCB_t *pxUnblockedCRCB; - /* The pending ready list can be accessed by an ISR. */ - portDISABLE_INTERRUPTS(); - { - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - } - portENABLE_INTERRUPTS(); + /* The pending ready list can be accessed by an ISR. */ + portDISABLE_INTERRUPTS(); + { + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + } + portENABLE_INTERRUPTS(); - ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); - prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); - } + ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); + prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); + } } /*-----------------------------------------------------------*/ @@ -221,87 +221,87 @@ static void prvCheckDelayedList( void ) { CRCB_t *pxCRCB; - xPassedTicks = xTaskGetTickCount() - xLastTickCount; - while( xPassedTicks ) - { - xCoRoutineTickCount++; - xPassedTicks--; + xPassedTicks = xTaskGetTickCount() - xLastTickCount; + while( xPassedTicks ) + { + xCoRoutineTickCount++; + xPassedTicks--; - /* If the tick count has overflowed we need to swap the ready lists. */ - if( xCoRoutineTickCount == 0 ) - { - List_t * pxTemp; + /* If the tick count has overflowed we need to swap the ready lists. */ + if( xCoRoutineTickCount == 0 ) + { + List_t * pxTemp; - /* Tick count has overflowed so we need to swap the delay lists. If there are - any items in pxDelayedCoRoutineList here then there is an error! */ - pxTemp = pxDelayedCoRoutineList; - pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; - pxOverflowDelayedCoRoutineList = pxTemp; - } + /* Tick count has overflowed so we need to swap the delay lists. If there are + any items in pxDelayedCoRoutineList here then there is an error! */ + pxTemp = pxDelayedCoRoutineList; + pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; + pxOverflowDelayedCoRoutineList = pxTemp; + } - /* See if this tick has made a timeout expire. */ - while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) - { - pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); + /* See if this tick has made a timeout expire. */ + while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) + { + pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); - if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) - { - /* Timeout not yet expired. */ - break; - } + if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) + { + /* Timeout not yet expired. */ + break; + } - portDISABLE_INTERRUPTS(); - { - /* The event could have occurred just before this critical - section. If this is the case then the generic list item will - have been moved to the pending ready list and the following - line is still valid. Also the pvContainer parameter will have - been set to NULL so the following lines are also valid. */ - ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); + portDISABLE_INTERRUPTS(); + { + /* The event could have occurred just before this critical + section. If this is the case then the generic list item will + have been moved to the pending ready list and the following + line is still valid. Also the pvContainer parameter will have + been set to NULL so the following lines are also valid. */ + ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); - /* Is the co-routine waiting on an event also? */ - if( pxCRCB->xEventListItem.pxContainer ) - { - ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); - } - } - portENABLE_INTERRUPTS(); + /* Is the co-routine waiting on an event also? */ + if( pxCRCB->xEventListItem.pxContainer ) + { + ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); + } + } + portENABLE_INTERRUPTS(); - prvAddCoRoutineToReadyQueue( pxCRCB ); - } - } + prvAddCoRoutineToReadyQueue( pxCRCB ); + } + } - xLastTickCount = xCoRoutineTickCount; + xLastTickCount = xCoRoutineTickCount; } /*-----------------------------------------------------------*/ void vCoRoutineSchedule( void ) { - /* See if any co-routines readied by events need moving to the ready lists. */ - prvCheckPendingReadyList(); + /* See if any co-routines readied by events need moving to the ready lists. */ + prvCheckPendingReadyList(); - /* See if any delayed co-routines have timed out. */ - prvCheckDelayedList(); + /* See if any delayed co-routines have timed out. */ + prvCheckDelayedList(); - /* Find the highest priority queue that contains ready co-routines. */ - while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) - { - if( uxTopCoRoutineReadyPriority == 0 ) - { - /* No more co-routines to check. */ - return; - } - --uxTopCoRoutineReadyPriority; - } + /* Find the highest priority queue that contains ready co-routines. */ + while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) + { + if( uxTopCoRoutineReadyPriority == 0 ) + { + /* No more co-routines to check. */ + return; + } + --uxTopCoRoutineReadyPriority; + } - /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines - of the same priority get an equal share of the processor time. */ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); + /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines + of the same priority get an equal share of the processor time. */ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); - /* Call the co-routine. */ - ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); + /* Call the co-routine. */ + ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); - return; + return; } /*-----------------------------------------------------------*/ @@ -309,19 +309,19 @@ static void prvInitialiseCoRoutineLists( void ) { UBaseType_t uxPriority; - for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) - { - vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); - } + for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) + { + vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); + } - vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); - vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); - vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); + vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); + vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); + vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); - /* Start with pxDelayedCoRoutineList using list1 and the - pxOverflowDelayedCoRoutineList using list2. */ - pxDelayedCoRoutineList = &xDelayedCoRoutineList1; - pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; + /* Start with pxDelayedCoRoutineList using list1 and the + pxOverflowDelayedCoRoutineList using list2. */ + pxDelayedCoRoutineList = &xDelayedCoRoutineList1; + pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; } /*-----------------------------------------------------------*/ @@ -330,23 +330,23 @@ BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList ) CRCB_t *pxUnblockedCRCB; BaseType_t xReturn; - /* This function is called from within an interrupt. It can only access - event lists and the pending ready list. This function assumes that a - check has already been made to ensure pxEventList is not empty. */ - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); + /* This function is called from within an interrupt. It can only access + event lists and the pending ready list. This function assumes that a + check has already been made to ensure pxEventList is not empty. */ + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); - if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } #endif /* configUSE_CO_ROUTINES == 0 */ diff --git a/components/bl602/freertos_riscv/event_groups.c b/components/bl602/freertos_riscv/event_groups.c index 65a5ff25..155fc187 100644 --- a/components/bl602/freertos_riscv/event_groups.c +++ b/components/bl602/freertos_riscv/event_groups.c @@ -49,29 +49,29 @@ correct privileged Vs unprivileged linkage and placement. */ item value. It is important they don't clash with the taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */ #if configUSE_16_BIT_TICKS == 1 - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U - #define eventWAIT_FOR_ALL_BITS 0x0400U - #define eventEVENT_BITS_CONTROL_BYTES 0xff00U + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U + #define eventWAIT_FOR_ALL_BITS 0x0400U + #define eventEVENT_BITS_CONTROL_BYTES 0xff00U #else - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL - #define eventWAIT_FOR_ALL_BITS 0x04000000UL - #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL + #define eventWAIT_FOR_ALL_BITS 0x04000000UL + #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL #endif typedef struct EventGroupDef_t { - EventBits_t uxEventBits; - List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ + EventBits_t uxEventBits; + List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxEventGroupNumber; - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxEventGroupNumber; + #endif - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ + #endif } EventGroup_t; /*-----------------------------------------------------------*/ @@ -90,100 +90,100 @@ static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, co #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) - { - EventGroup_t *pxEventBits; + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) + { + EventGroup_t *pxEventBits; - /* A StaticEventGroup_t object must be provided. */ - configASSERT( pxEventGroupBuffer ); + /* A StaticEventGroup_t object must be provided. */ + configASSERT( pxEventGroupBuffer ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticEventGroup_t equals the size of the real - event group structure. */ - volatile size_t xSize = sizeof( StaticEventGroup_t ); - configASSERT( xSize == sizeof( EventGroup_t ) ); - } /*lint !e529 xSize is referenced if configASSERT() is defined. */ - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticEventGroup_t equals the size of the real + event group structure. */ + volatile size_t xSize = sizeof( StaticEventGroup_t ); + configASSERT( xSize == sizeof( EventGroup_t ) ); + } /*lint !e529 xSize is referenced if configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ - /* The user has provided a statically allocated event group - use it. */ - pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ + /* The user has provided a statically allocated event group - use it. */ + pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note that - this event group was created statically in case the event group - is later deleted. */ - pxEventBits->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note that + this event group was created statically in case the event group + is later deleted. */ + pxEventBits->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - /* xEventGroupCreateStatic should only ever be called with - pxEventGroupBuffer pointing to a pre-allocated (compile time - allocated) StaticEventGroup_t variable. */ - traceEVENT_GROUP_CREATE_FAILED(); - } + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + /* xEventGroupCreateStatic should only ever be called with + pxEventGroupBuffer pointing to a pre-allocated (compile time + allocated) StaticEventGroup_t variable. */ + traceEVENT_GROUP_CREATE_FAILED(); + } - return pxEventBits; - } + return pxEventBits; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreate( void ) - { - EventGroup_t *pxEventBits; + EventGroupHandle_t xEventGroupCreate( void ) + { + EventGroup_t *pxEventBits; - /* Allocate the event group. Justification for MISRA deviation as - follows: pvPortMalloc() always ensures returned memory blocks are - aligned per the requirements of the MCU stack. In this case - pvPortMalloc() must return a pointer that is guaranteed to meet the - alignment requirements of the EventGroup_t structure - which (if you - follow it through) is the alignment requirements of the TickType_t type - (EventBits_t being of TickType_t itself). Therefore, whenever the - stack alignment requirements are greater than or equal to the - TickType_t alignment requirements the cast is safe. In other cases, - where the natural word size of the architecture is less than - sizeof( TickType_t ), the TickType_t variables will be accessed in two - or more reads operations, and the alignment requirements is only that - of each individual read. */ - pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */ + /* Allocate the event group. Justification for MISRA deviation as + follows: pvPortMalloc() always ensures returned memory blocks are + aligned per the requirements of the MCU stack. In this case + pvPortMalloc() must return a pointer that is guaranteed to meet the + alignment requirements of the EventGroup_t structure - which (if you + follow it through) is the alignment requirements of the TickType_t type + (EventBits_t being of TickType_t itself). Therefore, whenever the + stack alignment requirements are greater than or equal to the + TickType_t alignment requirements the cast is safe. In other cases, + where the natural word size of the architecture is less than + sizeof( TickType_t ), the TickType_t variables will be accessed in two + or more reads operations, and the alignment requirements is only that + of each individual read. */ + pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */ - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note this - event group was allocated statically in case the event group is - later deleted. */ - pxEventBits->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note this + event group was allocated statically in case the event group is + later deleted. */ + pxEventBits->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */ - } + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */ + } - return pxEventBits; - } + return pxEventBits; + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ @@ -195,116 +195,116 @@ EventGroup_t *pxEventBits = xEventGroup; BaseType_t xAlreadyYielded; BaseType_t xTimeoutOccurred = pdFALSE; - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - vTaskSuspendAll(); - { - uxOriginalBitValue = pxEventBits->uxEventBits; + vTaskSuspendAll(); + { + uxOriginalBitValue = pxEventBits->uxEventBits; - ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); + ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); - if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - /* All the rendezvous bits are now set - no need to block. */ - uxReturn = ( uxOriginalBitValue | uxBitsToSet ); + if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + /* All the rendezvous bits are now set - no need to block. */ + uxReturn = ( uxOriginalBitValue | uxBitsToSet ); - /* Rendezvous always clear the bits. They will have been cleared - already unless this is the only task in the rendezvous. */ - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + /* Rendezvous always clear the bits. They will have been cleared + already unless this is the only task in the rendezvous. */ + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - xTicksToWait = 0; - } - else - { - if( xTicksToWait != ( TickType_t ) 0 ) - { - traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); + xTicksToWait = 0; + } + else + { + if( xTicksToWait != ( TickType_t ) 0 ) + { + traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); - /* Store the bits that the calling task is waiting for in the - task's event list item so the kernel knows when a match is - found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); + /* Store the bits that the calling task is waiting for in the + task's event list item so the kernel knows when a match is + found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); - /* This assignment is obsolete as uxReturn will get set after - the task unblocks, but some compilers mistakenly generate a - warning about uxReturn being returned without being set if the - assignment is omitted. */ - uxReturn = 0; - } - else - { - /* The rendezvous bits were not set, but no block time was - specified - just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; - xTimeoutOccurred = pdTRUE; - } - } - } - xAlreadyYielded = xTaskResumeAll(); + /* This assignment is obsolete as uxReturn will get set after + the task unblocks, but some compilers mistakenly generate a + warning about uxReturn being returned without being set if the + assignment is omitted. */ + uxReturn = 0; + } + else + { + /* The rendezvous bits were not set, but no block time was + specified - just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + xTimeoutOccurred = pdTRUE; + } + } + } + xAlreadyYielded = xTaskResumeAll(); - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The task blocked to wait for its required bits to be set - at this - point either the required bits were set or the block time expired. If - the required bits were set they will have been stored in the task's - event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); + /* The task blocked to wait for its required bits to be set - at this + point either the required bits were set or the block time expired. If + the required bits were set they will have been stored in the task's + event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - /* The task timed out, just return the current event bit value. */ - taskENTER_CRITICAL(); - { - uxReturn = pxEventBits->uxEventBits; + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + /* The task timed out, just return the current event bit value. */ + taskENTER_CRITICAL(); + { + uxReturn = pxEventBits->uxEventBits; - /* Although the task got here because it timed out before the - bits it was waiting for were set, it is possible that since it - unblocked another task has set the bits. If this is the case - then it needs to clear the bits before exiting. */ - if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* Although the task got here because it timed out before the + bits it was waiting for were set, it is possible that since it + unblocked another task has set the bits. If this is the case + then it needs to clear the bits before exiting. */ + if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task unblocked because the bits were set. */ - } + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task unblocked because the bits were set. */ + } - /* Control bits might be set as the task had blocked should not be - returned. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } + /* Control bits might be set as the task had blocked should not be + returned. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } - traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); + traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ @@ -315,146 +315,146 @@ EventBits_t uxReturn, uxControlBits = 0; BaseType_t xWaitConditionMet, xAlreadyYielded; BaseType_t xTimeoutOccurred = pdFALSE; - /* Check the user is not attempting to wait on the bits used by the kernel - itself, and that at least one bit is being requested. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Check the user is not attempting to wait on the bits used by the kernel + itself, and that at least one bit is being requested. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - vTaskSuspendAll(); - { - const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; + vTaskSuspendAll(); + { + const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; - /* Check to see if the wait condition is already met or not. */ - xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); + /* Check to see if the wait condition is already met or not. */ + xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); - if( xWaitConditionMet != pdFALSE ) - { - /* The wait condition has already been met so there is no need to - block. */ - uxReturn = uxCurrentEventBits; - xTicksToWait = ( TickType_t ) 0; + if( xWaitConditionMet != pdFALSE ) + { + /* The wait condition has already been met so there is no need to + block. */ + uxReturn = uxCurrentEventBits; + xTicksToWait = ( TickType_t ) 0; - /* Clear the wait bits if requested to do so. */ - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The wait condition has not been met, but no block time was - specified, so just return the current value. */ - uxReturn = uxCurrentEventBits; - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task is going to block to wait for its required bits to be - set. uxControlBits are used to remember the specified behaviour of - this call to xEventGroupWaitBits() - for use when the event bits - unblock the task. */ - if( xClearOnExit != pdFALSE ) - { - uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Clear the wait bits if requested to do so. */ + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The wait condition has not been met, but no block time was + specified, so just return the current value. */ + uxReturn = uxCurrentEventBits; + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task is going to block to wait for its required bits to be + set. uxControlBits are used to remember the specified behaviour of + this call to xEventGroupWaitBits() - for use when the event bits + unblock the task. */ + if( xClearOnExit != pdFALSE ) + { + uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xWaitForAllBits != pdFALSE ) - { - uxControlBits |= eventWAIT_FOR_ALL_BITS; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xWaitForAllBits != pdFALSE ) + { + uxControlBits |= eventWAIT_FOR_ALL_BITS; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Store the bits that the calling task is waiting for in the - task's event list item so the kernel knows when a match is - found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); + /* Store the bits that the calling task is waiting for in the + task's event list item so the kernel knows when a match is + found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); - /* This is obsolete as it will get set after the task unblocks, but - some compilers mistakenly generate a warning about the variable - being returned without being set if it is not done. */ - uxReturn = 0; + /* This is obsolete as it will get set after the task unblocks, but + some compilers mistakenly generate a warning about the variable + being returned without being set if it is not done. */ + uxReturn = 0; - traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); - } - } - xAlreadyYielded = xTaskResumeAll(); + traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); + } + } + xAlreadyYielded = xTaskResumeAll(); - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The task blocked to wait for its required bits to be set - at this - point either the required bits were set or the block time expired. If - the required bits were set they will have been stored in the task's - event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); + /* The task blocked to wait for its required bits to be set - at this + point either the required bits were set or the block time expired. If + the required bits were set they will have been stored in the task's + event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - taskENTER_CRITICAL(); - { - /* The task timed out, just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + taskENTER_CRITICAL(); + { + /* The task timed out, just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; - /* It is possible that the event bits were updated between this - task leaving the Blocked state and running again. */ - if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) - { - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - xTimeoutOccurred = pdTRUE; - } - taskEXIT_CRITICAL(); - } - else - { - /* The task unblocked because the bits were set. */ - } + /* It is possible that the event bits were updated between this + task leaving the Blocked state and running again. */ + if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) + { + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + xTimeoutOccurred = pdTRUE; + } + taskEXIT_CRITICAL(); + } + else + { + /* The task unblocked because the bits were set. */ + } - /* The task blocked so control bits may have been set. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } - traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); + /* The task blocked so control bits may have been set. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ @@ -463,39 +463,39 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit EventGroup_t *pxEventBits = xEventGroup; EventBits_t uxReturn; - /* Check the user is not attempting to clear the bits used by the kernel - itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + /* Check the user is not attempting to clear the bits used by the kernel + itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - taskENTER_CRITICAL(); - { - traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); + taskENTER_CRITICAL(); + { + traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); - /* The value returned is the event group value prior to the bits being - cleared. */ - uxReturn = pxEventBits->uxEventBits; + /* The value returned is the event group value prior to the bits being + cleared. */ + uxReturn = pxEventBits->uxEventBits; - /* Clear the bits. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - taskEXIT_CRITICAL(); + /* Clear the bits. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + taskEXIT_CRITICAL(); - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) - { - BaseType_t xReturn; + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) + { + BaseType_t xReturn; - traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ - return xReturn; - } + return xReturn; + } #endif /*-----------------------------------------------------------*/ @@ -506,13 +506,13 @@ UBaseType_t uxSavedInterruptStatus; EventGroup_t const * const pxEventBits = xEventGroup; EventBits_t uxReturn; - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - uxReturn = pxEventBits->uxEventBits; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + uxReturn = pxEventBits->uxEventBits; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return uxReturn; + return uxReturn; } /*lint !e818 EventGroupHandle_t is a typedef used in other functions to so can't be pointer to const. */ /*-----------------------------------------------------------*/ @@ -525,88 +525,88 @@ EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits; EventGroup_t *pxEventBits = xEventGroup; BaseType_t xMatchFound = pdFALSE; - /* Check the user is not attempting to set the bits used by the kernel - itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + /* Check the user is not attempting to set the bits used by the kernel + itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - pxList = &( pxEventBits->xTasksWaitingForBits ); - pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - vTaskSuspendAll(); - { - traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); + pxList = &( pxEventBits->xTasksWaitingForBits ); + pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + vTaskSuspendAll(); + { + traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); - pxListItem = listGET_HEAD_ENTRY( pxList ); + pxListItem = listGET_HEAD_ENTRY( pxList ); - /* Set the bits. */ - pxEventBits->uxEventBits |= uxBitsToSet; + /* Set the bits. */ + pxEventBits->uxEventBits |= uxBitsToSet; - /* See if the new bit value should unblock any tasks. */ - while( pxListItem != pxListEnd ) - { - pxNext = listGET_NEXT( pxListItem ); - uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); - xMatchFound = pdFALSE; + /* See if the new bit value should unblock any tasks. */ + while( pxListItem != pxListEnd ) + { + pxNext = listGET_NEXT( pxListItem ); + uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); + xMatchFound = pdFALSE; - /* Split the bits waited for from the control bits. */ - uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; - uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; + /* Split the bits waited for from the control bits. */ + uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; + uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; - if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) - { - /* Just looking for single bit being set. */ - if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) - { - xMatchFound = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) - { - /* All bits are set. */ - xMatchFound = pdTRUE; - } - else - { - /* Need all bits to be set, but not all the bits were set. */ - } + if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) + { + /* Just looking for single bit being set. */ + if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) + { + xMatchFound = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) + { + /* All bits are set. */ + xMatchFound = pdTRUE; + } + else + { + /* Need all bits to be set, but not all the bits were set. */ + } - if( xMatchFound != pdFALSE ) - { - /* The bits match. Should the bits be cleared on exit? */ - if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) - { - uxBitsToClear |= uxBitsWaitedFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xMatchFound != pdFALSE ) + { + /* The bits match. Should the bits be cleared on exit? */ + if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) + { + uxBitsToClear |= uxBitsWaitedFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Store the actual event flag value in the task's event list - item before removing the task from the event list. The - eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows - that is was unblocked due to its required bits matching, rather - than because it timed out. */ - vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); - } + /* Store the actual event flag value in the task's event list + item before removing the task from the event list. The + eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows + that is was unblocked due to its required bits matching, rather + than because it timed out. */ + vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); + } - /* Move onto the next list item. Note pxListItem->pxNext is not - used here as the list item may have been removed from the event list - and inserted into the ready/pending reading list. */ - pxListItem = pxNext; - } + /* Move onto the next list item. Note pxListItem->pxNext is not + used here as the list item may have been removed from the event list + and inserted into the ready/pending reading list. */ + pxListItem = pxNext; + } - /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT - bit was set in the control word. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - ( void ) xTaskResumeAll(); + /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT + bit was set in the control word. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + ( void ) xTaskResumeAll(); - return pxEventBits->uxEventBits; + return pxEventBits->uxEventBits; } /*-----------------------------------------------------------*/ @@ -615,40 +615,40 @@ void vEventGroupDelete( EventGroupHandle_t xEventGroup ) EventGroup_t *pxEventBits = xEventGroup; const List_t *pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); - vTaskSuspendAll(); - { - traceEVENT_GROUP_DELETE( xEventGroup ); + vTaskSuspendAll(); + { + traceEVENT_GROUP_DELETE( xEventGroup ); - while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) - { - /* Unblock the task, returning 0 as the event list is being deleted - and cannot therefore have any bits set. */ - configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); - vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); - } + while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) + { + /* Unblock the task, returning 0 as the event list is being deleted + and cannot therefore have any bits set. */ + configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); + vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); + } - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The event group can only have been allocated dynamically - free - it again. */ - vPortFree( pxEventBits ); - } - #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The event group could have been allocated statically or - dynamically, so check before attempting to free the memory. */ - if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxEventBits ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } - ( void ) xTaskResumeAll(); + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The event group can only have been allocated dynamically - free + it again. */ + vPortFree( pxEventBits ); + } + #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The event group could have been allocated statically or + dynamically, so check before attempting to free the memory. */ + if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxEventBits ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } + ( void ) xTaskResumeAll(); } /*-----------------------------------------------------------*/ @@ -656,7 +656,7 @@ const List_t *pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); an interrupt. */ void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet ) { - ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ + ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ } /*-----------------------------------------------------------*/ @@ -664,7 +664,7 @@ void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet an interrupt. */ void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear ) { - ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ + ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ } /*-----------------------------------------------------------*/ @@ -672,80 +672,80 @@ static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, co { BaseType_t xWaitConditionMet = pdFALSE; - if( xWaitForAllBits == pdFALSE ) - { - /* Task only has to wait for one bit within uxBitsToWaitFor to be - set. Is one already set? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Task has to wait for all the bits in uxBitsToWaitFor to be set. - Are they set already? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( xWaitForAllBits == pdFALSE ) + { + /* Task only has to wait for one bit within uxBitsToWaitFor to be + set. Is one already set? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Task has to wait for all the bits in uxBitsToWaitFor to be set. + Are they set already? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - return xWaitConditionMet; + return xWaitConditionMet; } /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) - { - BaseType_t xReturn; + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) + { + BaseType_t xReturn; - traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ - return xReturn; - } + return xReturn; + } #endif /*-----------------------------------------------------------*/ #if (configUSE_TRACE_FACILITY == 1) - UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) - { - UBaseType_t xReturn; - EventGroup_t const *pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) + { + UBaseType_t xReturn; + EventGroup_t const *pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ - if( xEventGroup == NULL ) - { - xReturn = 0; - } - else - { - xReturn = pxEventBits->uxEventGroupNumber; - } + if( xEventGroup == NULL ) + { + xReturn = 0; + } + else + { + xReturn = pxEventBits->uxEventGroupNumber; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vEventGroupSetNumber( void * xEventGroup, UBaseType_t uxEventGroupNumber ) - { - ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ - } + void vEventGroupSetNumber( void * xEventGroup, UBaseType_t uxEventGroupNumber ) + { + ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv/list.c b/components/bl602/freertos_riscv/list.c index 21dabdec..98855882 100644 --- a/components/bl602/freertos_riscv/list.c +++ b/components/bl602/freertos_riscv/list.c @@ -36,38 +36,38 @@ void vListInitialise( List_t * const pxList ) { - /* The list structure contains a list item which is used to mark the - end of the list. To initialise the list the list end is inserted - as the only list entry. */ - pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + /* The list structure contains a list item which is used to mark the + end of the list. To initialise the list the list end is inserted + as the only list entry. */ + pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - /* The list end value is the highest possible value in the list to - ensure it remains at the end of the list. */ - pxList->xListEnd.xItemValue = portMAX_DELAY; + /* The list end value is the highest possible value in the list to + ensure it remains at the end of the list. */ + pxList->xListEnd.xItemValue = portMAX_DELAY; - /* The list end next and previous pointers point to itself so we know - when the list is empty. */ - pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + /* The list end next and previous pointers point to itself so we know + when the list is empty. */ + pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - pxList->uxNumberOfItems = ( UBaseType_t ) 0U; + pxList->uxNumberOfItems = ( UBaseType_t ) 0U; - /* Write known values into the list if - configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); - listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); + /* Write known values into the list if + configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); + listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); } /*-----------------------------------------------------------*/ void vListInitialiseItem( ListItem_t * const pxItem ) { - /* Make sure the list item is not recorded as being on a list. */ - pxItem->pxContainer = NULL; + /* Make sure the list item is not recorded as being on a list. */ + pxItem->pxContainer = NULL; - /* Write known values into the list item if - configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); - listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + /* Write known values into the list item if + configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); } /*-----------------------------------------------------------*/ @@ -75,28 +75,28 @@ void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem ) { ListItem_t * const pxIndex = pxList->pxIndex; - /* Only effective when configASSERT() is also defined, these tests may catch - the list data structures being overwritten in memory. They will not catch - data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + /* Only effective when configASSERT() is also defined, these tests may catch + the list data structures being overwritten in memory. They will not catch + data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - /* Insert a new list item into pxList, but rather than sort the list, - makes the new list item the last item to be removed by a call to - listGET_OWNER_OF_NEXT_ENTRY(). */ - pxNewListItem->pxNext = pxIndex; - pxNewListItem->pxPrevious = pxIndex->pxPrevious; + /* Insert a new list item into pxList, but rather than sort the list, + makes the new list item the last item to be removed by a call to + listGET_OWNER_OF_NEXT_ENTRY(). */ + pxNewListItem->pxNext = pxIndex; + pxNewListItem->pxPrevious = pxIndex->pxPrevious; - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); - pxIndex->pxPrevious->pxNext = pxNewListItem; - pxIndex->pxPrevious = pxNewListItem; + pxIndex->pxPrevious->pxNext = pxNewListItem; + pxIndex->pxPrevious = pxNewListItem; - /* Remember which list the item is in. */ - pxNewListItem->pxContainer = pxList; + /* Remember which list the item is in. */ + pxNewListItem->pxContainer = pxList; - ( pxList->uxNumberOfItems )++; + ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ @@ -105,65 +105,65 @@ void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem ) ListItem_t *pxIterator; const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; - /* Only effective when configASSERT() is also defined, these tests may catch - the list data structures being overwritten in memory. They will not catch - data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + /* Only effective when configASSERT() is also defined, these tests may catch + the list data structures being overwritten in memory. They will not catch + data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - /* Insert the new list item into the list, sorted in xItemValue order. + /* Insert the new list item into the list, sorted in xItemValue order. - If the list already contains a list item with the same item value then the - new list item should be placed after it. This ensures that TCBs which are - stored in ready lists (all of which have the same xItemValue value) get a - share of the CPU. However, if the xItemValue is the same as the back marker - the iteration loop below will not end. Therefore the value is checked - first, and the algorithm slightly modified if necessary. */ - if( xValueOfInsertion == portMAX_DELAY ) - { - pxIterator = pxList->xListEnd.pxPrevious; - } - else - { - /* *** NOTE *********************************************************** - If you find your application is crashing here then likely causes are - listed below. In addition see https://www.freertos.org/FAQHelp.html for - more tips, and ensure configASSERT() is defined! - https://www.freertos.org/a00110.html#configASSERT + If the list already contains a list item with the same item value then the + new list item should be placed after it. This ensures that TCBs which are + stored in ready lists (all of which have the same xItemValue value) get a + share of the CPU. However, if the xItemValue is the same as the back marker + the iteration loop below will not end. Therefore the value is checked + first, and the algorithm slightly modified if necessary. */ + if( xValueOfInsertion == portMAX_DELAY ) + { + pxIterator = pxList->xListEnd.pxPrevious; + } + else + { + /* *** NOTE *********************************************************** + If you find your application is crashing here then likely causes are + listed below. In addition see https://www.freertos.org/FAQHelp.html for + more tips, and ensure configASSERT() is defined! + https://www.freertos.org/a00110.html#configASSERT - 1) Stack overflow - - see https://www.freertos.org/Stacks-and-stack-overflow-checking.html - 2) Incorrect interrupt priority assignment, especially on Cortex-M - parts where numerically high priority values denote low actual - interrupt priorities, which can seem counter intuitive. See - https://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition - of configMAX_SYSCALL_INTERRUPT_PRIORITY on - https://www.freertos.org/a00110.html - 3) Calling an API function from within a critical section or when - the scheduler is suspended, or calling an API function that does - not end in "FromISR" from an interrupt. - 4) Using a queue or semaphore before it has been initialised or - before the scheduler has been started (are interrupts firing - before vTaskStartScheduler() has been called?). - **********************************************************************/ + 1) Stack overflow - + see https://www.freertos.org/Stacks-and-stack-overflow-checking.html + 2) Incorrect interrupt priority assignment, especially on Cortex-M + parts where numerically high priority values denote low actual + interrupt priorities, which can seem counter intuitive. See + https://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition + of configMAX_SYSCALL_INTERRUPT_PRIORITY on + https://www.freertos.org/a00110.html + 3) Calling an API function from within a critical section or when + the scheduler is suspended, or calling an API function that does + not end in "FromISR" from an interrupt. + 4) Using a queue or semaphore before it has been initialised or + before the scheduler has been started (are interrupts firing + before vTaskStartScheduler() has been called?). + **********************************************************************/ - for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */ - { - /* There is nothing to do here, just iterating to the wanted - insertion position. */ - } - } + for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */ + { + /* There is nothing to do here, just iterating to the wanted + insertion position. */ + } + } - pxNewListItem->pxNext = pxIterator->pxNext; - pxNewListItem->pxNext->pxPrevious = pxNewListItem; - pxNewListItem->pxPrevious = pxIterator; - pxIterator->pxNext = pxNewListItem; + pxNewListItem->pxNext = pxIterator->pxNext; + pxNewListItem->pxNext->pxPrevious = pxNewListItem; + pxNewListItem->pxPrevious = pxIterator; + pxIterator->pxNext = pxNewListItem; - /* Remember which list the item is in. This allows fast removal of the - item later. */ - pxNewListItem->pxContainer = pxList; + /* Remember which list the item is in. This allows fast removal of the + item later. */ + pxNewListItem->pxContainer = pxList; - ( pxList->uxNumberOfItems )++; + ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ @@ -173,26 +173,26 @@ UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) item. */ List_t * const pxList = pxItemToRemove->pxContainer; - pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; - pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; + pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; + pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); - /* Make sure the index is left pointing to a valid item. */ - if( pxList->pxIndex == pxItemToRemove ) - { - pxList->pxIndex = pxItemToRemove->pxPrevious; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Make sure the index is left pointing to a valid item. */ + if( pxList->pxIndex == pxItemToRemove ) + { + pxList->pxIndex = pxItemToRemove->pxPrevious; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxItemToRemove->pxContainer = NULL; - ( pxList->uxNumberOfItems )--; + pxItemToRemove->pxContainer = NULL; + ( pxList->uxNumberOfItems )--; - return pxList->uxNumberOfItems; + return pxList->uxNumberOfItems; } /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h b/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h index ef954846..5fb31a71 100644 --- a/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h +++ b/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h @@ -62,48 +62,48 @@ #define portasmHAS_CLINT 0 /* Constants to define the additional registers found on the Pulpino RI5KY. */ -#define lpstart0 0x7b0 -#define lpend0 0x7b1 -#define lpcount0 0x7b2 -#define lpstart1 0x7b4 -#define lpend1 0x7b5 -#define lpcount1 0x7b6 +#define lpstart0 0x7b0 +#define lpend0 0x7b1 +#define lpcount0 0x7b2 +#define lpstart1 0x7b4 +#define lpend1 0x7b5 +#define lpcount1 0x7b6 /* Six additional registers to save and restore, as per the #defines above. */ #define portasmADDITIONAL_CONTEXT_SIZE 6 /* Must be even number on 32-bit cores. */ /* Save additional registers found on the Pulpino. */ .macro portasmSAVE_ADDITIONAL_REGISTERS - addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) /* Make room for the additional registers. */ - csrr t0, lpstart0 /* Load additional registers into accessible temporary registers. */ - csrr t1, lpend0 - csrr t2, lpcount0 - csrr t3, lpstart1 - csrr t4, lpend1 - csrr t5, lpcount1 - sw t0, 1 * portWORD_SIZE( sp ) - sw t1, 2 * portWORD_SIZE( sp ) - sw t2, 3 * portWORD_SIZE( sp ) - sw t3, 4 * portWORD_SIZE( sp ) - sw t4, 5 * portWORD_SIZE( sp ) - sw t5, 6 * portWORD_SIZE( sp ) - .endm + addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) /* Make room for the additional registers. */ + csrr t0, lpstart0 /* Load additional registers into accessible temporary registers. */ + csrr t1, lpend0 + csrr t2, lpcount0 + csrr t3, lpstart1 + csrr t4, lpend1 + csrr t5, lpcount1 + sw t0, 1 * portWORD_SIZE( sp ) + sw t1, 2 * portWORD_SIZE( sp ) + sw t2, 3 * portWORD_SIZE( sp ) + sw t3, 4 * portWORD_SIZE( sp ) + sw t4, 5 * portWORD_SIZE( sp ) + sw t5, 6 * portWORD_SIZE( sp ) + .endm /* Restore the additional registers found on the Pulpino. */ .macro portasmRESTORE_ADDITIONAL_REGISTERS - lw t0, 1 * portWORD_SIZE( sp ) /* Load additional registers into accessible temporary registers. */ - lw t1, 2 * portWORD_SIZE( sp ) - lw t2, 3 * portWORD_SIZE( sp ) - lw t3, 4 * portWORD_SIZE( sp ) - lw t4, 5 * portWORD_SIZE( sp ) - lw t5, 6 * portWORD_SIZE( sp ) - csrw lpstart0, t0 - csrw lpend0, t1 - csrw lpcount0, t2 - csrw lpstart1, t3 - csrw lpend1, t4 - csrw lpcount1, t5 - addi sp, sp, (portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE )/* Remove space added for additional registers. */ - .endm + lw t0, 1 * portWORD_SIZE( sp ) /* Load additional registers into accessible temporary registers. */ + lw t1, 2 * portWORD_SIZE( sp ) + lw t2, 3 * portWORD_SIZE( sp ) + lw t3, 4 * portWORD_SIZE( sp ) + lw t4, 5 * portWORD_SIZE( sp ) + lw t5, 6 * portWORD_SIZE( sp ) + csrw lpstart0, t0 + csrw lpend0, t1 + csrw lpcount0, t2 + csrw lpstart1, t3 + csrw lpend1, t4 + csrw lpcount1, t5 + addi sp, sp, (portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE )/* Remove space added for additional registers. */ + .endm #endif /* __FREERTOS_RISC_V_EXTENSIONS_H__ */ diff --git a/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h b/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h index b3562abe..e0849880 100644 --- a/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h +++ b/components/bl602/freertos_riscv/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h @@ -57,12 +57,12 @@ #define portasmADDITIONAL_CONTEXT_SIZE 0 /* Must be even number on 32-bit cores. */ .macro portasmSAVE_ADDITIONAL_REGISTERS - /* No additional registers to save, so this macro does nothing. */ - .endm + /* No additional registers to save, so this macro does nothing. */ + .endm /* Restore the additional registers found on the Pulpino. */ .macro portasmRESTORE_ADDITIONAL_REGISTERS - /* No additional registers to restore, so this macro does nothing. */ - .endm + /* No additional registers to restore, so this macro does nothing. */ + .endm #endif /* __FREERTOS_RISC_V_EXTENSIONS_H__ */ diff --git a/components/bl602/freertos_riscv/portable/GCC/RISC-V/port.c b/components/bl602/freertos_riscv/portable/GCC/RISC-V/port.c index fa61bf4f..a11eea50 100644 --- a/components/bl602/freertos_riscv/portable/GCC/RISC-V/port.c +++ b/components/bl602/freertos_riscv/portable/GCC/RISC-V/port.c @@ -35,16 +35,16 @@ #include "portmacro.h" #ifndef configCLINT_BASE_ADDRESS - #warning configCLINT_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a Core Local Interrupter (CLINT) then set configCLINT_BASE_ADDRESS to the CLINT base address. Otherwise set configCLINT_BASE_ADDRESS to 0. + #warning configCLINT_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a Core Local Interrupter (CLINT) then set configCLINT_BASE_ADDRESS to the CLINT base address. Otherwise set configCLINT_BASE_ADDRESS to 0. #endif /* Let the user override the pre-loading of the initial LR with the address of prvTaskExitError() in case it messes up unwinding of the stack in the debugger. */ #ifdef configTASK_RETURN_ADDRESS - #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS + #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS #else - #define portTASK_RETURN_ADDRESS prvTaskExitError + #define portTASK_RETURN_ADDRESS prvTaskExitError #endif /* The stack used by interrupt service routines. Set configISR_STACK_SIZE_WORDS @@ -55,10 +55,10 @@ of the stack used by main. Using the linker script method will repurpose the stack that was used by main before the scheduler was started for use as the interrupt stack after the scheduler has started. */ #ifdef configISR_STACK_SIZE_WORDS - static __attribute__ ((aligned(16))) StackType_t xISRStack[ configISR_STACK_SIZE_WORDS ] = { 0 }; - const StackType_t xISRStackTop = ( StackType_t ) &( xISRStack[ ( configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK ) - 1 ] ); + static __attribute__ ((aligned(16))) StackType_t xISRStack[ configISR_STACK_SIZE_WORDS ] = { 0 }; + const StackType_t xISRStackTop = ( StackType_t ) &( xISRStack[ ( configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK ) - 1 ] ); #else - StackType_t xISRStackTop; + StackType_t xISRStackTop; #endif /* @@ -83,50 +83,50 @@ stack checking. A problem in the ISR stack will trigger an assert, not call the stack overflow hook function (because the stack overflow hook is specific to a task stack, not the ISR stack). */ #if( configCHECK_FOR_STACK_OVERFLOW > 2 ) - #warning This path not tested, or even compiled yet. - /* Don't use 0xa5 as the stack fill bytes as that is used by the kernerl for - the task stacks, and so will legitimately appear in many positions within - the ISR stack. */ - #define portISR_STACK_FILL_BYTE 0xee + #warning This path not tested, or even compiled yet. + /* Don't use 0xa5 as the stack fill bytes as that is used by the kernerl for + the task stacks, and so will legitimately appear in many positions within + the ISR stack. */ + #define portISR_STACK_FILL_BYTE 0xee - static const uint8_t ucExpectedStackBytes[] = { - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE }; \ + static const uint8_t ucExpectedStackBytes[] = { + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE }; \ - #define portCHECK_ISR_STACK() configASSERT( ( memcmp( ( void * ) xISRStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) == 0 ) ) + #define portCHECK_ISR_STACK() configASSERT( ( memcmp( ( void * ) xISRStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) == 0 ) ) #else - /* Define the function away. */ - #define portCHECK_ISR_STACK() + /* Define the function away. */ + #define portCHECK_ISR_STACK() #endif /* configCHECK_FOR_STACK_OVERFLOW > 2 */ /*-----------------------------------------------------------*/ #if( configCLINT_BASE_ADDRESS != 0 ) - void vPortSetupTimerInterrupt( void ) - { - uint32_t ulCurrentTimeHigh, ulCurrentTimeLow; - volatile uint32_t * const pulTimeHigh = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFFC ); - volatile uint32_t * const pulTimeLow = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFF8 ); + void vPortSetupTimerInterrupt( void ) + { + uint32_t ulCurrentTimeHigh, ulCurrentTimeLow; + volatile uint32_t * const pulTimeHigh = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFFC ); + volatile uint32_t * const pulTimeLow = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFF8 ); - do - { - ulCurrentTimeHigh = *pulTimeHigh; - ulCurrentTimeLow = *pulTimeLow; - } while( ulCurrentTimeHigh != *pulTimeHigh ); + do + { + ulCurrentTimeHigh = *pulTimeHigh; + ulCurrentTimeLow = *pulTimeLow; + } while( ulCurrentTimeHigh != *pulTimeHigh ); - ullNextTime = ( uint64_t ) ulCurrentTimeHigh; - ullNextTime <<= 32ULL; - ullNextTime |= ( uint64_t ) ulCurrentTimeLow; - ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; - *pullMachineTimerCompareRegister = ullNextTime; + ullNextTime = ( uint64_t ) ulCurrentTimeHigh; + ullNextTime <<= 32ULL; + ullNextTime |= ( uint64_t ) ulCurrentTimeLow; + ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; + *pullMachineTimerCompareRegister = ullNextTime; - /* Prepare the time to use after the next tick interrupt. */ - ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; - } + /* Prepare the time to use after the next tick interrupt. */ + ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; + } #endif /* ( configCLINT_BASE_ADDRESS != 0 ) */ /*-----------------------------------------------------------*/ @@ -135,55 +135,55 @@ BaseType_t xPortStartScheduler( void ) { extern void xPortStartFirstTask( void ); - #if( configASSERT_DEFINED == 1 ) - { - volatile uint32_t mtvec = 0; + #if( configASSERT_DEFINED == 1 ) + { + volatile uint32_t mtvec = 0; - /* Check the least significant two bits of mtvec are 00 - indicating - single vector mode. */ - __asm volatile( "csrr %0, mtvec" : "=r"( mtvec ) ); + /* Check the least significant two bits of mtvec are 00 - indicating + single vector mode. */ + __asm volatile( "csrr %0, mtvec" : "=r"( mtvec ) ); - /* Check alignment of the interrupt stack - which is the same as the - stack that was being used by main() prior to the scheduler being - started. */ - configASSERT( ( xISRStackTop & portBYTE_ALIGNMENT_MASK ) == 0 ); - } - #endif /* configASSERT_DEFINED */ + /* Check alignment of the interrupt stack - which is the same as the + stack that was being used by main() prior to the scheduler being + started. */ + configASSERT( ( xISRStackTop & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + #endif /* configASSERT_DEFINED */ - /* If there is a CLINT then it is ok to use the default implementation - in this file, otherwise vPortSetupTimerInterrupt() must be implemented to - configure whichever clock is to be used to generate the tick interrupt. */ - vPortSetupTimerInterrupt(); + /* If there is a CLINT then it is ok to use the default implementation + in this file, otherwise vPortSetupTimerInterrupt() must be implemented to + configure whichever clock is to be used to generate the tick interrupt. */ + vPortSetupTimerInterrupt(); - #if( configCLINT_BASE_ADDRESS != 0 ) - { - /* Enable mtime and external interrupts. 1<<7 for timer interrupt, 1<<11 - for external interrupt. _RB_ What happens here when mtime is not present as - with pulpino? */ - __asm volatile( "csrs mie, %0" :: "r"(0x880) ); - } - #else - { - /* Enable external interrupts. */ - __asm volatile( "csrs mie, %0" :: "r"(0x800) ); - } - #endif /* configCLINT_BASE_ADDRESS */ + #if( configCLINT_BASE_ADDRESS != 0 ) + { + /* Enable mtime and external interrupts. 1<<7 for timer interrupt, 1<<11 + for external interrupt. _RB_ What happens here when mtime is not present as + with pulpino? */ + __asm volatile( "csrs mie, %0" :: "r"(0x880) ); + } + #else + { + /* Enable external interrupts. */ + __asm volatile( "csrs mie, %0" :: "r"(0x800) ); + } + #endif /* configCLINT_BASE_ADDRESS */ /*Enable mtimer interrrupt*/ *(volatile uint8_t*)configCLIC_TIMER_ENABLE_ADDRESS = 1; - xPortStartFirstTask(); + xPortStartFirstTask(); - /* Should not get here as after calling xPortStartFirstTask() only tasks - should be executing. */ - return pdFAIL; + /* Should not get here as after calling xPortStartFirstTask() only tasks + should be executing. */ + return pdFAIL; } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { - /* Not implemented. */ - for( ;; ); + /* Not implemented. */ + for( ;; ); } diff --git a/components/bl602/freertos_riscv/portable/GCC/RISC-V/portmacro.h b/components/bl602/freertos_riscv/portable/GCC/RISC-V/portmacro.h index 0ca2dc67..ba0168af 100644 --- a/components/bl602/freertos_riscv/portable/GCC/RISC-V/portmacro.h +++ b/components/bl602/freertos_riscv/portable/GCC/RISC-V/portmacro.h @@ -45,17 +45,17 @@ extern "C" { /* Type definitions. */ #if __riscv_xlen == 64 - #define portSTACK_TYPE uint64_t - #define portBASE_TYPE int64_t - #define portUBASE_TYPE uint64_t - #define portMAX_DELAY ( TickType_t ) 0xffffffffffffffffUL + #define portSTACK_TYPE uint64_t + #define portBASE_TYPE int64_t + #define portUBASE_TYPE uint64_t + #define portMAX_DELAY ( TickType_t ) 0xffffffffffffffffUL #elif __riscv_xlen == 32 - #define portSTACK_TYPE uint32_t - #define portBASE_TYPE int32_t - #define portUBASE_TYPE uint32_t - #define portMAX_DELAY ( TickType_t ) 0xffffffffUL + #define portSTACK_TYPE uint32_t + #define portBASE_TYPE int32_t + #define portUBASE_TYPE uint32_t + #define portMAX_DELAY ( TickType_t ) 0xffffffffUL #else - #error Assembler did not define __riscv_xlen + #error Assembler did not define __riscv_xlen #endif @@ -70,13 +70,13 @@ not need to be guarded with a critical section. */ /*-----------------------------------------------------------*/ /* Architecture specifics. */ -#define portSTACK_GROWTH ( -1 ) -#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) +#define portSTACK_GROWTH ( -1 ) +#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) #ifdef __riscv64 - #error This is the RV32 port that has not yet been adapted for 64. - #define portBYTE_ALIGNMENT 16 + #error This is the RV32 port that has not yet been adapted for 64. + #define portBYTE_ALIGNMENT 16 #else - #define portBYTE_ALIGNMENT 8 + #define portBYTE_ALIGNMENT 8 #endif /*-----------------------------------------------------------*/ @@ -90,38 +90,38 @@ extern void vTaskSwitchContext( void ); /* Critical section management. */ -#define portCRITICAL_NESTING_IN_TCB 1 +#define portCRITICAL_NESTING_IN_TCB 1 extern void vTaskEnterCritical( void ); extern void vTaskExitCritical( void ); #define portSET_INTERRUPT_MASK_FROM_ISR() 0 #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue -#define portDISABLE_INTERRUPTS() __asm volatile( "csrc mstatus, 8" ) -#define portENABLE_INTERRUPTS() __asm volatile( "csrs mstatus, 8" ) -#define portENTER_CRITICAL() vTaskEnterCritical() -#define portEXIT_CRITICAL() vTaskExitCritical() +#define portDISABLE_INTERRUPTS() __asm volatile( "csrc mstatus, 8" ) +#define portENABLE_INTERRUPTS() __asm volatile( "csrs mstatus, 8" ) +#define portENTER_CRITICAL() vTaskEnterCritical() +#define portEXIT_CRITICAL() vTaskExitCritical() /*-----------------------------------------------------------*/ /* Architecture specific optimisations. */ #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #endif #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 ) - /* Check the configuration. */ - #if( configMAX_PRIORITIES > 32 ) - #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. - #endif + /* Check the configuration. */ + #if( configMAX_PRIORITIES > 32 ) + #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. + #endif - /* Store/clear the ready priorities in a bit map. */ - #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) - #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) + /* Store/clear the ready priorities in a bit map. */ + #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) + #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - rtos_clz( uxReadyPriorities ) ) + #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - rtos_clz( uxReadyPriorities ) ) #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ @@ -136,12 +136,12 @@ not necessary for to use this port. They are defined so the common demo files /*-----------------------------------------------------------*/ -#define portNOP() __asm volatile ( " nop " ) +#define portNOP() __asm volatile ( " nop " ) -#define portINLINE __inline +#define portINLINE __inline #ifndef portFORCE_INLINE - #define portFORCE_INLINE inline __attribute__(( always_inline)) + #define portFORCE_INLINE inline __attribute__(( always_inline)) #endif #define portMEMORY_BARRIER() __asm volatile( "" ::: "memory" ) diff --git a/components/bl602/freertos_riscv/portable/MemMang/heap_1.c b/components/bl602/freertos_riscv/portable/MemMang/heap_1.c index 542317dc..a28bac89 100644 --- a/components/bl602/freertos_riscv/portable/MemMang/heap_1.c +++ b/components/bl602/freertos_riscv/portable/MemMang/heap_1.c @@ -46,19 +46,19 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* A few bytes might be lost to byte aligning the heap start address. */ -#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) +#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) /* Allocate the memory for the heap. */ #if( configAPPLICATION_ALLOCATED_HEAP == 1 ) - /* The application writer has already defined the array used for the RTOS - heap - probably so it can be placed in a special segment or address. */ - extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + /* The application writer has already defined the array used for the RTOS + heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #else - static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #endif /* configAPPLICATION_ALLOCATED_HEAP */ /* Index into the ucHeap array. */ @@ -71,75 +71,75 @@ void *pvPortMalloc( size_t xWantedSize ) void *pvReturn = NULL; static uint8_t *pucAlignedHeap = NULL; - /* Ensure that blocks are always aligned to the required number of bytes. */ - #if( portBYTE_ALIGNMENT != 1 ) - { - if( xWantedSize & portBYTE_ALIGNMENT_MASK ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - } - } - #endif + /* Ensure that blocks are always aligned to the required number of bytes. */ + #if( portBYTE_ALIGNMENT != 1 ) + { + if( xWantedSize & portBYTE_ALIGNMENT_MASK ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + } + #endif - vTaskSuspendAll(); - { - if( pucAlignedHeap == NULL ) - { - /* Ensure the heap starts on a correctly aligned boundary. */ - pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); - } + vTaskSuspendAll(); + { + if( pucAlignedHeap == NULL ) + { + /* Ensure the heap starts on a correctly aligned boundary. */ + pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + } - /* Check there is enough room left for the allocation. */ - if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) && - ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) )/* Check for overflow. */ - { - /* Return the next free byte then increment the index past this - block. */ - pvReturn = pucAlignedHeap + xNextFreeByte; - xNextFreeByte += xWantedSize; - } + /* Check there is enough room left for the allocation. */ + if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) && + ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) )/* Check for overflow. */ + { + /* Return the next free byte then increment the index past this + block. */ + pvReturn = pucAlignedHeap + xNextFreeByte; + xNextFreeByte += xWantedSize; + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ void vPortFree( void *pv ) { - /* Memory cannot be freed using this scheme. See heap_2.c, heap_3.c and - heap_4.c for alternative implementations, and the memory management pages of - http://www.FreeRTOS.org for more information. */ - ( void ) pv; + /* Memory cannot be freed using this scheme. See heap_2.c, heap_3.c and + heap_4.c for alternative implementations, and the memory management pages of + http://www.FreeRTOS.org for more information. */ + ( void ) pv; - /* Force an assert as it is invalid to call this function. */ - configASSERT( pv == NULL ); + /* Force an assert as it is invalid to call this function. */ + configASSERT( pv == NULL ); } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { - /* Only required when static memory is not cleared. */ - xNextFreeByte = ( size_t ) 0; + /* Only required when static memory is not cleared. */ + xNextFreeByte = ( size_t ) 0; } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return ( configADJUSTED_HEAP_SIZE - xNextFreeByte ); + return ( configADJUSTED_HEAP_SIZE - xNextFreeByte ); } diff --git a/components/bl602/freertos_riscv/portable/MemMang/heap_2.c b/components/bl602/freertos_riscv/portable/MemMang/heap_2.c index 7d069212..4d912dce 100644 --- a/components/bl602/freertos_riscv/portable/MemMang/heap_2.c +++ b/components/bl602/freertos_riscv/portable/MemMang/heap_2.c @@ -47,11 +47,11 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* A few bytes might be lost to byte aligning the heap start address. */ -#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) +#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) /* * Initialises the heap structures before their first use. @@ -60,11 +60,11 @@ static void prvHeapInit( void ); /* Allocate the memory for the heap. */ #if( configAPPLICATION_ALLOCATED_HEAP == 1 ) - /* The application writer has already defined the array used for the RTOS - heap - probably so it can be placed in a special segment or address. */ - extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + /* The application writer has already defined the array used for the RTOS + heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #else - static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #endif /* configAPPLICATION_ALLOCATED_HEAP */ @@ -72,13 +72,13 @@ static void prvHeapInit( void ); of their size. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; -static const uint16_t heapSTRUCT_SIZE = ( ( sizeof ( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK ); -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) ) +static const uint16_t heapSTRUCT_SIZE = ( ( sizeof ( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK ); +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) ) /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, xEnd; @@ -94,24 +94,24 @@ static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE; * the block. Small blocks at the start of the list and large blocks at the end * of the list. */ -#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \ -{ \ -BlockLink_t *pxIterator; \ -size_t xBlockSize; \ - \ - xBlockSize = pxBlockToInsert->xBlockSize; \ - \ - /* Iterate through the list until a block is found that has a larger size */ \ - /* than the block we are inserting. */ \ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \ - { \ - /* There is nothing to do here - just iterate to the correct position. */ \ - } \ - \ - /* Update the list to include the block being inserted in the correct */ \ - /* position. */ \ - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \ - pxIterator->pxNextFreeBlock = pxBlockToInsert; \ +#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \ +{ \ +BlockLink_t *pxIterator; \ +size_t xBlockSize; \ + \ + xBlockSize = pxBlockToInsert->xBlockSize; \ + \ + /* Iterate through the list until a block is found that has a larger size */ \ + /* than the block we are inserting. */ \ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \ + { \ + /* There is nothing to do here - just iterate to the correct position. */ \ + } \ + \ + /* Update the list to include the block being inserted in the correct */ \ + /* position. */ \ + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \ + pxIterator->pxNextFreeBlock = pxBlockToInsert; \ } /*-----------------------------------------------------------*/ @@ -121,89 +121,89 @@ BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; static BaseType_t xHeapHasBeenInitialised = pdFALSE; void *pvReturn = NULL; - vTaskSuspendAll(); - { - /* If this is the first call to malloc then the heap will require - initialisation to setup the list of free blocks. */ - if( xHeapHasBeenInitialised == pdFALSE ) - { - prvHeapInit(); - xHeapHasBeenInitialised = pdTRUE; - } + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + initialisation to setup the list of free blocks. */ + if( xHeapHasBeenInitialised == pdFALSE ) + { + prvHeapInit(); + xHeapHasBeenInitialised = pdTRUE; + } - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += heapSTRUCT_SIZE; + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += heapSTRUCT_SIZE; - /* Ensure that blocks are always aligned to the required number of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - } - } + /* Ensure that blocks are always aligned to the required number of bytes. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + } - if( ( xWantedSize > 0 ) && ( xWantedSize < configADJUSTED_HEAP_SIZE ) ) - { - /* Blocks are stored in byte order - traverse the list from the start - (smallest) block until one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } + if( ( xWantedSize > 0 ) && ( xWantedSize < configADJUSTED_HEAP_SIZE ) ) + { + /* Blocks are stored in byte order - traverse the list from the start + (smallest) block until one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } - /* If we found the end marker then a block of adequate size was not found. */ - if( pxBlock != &xEnd ) - { - /* Return the memory space - jumping over the BlockLink_t structure - at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE ); + /* If we found the end marker then a block of adequate size was not found. */ + if( pxBlock != &xEnd ) + { + /* Return the memory space - jumping over the BlockLink_t structure + at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE ); - /* This block is being returned for use so must be taken out of the - list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + /* This block is being returned for use so must be taken out of the + list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - /* If the block is larger than required it can be split into two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new block - following the number of bytes requested. The void cast is - used to prevent byte alignment warnings from the compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + /* If the block is larger than required it can be split into two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new block + following the number of bytes requested. The void cast is + used to prevent byte alignment warnings from the compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - /* Calculate the sizes of two blocks split from the single - block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; + /* Calculate the sizes of two blocks split from the single + block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); - } + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + } - xFreeBytesRemaining -= pxBlock->xBlockSize; - } - } + xFreeBytesRemaining -= pxBlock->xBlockSize; + } + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ @@ -212,37 +212,37 @@ void vPortFree( void *pv ) uint8_t *puc = ( uint8_t * ) pv; BlockLink_t *pxLink; - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= heapSTRUCT_SIZE; + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= heapSTRUCT_SIZE; - /* This unexpected casting is to keep some compilers from issuing - byte alignment warnings. */ - pxLink = ( void * ) puc; + /* This unexpected casting is to keep some compilers from issuing + byte alignment warnings. */ + pxLink = ( void * ) puc; - vTaskSuspendAll(); - { - /* Add this block to the list of free blocks. */ - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - } - ( void ) xTaskResumeAll(); - } + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + } + ( void ) xTaskResumeAll(); + } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return xFreeBytesRemaining; + return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { - /* This just exists to keep the linker quiet. */ + /* This just exists to keep the linker quiet. */ } /*-----------------------------------------------------------*/ @@ -251,22 +251,22 @@ static void prvHeapInit( void ) BlockLink_t *pxFirstFreeBlock; uint8_t *pucAlignedHeap; - /* Ensure the heap starts on a correctly aligned boundary. */ - pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + /* Ensure the heap starts on a correctly aligned boundary. */ + pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); - /* xStart is used to hold a pointer to the first item in the list of free - blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; + /* xStart is used to hold a pointer to the first item in the list of free + blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; - /* xEnd is used to mark the end of the list of free blocks. */ - xEnd.xBlockSize = configADJUSTED_HEAP_SIZE; - xEnd.pxNextFreeBlock = NULL; + /* xEnd is used to mark the end of the list of free blocks. */ + xEnd.xBlockSize = configADJUSTED_HEAP_SIZE; + xEnd.pxNextFreeBlock = NULL; - /* To start with there is a single free block that is sized to take up the - entire heap space. */ - pxFirstFreeBlock = ( void * ) pucAlignedHeap; - pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE; - pxFirstFreeBlock->pxNextFreeBlock = &xEnd; + /* To start with there is a single free block that is sized to take up the + entire heap space. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE; + pxFirstFreeBlock->pxNextFreeBlock = &xEnd; } /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv/portable/MemMang/heap_3.c b/components/bl602/freertos_riscv/portable/MemMang/heap_3.c index e6a29908..5f575cf9 100644 --- a/components/bl602/freertos_riscv/portable/MemMang/heap_3.c +++ b/components/bl602/freertos_riscv/portable/MemMang/heap_3.c @@ -50,7 +50,7 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /*-----------------------------------------------------------*/ @@ -59,38 +59,38 @@ void *pvPortMalloc( size_t xWantedSize ) { void *pvReturn; - vTaskSuspendAll(); - { - pvReturn = malloc( xWantedSize ); - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + vTaskSuspendAll(); + { + pvReturn = malloc( xWantedSize ); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ void vPortFree( void *pv ) { - if( pv ) - { - vTaskSuspendAll(); - { - free( pv ); - traceFREE( pv, 0 ); - } - ( void ) xTaskResumeAll(); - } + if( pv ) + { + vTaskSuspendAll(); + { + free( pv ); + traceFREE( pv, 0 ); + } + ( void ) xTaskResumeAll(); + } } diff --git a/components/bl602/freertos_riscv/portable/MemMang/heap_4.c b/components/bl602/freertos_riscv/portable/MemMang/heap_4.c index d7cd8a5b..aa2a885a 100644 --- a/components/bl602/freertos_riscv/portable/MemMang/heap_4.c +++ b/components/bl602/freertos_riscv/portable/MemMang/heap_4.c @@ -46,30 +46,30 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* Block sizes must not get too small. */ -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) /* Assumes 8bit bytes! */ -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) /* Allocate the memory for the heap. */ #if( configAPPLICATION_ALLOCATED_HEAP == 1 ) - /* The application writer has already defined the array used for the RTOS - heap - probably so it can be placed in a special segment or address. */ - extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + /* The application writer has already defined the array used for the RTOS + heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #else - static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #endif /* configAPPLICATION_ALLOCATED_HEAP */ /* Define the linked list structure. This is used to link free blocks in order of their memory address. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; /*-----------------------------------------------------------*/ @@ -92,7 +92,7 @@ static void prvHeapInit( void ); /* The size of the structure placed at the beginning of each allocated memory block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); +static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; @@ -115,148 +115,148 @@ void *pvPortMalloc( size_t xWantedSize ) BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; void *pvReturn = NULL; - vTaskSuspendAll(); - { - /* If this is the first call to malloc then the heap will require - initialisation to setup the list of free blocks. */ - if( pxEnd == NULL ) - { - prvHeapInit(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + initialisation to setup the list of free blocks. */ + if( pxEnd == NULL ) + { + prvHeapInit(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Check the requested block size is not so large that the top bit is - set. The top bit of the block size member of the BlockLink_t structure - is used to determine who owns the block - the application or the - kernel, so it must be free. */ - if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) - { - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += xHeapStructSize; + /* Check the requested block size is not so large that the top bit is + set. The top bit of the block size member of the BlockLink_t structure + is used to determine who owns the block - the application or the + kernel, so it must be free. */ + if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) + { + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += xHeapStructSize; - /* Ensure that blocks are always aligned to the required number - of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Ensure that blocks are always aligned to the required number + of bytes. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) - { - /* Traverse the list from the start (lowest address) block until - one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } - /* If the end marker was reached then a block of adequate size - was not found. */ - if( pxBlock != pxEnd ) - { - /* Return the memory space pointed to - jumping over the - BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + /* If the end marker was reached then a block of adequate size + was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); - /* This block is being returned for use so must be taken out - of the list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + /* This block is being returned for use so must be taken out + of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - /* If the block is larger than required it can be split into - two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new - block following the number of bytes requested. The void - cast is used to prevent byte alignment warnings from the - compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); + /* If the block is larger than required it can be split into + two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + block following the number of bytes requested. The void + cast is used to prevent byte alignment warnings from the + compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); - /* Calculate the sizes of two blocks split from the - single block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; + /* Calculate the sizes of two blocks split from the + single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( pxNewBlockLink ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( pxNewBlockLink ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xFreeBytesRemaining -= pxBlock->xBlockSize; + xFreeBytesRemaining -= pxBlock->xBlockSize; - if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) - { - xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The block is being returned - it is allocated and owned - by the application and has no "next" block. */ - pxBlock->xBlockSize |= xBlockAllocatedBit; - pxBlock->pxNextFreeBlock = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* The block is being returned - it is allocated and owned + by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif - configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); - return pvReturn; + configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); + return pvReturn; } /*-----------------------------------------------------------*/ @@ -265,64 +265,64 @@ void vPortFree( void *pv ) uint8_t *puc = ( uint8_t * ) pv; BlockLink_t *pxLink; - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= xHeapStructSize; + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= xHeapStructSize; - /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; - /* Check the block is actually allocated. */ - configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - configASSERT( pxLink->pxNextFreeBlock == NULL ); + /* Check the block is actually allocated. */ + configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + configASSERT( pxLink->pxNextFreeBlock == NULL ); - if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) - { - if( pxLink->pxNextFreeBlock == NULL ) - { - /* The block is being returned to the heap - it is no longer - allocated. */ - pxLink->xBlockSize &= ~xBlockAllocatedBit; + if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) + { + if( pxLink->pxNextFreeBlock == NULL ) + { + /* The block is being returned to the heap - it is no longer + allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; - vTaskSuspendAll(); - { - /* Add this block to the list of free blocks. */ - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return xFreeBytesRemaining; + return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ size_t xPortGetMinimumEverFreeHeapSize( void ) { - return xMinimumEverFreeBytesRemaining; + return xMinimumEverFreeBytesRemaining; } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { - /* This just exists to keep the linker quiet. */ + /* This just exists to keep the linker quiet. */ } /*-----------------------------------------------------------*/ @@ -333,44 +333,44 @@ uint8_t *pucAlignedHeap; size_t uxAddress; size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; - /* Ensure the heap starts on a correctly aligned boundary. */ - uxAddress = ( size_t ) ucHeap; + /* Ensure the heap starts on a correctly aligned boundary. */ + uxAddress = ( size_t ) ucHeap; - if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - uxAddress += ( portBYTE_ALIGNMENT - 1 ); - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; - } + if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + uxAddress += ( portBYTE_ALIGNMENT - 1 ); + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; + } - pucAlignedHeap = ( uint8_t * ) uxAddress; + pucAlignedHeap = ( uint8_t * ) uxAddress; - /* xStart is used to hold a pointer to the first item in the list of free - blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; + /* xStart is used to hold a pointer to the first item in the list of free + blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; - /* pxEnd is used to mark the end of the list of free blocks and is inserted - at the end of the heap space. */ - uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; - uxAddress -= xHeapStructSize; - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - pxEnd = ( void * ) uxAddress; - pxEnd->xBlockSize = 0; - pxEnd->pxNextFreeBlock = NULL; + /* pxEnd is used to mark the end of the list of free blocks and is inserted + at the end of the heap space. */ + uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; + uxAddress -= xHeapStructSize; + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + pxEnd = ( void * ) uxAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; - /* To start with there is a single free block that is sized to take up the - entire heap space, minus the space taken by pxEnd. */ - pxFirstFreeBlock = ( void * ) pucAlignedHeap; - pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; - pxFirstFreeBlock->pxNextFreeBlock = pxEnd; + /* To start with there is a single free block that is sized to take up the + entire heap space, minus the space taken by pxEnd. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; + pxFirstFreeBlock->pxNextFreeBlock = pxEnd; - /* Only one block exists - and it covers the entire usable heap space. */ - xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + /* Only one block exists - and it covers the entire usable heap space. */ + xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); } /*-----------------------------------------------------------*/ @@ -379,58 +379,58 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) BlockLink_t *pxIterator; uint8_t *puc; - /* Iterate through the list until a block is found that has a higher address - than the block being inserted. */ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) - { - /* Nothing to do here, just iterate to the right position. */ - } + /* Iterate through the list until a block is found that has a higher address + than the block being inserted. */ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) + { + /* Nothing to do here, just iterate to the right position. */ + } - /* Do the block being inserted, and the block it is being inserted after - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; - if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) - { - pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; - pxBlockToInsert = pxIterator; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Do the block being inserted, and the block it is being inserted after + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxIterator; + if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) + { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Do the block being inserted, and the block it is being inserted before - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; - if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) - { - if( pxIterator->pxNextFreeBlock != pxEnd ) - { - /* Form one big block from the two blocks. */ - pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxEnd; - } - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; - } + /* Do the block being inserted, and the block it is being inserted before + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxBlockToInsert; + if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) + { + if( pxIterator->pxNextFreeBlock != pxEnd ) + { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } - /* If the block being inserted plugged a gab, so was merged with the block - before and the block after, then it's pxNextFreeBlock pointer will have - already been set, and should not be set here as that would make it point - to itself. */ - if( pxIterator != pxBlockToInsert ) - { - pxIterator->pxNextFreeBlock = pxBlockToInsert; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the block being inserted plugged a gab, so was merged with the block + before and the block after, then it's pxNextFreeBlock pointer will have + already been set, and should not be set here as that would make it point + to itself. */ + if( pxIterator != pxBlockToInsert ) + { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } diff --git a/components/bl602/freertos_riscv/portable/MemMang/heap_5.c b/components/bl602/freertos_riscv/portable/MemMang/heap_5.c index 035a48d7..e01ca558 100644 --- a/components/bl602/freertos_riscv/portable/MemMang/heap_5.c +++ b/components/bl602/freertos_riscv/portable/MemMang/heap_5.c @@ -46,8 +46,8 @@ * * typedef struct HeapRegion * { - * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap. - * size_t xSizeInBytes; << Size of the block of memory. + * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap. + * size_t xSizeInBytes; << Size of the block of memory. * } HeapRegion_t; * * The array is terminated using a NULL zero sized region definition, and the @@ -57,9 +57,9 @@ * * HeapRegion_t xHeapRegions[] = * { - * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000 - * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000 - * { NULL, 0 } << Terminates the array. + * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000 + * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000 + * { NULL, 0 } << Terminates the array. * }; * * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions(). @@ -80,21 +80,21 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* Block sizes must not get too small. */ -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) /* Assumes 8bit bytes! */ -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) /* Define the linked list structure. This is used to link free blocks in order of their memory address. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; /*-----------------------------------------------------------*/ @@ -111,7 +111,7 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); /* The size of the structure placed at the beginning of each allocated memory block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); +static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; @@ -134,138 +134,138 @@ void *pvPortMalloc( size_t xWantedSize ) BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; void *pvReturn = NULL; - /* The heap must be initialised before the first call to - prvPortMalloc(). */ - configASSERT( pxEnd ); + /* The heap must be initialised before the first call to + prvPortMalloc(). */ + configASSERT( pxEnd ); - vTaskSuspendAll(); - { - /* Check the requested block size is not so large that the top bit is - set. The top bit of the block size member of the BlockLink_t structure - is used to determine who owns the block - the application or the - kernel, so it must be free. */ - if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) - { - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += xHeapStructSize; + vTaskSuspendAll(); + { + /* Check the requested block size is not so large that the top bit is + set. The top bit of the block size member of the BlockLink_t structure + is used to determine who owns the block - the application or the + kernel, so it must be free. */ + if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) + { + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += xHeapStructSize; - /* Ensure that blocks are always aligned to the required number - of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Ensure that blocks are always aligned to the required number + of bytes. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) - { - /* Traverse the list from the start (lowest address) block until - one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } - /* If the end marker was reached then a block of adequate size - was not found. */ - if( pxBlock != pxEnd ) - { - /* Return the memory space pointed to - jumping over the - BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + /* If the end marker was reached then a block of adequate size + was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); - /* This block is being returned for use so must be taken out - of the list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + /* This block is being returned for use so must be taken out + of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - /* If the block is larger than required it can be split into - two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new - block following the number of bytes requested. The void - cast is used to prevent byte alignment warnings from the - compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + /* If the block is larger than required it can be split into + two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + block following the number of bytes requested. The void + cast is used to prevent byte alignment warnings from the + compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - /* Calculate the sizes of two blocks split from the - single block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; + /* Calculate the sizes of two blocks split from the + single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xFreeBytesRemaining -= pxBlock->xBlockSize; + xFreeBytesRemaining -= pxBlock->xBlockSize; - if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) - { - xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The block is being returned - it is allocated and owned - by the application and has no "next" block. */ - pxBlock->xBlockSize |= xBlockAllocatedBit; - pxBlock->pxNextFreeBlock = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* The block is being returned - it is allocated and owned + by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void (*vApplicationMallocFailedHook)( void ); - vApplicationMallocFailedHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void (*vApplicationMallocFailedHook)( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ @@ -274,58 +274,58 @@ void vPortFree( void *pv ) uint8_t *puc = ( uint8_t * ) pv; BlockLink_t *pxLink; - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= xHeapStructSize; + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= xHeapStructSize; - /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; - /* Check the block is actually allocated. */ - configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - configASSERT( pxLink->pxNextFreeBlock == NULL ); + /* Check the block is actually allocated. */ + configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + configASSERT( pxLink->pxNextFreeBlock == NULL ); - if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) - { - if( pxLink->pxNextFreeBlock == NULL ) - { - /* The block is being returned to the heap - it is no longer - allocated. */ - pxLink->xBlockSize &= ~xBlockAllocatedBit; + if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) + { + if( pxLink->pxNextFreeBlock == NULL ) + { + /* The block is being returned to the heap - it is no longer + allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; - vTaskSuspendAll(); - { - /* Add this block to the list of free blocks. */ - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return xFreeBytesRemaining; + return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ size_t xPortGetMinimumEverFreeHeapSize( void ) { - return xMinimumEverFreeBytesRemaining; + return xMinimumEverFreeBytesRemaining; } /*-----------------------------------------------------------*/ @@ -334,59 +334,59 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) BlockLink_t *pxIterator; uint8_t *puc; - /* Iterate through the list until a block is found that has a higher address - than the block being inserted. */ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) - { - /* Nothing to do here, just iterate to the right position. */ - } + /* Iterate through the list until a block is found that has a higher address + than the block being inserted. */ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) + { + /* Nothing to do here, just iterate to the right position. */ + } - /* Do the block being inserted, and the block it is being inserted after - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; - if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) - { - pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; - pxBlockToInsert = pxIterator; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Do the block being inserted, and the block it is being inserted after + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxIterator; + if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) + { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Do the block being inserted, and the block it is being inserted before - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; - if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) - { - if( pxIterator->pxNextFreeBlock != pxEnd ) - { - /* Form one big block from the two blocks. */ - pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxEnd; - } - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; - } + /* Do the block being inserted, and the block it is being inserted before + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxBlockToInsert; + if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) + { + if( pxIterator->pxNextFreeBlock != pxEnd ) + { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } - /* If the block being inserted plugged a gab, so was merged with the block - before and the block after, then it's pxNextFreeBlock pointer will have - already been set, and should not be set here as that would make it point - to itself. */ - if( pxIterator != pxBlockToInsert ) - { - pxIterator->pxNextFreeBlock = pxBlockToInsert; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the block being inserted plugged a gab, so was merged with the block + before and the block after, then it's pxNextFreeBlock pointer will have + already been set, and should not be set here as that would make it point + to itself. */ + if( pxIterator != pxBlockToInsert ) + { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } /*-----------------------------------------------------------*/ @@ -399,87 +399,87 @@ BaseType_t xDefinedRegions = 0; size_t xAddress; const HeapRegion_t *pxHeapRegion; - /* Can only call once! */ - configASSERT( pxEnd == NULL ); + /* Can only call once! */ + configASSERT( pxEnd == NULL ); - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); - while( pxHeapRegion->xSizeInBytes > 0 ) - { - xTotalRegionSize = pxHeapRegion->xSizeInBytes; + while( pxHeapRegion->xSizeInBytes > 0 ) + { + xTotalRegionSize = pxHeapRegion->xSizeInBytes; - /* Ensure the heap region starts on a correctly aligned boundary. */ - xAddress = ( size_t ) pxHeapRegion->pucStartAddress; - if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - xAddress += ( portBYTE_ALIGNMENT - 1 ); - xAddress &= ~portBYTE_ALIGNMENT_MASK; + /* Ensure the heap region starts on a correctly aligned boundary. */ + xAddress = ( size_t ) pxHeapRegion->pucStartAddress; + if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + xAddress += ( portBYTE_ALIGNMENT - 1 ); + xAddress &= ~portBYTE_ALIGNMENT_MASK; - /* Adjust the size for the bytes lost to alignment. */ - xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress; - } + /* Adjust the size for the bytes lost to alignment. */ + xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress; + } - xAlignedHeap = xAddress; + xAlignedHeap = xAddress; - /* Set xStart if it has not already been set. */ - if( xDefinedRegions == 0 ) - { - /* xStart is used to hold a pointer to the first item in the list of - free blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; - } - else - { - /* Should only get here if one region has already been added to the - heap. */ - configASSERT( pxEnd != NULL ); + /* Set xStart if it has not already been set. */ + if( xDefinedRegions == 0 ) + { + /* xStart is used to hold a pointer to the first item in the list of + free blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; + } + else + { + /* Should only get here if one region has already been added to the + heap. */ + configASSERT( pxEnd != NULL ); - /* Check blocks are passed in with increasing start addresses. */ - configASSERT( xAddress > ( size_t ) pxEnd ); - } + /* Check blocks are passed in with increasing start addresses. */ + configASSERT( xAddress > ( size_t ) pxEnd ); + } - /* Remember the location of the end marker in the previous region, if - any. */ - pxPreviousFreeBlock = pxEnd; + /* Remember the location of the end marker in the previous region, if + any. */ + pxPreviousFreeBlock = pxEnd; - /* pxEnd is used to mark the end of the list of free blocks and is - inserted at the end of the region space. */ - xAddress = xAlignedHeap + xTotalRegionSize; - xAddress -= xHeapStructSize; - xAddress &= ~portBYTE_ALIGNMENT_MASK; - pxEnd = ( BlockLink_t * ) xAddress; - pxEnd->xBlockSize = 0; - pxEnd->pxNextFreeBlock = NULL; + /* pxEnd is used to mark the end of the list of free blocks and is + inserted at the end of the region space. */ + xAddress = xAlignedHeap + xTotalRegionSize; + xAddress -= xHeapStructSize; + xAddress &= ~portBYTE_ALIGNMENT_MASK; + pxEnd = ( BlockLink_t * ) xAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; - /* To start with there is a single free block in this region that is - sized to take up the entire heap region minus the space taken by the - free block structure. */ - pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap; - pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion; - pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd; + /* To start with there is a single free block in this region that is + sized to take up the entire heap region minus the space taken by the + free block structure. */ + pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap; + pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion; + pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd; - /* If this is not the first region that makes up the entire heap space - then link the previous region to this region. */ - if( pxPreviousFreeBlock != NULL ) - { - pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion; - } + /* If this is not the first region that makes up the entire heap space + then link the previous region to this region. */ + if( pxPreviousFreeBlock != NULL ) + { + pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion; + } - xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize; + xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize; - /* Move onto the next HeapRegion_t structure. */ - xDefinedRegions++; - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); - } + /* Move onto the next HeapRegion_t structure. */ + xDefinedRegions++; + pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + } - xMinimumEverFreeBytesRemaining = xTotalHeapSize; - xFreeBytesRemaining = xTotalHeapSize; + xMinimumEverFreeBytesRemaining = xTotalHeapSize; + xFreeBytesRemaining = xTotalHeapSize; - /* Check something was actually defined before it is accessed. */ - configASSERT( xTotalHeapSize ); + /* Check something was actually defined before it is accessed. */ + configASSERT( xTotalHeapSize ); - /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); } diff --git a/components/bl602/freertos_riscv/queue.c b/components/bl602/freertos_riscv/queue.c index d3f19cb3..46688d0d 100644 --- a/components/bl602/freertos_riscv/queue.c +++ b/components/bl602/freertos_riscv/queue.c @@ -38,7 +38,7 @@ task.h is included from an application file. */ #include "queue.h" #if ( configUSE_CO_ROUTINES == 1 ) - #include "croutine.h" + #include "croutine.h" #endif /* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified @@ -49,8 +49,8 @@ correct privileged Vs unprivileged linkage and placement. */ /* Constants used with the cRxLock and cTxLock structure members. */ -#define queueUNLOCKED ( ( int8_t ) -1 ) -#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) +#define queueUNLOCKED ( ( int8_t ) -1 ) +#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) /* When the Queue_t structure is used to represent a base queue its pcHead and pcTail members are used as pointers into the queue storage area. When the @@ -61,32 +61,32 @@ names to the pcHead and structure member to ensure the readability of the code is maintained. The QueuePointers_t and SemaphoreData_t types are used to form a union as their usage is mutually exclusive dependent on what the queue is being used for. */ -#define uxQueueType pcHead -#define queueQUEUE_IS_MUTEX NULL +#define uxQueueType pcHead +#define queueQUEUE_IS_MUTEX NULL typedef struct QueuePointers { - int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ - int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ + int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ + int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ } QueuePointers_t; typedef struct SemaphoreData { - TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ - UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ + TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ + UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ } SemaphoreData_t; /* Semaphores do not actually store or copy data, so have an item size of zero. */ #define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) -#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) +#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) #if( configUSE_PREEMPTION == 0 ) - /* If the cooperative scheduler is being used then a yield should not be - performed just because a higher priority task has been woken. */ - #define queueYIELD_IF_USING_PREEMPTION() + /* If the cooperative scheduler is being used then a yield should not be + performed just because a higher priority task has been woken. */ + #define queueYIELD_IF_USING_PREEMPTION() #else - #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() + #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() #endif /* @@ -94,39 +94,39 @@ zero. */ * Items are queued by copy, not reference. See the following link for the * rationale: https://www.freertos.org/Embedded-RTOS-Queues.html */ -typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ { - int8_t *pcHead; /*< Points to the beginning of the queue storage area. */ - int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */ + int8_t *pcHead; /*< Points to the beginning of the queue storage area. */ + int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */ - union - { - QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ - SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ - } u; + union + { + QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ + SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ + } u; - List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ - List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ + List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ + List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ - volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */ - UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ - UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ + volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */ + UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ + UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ - volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ + #endif - #if ( configUSE_QUEUE_SETS == 1 ) - struct QueueDefinition *pxQueueSetContainer; - #endif + #if ( configUSE_QUEUE_SETS == 1 ) + struct QueueDefinition *pxQueueSetContainer; + #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxQueueNumber; - uint8_t ucQueueType; - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxQueueNumber; + uint8_t ucQueueType; + #endif } xQUEUE; @@ -142,24 +142,24 @@ typedef xQUEUE Queue_t; */ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - /* The type stored within the queue registry array. This allows a name - to be assigned to each queue making kernel aware debugging a little - more user friendly. */ - typedef struct QUEUE_REGISTRY_ITEM - { - const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - QueueHandle_t xHandle; - } xQueueRegistryItem; + /* The type stored within the queue registry array. This allows a name + to be assigned to each queue making kernel aware debugging a little + more user friendly. */ + typedef struct QUEUE_REGISTRY_ITEM + { + const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + QueueHandle_t xHandle; + } xQueueRegistryItem; - /* The old xQueueRegistryItem name is maintained above then typedefed to the - new xQueueRegistryItem name below to enable the use of older kernel aware - debuggers. */ - typedef xQueueRegistryItem QueueRegistryItem_t; + /* The old xQueueRegistryItem name is maintained above then typedefed to the + new xQueueRegistryItem name below to enable the use of older kernel aware + debuggers. */ + typedef xQueueRegistryItem QueueRegistryItem_t; - /* The queue registry is simply an array of QueueRegistryItem_t structures. - The pcQueueName member of a structure being NULL is indicative of the - array position being vacant. */ - PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; + /* The queue registry is simply an array of QueueRegistryItem_t structures. + The pcQueueName member of a structure being NULL is indicative of the + array position being vacant. */ + PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; #endif /* configQUEUE_REGISTRY_SIZE */ @@ -199,11 +199,11 @@ static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvIte static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION; #if ( configUSE_QUEUE_SETS == 1 ) - /* - * Checks to see if a queue is a member of a queue set, and if so, notifies - * the queue set that the queue contains data. - */ - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; + /* + * Checks to see if a queue is a member of a queue set, and if so, notifies + * the queue set that the queue contains data. + */ + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; #endif /* @@ -218,18 +218,18 @@ static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseT * as a mutex. */ #if( configUSE_MUTEXES == 1 ) - static void prvInitialiseMutex( Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; + static void prvInitialiseMutex( Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; #endif #if( configUSE_MUTEXES == 1 ) - /* - * If a task waiting for a mutex causes the mutex holder to inherit a - * priority, but the waiting task times out, then the holder should - * disinherit the priority - but only down to the highest priority of any - * other tasks that are waiting for the same mutex. This function returns - * that priority. - */ - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; + /* + * If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. This function returns + * that priority. + */ + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; #endif /*-----------------------------------------------------------*/ @@ -237,509 +237,509 @@ static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseT * Macro to mark a queue as locked. Locking a queue prevents an ISR from * accessing the queue event lists. */ -#define prvLockQueue( pxQueue ) \ - taskENTER_CRITICAL(); \ - { \ - if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ - } \ - if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ - } \ - } \ - taskEXIT_CRITICAL() +#define prvLockQueue( pxQueue ) \ + taskENTER_CRITICAL(); \ + { \ + if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ + } \ + if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ + } \ + } \ + taskEXIT_CRITICAL() /*-----------------------------------------------------------*/ BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) { Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); + configASSERT( pxQueue ); - taskENTER_CRITICAL(); - { - pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; - pxQueue->pcWriteTo = pxQueue->pcHead; - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - pxQueue->cRxLock = queueUNLOCKED; - pxQueue->cTxLock = queueUNLOCKED; + taskENTER_CRITICAL(); + { + pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; + pxQueue->pcWriteTo = pxQueue->pcHead; + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->cRxLock = queueUNLOCKED; + pxQueue->cTxLock = queueUNLOCKED; - if( xNewQueue == pdFALSE ) - { - /* If there are tasks blocked waiting to read from the queue, then - the tasks will remain blocked as after this function exits the queue - will still be empty. If there are tasks blocked waiting to write to - the queue, then one should be unblocked as after this function exits - it will be possible to write to it. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Ensure the event queues start in the correct state. */ - vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); - vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); - } - } - taskEXIT_CRITICAL(); + if( xNewQueue == pdFALSE ) + { + /* If there are tasks blocked waiting to read from the queue, then + the tasks will remain blocked as after this function exits the queue + will still be empty. If there are tasks blocked waiting to write to + the queue, then one should be unblocked as after this function exits + it will be possible to write to it. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Ensure the event queues start in the correct state. */ + vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); + vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); + } + } + taskEXIT_CRITICAL(); - /* A value is returned for calling semantic consistency with previous - versions. */ - return pdPASS; + /* A value is returned for calling semantic consistency with previous + versions. */ + return pdPASS; } /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) - { - Queue_t *pxNewQueue; + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) + { + Queue_t *pxNewQueue; - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); + configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - /* The StaticQueue_t structure and the queue storage area must be - supplied. */ - configASSERT( pxStaticQueue != NULL ); + /* The StaticQueue_t structure and the queue storage area must be + supplied. */ + configASSERT( pxStaticQueue != NULL ); - /* A queue storage area should be provided if the item size is not 0, and - should not be provided if the item size is 0. */ - configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); - configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); + /* A queue storage area should be provided if the item size is not 0, and + should not be provided if the item size is 0. */ + configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); + configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticQueue_t or StaticSemaphore_t equals the size of - the real queue and semaphore structures. */ - volatile size_t xSize = sizeof( StaticQueue_t ); - configASSERT( xSize == sizeof( Queue_t ) ); - ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ - } - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticQueue_t or StaticSemaphore_t equals the size of + the real queue and semaphore structures. */ + volatile size_t xSize = sizeof( StaticQueue_t ); + configASSERT( xSize == sizeof( Queue_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ - /* The address of a statically allocated queue was passed in, use it. - The address of a statically allocated storage area was also passed in - but is already set. */ - pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + /* The address of a statically allocated queue was passed in, use it. + The address of a statically allocated storage area was also passed in + but is already set. */ + pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - if( pxNewQueue != NULL ) - { - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Queues can be allocated wither statically or dynamically, so - note this queue was allocated statically in case the queue is - later deleted. */ - pxNewQueue->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + if( pxNewQueue != NULL ) + { + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Queues can be allocated wither statically or dynamically, so + note this queue was allocated statically in case the queue is + later deleted. */ + pxNewQueue->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - mtCOVERAGE_TEST_MARKER(); - } + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } - return pxNewQueue; - } + return pxNewQueue; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) - { - Queue_t *pxNewQueue; - size_t xQueueSizeInBytes; - uint8_t *pucQueueStorage; + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) + { + Queue_t *pxNewQueue; + size_t xQueueSizeInBytes; + uint8_t *pucQueueStorage; - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); + configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - if( uxItemSize == ( UBaseType_t ) 0 ) - { - /* There is not going to be a queue storage area. */ - xQueueSizeInBytes = ( size_t ) 0; - } - else - { - /* Allocate enough space to hold the maximum number of items that - can be in the queue at any time. */ - xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } + if( uxItemSize == ( UBaseType_t ) 0 ) + { + /* There is not going to be a queue storage area. */ + xQueueSizeInBytes = ( size_t ) 0; + } + else + { + /* Allocate enough space to hold the maximum number of items that + can be in the queue at any time. */ + xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } - /* Allocate the queue and storage area. Justification for MISRA - deviation as follows: pvPortMalloc() always ensures returned memory - blocks are aligned per the requirements of the MCU stack. In this case - pvPortMalloc() must return a pointer that is guaranteed to meet the - alignment requirements of the Queue_t structure - which in this case - is an int8_t *. Therefore, whenever the stack alignment requirements - are greater than or equal to the pointer to char requirements the cast - is safe. In other cases alignment requirements are not strict (one or - two bytes). */ - pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */ + /* Allocate the queue and storage area. Justification for MISRA + deviation as follows: pvPortMalloc() always ensures returned memory + blocks are aligned per the requirements of the MCU stack. In this case + pvPortMalloc() must return a pointer that is guaranteed to meet the + alignment requirements of the Queue_t structure - which in this case + is an int8_t *. Therefore, whenever the stack alignment requirements + are greater than or equal to the pointer to char requirements the cast + is safe. In other cases alignment requirements are not strict (one or + two bytes). */ + pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */ - if( pxNewQueue != NULL ) - { - /* Jump past the queue structure to find the location of the queue - storage area. */ - pucQueueStorage = ( uint8_t * ) pxNewQueue; - pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + if( pxNewQueue != NULL ) + { + /* Jump past the queue structure to find the location of the queue + storage area. */ + pucQueueStorage = ( uint8_t * ) pxNewQueue; + pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Queues can be created either statically or dynamically, so - note this task was created dynamically in case it is later - deleted. */ - pxNewQueue->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Queues can be created either statically or dynamically, so + note this task was created dynamically in case it is later + deleted. */ + pxNewQueue->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - mtCOVERAGE_TEST_MARKER(); - } + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } - return pxNewQueue; - } + return pxNewQueue; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) { - /* Remove compiler warnings about unused parameters should - configUSE_TRACE_FACILITY not be set to 1. */ - ( void ) ucQueueType; + /* Remove compiler warnings about unused parameters should + configUSE_TRACE_FACILITY not be set to 1. */ + ( void ) ucQueueType; - if( uxItemSize == ( UBaseType_t ) 0 ) - { - /* No RAM was allocated for the queue storage area, but PC head cannot - be set to NULL because NULL is used as a key to say the queue is used as - a mutex. Therefore just set pcHead to point to the queue as a benign - value that is known to be within the memory map. */ - pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; - } - else - { - /* Set the head to the start of the queue storage area. */ - pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; - } + if( uxItemSize == ( UBaseType_t ) 0 ) + { + /* No RAM was allocated for the queue storage area, but PC head cannot + be set to NULL because NULL is used as a key to say the queue is used as + a mutex. Therefore just set pcHead to point to the queue as a benign + value that is known to be within the memory map. */ + pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; + } + else + { + /* Set the head to the start of the queue storage area. */ + pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; + } - /* Initialise the queue members as described where the queue type is - defined. */ - pxNewQueue->uxLength = uxQueueLength; - pxNewQueue->uxItemSize = uxItemSize; - ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); + /* Initialise the queue members as described where the queue type is + defined. */ + pxNewQueue->uxLength = uxQueueLength; + pxNewQueue->uxItemSize = uxItemSize; + ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); - #if ( configUSE_TRACE_FACILITY == 1 ) - { - pxNewQueue->ucQueueType = ucQueueType; - } - #endif /* configUSE_TRACE_FACILITY */ + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxNewQueue->ucQueueType = ucQueueType; + } + #endif /* configUSE_TRACE_FACILITY */ - #if( configUSE_QUEUE_SETS == 1 ) - { - pxNewQueue->pxQueueSetContainer = NULL; - } - #endif /* configUSE_QUEUE_SETS */ + #if( configUSE_QUEUE_SETS == 1 ) + { + pxNewQueue->pxQueueSetContainer = NULL; + } + #endif /* configUSE_QUEUE_SETS */ - traceQUEUE_CREATE( pxNewQueue ); + traceQUEUE_CREATE( pxNewQueue ); } /*-----------------------------------------------------------*/ #if( configUSE_MUTEXES == 1 ) - static void prvInitialiseMutex( Queue_t *pxNewQueue ) - { - if( pxNewQueue != NULL ) - { - /* The queue create function will set all the queue structure members - correctly for a generic queue, but this function is creating a - mutex. Overwrite those members that need to be set differently - - in particular the information required for priority inheritance. */ - pxNewQueue->u.xSemaphore.xMutexHolder = NULL; - pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; + static void prvInitialiseMutex( Queue_t *pxNewQueue ) + { + if( pxNewQueue != NULL ) + { + /* The queue create function will set all the queue structure members + correctly for a generic queue, but this function is creating a + mutex. Overwrite those members that need to be set differently - + in particular the information required for priority inheritance. */ + pxNewQueue->u.xSemaphore.xMutexHolder = NULL; + pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; - /* In case this is a recursive mutex. */ - pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; + /* In case this is a recursive mutex. */ + pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; - traceCREATE_MUTEX( pxNewQueue ); + traceCREATE_MUTEX( pxNewQueue ); - /* Start with the semaphore in the expected state. */ - ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); - } - else - { - traceCREATE_MUTEX_FAILED(); - } - } + /* Start with the semaphore in the expected state. */ + ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); + } + else + { + traceCREATE_MUTEX_FAILED(); + } + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) - { - QueueHandle_t xNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); - prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); - return xNewQueue; - } + return xNewQueue; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) - { - QueueHandle_t xNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - /* Prevent compiler warnings about unused parameters if - configUSE_TRACE_FACILITY does not equal 1. */ - ( void ) ucQueueType; + /* Prevent compiler warnings about unused parameters if + configUSE_TRACE_FACILITY does not equal 1. */ + ( void ) ucQueueType; - xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); - prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); - return xNewQueue; - } + return xNewQueue; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) - { - TaskHandle_t pxReturn; - Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; + TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; - /* This function is called by xSemaphoreGetMutexHolder(), and should not - be called directly. Note: This is a good way of determining if the - calling task is the mutex holder, but not a good way of determining the - identity of the mutex holder, as the holder may change between the - following critical section exiting and the function returning. */ - taskENTER_CRITICAL(); - { - if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; - } - else - { - pxReturn = NULL; - } - } - taskEXIT_CRITICAL(); + /* This function is called by xSemaphoreGetMutexHolder(), and should not + be called directly. Note: This is a good way of determining if the + calling task is the mutex holder, but not a good way of determining the + identity of the mutex holder, as the holder may change between the + following critical section exiting and the function returning. */ + taskENTER_CRITICAL(); + { + if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + } + taskEXIT_CRITICAL(); - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ #endif /*-----------------------------------------------------------*/ #if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) - { - TaskHandle_t pxReturn; + TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; - configASSERT( xSemaphore ); + configASSERT( xSemaphore ); - /* Mutexes cannot be used in interrupt service routines, so the mutex - holder should not change in an ISR, and therefore a critical section is - not required here. */ - if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; - } - else - { - pxReturn = NULL; - } + /* Mutexes cannot be used in interrupt service routines, so the mutex + holder should not change in an ISR, and therefore a critical section is + not required here. */ + if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ #endif /*-----------------------------------------------------------*/ #if ( configUSE_RECURSIVE_MUTEXES == 1 ) - BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; + BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; - configASSERT( pxMutex ); + configASSERT( pxMutex ); - /* If this is the task that holds the mutex then xMutexHolder will not - change outside of this task. If this task does not hold the mutex then - pxMutexHolder can never coincidentally equal the tasks handle, and as - this is the only condition we are interested in it does not matter if - pxMutexHolder is accessed simultaneously by another task. Therefore no - mutual exclusion is required to test the pxMutexHolder variable. */ - if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) - { - traceGIVE_MUTEX_RECURSIVE( pxMutex ); + /* If this is the task that holds the mutex then xMutexHolder will not + change outside of this task. If this task does not hold the mutex then + pxMutexHolder can never coincidentally equal the tasks handle, and as + this is the only condition we are interested in it does not matter if + pxMutexHolder is accessed simultaneously by another task. Therefore no + mutual exclusion is required to test the pxMutexHolder variable. */ + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + traceGIVE_MUTEX_RECURSIVE( pxMutex ); - /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to - the task handle, therefore no underflow check is required. Also, - uxRecursiveCallCount is only modified by the mutex holder, and as - there can only be one, no mutual exclusion is required to modify the - uxRecursiveCallCount member. */ - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; + /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to + the task handle, therefore no underflow check is required. Also, + uxRecursiveCallCount is only modified by the mutex holder, and as + there can only be one, no mutual exclusion is required to modify the + uxRecursiveCallCount member. */ + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; - /* Has the recursive call count unwound to 0? */ - if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) - { - /* Return the mutex. This will automatically unblock any other - task that might be waiting to access the mutex. */ - ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Has the recursive call count unwound to 0? */ + if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) + { + /* Return the mutex. This will automatically unblock any other + task that might be waiting to access the mutex. */ + ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xReturn = pdPASS; - } - else - { - /* The mutex cannot be given because the calling task is not the - holder. */ - xReturn = pdFAIL; + xReturn = pdPASS; + } + else + { + /* The mutex cannot be given because the calling task is not the + holder. */ + xReturn = pdFAIL; - traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } + traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_RECURSIVE_MUTEXES == 1 ) - BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; + BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; - configASSERT( pxMutex ); + configASSERT( pxMutex ); - /* Comments regarding mutual exclusion as per those within - xQueueGiveMutexRecursive(). */ + /* Comments regarding mutual exclusion as per those within + xQueueGiveMutexRecursive(). */ - traceTAKE_MUTEX_RECURSIVE( pxMutex ); + traceTAKE_MUTEX_RECURSIVE( pxMutex ); - if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) - { - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; - xReturn = pdPASS; - } - else - { - xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + xReturn = pdPASS; + } + else + { + xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); - /* pdPASS will only be returned if the mutex was successfully - obtained. The calling task may have entered the Blocked state - before reaching here. */ - if( xReturn != pdFAIL ) - { - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; - } - else - { - traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } - } + /* pdPASS will only be returned if the mutex was successfully + obtained. The calling task may have entered the Blocked state + before reaching here. */ + if( xReturn != pdFAIL ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + } + else + { + traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) - { - QueueHandle_t xHandle; + QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) + { + QueueHandle_t xHandle; - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); + configASSERT( uxMaxCount != 0 ); + configASSERT( uxInitialCount <= uxMaxCount ); - xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } - return xHandle; - } + return xHandle; + } #endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ #if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) - { - QueueHandle_t xHandle; + QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) + { + QueueHandle_t xHandle; - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); + configASSERT( uxMaxCount != 0 ); + configASSERT( uxInitialCount <= uxMaxCount ); - xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } - return xHandle; - } + return xHandle; + } #endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ @@ -750,207 +750,207 @@ BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired; TimeOut_t xTimeOut; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to - allow return statements within the function itself. This is done in the - interest of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - /* Is there room on the queue now? The running task must be the - highest priority task wanting to access the queue. If the head item - in the queue is to be overwritten then it does not matter if the - queue is full. */ - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - traceQUEUE_SEND( pxQueue ); + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + /* Is there room on the queue now? The running task must be the + highest priority task wanting to access the queue. If the head item + in the queue is to be overwritten then it does not matter if the + queue is full. */ + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + traceQUEUE_SEND( pxQueue ); - #if ( configUSE_QUEUE_SETS == 1 ) - { - UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + #if ( configUSE_QUEUE_SETS == 1 ) + { + UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; - xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) - { - /* Do not notify the queue set as an existing item - was overwritten in the queue so the number of items - in the queue has not changed. */ - mtCOVERAGE_TEST_MARKER(); - } - else if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - to the queue set caused a higher priority task to - unblock. A context switch is required. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If there was a task waiting for data to arrive on the - queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - our own so yield immediately. Yes it is ok to - do this from within the critical section - the - kernel takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - executed if the task was holding multiple mutexes - and the mutexes were given back in an order that is - different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + was overwritten in the queue so the number of items + in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + to the queue set caused a higher priority task to + unblock. A context switch is required. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If there was a task waiting for data to arrive on the + queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + our own so yield immediately. Yes it is ok to + do this from within the critical section - the + kernel takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + executed if the task was holding multiple mutexes + and the mutexes were given back in an order that is + different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - /* If there was a task waiting for data to arrive on the - queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - our own so yield immediately. Yes it is ok to do - this from within the critical section - the kernel - takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - executed if the task was holding multiple mutexes and - the mutexes were given back in an order that is - different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ + /* If there was a task waiting for data to arrive on the + queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + our own so yield immediately. Yes it is ok to do + this from within the critical section - the kernel + takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + executed if the task was holding multiple mutexes and + the mutexes were given back in an order that is + different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was full and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was full and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); - /* Return to the original privilege level before exiting - the function. */ - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was full and a block time was specified so - configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + /* Return to the original privilege level before exiting + the function. */ + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was full and a block time was specified so + configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_SEND( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_SEND( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); - /* Unlocking the queue means queue events can effect the - event list. It is possible that interrupts occurring now - remove this task from the event list again - but as the - scheduler is suspended the task will go onto the pending - ready last instead of the actual ready list. */ - prvUnlockQueue( pxQueue ); + /* Unlocking the queue means queue events can effect the + event list. It is possible that interrupts occurring now + remove this task from the event list again - but as the + scheduler is suspended the task will go onto the pending + ready last instead of the actual ready list. */ + prvUnlockQueue( pxQueue ); - /* Resuming the scheduler will move tasks from the pending - ready list into the ready list - so it is feasible that this - task is already in a ready list before it yields - in which - case the yield will not cause a context switch unless there - is also a higher priority task in the pending ready list. */ - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - } - else - { - /* Try again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + /* Resuming the scheduler will move tasks from the pending + ready list into the ready list - so it is feasible that this + task is already in a ready list before it yields - in which + case the yield will not cause a context switch unless there + is also a higher priority task in the pending ready list. */ + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + } + else + { + /* Try again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - } /*lint -restore */ + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -960,148 +960,148 @@ BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - /* Similar to xQueueGenericSend, except without blocking if there is no room - in the queue. Also don't directly wake a task that was blocked on a queue - read, instead return a flag to say whether a context switch is required or - not (i.e. has a task with a higher priority than us been woken by this - post). */ - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - const int8_t cTxLock = pxQueue->cTxLock; + /* Similar to xQueueGenericSend, except without blocking if there is no room + in the queue. Also don't directly wake a task that was blocked on a queue + read, instead return a flag to say whether a context switch is required or + not (i.e. has a task with a higher priority than us been woken by this + post). */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + const int8_t cTxLock = pxQueue->cTxLock; - traceQUEUE_SEND_FROM_ISR( pxQueue ); + traceQUEUE_SEND_FROM_ISR( pxQueue ); - /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a - semaphore or mutex. That means prvCopyDataToQueue() cannot result - in a task disinheriting a priority and prvCopyDataToQueue() can be - called here even though the disinherit function does not check if - the scheduler is suspended before accessing the ready lists. */ - ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a + semaphore or mutex. That means prvCopyDataToQueue() cannot result + in a task disinheriting a priority and prvCopyDataToQueue() can be + called here even though the disinherit function does not check if + the scheduler is suspended before accessing the ready lists. */ + ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - /* The event list is not altered if the queue is locked. This will - be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - to the queue set caused a higher priority task to - unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was posted while it was locked. */ - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } + /* The event list is not altered if the queue is locked. This will + be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + to the queue set caused a higher priority task to + unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was posted while it was locked. */ + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1111,162 +1111,162 @@ BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; Queue_t * const pxQueue = xQueue; - /* Similar to xQueueGenericSendFromISR() but used with semaphores where the - item size is 0. Don't directly wake a task that was blocked on a queue - read, instead return a flag to say whether a context switch is required or - not (i.e. has a task with a higher priority than us been woken by this - post). */ + /* Similar to xQueueGenericSendFromISR() but used with semaphores where the + item size is 0. Don't directly wake a task that was blocked on a queue + read, instead return a flag to say whether a context switch is required or + not (i.e. has a task with a higher priority than us been woken by this + post). */ - configASSERT( pxQueue ); + configASSERT( pxQueue ); - /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() - if the item size is not 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); + /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() + if the item size is not 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); - /* Normally a mutex would not be given from an interrupt, especially if - there is a mutex holder, as priority inheritance makes no sense for an - interrupts, only tasks. */ - configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); + /* Normally a mutex would not be given from an interrupt, especially if + there is a mutex holder, as priority inheritance makes no sense for an + interrupts, only tasks. */ + configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* When the queue is used to implement a semaphore no data is ever - moved through the queue but it is still valid to see if the queue 'has - space'. */ - if( uxMessagesWaiting < pxQueue->uxLength ) - { - const int8_t cTxLock = pxQueue->cTxLock; + /* When the queue is used to implement a semaphore no data is ever + moved through the queue but it is still valid to see if the queue 'has + space'. */ + if( uxMessagesWaiting < pxQueue->uxLength ) + { + const int8_t cTxLock = pxQueue->cTxLock; - traceQUEUE_SEND_FROM_ISR( pxQueue ); + traceQUEUE_SEND_FROM_ISR( pxQueue ); - /* A task can only have an inherited priority if it is a mutex - holder - and if there is a mutex holder then the mutex cannot be - given from an ISR. As this is the ISR version of the function it - can be assumed there is no mutex holder and no need to determine if - priority disinheritance is needed. Simply increase the count of - messages (semaphores) available. */ - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + /* A task can only have an inherited priority if it is a mutex + holder - and if there is a mutex holder then the mutex cannot be + given from an ISR. As this is the ISR version of the function it + can be assumed there is no mutex holder and no need to determine if + priority disinheritance is needed. Simply increase the count of + messages (semaphores) available. */ + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - /* The event list is not altered if the queue is locked. This will - be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) - { - /* The semaphore is a member of a queue set, and - posting to the queue set caused a higher priority - task to unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was posted while it was locked. */ - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } + /* The event list is not altered if the queue is locked. This will + be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) + { + /* The semaphore is a member of a queue set, and + posting to the queue set caused a higher priority + task to unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was posted while it was locked. */ + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1276,138 +1276,138 @@ BaseType_t xEntryTimeSet = pdFALSE; TimeOut_t xTimeOut; Queue_t * const pxQueue = xQueue; - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); - /* The buffer into which data is received can only be NULL if the data size - is zero (so no data is copied into the buffer. */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + /* The buffer into which data is received can only be NULL if the data size + is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to - allow return statements within the function itself. This is done in the - interest of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data available, remove one item. */ - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_RECEIVE( pxQueue ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data available, remove one item. */ + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_RECEIVE( pxQueue ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - /* There is now space in the queue, were any tasks waiting to - post to the queue? If so, unblock the highest priority waiting - task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* There is now space in the queue, were any tasks waiting to + post to the queue? If so, unblock the highest priority waiting + task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* The timeout has not expired. If the queue is still empty place - the task on the list of tasks waiting to receive from the queue. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The queue contains data again. Loop back to try and read the - data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. If there is no data in the queue exit, otherwise loop - back and attempt to read the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* The timeout has not expired. If the queue is still empty place + the task on the list of tasks waiting to receive from the queue. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The queue contains data again. Loop back to try and read the + data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. If there is no data in the queue exit, otherwise loop + back and attempt to read the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -1418,214 +1418,214 @@ TimeOut_t xTimeOut; Queue_t * const pxQueue = xQueue; #if( configUSE_MUTEXES == 1 ) - BaseType_t xInheritanceOccurred = pdFALSE; + BaseType_t xInheritanceOccurred = pdFALSE; #endif - /* Check the queue pointer is not NULL. */ - configASSERT( ( pxQueue ) ); + /* Check the queue pointer is not NULL. */ + configASSERT( ( pxQueue ) ); - /* Check this really is a semaphore, in which case the item size will be - 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); + /* Check this really is a semaphore, in which case the item size will be + 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to allow return - statements within the function itself. This is done in the interest - of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - /* Semaphores are queues with an item size of 0, and where the - number of messages in the queue is the semaphore's count value. */ - const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; + /*lint -save -e904 This function relaxes the coding standard somewhat to allow return + statements within the function itself. This is done in the interest + of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + /* Semaphores are queues with an item size of 0, and where the + number of messages in the queue is the semaphore's count value. */ + const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxSemaphoreCount > ( UBaseType_t ) 0 ) - { - traceQUEUE_RECEIVE( pxQueue ); + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxSemaphoreCount > ( UBaseType_t ) 0 ) + { + traceQUEUE_RECEIVE( pxQueue ); - /* Semaphores are queues with a data size of zero and where the - messages waiting is the semaphore's count. Reduce the count. */ - pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; + /* Semaphores are queues with a data size of zero and where the + messages waiting is the semaphore's count. Reduce the count. */ + pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* Record the information required to implement - priority inheritance should it become necessary. */ - pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* Record the information required to implement + priority inheritance should it become necessary. */ + pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ - /* Check to see if other tasks are blocked waiting to give the - semaphore, and if so, unblock the highest priority such task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Check to see if other tasks are blocked waiting to give the + semaphore, and if so, unblock the highest priority such task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* For inheritance to have occurred there must have been an - initial timeout, and an adjusted timeout cannot become 0, as - if it were 0 the function would have exited. */ - #if( configUSE_MUTEXES == 1 ) - { - configASSERT( xInheritanceOccurred == pdFALSE ); - } - #endif /* configUSE_MUTEXES */ + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* For inheritance to have occurred there must have been an + initial timeout, and an adjusted timeout cannot become 0, as + if it were 0 the function would have exited. */ + #if( configUSE_MUTEXES == 1 ) + { + configASSERT( xInheritanceOccurred == pdFALSE ); + } + #endif /* configUSE_MUTEXES */ - /* The semaphore count was 0 and no block time is specified - (or the block time has expired) so exit now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The semaphore count was 0 and a block time was specified - so configure the timeout structure ready to block. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + /* The semaphore count was 0 and no block time is specified + (or the block time has expired) so exit now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The semaphore count was 0 and a block time was specified + so configure the timeout structure ready to block. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can give to and take from the semaphore - now the critical section has been exited. */ + /* Interrupts and other tasks can give to and take from the semaphore + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* A block time is specified and not expired. If the semaphore - count is 0 then enter the Blocked state to wait for a semaphore to - become available. As semaphores are implemented with queues the - queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* A block time is specified and not expired. If the semaphore + count is 0 then enter the Blocked state to wait for a semaphore to + become available. As semaphores are implemented with queues the + queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - taskENTER_CRITICAL(); - { - xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + taskENTER_CRITICAL(); + { + xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There was no timeout and the semaphore count was not 0, so - attempt to take the semaphore again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There was no timeout and the semaphore count was not 0, so + attempt to take the semaphore again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - /* If the semaphore count is 0 exit now as the timeout has - expired. Otherwise return to attempt to take the semaphore that is - known to be available. As semaphores are implemented by queues the - queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - #if ( configUSE_MUTEXES == 1 ) - { - /* xInheritanceOccurred could only have be set if - pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to - test the mutex type again to check it is actually a mutex. */ - if( xInheritanceOccurred != pdFALSE ) - { - taskENTER_CRITICAL(); - { - UBaseType_t uxHighestWaitingPriority; + /* If the semaphore count is 0 exit now as the timeout has + expired. Otherwise return to attempt to take the semaphore that is + known to be available. As semaphores are implemented by queues the + queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + #if ( configUSE_MUTEXES == 1 ) + { + /* xInheritanceOccurred could only have be set if + pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to + test the mutex type again to check it is actually a mutex. */ + if( xInheritanceOccurred != pdFALSE ) + { + taskENTER_CRITICAL(); + { + UBaseType_t uxHighestWaitingPriority; - /* This task blocking on the mutex caused another - task to inherit this task's priority. Now this task - has timed out the priority should be disinherited - again, but only as low as the next highest priority - task that is waiting for the same mutex. */ - uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); - vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); - } - taskEXIT_CRITICAL(); - } - } - #endif /* configUSE_MUTEXES */ + /* This task blocking on the mutex caused another + task to inherit this task's priority. Now this task + has timed out the priority should be disinherited + again, but only as low as the next highest priority + task that is waiting for the same mutex. */ + uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); + vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); + } + taskEXIT_CRITICAL(); + } + } + #endif /* configUSE_MUTEXES */ - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -1636,145 +1636,145 @@ TimeOut_t xTimeOut; int8_t *pcOriginalReadPosition; Queue_t * const pxQueue = xQueue; - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); - /* The buffer into which data is received can only be NULL if the data size - is zero (so no data is copied into the buffer. */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + /* The buffer into which data is received can only be NULL if the data size + is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to - allow return statements within the function itself. This is done in the - interest of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Remember the read position so it can be reset after the data - is read from the queue as this function is only peeking the - data, not removing it. */ - pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Remember the read position so it can be reset after the data + is read from the queue as this function is only peeking the + data, not removing it. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_PEEK( pxQueue ); + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_PEEK( pxQueue ); - /* The data is not being removed, so reset the read pointer. */ - pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + /* The data is not being removed, so reset the read pointer. */ + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; - /* The data is being left in the queue, so see if there are - any other tasks waiting for the data. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than this task. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* The data is being left in the queue, so see if there are + any other tasks waiting for the data. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than this task. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - configure the timeout structure ready to enter the blocked - state. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + configure the timeout structure ready to enter the blocked + state. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* Timeout has not expired yet, check to see if there is data in the - queue now, and if not enter the Blocked state to wait for data. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There is data in the queue now, so don't enter the blocked - state, instead return to try and obtain the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. If there is still no data in the queue - exit, otherwise go back and try to read the data again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* Timeout has not expired yet, check to see if there is data in the + queue now, and if not enter the Blocked state to wait for data. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There is data in the queue now, so don't enter the blocked + state, instead return to try and obtain the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. If there is still no data in the queue + exit, otherwise go back and try to read the data again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -1784,88 +1784,88 @@ BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* Cannot block in an ISR, so check there is data available. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - const int8_t cRxLock = pxQueue->cRxLock; + /* Cannot block in an ISR, so check there is data available. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + const int8_t cRxLock = pxQueue->cRxLock; - traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); + traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - /* If the queue is locked the event list will not be modified. - Instead update the lock count so the task that unlocks the queue - will know that an ISR has removed data while the queue was - locked. */ - if( cRxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than us so - force a context switch. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was removed while it was locked. */ - pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); - } + /* If the queue is locked the event list will not be modified. + Instead update the lock count so the task that unlocks the queue + will know that an ISR has removed data while the queue was + locked. */ + if( cRxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than us so + force a context switch. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was removed while it was locked. */ + pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); + } - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1876,50 +1876,50 @@ UBaseType_t uxSavedInterruptStatus; int8_t *pcOriginalReadPosition; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* Cannot block in an ISR, so check there is data available. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - traceQUEUE_PEEK_FROM_ISR( pxQueue ); + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* Cannot block in an ISR, so check there is data available. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + traceQUEUE_PEEK_FROM_ISR( pxQueue ); - /* Remember the read position so it can be reset as nothing is - actually being removed from the queue. */ - pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + /* Remember the read position so it can be reset as nothing is + actually being removed from the queue. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1927,15 +1927,15 @@ UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) { UBaseType_t uxReturn; - configASSERT( xQueue ); + configASSERT( xQueue ); - taskENTER_CRITICAL(); - { - uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); - return uxReturn; + return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ @@ -1944,15 +1944,15 @@ UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) UBaseType_t uxReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); + configASSERT( pxQueue ); - taskENTER_CRITICAL(); - { - uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); - return uxReturn; + return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ @@ -1961,10 +1961,10 @@ UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) UBaseType_t uxReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - uxReturn = pxQueue->uxMessagesWaiting; + configASSERT( pxQueue ); + uxReturn = pxQueue->uxMessagesWaiting; - return uxReturn; + return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ @@ -1972,97 +1972,97 @@ void vQueueDelete( QueueHandle_t xQueue ) { Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - traceQUEUE_DELETE( pxQueue ); + configASSERT( pxQueue ); + traceQUEUE_DELETE( pxQueue ); - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - vQueueUnregisterQueue( pxQueue ); - } - #endif + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + vQueueUnregisterQueue( pxQueue ); + } + #endif - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The queue can only have been allocated dynamically - free it - again. */ - vPortFree( pxQueue ); - } - #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The queue could have been allocated statically or dynamically, so - check before attempting to free the memory. */ - if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxQueue ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #else - { - /* The queue must have been statically allocated, so is not going to be - deleted. Avoid compiler warnings about the unused parameter. */ - ( void ) pxQueue; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The queue can only have been allocated dynamically - free it + again. */ + vPortFree( pxQueue ); + } + #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The queue could have been allocated statically or dynamically, so + check before attempting to free the memory. */ + if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxQueue ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else + { + /* The queue must have been statically allocated, so is not going to be + deleted. Avoid compiler warnings about the unused parameter. */ + ( void ) pxQueue; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->uxQueueNumber; - } + UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->uxQueueNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) - { - ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; - } + void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) + { + ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->ucQueueType; - } + uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->ucQueueType; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if( configUSE_MUTEXES == 1 ) - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) - { - UBaseType_t uxHighestPriorityOfWaitingTasks; + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) + { + UBaseType_t uxHighestPriorityOfWaitingTasks; - /* If a task waiting for a mutex causes the mutex holder to inherit a - priority, but the waiting task times out, then the holder should - disinherit the priority - but only down to the highest priority of any - other tasks that are waiting for the same mutex. For this purpose, - return the priority of the highest priority task that is waiting for the - mutex. */ - if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) - { - uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); - } - else - { - uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; - } + /* If a task waiting for a mutex causes the mutex holder to inherit a + priority, but the waiting task times out, then the holder should + disinherit the priority - but only down to the highest priority of any + other tasks that are waiting for the same mutex. For this purpose, + return the priority of the highest priority task that is waiting for the + mutex. */ + if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) + { + uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); + } + else + { + uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; + } - return uxHighestPriorityOfWaitingTasks; - } + return uxHighestPriorityOfWaitingTasks; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ @@ -2072,215 +2072,215 @@ static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvIte BaseType_t xReturn = pdFALSE; UBaseType_t uxMessagesWaiting; - /* This function is called from a critical section. */ + /* This function is called from a critical section. */ - uxMessagesWaiting = pxQueue->uxMessagesWaiting; + uxMessagesWaiting = pxQueue->uxMessagesWaiting; - if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) - { - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* The mutex is no longer being held. */ - xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); - pxQueue->u.xSemaphore.xMutexHolder = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ - } - else if( xPosition == queueSEND_TO_BACK ) - { - ( void ) rtos_memcpy_ptr( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ - pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ - if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->pcWriteTo = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - ( void ) rtos_memcpy_ptr( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ - pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; - if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) + { + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* The mutex is no longer being held. */ + xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); + pxQueue->u.xSemaphore.xMutexHolder = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + } + else if( xPosition == queueSEND_TO_BACK ) + { + ( void ) rtos_memcpy_ptr( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->pcWriteTo = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + ( void ) rtos_memcpy_ptr( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ + pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xPosition == queueOVERWRITE ) - { - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* An item is not being added but overwritten, so subtract - one from the recorded number of items in the queue so when - one is added again below the number of recorded items remains - correct. */ - --uxMessagesWaiting; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( xPosition == queueOVERWRITE ) + { + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* An item is not being added but overwritten, so subtract + one from the recorded number of items in the queue so when + one is added again below the number of recorded items remains + correct. */ + --uxMessagesWaiting; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) { - if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) - { - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - ( void ) rtos_memcpy_ptr( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ - } + if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) + { + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + ( void ) rtos_memcpy_ptr( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + } } /*-----------------------------------------------------------*/ static void prvUnlockQueue( Queue_t * const pxQueue ) { - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ - /* The lock counts contains the number of extra data items placed or - removed from the queue while the queue was locked. When a queue is - locked items can be added or removed, but the event lists cannot be - updated. */ - taskENTER_CRITICAL(); - { - int8_t cTxLock = pxQueue->cTxLock; + /* The lock counts contains the number of extra data items placed or + removed from the queue while the queue was locked. When a queue is + locked items can be added or removed, but the event lists cannot be + updated. */ + taskENTER_CRITICAL(); + { + int8_t cTxLock = pxQueue->cTxLock; - /* See if data was added to the queue while it was locked. */ - while( cTxLock > queueLOCKED_UNMODIFIED ) - { - /* Data was posted while the queue was locked. Are any tasks - blocked waiting for data to become available? */ - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting to - the queue set caused a higher priority task to unblock. - A context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Tasks that are removed from the event list will get - added to the pending ready list as the scheduler is still - suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - /* Tasks that are removed from the event list will get added to - the pending ready list as the scheduler is still suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that - a context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - #endif /* configUSE_QUEUE_SETS */ + /* See if data was added to the queue while it was locked. */ + while( cTxLock > queueLOCKED_UNMODIFIED ) + { + /* Data was posted while the queue was locked. Are any tasks + blocked waiting for data to become available? */ + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting to + the queue set caused a higher priority task to unblock. + A context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Tasks that are removed from the event list will get + added to the pending ready list as the scheduler is still + suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + /* Tasks that are removed from the event list will get added to + the pending ready list as the scheduler is still suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that + a context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + #endif /* configUSE_QUEUE_SETS */ - --cTxLock; - } + --cTxLock; + } - pxQueue->cTxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); + pxQueue->cTxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); - /* Do the same for the Rx lock. */ - taskENTER_CRITICAL(); - { - int8_t cRxLock = pxQueue->cRxLock; + /* Do the same for the Rx lock. */ + taskENTER_CRITICAL(); + { + int8_t cRxLock = pxQueue->cRxLock; - while( cRxLock > queueLOCKED_UNMODIFIED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + while( cRxLock > queueLOCKED_UNMODIFIED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - --cRxLock; - } - else - { - break; - } - } + --cRxLock; + } + else + { + break; + } + } - pxQueue->cRxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); + pxQueue->cRxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ @@ -2288,20 +2288,20 @@ static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) { BaseType_t xReturn; - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -2310,17 +2310,17 @@ BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) BaseType_t xReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + configASSERT( pxQueue ); + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ /*-----------------------------------------------------------*/ @@ -2328,20 +2328,20 @@ static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) { BaseType_t xReturn; - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -2350,581 +2350,581 @@ BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) BaseType_t xReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + configASSERT( pxQueue ); + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; - /* If the queue is already full we may have to block. A critical section - is required to prevent an interrupt removing something from the queue - between the check to see if the queue is full and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - /* The queue is full - do we want to block or just leave without - posting? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is called from a coroutine we cannot block directly, but - return indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - } - portENABLE_INTERRUPTS(); + /* If the queue is already full we may have to block. A critical section + is required to prevent an interrupt removing something from the queue + between the check to see if the queue is full and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + /* The queue is full - do we want to block or just leave without + posting? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is called from a coroutine we cannot block directly, but + return indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + } + portENABLE_INTERRUPTS(); - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - /* There is room in the queue, copy the data into the queue. */ - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - xReturn = pdPASS; + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + /* There is room in the queue, copy the data into the queue. */ + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + xReturn = pdPASS; - /* Were any co-routines waiting for data to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - into the ready list as we are within a critical section. - Instead the same pending ready list mechanism is used as if - the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The co-routine waiting has a higher priority so record - that a yield might be appropriate. */ - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = errQUEUE_FULL; - } - } - portENABLE_INTERRUPTS(); + /* Were any co-routines waiting for data to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + into the ready list as we are within a critical section. + Instead the same pending ready list mechanism is used as if + the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The co-routine waiting has a higher priority so record + that a yield might be appropriate. */ + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = errQUEUE_FULL; + } + } + portENABLE_INTERRUPTS(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; - /* If the queue is already empty we may have to block. A critical section - is required to prevent an interrupt adding something to the queue - between the check to see if the queue is empty and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - /* There are no messages in the queue, do we want to block or just - leave with nothing? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is a co-routine we cannot block directly, but return - indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portENABLE_INTERRUPTS(); + /* If the queue is already empty we may have to block. A critical section + is required to prevent an interrupt adding something to the queue + between the check to see if the queue is empty and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + /* There are no messages in the queue, do we want to block or just + leave with nothing? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is a co-routine we cannot block directly, but return + indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portENABLE_INTERRUPTS(); - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data is available from the queue. */ - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --( pxQueue->uxMessagesWaiting ); - ( void ) rtos_memcpy_ptr( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data is available from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --( pxQueue->uxMessagesWaiting ); + ( void ) rtos_memcpy_ptr( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - xReturn = pdPASS; + xReturn = pdPASS; - /* Were any co-routines waiting for space to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - into the ready list as we are within a critical section. - Instead the same pending ready list mechanism is used as if - the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = pdFAIL; - } - } - portENABLE_INTERRUPTS(); + /* Were any co-routines waiting for space to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + into the ready list as we are within a critical section. + Instead the same pending ready list mechanism is used as if + the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = pdFAIL; + } + } + portENABLE_INTERRUPTS(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ) - { - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ) + { + Queue_t * const pxQueue = xQueue; - /* Cannot block within an ISR so if there is no space on the queue then - exit without doing anything. */ - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + /* Cannot block within an ISR so if there is no space on the queue then + exit without doing anything. */ + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - /* We only want to wake one co-routine per ISR, so check that a - co-routine has not already been woken. */ - if( xCoRoutinePreviouslyWoken == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - return pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* We only want to wake one co-routine per ISR, so check that a + co-routine has not already been woken. */ + if( xCoRoutinePreviouslyWoken == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + return pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xCoRoutinePreviouslyWoken; - } + return xCoRoutinePreviouslyWoken; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; - /* We cannot block from an ISR, so check there is data available. If - not then just leave without doing anything. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Copy the data from the queue. */ - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --( pxQueue->uxMessagesWaiting ); - ( void ) rtos_memcpy_ptr( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + /* We cannot block from an ISR, so check there is data available. If + not then just leave without doing anything. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Copy the data from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --( pxQueue->uxMessagesWaiting ); + ( void ) rtos_memcpy_ptr( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - if( ( *pxCoRoutineWoken ) == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - *pxCoRoutineWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( ( *pxCoRoutineWoken ) == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + *pxCoRoutineWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; + void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; - /* See if there is an empty space in the registry. A NULL name denotes - a free slot. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].pcQueueName == NULL ) - { - /* Store the information on this queue. */ - xQueueRegistry[ ux ].pcQueueName = pcQueueName; - xQueueRegistry[ ux ].xHandle = xQueue; + /* See if there is an empty space in the registry. A NULL name denotes + a free slot. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].pcQueueName == NULL ) + { + /* Store the information on this queue. */ + xQueueRegistry[ ux ].pcQueueName = pcQueueName; + xQueueRegistry[ ux ].xHandle = xQueue; - traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } + traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - const char *pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; - const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const char *pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; + const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - /* Note there is nothing here to protect against another task adding or - removing entries from the registry while it is being searched. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - pcReturn = xQueueRegistry[ ux ].pcQueueName; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Note there is nothing here to protect against another task adding or + removing entries from the registry while it is being searched. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + pcReturn = xQueueRegistry[ ux ].pcQueueName; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - return pcReturn; - } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ + return pcReturn; + } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueUnregisterQueue( QueueHandle_t xQueue ) - { - UBaseType_t ux; + void vQueueUnregisterQueue( QueueHandle_t xQueue ) + { + UBaseType_t ux; - /* See if the handle of the queue being unregistered in actually in the - registry. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - /* Set the name to NULL to show that this slot if free again. */ - xQueueRegistry[ ux ].pcQueueName = NULL; + /* See if the handle of the queue being unregistered in actually in the + registry. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + /* Set the name to NULL to show that this slot if free again. */ + xQueueRegistry[ ux ].pcQueueName = NULL; - /* Set the handle to NULL to ensure the same queue handle cannot - appear in the registry twice if it is added, removed, then - added again. */ - xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Set the handle to NULL to ensure the same queue handle cannot + appear in the registry twice if it is added, removed, then + added again. */ + xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ + } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configUSE_TIMERS == 1 ) - void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) - { - Queue_t * const pxQueue = xQueue; + void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) + { + Queue_t * const pxQueue = xQueue; - /* This function should not be called by application code hence the - 'Restricted' in its name. It is not part of the public API. It is - designed for use by kernel code, and has special calling requirements. - It can result in vListInsert() being called on a list that can only - possibly ever have one item in it, so the list will be fast, but even - so it should be called with the scheduler locked and not from a critical - section. */ + /* This function should not be called by application code hence the + 'Restricted' in its name. It is not part of the public API. It is + designed for use by kernel code, and has special calling requirements. + It can result in vListInsert() being called on a list that can only + possibly ever have one item in it, so the list will be fast, but even + so it should be called with the scheduler locked and not from a critical + section. */ - /* Only do anything if there are no messages in the queue. This function - will not actually cause the task to block, just place it on a blocked - list. It will not block until the scheduler is unlocked - at which - time a yield will be performed. If an item is added to the queue while - the queue is locked, and the calling task blocks on the queue, then the - calling task will be immediately unblocked when the queue is unlocked. */ - prvLockQueue( pxQueue ); - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) - { - /* There is nothing in the queue, block for the specified period. */ - vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - prvUnlockQueue( pxQueue ); - } + /* Only do anything if there are no messages in the queue. This function + will not actually cause the task to block, just place it on a blocked + list. It will not block until the scheduler is unlocked - at which + time a yield will be performed. If an item is added to the queue while + the queue is locked, and the calling task blocks on the queue, then the + calling task will be immediately unblocked when the queue is unlocked. */ + prvLockQueue( pxQueue ); + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) + { + /* There is nothing in the queue, block for the specified period. */ + vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + prvUnlockQueue( pxQueue ); + } #endif /* configUSE_TIMERS */ /*-----------------------------------------------------------*/ #if( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) - { - QueueSetHandle_t pxQueue; + QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) + { + QueueSetHandle_t pxQueue; - pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); + pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); - return pxQueue; - } + return pxQueue; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; + BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; - taskENTER_CRITICAL(); - { - if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) - { - /* Cannot add a queue/semaphore to more than one queue set. */ - xReturn = pdFAIL; - } - else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* Cannot add a queue/semaphore to a queue set if there are already - items in the queue/semaphore. */ - xReturn = pdFAIL; - } - else - { - ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; - xReturn = pdPASS; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) + { + /* Cannot add a queue/semaphore to more than one queue set. */ + xReturn = pdFAIL; + } + else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* Cannot add a queue/semaphore to a queue set if there are already + items in the queue/semaphore. */ + xReturn = pdFAIL; + } + else + { + ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; + xReturn = pdPASS; + } + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; + BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; - if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) - { - /* The queue was not a member of the set. */ - xReturn = pdFAIL; - } - else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* It is dangerous to remove a queue from a set when the queue is - not empty because the queue set will still hold pending events for - the queue. */ - xReturn = pdFAIL; - } - else - { - taskENTER_CRITICAL(); - { - /* The queue is no longer contained in the set. */ - pxQueueOrSemaphore->pxQueueSetContainer = NULL; - } - taskEXIT_CRITICAL(); - xReturn = pdPASS; - } + if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) + { + /* The queue was not a member of the set. */ + xReturn = pdFAIL; + } + else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* It is dangerous to remove a queue from a set when the queue is + not empty because the queue set will still hold pending events for + the queue. */ + xReturn = pdFAIL; + } + else + { + taskENTER_CRITICAL(); + { + /* The queue is no longer contained in the set. */ + pxQueueOrSemaphore->pxQueueSetContainer = NULL; + } + taskEXIT_CRITICAL(); + xReturn = pdPASS; + } - return xReturn; - } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ + return xReturn; + } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait ) - { - QueueSetMemberHandle_t xReturn = NULL; + QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait ) + { + QueueSetMemberHandle_t xReturn = NULL; - ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } + ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) - { - QueueSetMemberHandle_t xReturn = NULL; + QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) + { + QueueSetMemberHandle_t xReturn = NULL; - ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } + ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) - { - Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer; - BaseType_t xReturn = pdFALSE; + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) + { + Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer; + BaseType_t xReturn = pdFALSE; - /* This function must be called form a critical section. */ + /* This function must be called form a critical section. */ - configASSERT( pxQueueSetContainer ); - configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); + configASSERT( pxQueueSetContainer ); + configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); - if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) - { - const int8_t cTxLock = pxQueueSetContainer->cTxLock; + if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) + { + const int8_t cTxLock = pxQueueSetContainer->cTxLock; - traceQUEUE_SEND( pxQueueSetContainer ); + traceQUEUE_SEND( pxQueueSetContainer ); - /* The data copied is the handle of the queue that contains data. */ - xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition ); + /* The data copied is the handle of the queue that contains data. */ + xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition ); - if( cTxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( cTxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ diff --git a/components/bl602/freertos_riscv/stream_buffer.c b/components/bl602/freertos_riscv/stream_buffer.c index 6712565c..7d9478d8 100644 --- a/components/bl602/freertos_riscv/stream_buffer.c +++ b/components/bl602/freertos_riscv/stream_buffer.c @@ -40,7 +40,7 @@ task.h is included from an application file. */ #include "stream_buffer.h" #if( configUSE_TASK_NOTIFICATIONS != 1 ) - #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c + #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c #endif /* Lint e961, e9021 and e750 are suppressed as a MISRA exception justified @@ -54,77 +54,77 @@ or #defined the notification macros away, them provide default implementations that uses task notifications. */ /*lint -save -e9026 Function like macros allowed and needed here so they can be overidden. */ #ifndef sbRECEIVE_COMPLETED - #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); + #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); #endif /* sbRECEIVE_COMPLETED */ #ifndef sbRECEIVE_COMPLETED_FROM_ISR - #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ - pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } + #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ + pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } #endif /* sbRECEIVE_COMPLETED_FROM_ISR */ /* If the user has not provided an application specific Tx notification macro, or #defined the notification macro away, them provide a default implementation that uses task notifications. */ #ifndef sbSEND_COMPLETED - #define sbSEND_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); + #define sbSEND_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); #endif /* sbSEND_COMPLETED */ #ifndef sbSEND_COMPLETE_FROM_ISR - #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } + #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } #endif /* sbSEND_COMPLETE_FROM_ISR */ /*lint -restore (9026) */ @@ -132,7 +132,7 @@ that uses task notifications. */ #define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) /* Bits stored in the ucFlags field of the stream buffer. */ -#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ +#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ #define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ /*-----------------------------------------------------------*/ @@ -140,18 +140,18 @@ that uses task notifications. */ /* Structure that hold state information on the buffer. */ typedef struct StreamBufferDef_t /*lint !e9058 Style convention uses tag. */ { - volatile size_t xTail; /* Index to the next item to read within the buffer. */ - volatile size_t xHead; /* Index to the next item to write within the buffer. */ - size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ - size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ - volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ - volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ - uint8_t *pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ - uint8_t ucFlags; + volatile size_t xTail; /* Index to the next item to read within the buffer. */ + volatile size_t xHead; /* Index to the next item to write within the buffer. */ + size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ + size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ + volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ + volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ + uint8_t *pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ + uint8_t ucFlags; - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ + #endif } StreamBuffer_t; /* @@ -175,10 +175,10 @@ static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, cons * buffer's data storage area. */ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) PRIVILEGED_FUNCTION; + void *pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable, + size_t xBytesToStoreMessageLength ) PRIVILEGED_FUNCTION; /* * If the stream buffer is being used as a message buffer, then writes an entire @@ -188,170 +188,170 @@ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, * data storage area. */ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) PRIVILEGED_FUNCTION; + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) PRIVILEGED_FUNCTION; /* * Read xMaxCount bytes from the pxStreamBuffer message buffer and write them * to pucData. */ static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, - uint8_t *pucData, - size_t xMaxCount, - size_t xBytesAvailable ) PRIVILEGED_FUNCTION; + uint8_t *pucData, + size_t xMaxCount, + size_t xBytesAvailable ) PRIVILEGED_FUNCTION; /* * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to * initialise the members of the newly created stream buffer structure. */ static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - uint8_t ucFlags ) PRIVILEGED_FUNCTION; + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) PRIVILEGED_FUNCTION; /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) - { - uint8_t *pucAllocatedMemory; - uint8_t ucFlags; + StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) + { + uint8_t *pucAllocatedMemory; + uint8_t ucFlags; - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - if( xIsMessageBuffer == pdTRUE ) - { - /* Is a message buffer but not statically allocated. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* Not a message buffer and not statically allocated. */ - ucFlags = 0; - configASSERT( xBufferSizeBytes > 0 ); - } - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + /* In case the stream buffer is going to be used as a message buffer + (that is, it will hold discrete messages with a little meta data that + says how big the next message is) check the buffer will be large enough + to hold at least one message. */ + if( xIsMessageBuffer == pdTRUE ) + { + /* Is a message buffer but not statically allocated. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else + { + /* Not a message buffer and not statically allocated. */ + ucFlags = 0; + configASSERT( xBufferSizeBytes > 0 ); + } + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } + /* A trigger level of 0 would cause a waiting task to unblock even when + the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } - /* A stream buffer requires a StreamBuffer_t structure and a buffer. - Both are allocated in a single call to pvPortMalloc(). The - StreamBuffer_t structure is placed at the start of the allocated memory - and the buffer follows immediately after. The requested size is - incremented so the free space is returned as the user would expect - - this is a quirk of the implementation that means otherwise the free - space would be reported as one byte smaller than would be logically - expected. */ - xBufferSizeBytes++; - pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ + /* A stream buffer requires a StreamBuffer_t structure and a buffer. + Both are allocated in a single call to pvPortMalloc(). The + StreamBuffer_t structure is placed at the start of the allocated memory + and the buffer follows immediately after. The requested size is + incremented so the free space is returned as the user would expect - + this is a quirk of the implementation that means otherwise the free + space would be reported as one byte smaller than would be logically + expected. */ + xBufferSizeBytes++; + pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ - if( pucAllocatedMemory != NULL ) - { - prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ - pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); + if( pucAllocatedMemory != NULL ) + { + prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ + pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); - traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); - } - else - { - traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); - } + traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); + } + else + { + traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); + } - return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ - } + return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) - { - StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ - StreamBufferHandle_t xReturn; - uint8_t ucFlags; + StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) + { + StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ + StreamBufferHandle_t xReturn; + uint8_t ucFlags; - configASSERT( pucStreamBufferStorageArea ); - configASSERT( pxStaticStreamBuffer ); - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + configASSERT( pucStreamBufferStorageArea ); + configASSERT( pxStaticStreamBuffer ); + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } + /* A trigger level of 0 would cause a waiting task to unblock even when + the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } - if( xIsMessageBuffer != pdFALSE ) - { - /* Statically allocated message buffer. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; - } - else - { - /* Statically allocated stream buffer. */ - ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; - } + if( xIsMessageBuffer != pdFALSE ) + { + /* Statically allocated message buffer. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; + } + else + { + /* Statically allocated stream buffer. */ + ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; + } - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + /* In case the stream buffer is going to be used as a message buffer + (that is, it will hold discrete messages with a little meta data that + says how big the next message is) check the buffer will be large enough + to hold at least one message. */ + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticStreamBuffer_t equals the size of the real - message buffer structure. */ - volatile size_t xSize = sizeof( StaticStreamBuffer_t ); - configASSERT( xSize == sizeof( StreamBuffer_t ) ); - } /*lint !e529 xSize is referenced is configASSERT() is defined. */ - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticStreamBuffer_t equals the size of the real + message buffer structure. */ + volatile size_t xSize = sizeof( StaticStreamBuffer_t ); + configASSERT( xSize == sizeof( StreamBuffer_t ) ); + } /*lint !e529 xSize is referenced is configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ - if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pucStreamBufferStorageArea, - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); + if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pucStreamBufferStorageArea, + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); - /* Remember this was statically allocated in case it is ever deleted - again. */ - pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; + /* Remember this was statically allocated in case it is ever deleted + again. */ + pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; - traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); + traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); - xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ - } - else - { - xReturn = NULL; - traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); - } + xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ + } + else + { + xReturn = NULL; + traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); + } - return xReturn; - } + return xReturn; + } #endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ /*-----------------------------------------------------------*/ @@ -360,32 +360,32 @@ void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) { StreamBuffer_t * pxStreamBuffer = xStreamBuffer; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - traceSTREAM_BUFFER_DELETE( xStreamBuffer ); + traceSTREAM_BUFFER_DELETE( xStreamBuffer ); - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) - { - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both the structure and the buffer were allocated using a single call - to pvPortMalloc(), hence only one call to vPortFree() is required. */ - vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ - } - #else - { - /* Should not be possible to get here, ucFlags must be corrupt. - Force an assert. */ - configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); - } - #endif - } - else - { - /* The structure and buffer were not allocated dynamically and cannot be - freed - just scrub the structure so future use will assert. */ - ( void ) rtos_memset_ptr( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); - } + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) + { + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both the structure and the buffer were allocated using a single call + to pvPortMalloc(), hence only one call to vPortFree() is required. */ + vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ + } + #else + { + /* Should not be possible to get here, ucFlags must be corrupt. + Force an assert. */ + configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); + } + #endif + } + else + { + /* The structure and buffer were not allocated dynamically and cannot be + freed - just scrub the structure so future use will assert. */ + ( void ) rtos_memset_ptr( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); + } } /*-----------------------------------------------------------*/ @@ -395,46 +395,46 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn = pdFAIL; #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; + UBaseType_t uxStreamBufferNumber; #endif - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - #if( configUSE_TRACE_FACILITY == 1 ) - { - /* Store the stream buffer number so it can be restored after the - reset. */ - uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; - } - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + { + /* Store the stream buffer number so it can be restored after the + reset. */ + uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; + } + #endif - /* Can only reset a message buffer if there are no tasks blocked on it. */ - taskENTER_CRITICAL(); - { - if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) - { - if( pxStreamBuffer->xTaskWaitingToSend == NULL ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pxStreamBuffer->pucBuffer, - pxStreamBuffer->xLength, - pxStreamBuffer->xTriggerLevelBytes, - pxStreamBuffer->ucFlags ); - xReturn = pdPASS; + /* Can only reset a message buffer if there are no tasks blocked on it. */ + taskENTER_CRITICAL(); + { + if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) + { + if( pxStreamBuffer->xTaskWaitingToSend == NULL ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pxStreamBuffer->pucBuffer, + pxStreamBuffer->xLength, + pxStreamBuffer->xTriggerLevelBytes, + pxStreamBuffer->ucFlags ); + xReturn = pdPASS; - #if( configUSE_TRACE_FACILITY == 1 ) - { - pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; - } - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + { + pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + #endif - traceSTREAM_BUFFER_RESET( xStreamBuffer ); - } - } - } - taskEXIT_CRITICAL(); + traceSTREAM_BUFFER_RESET( xStreamBuffer ); + } + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -443,27 +443,27 @@ BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, siz StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* It is not valid for the trigger level to be 0. */ - if( xTriggerLevel == ( size_t ) 0 ) - { - xTriggerLevel = ( size_t ) 1; - } + /* It is not valid for the trigger level to be 0. */ + if( xTriggerLevel == ( size_t ) 0 ) + { + xTriggerLevel = ( size_t ) 1; + } - /* The trigger level is the number of bytes that must be in the stream - buffer before a task that is waiting for data is unblocked. */ - if( xTriggerLevel <= pxStreamBuffer->xLength ) - { - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; - xReturn = pdPASS; - } - else - { - xReturn = pdFALSE; - } + /* The trigger level is the number of bytes that must be in the stream + buffer before a task that is waiting for data is unblocked. */ + if( xTriggerLevel <= pxStreamBuffer->xLength ) + { + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; + xReturn = pdPASS; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -472,22 +472,22 @@ size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xSpace; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; - xSpace -= pxStreamBuffer->xHead; - xSpace -= ( size_t ) 1; + xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; + xSpace -= pxStreamBuffer->xHead; + xSpace -= ( size_t ) 1; - if( xSpace >= pxStreamBuffer->xLength ) - { - xSpace -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSpace >= pxStreamBuffer->xLength ) + { + xSpace -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xSpace; + return xSpace; } /*-----------------------------------------------------------*/ @@ -496,321 +496,321 @@ size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - xReturn = prvBytesInBuffer( pxStreamBuffer ); - return xReturn; + xReturn = prvBytesInBuffer( pxStreamBuffer ); + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - TickType_t xTicksToWait ) + const void *pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn, xSpace = 0; size_t xRequiredSpace = xDataLengthBytes; TimeOut_t xTimeOut; - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); - /* This send function is used to write to both message buffers and stream - buffers. If this is a message buffer then the space needed must be - increased by the amount of bytes needed to store the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + /* This send function is used to write to both message buffers and stream + buffers. If this is a message buffer then the space needed must be + increased by the amount of bytes needed to store the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - /* Overflow? */ - configASSERT( xRequiredSpace > xDataLengthBytes ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Overflow? */ + configASSERT( xRequiredSpace > xDataLengthBytes ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xTicksToWait != ( TickType_t ) 0 ) - { - vTaskSetTimeOutState( &xTimeOut ); + if( xTicksToWait != ( TickType_t ) 0 ) + { + vTaskSetTimeOutState( &xTimeOut ); - do - { - /* Wait until the required number of bytes are free in the message - buffer. */ - taskENTER_CRITICAL(); - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + do + { + /* Wait until the required number of bytes are free in the message + buffer. */ + taskENTER_CRITICAL(); + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - if( xSpace < xRequiredSpace ) - { - /* Clear notification state as going to wait for space. */ - ( void ) xTaskNotifyStateClear( NULL ); + if( xSpace < xRequiredSpace ) + { + /* Clear notification state as going to wait for space. */ + ( void ) xTaskNotifyStateClear( NULL ); - /* Should only be one writer. */ - configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); - pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); - } - else - { - taskEXIT_CRITICAL(); - break; - } - } - taskEXIT_CRITICAL(); + /* Should only be one writer. */ + configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); + pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); + } + else + { + taskEXIT_CRITICAL(); + break; + } + } + taskEXIT_CRITICAL(); - traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToSend = NULL; + traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToSend = NULL; - } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xSpace == ( size_t ) 0 ) - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSpace == ( size_t ) 0 ) + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - if( xReturn > ( size_t ) 0 ) - { - traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); + if( xReturn > ( size_t ) 0 ) + { + traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); - } + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) + const void *pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn, xSpace; size_t xRequiredSpace = xDataLengthBytes; - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); - /* This send function is used to write to both message buffers and stream - buffers. If this is a message buffer then the space needed must be - increased by the amount of bytes needed to store the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* This send function is used to write to both message buffers and stream + buffers. If this is a message buffer then the space needed must be + increased by the amount of bytes needed to store the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - if( xReturn > ( size_t ) 0 ) - { - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xReturn > ( size_t ) 0 ) + { + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); + traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) { - BaseType_t xShouldWrite; - size_t xReturn; + BaseType_t xShouldWrite; + size_t xReturn; - if( xSpace == ( size_t ) 0 ) - { - /* Doesn't matter if this is a stream buffer or a message buffer, there - is no space to write. */ - xShouldWrite = pdFALSE; - } - else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) - { - /* This is a stream buffer, as opposed to a message buffer, so writing a - stream of bytes rather than discrete messages. Write as many bytes as - possible. */ - xShouldWrite = pdTRUE; - xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); - } - else if( xSpace >= xRequiredSpace ) - { - /* This is a message buffer, as opposed to a stream buffer, and there - is enough space to write both the message length and the message itself - into the buffer. Start by writing the length of the data, the data - itself will be written later in this function. */ - xShouldWrite = pdTRUE; - ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* There is space available, but not enough space. */ - xShouldWrite = pdFALSE; - } + if( xSpace == ( size_t ) 0 ) + { + /* Doesn't matter if this is a stream buffer or a message buffer, there + is no space to write. */ + xShouldWrite = pdFALSE; + } + else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) + { + /* This is a stream buffer, as opposed to a message buffer, so writing a + stream of bytes rather than discrete messages. Write as many bytes as + possible. */ + xShouldWrite = pdTRUE; + xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); + } + else if( xSpace >= xRequiredSpace ) + { + /* This is a message buffer, as opposed to a stream buffer, and there + is enough space to write both the message length and the message itself + into the buffer. Start by writing the length of the data, the data + itself will be written later in this function. */ + xShouldWrite = pdTRUE; + ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else + { + /* There is space available, but not enough space. */ + xShouldWrite = pdFALSE; + } - if( xShouldWrite != pdFALSE ) - { - /* Writes the data itself. */ - xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */ - } - else - { - xReturn = 0; - } + if( xShouldWrite != pdFALSE ) + { + /* Writes the data itself. */ + xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */ + } + else + { + xReturn = 0; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - TickType_t xTicksToWait ) + void *pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); - /* This receive function is used by both message buffers, which store - discrete messages, and stream buffers, which store a continuous stream of - bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } + /* This receive function is used by both message buffers, which store + discrete messages, and stream buffers, which store a continuous stream of + bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } - if( xTicksToWait != ( TickType_t ) 0 ) - { - /* Checking if there is data and clearing the notification state must be - performed atomically. */ - taskENTER_CRITICAL(); - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + if( xTicksToWait != ( TickType_t ) 0 ) + { + /* Checking if there is data and clearing the notification state must be + performed atomically. */ + taskENTER_CRITICAL(); + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - /* If this function was invoked by a message buffer read then - xBytesToStoreMessageLength holds the number of bytes used to hold - the length of the next discrete message. If this function was - invoked by a stream buffer read then xBytesToStoreMessageLength will - be 0. */ - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Clear notification state as going to wait for data. */ - ( void ) xTaskNotifyStateClear( NULL ); + /* If this function was invoked by a message buffer read then + xBytesToStoreMessageLength holds the number of bytes used to hold + the length of the next discrete message. If this function was + invoked by a stream buffer read then xBytesToStoreMessageLength will + be 0. */ + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Clear notification state as going to wait for data. */ + ( void ) xTaskNotifyStateClear( NULL ); - /* Should only be one reader. */ - configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); - pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* Should only be one reader. */ + configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); + pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Wait for data to be available. */ - traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToReceive = NULL; + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Wait for data to be available. */ + traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToReceive = NULL; - /* Recheck the data available after blocking. */ - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } + /* Recheck the data available after blocking. */ + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - holds the number of bytes used to store the message length) or a stream of - bytes (where xBytesToStoreMessageLength is zero), the number of bytes - available must be greater than xBytesToStoreMessageLength to be able to - read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + holds the number of bytes used to store the message length) or a stream of + bytes (where xBytesToStoreMessageLength is zero), the number of bytes + available must be greater than xBytesToStoreMessageLength to be able to + read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); - sbRECEIVE_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); - mtCOVERAGE_TEST_MARKER(); - } + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); + sbRECEIVE_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); + mtCOVERAGE_TEST_MARKER(); + } - return xReceivedLength; + return xReceivedLength; } /*-----------------------------------------------------------*/ @@ -820,150 +820,150 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn, xBytesAvailable, xOriginalTail; configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* Ensure the stream buffer is being used as a message buffer. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) - { - /* The number of bytes available is greater than the number of bytes - required to hold the length of the next message, so another message - is available. Return its length without removing the length bytes - from the buffer. A copy of the tail is stored so the buffer can be - returned to its prior state as the message is not actually being - removed from the buffer. */ - xOriginalTail = pxStreamBuffer->xTail; - ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, xBytesAvailable ); - xReturn = ( size_t ) xTempReturn; - pxStreamBuffer->xTail = xOriginalTail; - } - else - { - /* The minimum amount of bytes in a message buffer is - ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is - less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid - value is 0. */ - configASSERT( xBytesAvailable == 0 ); - xReturn = 0; - } - } - else - { - xReturn = 0; - } + /* Ensure the stream buffer is being used as a message buffer. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) + { + /* The number of bytes available is greater than the number of bytes + required to hold the length of the next message, so another message + is available. Return its length without removing the length bytes + from the buffer. A copy of the tail is stored so the buffer can be + returned to its prior state as the message is not actually being + removed from the buffer. */ + xOriginalTail = pxStreamBuffer->xTail; + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, xBytesAvailable ); + xReturn = ( size_t ) xTempReturn; + pxStreamBuffer->xTail = xOriginalTail; + } + else + { + /* The minimum amount of bytes in a message buffer is + ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is + less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid + value is 0. */ + configASSERT( xBytesAvailable == 0 ); + xReturn = 0; + } + } + else + { + xReturn = 0; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) + void *pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); - /* This receive function is used by both message buffers, which store - discrete messages, and stream buffers, which store a continuous stream of - bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } + /* This receive function is used by both message buffers, which store + discrete messages, and stream buffers, which store a continuous stream of + bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - holds the number of bytes used to store the message length) or a stream of - bytes (where xBytesToStoreMessageLength is zero), the number of bytes - available must be greater than xBytesToStoreMessageLength to be able to - read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + holds the number of bytes used to store the message length) or a stream of + bytes (where xBytesToStoreMessageLength is zero), the number of bytes + available must be greater than xBytesToStoreMessageLength to be able to + read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); + traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); - return xReceivedLength; + return xReceivedLength; } /*-----------------------------------------------------------*/ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) + void *pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable, + size_t xBytesToStoreMessageLength ) { size_t xOriginalTail, xReceivedLength, xNextMessageLength; configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength; - if( xBytesToStoreMessageLength != ( size_t ) 0 ) - { - /* A discrete message is being received. First receive the length - of the message. A copy of the tail is stored so the buffer can be - returned to its prior state if the length of the message is too - large for the provided buffer. */ - xOriginalTail = pxStreamBuffer->xTail; - ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); - xNextMessageLength = ( size_t ) xTempNextMessageLength; + if( xBytesToStoreMessageLength != ( size_t ) 0 ) + { + /* A discrete message is being received. First receive the length + of the message. A copy of the tail is stored so the buffer can be + returned to its prior state if the length of the message is too + large for the provided buffer. */ + xOriginalTail = pxStreamBuffer->xTail; + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); + xNextMessageLength = ( size_t ) xTempNextMessageLength; - /* Reduce the number of bytes available by the number of bytes just - read out. */ - xBytesAvailable -= xBytesToStoreMessageLength; + /* Reduce the number of bytes available by the number of bytes just + read out. */ + xBytesAvailable -= xBytesToStoreMessageLength; - /* Check there is enough space in the buffer provided by the - user. */ - if( xNextMessageLength > xBufferLengthBytes ) - { - /* The user has provided insufficient space to read the message - so return the buffer to its previous state (so the length of - the message is in the buffer again). */ - pxStreamBuffer->xTail = xOriginalTail; - xNextMessageLength = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* A stream of bytes is being received (as opposed to a discrete - message), so read as many bytes as possible. */ - xNextMessageLength = xBufferLengthBytes; - } + /* Check there is enough space in the buffer provided by the + user. */ + if( xNextMessageLength > xBufferLengthBytes ) + { + /* The user has provided insufficient space to read the message + so return the buffer to its previous state (so the length of + the message is in the buffer again). */ + pxStreamBuffer->xTail = xOriginalTail; + xNextMessageLength = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* A stream of bytes is being received (as opposed to a discrete + message), so read as many bytes as possible. */ + xNextMessageLength = xBufferLengthBytes; + } - /* Read the actual data. */ - xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ + /* Read the actual data. */ + xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ - return xReceivedLength; + return xReceivedLength; } /*-----------------------------------------------------------*/ @@ -973,20 +973,20 @@ const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; size_t xTail; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* True if no bytes are available. */ - xTail = pxStreamBuffer->xTail; - if( pxStreamBuffer->xHead == xTail ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + /* True if no bytes are available. */ + xTail = pxStreamBuffer->xTail; + if( pxStreamBuffer->xHead == xTail ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -996,32 +996,32 @@ BaseType_t xReturn; size_t xBytesToStoreMessageLength; const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* This generic version of the receive function is used by both message - buffers, which store discrete messages, and stream buffers, which store a - continuous stream of bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } + /* This generic version of the receive function is used by both message + buffers, which store discrete messages, and stream buffers, which store a + continuous stream of bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } - /* True if the available space equals zero. */ - if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + /* True if the available space equals zero. */ + if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1031,27 +1031,27 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1061,27 +1061,27 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1089,45 +1089,45 @@ static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, cons { size_t xNextHead, xFirstLength; - configASSERT( xCount > ( size_t ) 0 ); + configASSERT( xCount > ( size_t ) 0 ); - xNextHead = pxStreamBuffer->xHead; + xNextHead = pxStreamBuffer->xHead; - /* Calculate the number of bytes that can be added in the first write - - which may be less than the total number of bytes that need to be added if - the buffer will wrap back to the beginning. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); + /* Calculate the number of bytes that can be added in the first write - + which may be less than the total number of bytes that need to be added if + the buffer will wrap back to the beginning. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); - /* Write as many bytes as can be written in the first write. */ - configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) rtos_memcpy_ptr( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + /* Write as many bytes as can be written in the first write. */ + configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) rtos_memcpy_ptr( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - /* If the number of bytes written was less than the number that could be - written in the first write... */ - if( xCount > xFirstLength ) - { - /* ...then write the remaining bytes to the start of the buffer. */ - configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) rtos_memcpy_ptr( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the number of bytes written was less than the number that could be + written in the first write... */ + if( xCount > xFirstLength ) + { + /* ...then write the remaining bytes to the start of the buffer. */ + configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) rtos_memcpy_ptr( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xNextHead += xCount; - if( xNextHead >= pxStreamBuffer->xLength ) - { - xNextHead -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + xNextHead += xCount; + if( xNextHead >= pxStreamBuffer->xLength ) + { + xNextHead -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxStreamBuffer->xHead = xNextHead; + pxStreamBuffer->xHead = xNextHead; - return xCount; + return xCount; } /*-----------------------------------------------------------*/ @@ -1135,54 +1135,54 @@ static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, uint8_t *p { size_t xCount, xFirstLength, xNextTail; - /* Use the minimum of the wanted bytes and the available bytes. */ - xCount = configMIN( xBytesAvailable, xMaxCount ); + /* Use the minimum of the wanted bytes and the available bytes. */ + xCount = configMIN( xBytesAvailable, xMaxCount ); - if( xCount > ( size_t ) 0 ) - { - xNextTail = pxStreamBuffer->xTail; + if( xCount > ( size_t ) 0 ) + { + xNextTail = pxStreamBuffer->xTail; - /* Calculate the number of bytes that can be read - which may be - less than the number wanted if the data wraps around to the start of - the buffer. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); + /* Calculate the number of bytes that can be read - which may be + less than the number wanted if the data wraps around to the start of + the buffer. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); - /* Obtain the number of bytes it is possible to obtain in the first - read. Asserts check bounds of read and write. */ - configASSERT( xFirstLength <= xMaxCount ); - configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) rtos_memcpy_ptr( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + /* Obtain the number of bytes it is possible to obtain in the first + read. Asserts check bounds of read and write. */ + configASSERT( xFirstLength <= xMaxCount ); + configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) rtos_memcpy_ptr( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - /* If the total number of wanted bytes is greater than the number - that could be read in the first read... */ - if( xCount > xFirstLength ) - { - /*...then read the remaining bytes from the start of the buffer. */ - configASSERT( xCount <= xMaxCount ); - ( void ) rtos_memcpy_ptr( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the total number of wanted bytes is greater than the number + that could be read in the first read... */ + if( xCount > xFirstLength ) + { + /*...then read the remaining bytes from the start of the buffer. */ + configASSERT( xCount <= xMaxCount ); + ( void ) rtos_memcpy_ptr( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Move the tail pointer to effectively remove the data read from - the buffer. */ - xNextTail += xCount; + /* Move the tail pointer to effectively remove the data read from + the buffer. */ + xNextTail += xCount; - if( xNextTail >= pxStreamBuffer->xLength ) - { - xNextTail -= pxStreamBuffer->xLength; - } + if( xNextTail >= pxStreamBuffer->xLength ) + { + xNextTail -= pxStreamBuffer->xLength; + } - pxStreamBuffer->xTail = xNextTail; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + pxStreamBuffer->xTail = xNextTail; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xCount; + return xCount; } /*-----------------------------------------------------------*/ @@ -1191,73 +1191,73 @@ static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) /* Returns the distance between xTail and xHead. */ size_t xCount; - xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; - xCount -= pxStreamBuffer->xTail; - if ( xCount >= pxStreamBuffer->xLength ) - { - xCount -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; + xCount -= pxStreamBuffer->xTail; + if ( xCount >= pxStreamBuffer->xLength ) + { + xCount -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xCount; + return xCount; } /*-----------------------------------------------------------*/ static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - uint8_t ucFlags ) + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) { - /* Assert here is deliberately writing to the entire buffer to ensure it can - be written to without generating exceptions, and is setting the buffer to a - known value to assist in development/debugging. */ - #if( configASSERT_DEFINED == 1 ) - { - /* The value written just has to be identifiable when looking at the - memory. Don't use 0xA5 as that is the stack fill value and could - result in confusion as to what is actually being observed. */ - const BaseType_t xWriteValue = 0x55; - configASSERT( rtos_memset_ptr( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); - } /*lint !e529 !e438 xWriteValue is only used if configASSERT() is defined. */ - #endif + /* Assert here is deliberately writing to the entire buffer to ensure it can + be written to without generating exceptions, and is setting the buffer to a + known value to assist in development/debugging. */ + #if( configASSERT_DEFINED == 1 ) + { + /* The value written just has to be identifiable when looking at the + memory. Don't use 0xA5 as that is the stack fill value and could + result in confusion as to what is actually being observed. */ + const BaseType_t xWriteValue = 0x55; + configASSERT( rtos_memset_ptr( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); + } /*lint !e529 !e438 xWriteValue is only used if configASSERT() is defined. */ + #endif - ( void ) rtos_memset_ptr( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ - pxStreamBuffer->pucBuffer = pucBuffer; - pxStreamBuffer->xLength = xBufferSizeBytes; - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; - pxStreamBuffer->ucFlags = ucFlags; + ( void ) rtos_memset_ptr( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ + pxStreamBuffer->pucBuffer = pucBuffer; + pxStreamBuffer->xLength = xBufferSizeBytes; + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; + pxStreamBuffer->ucFlags = ucFlags; } #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) - { - return xStreamBuffer->uxStreamBufferNumber; - } + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) + { + return xStreamBuffer->uxStreamBufferNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) - { - xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; - } + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) + { + xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) - { - return ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ); - } + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) + { + return ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ); + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv/tasks.c b/components/bl602/freertos_riscv/tasks.c index 0fb215db..5dc6cd34 100644 --- a/components/bl602/freertos_riscv/tasks.c +++ b/components/bl602/freertos_riscv/tasks.c @@ -49,145 +49,145 @@ correct privileged Vs unprivileged linkage and placement. */ /* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting functions but without including stdio.h here. */ #if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) - /* At the bottom of this file are two optional functions that can be used - to generate human readable text from the raw data generated by the - uxTaskGetSystemState() function. Note the formatting functions are provided - for convenience only, and are NOT considered part of the kernel. */ - #include + /* At the bottom of this file are two optional functions that can be used + to generate human readable text from the raw data generated by the + uxTaskGetSystemState() function. Note the formatting functions are provided + for convenience only, and are NOT considered part of the kernel. */ + #include #endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ #if( configUSE_PREEMPTION == 0 ) - /* If the cooperative scheduler is being used then a yield should not be - performed just because a higher priority task has been woken. */ - #define taskYIELD_IF_USING_PREEMPTION() + /* If the cooperative scheduler is being used then a yield should not be + performed just because a higher priority task has been woken. */ + #define taskYIELD_IF_USING_PREEMPTION() #else - #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() + #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() #endif /* Values that can be assigned to the ucNotifyState member of the TCB. */ -#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) -#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) -#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) +#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) +#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) +#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) /* * The value used to fill the stack of a task when the task is created. This * is used purely for checking the high water mark for tasks. */ -#define tskSTACK_FILL_BYTE ( 0xa5U ) +#define tskSTACK_FILL_BYTE ( 0xa5U ) /* Bits used to recored how a task's stack and TCB were allocated. */ -#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) -#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) -#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) +#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) +#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) +#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) /* If any of the following are set then task stacks are filled with a known value so the high water mark can be determined. If none of the following are set then don't fill the stack so there is no unnecessary dependency on memset. */ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 #else - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 #endif /* * Macros used by vListTask to indicate which state a task is in. */ -#define tskRUNNING_CHAR ( 'X' ) -#define tskBLOCKED_CHAR ( 'B' ) -#define tskREADY_CHAR ( 'R' ) -#define tskDELETED_CHAR ( 'D' ) -#define tskSUSPENDED_CHAR ( 'S' ) +#define tskRUNNING_CHAR ( 'X' ) +#define tskBLOCKED_CHAR ( 'B' ) +#define tskREADY_CHAR ( 'R' ) +#define tskDELETED_CHAR ( 'D' ) +#define tskSUSPENDED_CHAR ( 'S' ) /* * Some kernel aware debuggers require the data the debugger needs access to be * global, rather than file scope. */ #ifdef portREMOVE_STATIC_QUALIFIER - #define static + #define static #endif /* The name allocated to the Idle task. This can be overridden by defining configIDLE_TASK_NAME in FreeRTOSConfig.h. */ #ifndef configIDLE_TASK_NAME - #define configIDLE_TASK_NAME "IDLE" + #define configIDLE_TASK_NAME "IDLE" #endif #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is - performed in a generic way that is not optimised to any particular - microcontroller architecture. */ + /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is + performed in a generic way that is not optimised to any particular + microcontroller architecture. */ - /* uxTopReadyPriority holds the priority of the highest priority ready - state task. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) \ - { \ - if( ( uxPriority ) > uxTopReadyPriority ) \ - { \ - uxTopReadyPriority = ( uxPriority ); \ - } \ - } /* taskRECORD_READY_PRIORITY */ + /* uxTopReadyPriority holds the priority of the highest priority ready + state task. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) \ + { \ + if( ( uxPriority ) > uxTopReadyPriority ) \ + { \ + uxTopReadyPriority = ( uxPriority ); \ + } \ + } /* taskRECORD_READY_PRIORITY */ - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority = uxTopReadyPriority; \ - \ - /* Find the highest priority queue that contains ready tasks. */ \ - while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ - { \ - configASSERT( uxTopPriority ); \ - --uxTopPriority; \ - } \ - \ - /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ - the same priority get an equal share of the processor time. */ \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - uxTopReadyPriority = uxTopPriority; \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK */ + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority = uxTopReadyPriority; \ + \ + /* Find the highest priority queue that contains ready tasks. */ \ + while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ + { \ + configASSERT( uxTopPriority ); \ + --uxTopPriority; \ + } \ + \ + /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ + the same priority get an equal share of the processor time. */ \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + uxTopReadyPriority = uxTopPriority; \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK */ - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as - they are only required when a port optimised method of task selection is - being used. */ - #define taskRESET_READY_PRIORITY( uxPriority ) - #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as + they are only required when a port optimised method of task selection is + being used. */ + #define taskRESET_READY_PRIORITY( uxPriority ) + #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) #else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is - performed in a way that is tailored to the particular microcontroller - architecture being used. */ + /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is + performed in a way that is tailored to the particular microcontroller + architecture being used. */ - /* A port optimised version is provided. Call the port defined macros. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + /* A port optimised version is provided. Call the port defined macros. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority; \ - \ - /* Find the highest priority list that contains ready tasks. */ \ - portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ - configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority; \ + \ + /* Find the highest priority list that contains ready tasks. */ \ + portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ + configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - /* A port optimised version is provided, call it only if the TCB being reset - is being referenced from a ready list. If it is referenced from a delayed - or suspended list then it won't be in a ready list. */ - #define taskRESET_READY_PRIORITY( uxPriority ) \ - { \ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ - { \ - portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ - } \ - } + /* A port optimised version is provided, call it only if the TCB being reset + is being referenced from a ready list. If it is referenced from a delayed + or suspended list then it won't be in a ready list. */ + #define taskRESET_READY_PRIORITY( uxPriority ) \ + { \ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ + { \ + portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ + } \ + } #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ @@ -195,18 +195,18 @@ configIDLE_TASK_NAME in FreeRTOSConfig.h. */ /* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick count overflows. */ -#define taskSWITCH_DELAYED_LISTS() \ -{ \ - List_t *pxTemp; \ - \ - /* The delayed tasks list should be empty when the lists are switched. */ \ - configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ - \ - pxTemp = pxDelayedTaskList; \ - pxDelayedTaskList = pxOverflowDelayedTaskList; \ - pxOverflowDelayedTaskList = pxTemp; \ - xNumOfOverflows++; \ - prvResetNextTaskUnblockTime(); \ +#define taskSWITCH_DELAYED_LISTS() \ +{ \ + List_t *pxTemp; \ + \ + /* The delayed tasks list should be empty when the lists are switched. */ \ + configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ + \ + pxTemp = pxDelayedTaskList; \ + pxDelayedTaskList = pxOverflowDelayedTaskList; \ + pxOverflowDelayedTaskList = pxTemp; \ + xNumOfOverflows++; \ + prvResetNextTaskUnblockTime(); \ } /*-----------------------------------------------------------*/ @@ -215,11 +215,11 @@ count overflows. */ * Place the task represented by pxTCB into the appropriate ready list for * the task. It is inserted at the end of the list. */ -#define prvAddTaskToReadyList( pxTCB ) \ - traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ - taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ - vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ - tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +#define prvAddTaskToReadyList( pxTCB ) \ + traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ + taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ + vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ + tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) /*-----------------------------------------------------------*/ /* @@ -239,9 +239,9 @@ the scheduler that the value should not be changed - in which case it is the responsibility of whichever module is using the value to ensure it gets set back to its original value when it is released. */ #if( configUSE_16_BIT_TICKS == 1 ) - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U #else - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL #endif /* @@ -249,79 +249,79 @@ to its original value when it is released. */ * and stores task state information, including a pointer to the task's context * (the task's run time environment, including register values) */ -typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ { - volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ + volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ - #endif + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ + #endif - ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ - ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ - UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ - StackType_t *pxStack; /*< Points to the start of the stack. */ - char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ + ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ + UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ + StackType_t *pxStack; /*< Points to the start of the stack. */ + char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */ - #endif + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */ + #endif - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ - #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ + #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ - UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ + UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ + #endif - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ - UBaseType_t uxMutexesHeld; - #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ + UBaseType_t uxMutexesHeld; + #endif - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t pxTaskTag; - #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + TaskHookFunction_t pxTaskTag; + #endif - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif - #if( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ - #endif + #if( configGENERATE_RUN_TIME_STATS == 1 ) + uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ + #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - /* Allocate a Newlib reent structure that is specific to this task. - Note Newlib support has been included by popular demand, but is not - used by the FreeRTOS maintainers themselves. FreeRTOS is not - responsible for resulting newlib operation. User must be familiar with - newlib and must provide system-wide implementations of the necessary - stubs. Be warned that (at the time of writing) the current newlib design - implements a system-wide malloc() that must be provided with locks. */ - struct _reent xNewLib_reent; - #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + /* Allocate a Newlib reent structure that is specific to this task. + Note Newlib support has been included by popular demand, but is not + used by the FreeRTOS maintainers themselves. FreeRTOS is not + responsible for resulting newlib operation. User must be familiar with + newlib and must provide system-wide implementations of the necessary + stubs. Be warned that (at the time of writing) the current newlib design + implements a system-wide malloc() that must be provided with locks. */ + struct _reent xNewLib_reent; + #endif - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - volatile uint32_t ulNotifiedValue; - volatile uint8_t ucNotifyState; - #endif + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + volatile uint32_t ulNotifiedValue; + volatile uint8_t ucNotifyState; + #endif - /* See the comments in FreeRTOS.h with the definition of - tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ - #endif + /* See the comments in FreeRTOS.h with the definition of + tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ + #endif - #if( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDelayAborted; - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDelayAborted; + #endif - #if( configUSE_POSIX_ERRNO == 1 ) - int iTaskErrno; - #endif + #if( configUSE_POSIX_ERRNO == 1 ) + int iTaskErrno; + #endif } tskTCB; @@ -338,42 +338,42 @@ xDelayedTaskList1 and xDelayedTaskList2 could be move to function scople but doing so breaks some kernel aware debuggers and debuggers that rely on removing the static qualifier. */ PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ -PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ +PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ +PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ #if( INCLUDE_vTaskDelete == 1 ) - PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ - PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; + PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ + PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; #endif #if ( INCLUDE_vTaskSuspend == 1 ) - PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ + PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ #endif /* Global POSIX errno. Its value is changed upon context switching to match the errno of the currently running task. */ #if ( configUSE_POSIX_ERRNO == 1 ) - int FreeRTOS_errno = 0; + int FreeRTOS_errno = 0; #endif /* Other file private variables. --------------------------------*/ -PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; -PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; -PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; -PRIVILEGED_DATA static volatile UBaseType_t uxPendedTicks = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; -PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; -PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ -PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ +PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; +PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; +PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; +PRIVILEGED_DATA static volatile UBaseType_t uxPendedTicks = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; +PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; +PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ +PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ /* Context switches are held pending while the scheduler is suspended. Also, interrupts must not manipulate the xStateListItem of a TCB, or any of the @@ -383,14 +383,14 @@ moves the task's event list item into the xPendingReadyList, ready for the kernel to move the task from the pending ready list into the real ready list when the scheduler is unsuspended. The pending ready list itself can only be accessed from a critical section. */ -PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; +PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; #if ( configGENERATE_RUN_TIME_STATS == 1 ) - /* Do not move these variables to function scope as doing so prevents the - code working with debuggers that need to remove the static qualifier. */ - PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ - PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ + /* Do not move these variables to function scope as doing so prevents the + code working with debuggers that need to remove the static qualifier. */ + PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ + PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ #endif @@ -401,19 +401,19 @@ PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t /* Callback function prototypes. --------------------------*/ #if( configCHECK_FOR_STACK_OVERFLOW > 0 ) - extern void (*vApplicationStackOverflowHook)( TaskHandle_t xTask, char *pcTaskName ); + extern void (*vApplicationStackOverflowHook)( TaskHandle_t xTask, char *pcTaskName ); #endif #if( configUSE_TICK_HOOK > 0 ) - extern void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ + extern void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ #endif #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - extern void (*vApplicationGetIdleTaskMemory)( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ + extern void (*vApplicationGetIdleTaskMemory)( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ #endif @@ -426,7 +426,7 @@ PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t */ #if ( INCLUDE_vTaskSuspend == 1 ) - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; #endif /* INCLUDE_vTaskSuspend */ @@ -458,7 +458,7 @@ static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ); */ #if ( INCLUDE_vTaskDelete == 1 ) - static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION; + static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION; #endif @@ -485,7 +485,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( configUSE_TRACE_FACILITY == 1 ) - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION; + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION; #endif @@ -495,7 +495,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( INCLUDE_xTaskGetHandle == 1 ) - static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; + static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; #endif @@ -506,7 +506,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; #endif @@ -521,7 +521,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( configUSE_TICKLESS_IDLE != 0 ) - static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; + static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; #endif @@ -533,11 +533,11 @@ static void prvResetNextTaskUnblockTime( void ); #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - /* - * Helper function used to pad task names with spaces when printing out - * human readable tables of task information. - */ - static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) PRIVILEGED_FUNCTION; + /* + * Helper function used to pad task names with spaces when printing out + * human readable tables of task information. + */ + static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) PRIVILEGED_FUNCTION; #endif @@ -545,14 +545,14 @@ static void prvResetNextTaskUnblockTime( void ); * Called after a Task_t structure has been allocated either statically or * dynamically to fill in the structure's members. */ -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t *pxNewTCB, - const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t *pxNewTCB, + const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; /* * Called after a new task has been created and initialised to place the task @@ -567,7 +567,7 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION; */ #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; + static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; #endif @@ -575,1318 +575,1318 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION; #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) - { - TCB_t *pxNewTCB; - TaskHandle_t xReturn; + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) + { + TCB_t *pxNewTCB; + TaskHandle_t xReturn; - configASSERT( puxStackBuffer != NULL ); - configASSERT( pxTaskBuffer != NULL ); + configASSERT( puxStackBuffer != NULL ); + configASSERT( pxTaskBuffer != NULL ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticTask_t equals the size of the real task - structure. */ - volatile size_t xSize = sizeof( StaticTask_t ); - configASSERT( xSize == sizeof( TCB_t ) ); - ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ - } - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticTask_t equals the size of the real task + structure. */ + volatile size_t xSize = sizeof( StaticTask_t ); + configASSERT( xSize == sizeof( TCB_t ) ); + ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ + } + #endif /* configASSERT_DEFINED */ - if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) - { - /* The memory used for the task's TCB and stack are passed into this - function - use them. */ - pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; + if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) + { + /* The memory used for the task's TCB and stack are passed into this + function - use them. */ + pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - } - else - { - xReturn = NULL; - } + prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + } + else + { + xReturn = NULL; + } - return xReturn; - } + return xReturn; + } #endif /* SUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); - configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); + configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); + configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); - if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) - { - /* Allocate space for the TCB. Where the memory comes from depends - on the implementation of the port malloc function and whether or - not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; + if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) + { + /* Allocate space for the TCB. Where the memory comes from depends + on the implementation of the port malloc function and whether or + not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - { - /* Tasks can be created statically or dynamically, so note this - task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } - return xReturn; - } + return xReturn; + } #endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ /*-----------------------------------------------------------*/ #if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - configASSERT( pxTaskDefinition->puxStackBuffer ); + configASSERT( pxTaskDefinition->puxStackBuffer ); - if( pxTaskDefinition->puxStackBuffer != NULL ) - { - /* Allocate space for the TCB. Where the memory comes from depends - on the implementation of the port malloc function and whether or - not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + if( pxTaskDefinition->puxStackBuffer != NULL ) + { + /* Allocate space for the TCB. Where the memory comes from depends + on the implementation of the port malloc function and whether or + not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - { - /* Tasks can be created statically or dynamically, so note - this task had a statically allocated stack in case it is - later deleted. The TCB was allocated dynamically. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note + this task had a statically allocated stack in case it is + later deleted. The TCB was allocated dynamically. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - } + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + } - return xReturn; - } + return xReturn; + } #endif /* portUSING_MPU_WRAPPERS */ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn; + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn; - /* If the stack grows down then allocate the stack then the TCB so the stack - does not grow into the TCB. Likewise if the stack grows up then allocate - the TCB then the stack. */ - #if( portSTACK_GROWTH > 0 ) - { - /* Allocate space for the TCB. Where the memory comes from depends on - the implementation of the port malloc function and whether or not static - allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + /* If the stack grows down then allocate the stack then the TCB so the stack + does not grow into the TCB. Likewise if the stack grows up then allocate + the TCB then the stack. */ + #if( portSTACK_GROWTH > 0 ) + { + /* Allocate space for the TCB. Where the memory comes from depends on + the implementation of the port malloc function and whether or not static + allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - if( pxNewTCB != NULL ) - { - /* Allocate space for the stack used by the task being created. - The base of the stack memory stored in the TCB so the task can - be deleted later if required. */ - pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + if( pxNewTCB != NULL ) + { + /* Allocate space for the stack used by the task being created. + The base of the stack memory stored in the TCB so the task can + be deleted later if required. */ + pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - if( pxNewTCB->pxStack == NULL ) - { - /* Could not allocate the stack. Delete the allocated TCB. */ - vPortFree( pxNewTCB ); - pxNewTCB = NULL; - } - } - } - #else /* portSTACK_GROWTH */ - { - StackType_t *pxStack; + if( pxNewTCB->pxStack == NULL ) + { + /* Could not allocate the stack. Delete the allocated TCB. */ + vPortFree( pxNewTCB ); + pxNewTCB = NULL; + } + } + } + #else /* portSTACK_GROWTH */ + { + StackType_t *pxStack; - /* Allocate space for the stack used by the task being created. */ - pxStack = pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */ + /* Allocate space for the stack used by the task being created. */ + pxStack = pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */ - if( pxStack != NULL ) - { - /* Allocate space for the TCB. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */ + if( pxStack != NULL ) + { + /* Allocate space for the TCB. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */ - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxStack; - } - else - { - /* The stack cannot be used as the TCB was not created. Free - it again. */ - vPortFree( pxStack ); - } - } - else - { - pxNewTCB = NULL; - } - } - #endif /* portSTACK_GROWTH */ + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxStack; + } + else + { + /* The stack cannot be used as the TCB was not created. Free + it again. */ + vPortFree( pxStack ); + } + } + else + { + pxNewTCB = NULL; + } + } + #endif /* portSTACK_GROWTH */ - if( pxNewTCB != NULL ) - { - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - task was created dynamically in case it is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + if( pxNewTCB != NULL ) + { + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + task was created dynamically in case it is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } + prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } - return xReturn; - } + return xReturn; + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t *pxNewTCB, - const MemoryRegion_t * const xRegions ) +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t *pxNewTCB, + const MemoryRegion_t * const xRegions ) { StackType_t *pxTopOfStack; UBaseType_t x; - #if( portUSING_MPU_WRAPPERS == 1 ) - /* Should the task be created in privileged mode? */ - BaseType_t xRunPrivileged; - if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) - { - xRunPrivileged = pdTRUE; - } - else - { - xRunPrivileged = pdFALSE; - } - uxPriority &= ~portPRIVILEGE_BIT; - #endif /* portUSING_MPU_WRAPPERS == 1 */ + #if( portUSING_MPU_WRAPPERS == 1 ) + /* Should the task be created in privileged mode? */ + BaseType_t xRunPrivileged; + if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) + { + xRunPrivileged = pdTRUE; + } + else + { + xRunPrivileged = pdFALSE; + } + uxPriority &= ~portPRIVILEGE_BIT; + #endif /* portUSING_MPU_WRAPPERS == 1 */ - /* Avoid dependency on memset() if it is not required. */ - #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) - { - /* Fill the stack with a known value to assist debugging. */ - ( void ) rtos_memset_ptr( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); - } - #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ + /* Avoid dependency on memset() if it is not required. */ + #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) + { + /* Fill the stack with a known value to assist debugging. */ + ( void ) rtos_memset_ptr( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); + } + #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ - /* Calculate the top of stack address. This depends on whether the stack - grows from high memory to low (as per the 80x86) or vice versa. - portSTACK_GROWTH is used to make the result positive or negative as required - by the port. */ - #if( portSTACK_GROWTH < 0 ) - { - pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] ); - pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */ + /* Calculate the top of stack address. This depends on whether the stack + grows from high memory to low (as per the 80x86) or vice versa. + portSTACK_GROWTH is used to make the result positive or negative as required + by the port. */ + #if( portSTACK_GROWTH < 0 ) + { + pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] ); + pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */ - /* Check the alignment of the calculated top of stack is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + /* Check the alignment of the calculated top of stack is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - #if( configRECORD_STACK_HIGH_ADDRESS == 1 ) - { - /* Also record the stack's high address, which may assist - debugging. */ - pxNewTCB->pxEndOfStack = pxTopOfStack; - } - #endif /* configRECORD_STACK_HIGH_ADDRESS */ - } - #else /* portSTACK_GROWTH */ - { - pxTopOfStack = pxNewTCB->pxStack; + #if( configRECORD_STACK_HIGH_ADDRESS == 1 ) + { + /* Also record the stack's high address, which may assist + debugging. */ + pxNewTCB->pxEndOfStack = pxTopOfStack; + } + #endif /* configRECORD_STACK_HIGH_ADDRESS */ + } + #else /* portSTACK_GROWTH */ + { + pxTopOfStack = pxNewTCB->pxStack; - /* Check the alignment of the stack buffer is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + /* Check the alignment of the stack buffer is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - /* The other extreme of the stack space is required if stack checking is - performed. */ - pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); - } - #endif /* portSTACK_GROWTH */ + /* The other extreme of the stack space is required if stack checking is + performed. */ + pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); + } + #endif /* portSTACK_GROWTH */ - /* Store the task name in the TCB. */ - if( pcName != NULL ) - { - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - pxNewTCB->pcTaskName[ x ] = pcName[ x ]; + /* Store the task name in the TCB. */ + if( pcName != NULL ) + { + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + pxNewTCB->pcTaskName[ x ] = pcName[ x ]; - /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than - configMAX_TASK_NAME_LEN characters just in case the memory after the - string is not accessible (extremely unlikely). */ - if( pcName[ x ] == ( char ) 0x00 ) - { - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than + configMAX_TASK_NAME_LEN characters just in case the memory after the + string is not accessible (extremely unlikely). */ + if( pcName[ x ] == ( char ) 0x00 ) + { + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - /* Ensure the name string is terminated in the case that the string length - was greater or equal to configMAX_TASK_NAME_LEN. */ - pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; - } - else - { - /* The task has not been given a name, so just ensure there is a NULL - terminator when it is read out. */ - pxNewTCB->pcTaskName[ 0 ] = 0x00; - } + /* Ensure the name string is terminated in the case that the string length + was greater or equal to configMAX_TASK_NAME_LEN. */ + pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; + } + else + { + /* The task has not been given a name, so just ensure there is a NULL + terminator when it is read out. */ + pxNewTCB->pcTaskName[ 0 ] = 0x00; + } - /* This is used as an array index so must ensure it's not too large. First - remove the privilege bit if one is present. */ - if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* This is used as an array index so must ensure it's not too large. First + remove the privilege bit if one is present. */ + if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxNewTCB->uxPriority = uxPriority; - #if ( configUSE_MUTEXES == 1 ) - { - pxNewTCB->uxBasePriority = uxPriority; - pxNewTCB->uxMutexesHeld = 0; - } - #endif /* configUSE_MUTEXES */ + pxNewTCB->uxPriority = uxPriority; + #if ( configUSE_MUTEXES == 1 ) + { + pxNewTCB->uxBasePriority = uxPriority; + pxNewTCB->uxMutexesHeld = 0; + } + #endif /* configUSE_MUTEXES */ - vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); - vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); + vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); + vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); - /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get - back to the containing TCB from a generic item in a list. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); + /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get + back to the containing TCB from a generic item in a list. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - { - pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; - } - #endif /* portCRITICAL_NESTING_IN_TCB */ + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + { + pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; + } + #endif /* portCRITICAL_NESTING_IN_TCB */ - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - { - pxNewTCB->pxTaskTag = NULL; - } - #endif /* configUSE_APPLICATION_TASK_TAG */ + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + { + pxNewTCB->pxTaskTag = NULL; + } + #endif /* configUSE_APPLICATION_TASK_TAG */ - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxNewTCB->ulRunTimeCounter = 0UL; - } - #endif /* configGENERATE_RUN_TIME_STATS */ + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxNewTCB->ulRunTimeCounter = 0UL; + } + #endif /* configGENERATE_RUN_TIME_STATS */ - #if ( portUSING_MPU_WRAPPERS == 1 ) - { - vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); - } - #else - { - /* Avoid compiler warning about unreferenced parameter. */ - ( void ) xRegions; - } - #endif + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); + } + #else + { + /* Avoid compiler warning about unreferenced parameter. */ + ( void ) xRegions; + } + #endif - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - { - for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ ) - { - pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL; - } - } - #endif + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + { + for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ ) + { + pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL; + } + } + #endif - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - { - pxNewTCB->ulNotifiedValue = 0; - pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + pxNewTCB->ulNotifiedValue = 0; + pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Initialise this task's Newlib reent structure. */ - _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); - } - #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Initialise this task's Newlib reent structure. */ + _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); + } + #endif - #if( INCLUDE_xTaskAbortDelay == 1 ) - { - pxNewTCB->ucDelayAborted = pdFALSE; - } - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + { + pxNewTCB->ucDelayAborted = pdFALSE; + } + #endif - /* Initialize the TCB stack to look as if the task was already running, - but had been interrupted by the scheduler. The return address is set - to the start of the task function. Once the stack has been initialised - the top of stack variable is updated. */ - #if( portUSING_MPU_WRAPPERS == 1 ) - { - /* If the port has capability to detect stack overflow, - pass the stack end address to the stack initialization - function as well. */ - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - { - #if( portSTACK_GROWTH < 0 ) - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #else /* portSTACK_GROWTH */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #endif /* portSTACK_GROWTH */ - } - #else /* portHAS_STACK_OVERFLOW_CHECKING */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #endif /* portHAS_STACK_OVERFLOW_CHECKING */ - } - #else /* portUSING_MPU_WRAPPERS */ - { - /* If the port has capability to detect stack overflow, - pass the stack end address to the stack initialization - function as well. */ - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - { - #if( portSTACK_GROWTH < 0 ) - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); - } - #else /* portSTACK_GROWTH */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); - } - #endif /* portSTACK_GROWTH */ - } - #else /* portHAS_STACK_OVERFLOW_CHECKING */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); - } - #endif /* portHAS_STACK_OVERFLOW_CHECKING */ - } - #endif /* portUSING_MPU_WRAPPERS */ + /* Initialize the TCB stack to look as if the task was already running, + but had been interrupted by the scheduler. The return address is set + to the start of the task function. Once the stack has been initialised + the top of stack variable is updated. */ + #if( portUSING_MPU_WRAPPERS == 1 ) + { + /* If the port has capability to detect stack overflow, + pass the stack end address to the stack initialization + function as well. */ + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #else /* portUSING_MPU_WRAPPERS */ + { + /* If the port has capability to detect stack overflow, + pass the stack end address to the stack initialization + function as well. */ + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #endif /* portUSING_MPU_WRAPPERS */ - if( pxCreatedTask != NULL ) - { - /* Pass the handle out in an anonymous way. The handle can be used to - change the created task's priority, delete the created task, etc.*/ - *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( pxCreatedTask != NULL ) + { + /* Pass the handle out in an anonymous way. The handle can be used to + change the created task's priority, delete the created task, etc.*/ + *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } /*-----------------------------------------------------------*/ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) { - /* Ensure interrupts don't access the task lists while the lists are being - updated. */ - taskENTER_CRITICAL(); - { - uxCurrentNumberOfTasks++; - if( pxCurrentTCB == NULL ) - { - /* There are no other tasks, or all the other tasks are in - the suspended state - make this the current task. */ - pxCurrentTCB = pxNewTCB; + /* Ensure interrupts don't access the task lists while the lists are being + updated. */ + taskENTER_CRITICAL(); + { + uxCurrentNumberOfTasks++; + if( pxCurrentTCB == NULL ) + { + /* There are no other tasks, or all the other tasks are in + the suspended state - make this the current task. */ + pxCurrentTCB = pxNewTCB; - if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) - { - /* This is the first task to be created so do the preliminary - initialisation required. We will not recover if this call - fails, but we will report the failure. */ - prvInitialiseTaskLists(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If the scheduler is not already running, make this task the - current task if it is the highest priority task to be created - so far. */ - if( xSchedulerRunning == pdFALSE ) - { - if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) - { - pxCurrentTCB = pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) + { + /* This is the first task to be created so do the preliminary + initialisation required. We will not recover if this call + fails, but we will report the failure. */ + prvInitialiseTaskLists(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If the scheduler is not already running, make this task the + current task if it is the highest priority task to be created + so far. */ + if( xSchedulerRunning == pdFALSE ) + { + if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) + { + pxCurrentTCB = pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - uxTaskNumber++; + uxTaskNumber++; - #if ( configUSE_TRACE_FACILITY == 1 ) - { - /* Add a counter into the TCB for tracing only. */ - pxNewTCB->uxTCBNumber = uxTaskNumber; - } - #endif /* configUSE_TRACE_FACILITY */ - traceTASK_CREATE( pxNewTCB ); + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Add a counter into the TCB for tracing only. */ + pxNewTCB->uxTCBNumber = uxTaskNumber; + } + #endif /* configUSE_TRACE_FACILITY */ + traceTASK_CREATE( pxNewTCB ); - prvAddTaskToReadyList( pxNewTCB ); + prvAddTaskToReadyList( pxNewTCB ); - portSETUP_TCB( pxNewTCB ); - } - taskEXIT_CRITICAL(); + portSETUP_TCB( pxNewTCB ); + } + taskEXIT_CRITICAL(); - if( xSchedulerRunning != pdFALSE ) - { - /* If the created task is of a higher priority than the current task - then it should run now. */ - if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSchedulerRunning != pdFALSE ) + { + /* If the created task is of a higher priority than the current task + then it should run now. */ + if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelete == 1 ) - void vTaskDelete( TaskHandle_t xTaskToDelete ) - { - TCB_t *pxTCB; + void vTaskDelete( TaskHandle_t xTaskToDelete ) + { + TCB_t *pxTCB; - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the calling task that is - being deleted. */ - pxTCB = prvGetTCBFromHandle( xTaskToDelete ); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the calling task that is + being deleted. */ + pxTCB = prvGetTCBFromHandle( xTaskToDelete ); - /* Remove task from the ready list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Remove task from the ready list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Increment the uxTaskNumber also so kernel aware debuggers can - detect that the task lists need re-generating. This is done before - portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will - not return. */ - uxTaskNumber++; + /* Increment the uxTaskNumber also so kernel aware debuggers can + detect that the task lists need re-generating. This is done before + portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will + not return. */ + uxTaskNumber++; - if( pxTCB == pxCurrentTCB ) - { - /* A task is deleting itself. This cannot complete within the - task itself, as a context switch to another task is required. - Place the task in the termination list. The idle task will - check the termination list and free up any memory allocated by - the scheduler for the TCB and stack of the deleted task. */ - vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); + if( pxTCB == pxCurrentTCB ) + { + /* A task is deleting itself. This cannot complete within the + task itself, as a context switch to another task is required. + Place the task in the termination list. The idle task will + check the termination list and free up any memory allocated by + the scheduler for the TCB and stack of the deleted task. */ + vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); - /* Increment the ucTasksDeleted variable so the idle task knows - there is a task that has been deleted and that it should therefore - check the xTasksWaitingTermination list. */ - ++uxDeletedTasksWaitingCleanUp; + /* Increment the ucTasksDeleted variable so the idle task knows + there is a task that has been deleted and that it should therefore + check the xTasksWaitingTermination list. */ + ++uxDeletedTasksWaitingCleanUp; - /* The pre-delete hook is primarily for the Windows simulator, - in which Windows specific clean up operations are performed, - after which it is not possible to yield away from this task - - hence xYieldPending is used to latch that a context switch is - required. */ - portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); - } - else - { - --uxCurrentNumberOfTasks; - prvDeleteTCB( pxTCB ); + /* The pre-delete hook is primarily for the Windows simulator, + in which Windows specific clean up operations are performed, + after which it is not possible to yield away from this task - + hence xYieldPending is used to latch that a context switch is + required. */ + portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); + } + else + { + --uxCurrentNumberOfTasks; + prvDeleteTCB( pxTCB ); - /* Reset the next expected unblock time in case it referred to - the task that has just been deleted. */ - prvResetNextTaskUnblockTime(); - } + /* Reset the next expected unblock time in case it referred to + the task that has just been deleted. */ + prvResetNextTaskUnblockTime(); + } - traceTASK_DELETE( pxTCB ); - } - taskEXIT_CRITICAL(); + traceTASK_DELETE( pxTCB ); + } + taskEXIT_CRITICAL(); - /* Force a reschedule if it is the currently running task that has just - been deleted. */ - if( xSchedulerRunning != pdFALSE ) - { - if( pxTCB == pxCurrentTCB ) - { - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } + /* Force a reschedule if it is the currently running task that has just + been deleted. */ + if( xSchedulerRunning != pdFALSE ) + { + if( pxTCB == pxCurrentTCB ) + { + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } #endif /* INCLUDE_vTaskDelete */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelayUntil == 1 ) - void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) - { - TickType_t xTimeToWake; - BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; + void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) + { + TickType_t xTimeToWake; + BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; - configASSERT( pxPreviousWakeTime ); - configASSERT( ( xTimeIncrement > 0U ) ); - configASSERT( uxSchedulerSuspended == 0 ); + configASSERT( pxPreviousWakeTime ); + configASSERT( ( xTimeIncrement > 0U ) ); + configASSERT( uxSchedulerSuspended == 0 ); - vTaskSuspendAll(); - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount; + vTaskSuspendAll(); + { + /* Minor optimisation. The tick count cannot change in this + block. */ + const TickType_t xConstTickCount = xTickCount; - /* Generate the tick time at which the task wants to wake. */ - xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; + /* Generate the tick time at which the task wants to wake. */ + xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; - if( xConstTickCount < *pxPreviousWakeTime ) - { - /* The tick count has overflowed since this function was - lasted called. In this case the only time we should ever - actually delay is if the wake time has also overflowed, - and the wake time is greater than the tick time. When this - is the case it is as if neither time had overflowed. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The tick time has not overflowed. In this case we will - delay if either the wake time has overflowed, and/or the - tick time is less than the wake time. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( xConstTickCount < *pxPreviousWakeTime ) + { + /* The tick count has overflowed since this function was + lasted called. In this case the only time we should ever + actually delay is if the wake time has also overflowed, + and the wake time is greater than the tick time. When this + is the case it is as if neither time had overflowed. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The tick time has not overflowed. In this case we will + delay if either the wake time has overflowed, and/or the + tick time is less than the wake time. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - /* Update the wake time ready for the next call. */ - *pxPreviousWakeTime = xTimeToWake; + /* Update the wake time ready for the next call. */ + *pxPreviousWakeTime = xTimeToWake; - if( xShouldDelay != pdFALSE ) - { - traceTASK_DELAY_UNTIL( xTimeToWake ); + if( xShouldDelay != pdFALSE ) + { + traceTASK_DELAY_UNTIL( xTimeToWake ); - /* prvAddCurrentTaskToDelayedList() needs the block time, not - the time to wake, so subtract the current tick count. */ - prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - xAlreadyYielded = xTaskResumeAll(); + /* prvAddCurrentTaskToDelayedList() needs the block time, not + the time to wake, so subtract the current tick count. */ + prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); - /* Force a reschedule if xTaskResumeAll has not already done so, we may - have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Force a reschedule if xTaskResumeAll has not already done so, we may + have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskDelayUntil */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelay == 1 ) - void vTaskDelay( const TickType_t xTicksToDelay ) - { - BaseType_t xAlreadyYielded = pdFALSE; + void vTaskDelay( const TickType_t xTicksToDelay ) + { + BaseType_t xAlreadyYielded = pdFALSE; - /* A delay time of zero just forces a reschedule. */ - if( xTicksToDelay > ( TickType_t ) 0U ) - { - configASSERT( uxSchedulerSuspended == 0 ); - vTaskSuspendAll(); - { - traceTASK_DELAY(); + /* A delay time of zero just forces a reschedule. */ + if( xTicksToDelay > ( TickType_t ) 0U ) + { + configASSERT( uxSchedulerSuspended == 0 ); + vTaskSuspendAll(); + { + traceTASK_DELAY(); - /* A task that is removed from the event list while the - scheduler is suspended will not get placed in the ready - list or removed from the blocked list until the scheduler - is resumed. + /* A task that is removed from the event list while the + scheduler is suspended will not get placed in the ready + list or removed from the blocked list until the scheduler + is resumed. - This task cannot be in an event list as it is the currently - executing task. */ - prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); - } - xAlreadyYielded = xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + This task cannot be in an event list as it is the currently + executing task. */ + prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); + } + xAlreadyYielded = xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Force a reschedule if xTaskResumeAll has not already done so, we may - have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Force a reschedule if xTaskResumeAll has not already done so, we may + have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskDelay */ /*-----------------------------------------------------------*/ #if( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) - eTaskState eTaskGetState( TaskHandle_t xTask ) - { - eTaskState eReturn; - List_t const * pxStateList, *pxDelayedList, *pxOverflowedDelayedList; - const TCB_t * const pxTCB = xTask; + eTaskState eTaskGetState( TaskHandle_t xTask ) + { + eTaskState eReturn; + List_t const * pxStateList, *pxDelayedList, *pxOverflowedDelayedList; + const TCB_t * const pxTCB = xTask; - configASSERT( pxTCB ); + configASSERT( pxTCB ); - if( pxTCB == pxCurrentTCB ) - { - /* The task calling this function is querying its own state. */ - eReturn = eRunning; - } - else - { - taskENTER_CRITICAL(); - { - pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); - pxDelayedList = pxDelayedTaskList; - pxOverflowedDelayedList = pxOverflowDelayedTaskList; - } - taskEXIT_CRITICAL(); + if( pxTCB == pxCurrentTCB ) + { + /* The task calling this function is querying its own state. */ + eReturn = eRunning; + } + else + { + taskENTER_CRITICAL(); + { + pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); + pxDelayedList = pxDelayedTaskList; + pxOverflowedDelayedList = pxOverflowDelayedTaskList; + } + taskEXIT_CRITICAL(); - if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) - { - /* The task being queried is referenced from one of the Blocked - lists. */ - eReturn = eBlocked; - } + if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) + { + /* The task being queried is referenced from one of the Blocked + lists. */ + eReturn = eBlocked; + } - #if ( INCLUDE_vTaskSuspend == 1 ) - else if( pxStateList == &xSuspendedTaskList ) - { - /* The task being queried is referenced from the suspended - list. Is it genuinely suspended or is it blocked - indefinitely? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) - { - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - { - /* The task does not appear on the event list item of - and of the RTOS objects, but could still be in the - blocked state if it is waiting on its notification - rather than waiting on an object. */ - if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) - { - eReturn = eBlocked; - } - else - { - eReturn = eSuspended; - } - } - #else - { - eReturn = eSuspended; - } - #endif - } - else - { - eReturn = eBlocked; - } - } - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + else if( pxStateList == &xSuspendedTaskList ) + { + /* The task being queried is referenced from the suspended + list. Is it genuinely suspended or is it blocked + indefinitely? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) + { + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + { + /* The task does not appear on the event list item of + and of the RTOS objects, but could still be in the + blocked state if it is waiting on its notification + rather than waiting on an object. */ + if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) + { + eReturn = eBlocked; + } + else + { + eReturn = eSuspended; + } + } + #else + { + eReturn = eSuspended; + } + #endif + } + else + { + eReturn = eBlocked; + } + } + #endif - #if ( INCLUDE_vTaskDelete == 1 ) - else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) - { - /* The task being queried is referenced from the deleted - tasks list, or it is not referenced from any lists at - all. */ - eReturn = eDeleted; - } - #endif + #if ( INCLUDE_vTaskDelete == 1 ) + else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) + { + /* The task being queried is referenced from the deleted + tasks list, or it is not referenced from any lists at + all. */ + eReturn = eDeleted; + } + #endif - else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ - { - /* If the task is not in any other state, it must be in the - Ready (including pending ready) state. */ - eReturn = eReady; - } - } + else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ + { + /* If the task is not in any other state, it must be in the + Ready (including pending ready) state. */ + eReturn = eReady; + } + } - return eReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + return eReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ #endif /* INCLUDE_eTaskGetState */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskPriorityGet == 1 ) - UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) - { - TCB_t const *pxTCB; - UBaseType_t uxReturn; + UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) + { + TCB_t const *pxTCB; + UBaseType_t uxReturn; - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the task - that called uxTaskPriorityGet() that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the task + that called uxTaskPriorityGet() that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + taskEXIT_CRITICAL(); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskPriorityGet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskPriorityGet == 1 ) - UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) - { - TCB_t const *pxTCB; - UBaseType_t uxReturn, uxSavedInterruptState; + UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) + { + TCB_t const *pxTCB; + UBaseType_t uxReturn, uxSavedInterruptState; - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - https://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* If null is passed in here then it is the priority of the calling - task that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); + uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* If null is passed in here then it is the priority of the calling + task that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskPriorityGet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskPrioritySet == 1 ) - void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) - { - TCB_t *pxTCB; - UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; - BaseType_t xYieldRequired = pdFALSE; + void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) + { + TCB_t *pxTCB; + UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; + BaseType_t xYieldRequired = pdFALSE; - configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); + configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); - /* Ensure the new priority is valid. */ - if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Ensure the new priority is valid. */ + if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the calling - task that is being changed. */ - pxTCB = prvGetTCBFromHandle( xTask ); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the calling + task that is being changed. */ + pxTCB = prvGetTCBFromHandle( xTask ); - traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); + traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); - #if ( configUSE_MUTEXES == 1 ) - { - uxCurrentBasePriority = pxTCB->uxBasePriority; - } - #else - { - uxCurrentBasePriority = pxTCB->uxPriority; - } - #endif + #if ( configUSE_MUTEXES == 1 ) + { + uxCurrentBasePriority = pxTCB->uxBasePriority; + } + #else + { + uxCurrentBasePriority = pxTCB->uxPriority; + } + #endif - if( uxCurrentBasePriority != uxNewPriority ) - { - /* The priority change may have readied a task of higher - priority than the calling task. */ - if( uxNewPriority > uxCurrentBasePriority ) - { - if( pxTCB != pxCurrentTCB ) - { - /* The priority of a task other than the currently - running task is being raised. Is the priority being - raised above that of the running task? */ - if( uxNewPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The priority of the running task is being raised, - but the running task must already be the highest - priority task able to run so no yield is required. */ - } - } - else if( pxTCB == pxCurrentTCB ) - { - /* Setting the priority of the running task down means - there may now be another task of higher priority that - is ready to execute. */ - xYieldRequired = pdTRUE; - } - else - { - /* Setting the priority of any other task down does not - require a yield as the running task must be above the - new priority of the task being modified. */ - } + if( uxCurrentBasePriority != uxNewPriority ) + { + /* The priority change may have readied a task of higher + priority than the calling task. */ + if( uxNewPriority > uxCurrentBasePriority ) + { + if( pxTCB != pxCurrentTCB ) + { + /* The priority of a task other than the currently + running task is being raised. Is the priority being + raised above that of the running task? */ + if( uxNewPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The priority of the running task is being raised, + but the running task must already be the highest + priority task able to run so no yield is required. */ + } + } + else if( pxTCB == pxCurrentTCB ) + { + /* Setting the priority of the running task down means + there may now be another task of higher priority that + is ready to execute. */ + xYieldRequired = pdTRUE; + } + else + { + /* Setting the priority of any other task down does not + require a yield as the running task must be above the + new priority of the task being modified. */ + } - /* Remember the ready list the task might be referenced from - before its uxPriority member is changed so the - taskRESET_READY_PRIORITY() macro can function correctly. */ - uxPriorityUsedOnEntry = pxTCB->uxPriority; + /* Remember the ready list the task might be referenced from + before its uxPriority member is changed so the + taskRESET_READY_PRIORITY() macro can function correctly. */ + uxPriorityUsedOnEntry = pxTCB->uxPriority; - #if ( configUSE_MUTEXES == 1 ) - { - /* Only change the priority being used if the task is not - currently using an inherited priority. */ - if( pxTCB->uxBasePriority == pxTCB->uxPriority ) - { - pxTCB->uxPriority = uxNewPriority; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + #if ( configUSE_MUTEXES == 1 ) + { + /* Only change the priority being used if the task is not + currently using an inherited priority. */ + if( pxTCB->uxBasePriority == pxTCB->uxPriority ) + { + pxTCB->uxPriority = uxNewPriority; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The base priority gets set whatever. */ - pxTCB->uxBasePriority = uxNewPriority; - } - #else - { - pxTCB->uxPriority = uxNewPriority; - } - #endif + /* The base priority gets set whatever. */ + pxTCB->uxBasePriority = uxNewPriority; + } + #else + { + pxTCB->uxPriority = uxNewPriority; + } + #endif - /* Only reset the event list item value if the value is not - being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Only reset the event list item value if the value is not + being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* If the task is in the blocked or suspended list we need do - nothing more than change its priority variable. However, if - the task is in a ready list it needs to be removed and placed - in the list appropriate to its new priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* The task is currently in its ready list - remove before - adding it to it's new ready list. As we are in a critical - section we can do this even if the scheduler is suspended. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* It is known that the task is in its ready list so - there is no need to check again and the port level - reset macro can be called directly. */ - portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the task is in the blocked or suspended list we need do + nothing more than change its priority variable. However, if + the task is in a ready list it needs to be removed and placed + in the list appropriate to its new priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* The task is currently in its ready list - remove before + adding it to it's new ready list. As we are in a critical + section we can do this even if the scheduler is suspended. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + there is no need to check again and the port level + reset macro can be called directly. */ + portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xYieldRequired != pdFALSE ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xYieldRequired != pdFALSE ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Remove compiler warning about unused variables when the port - optimised task selection is not being used. */ - ( void ) uxPriorityUsedOnEntry; - } - } - taskEXIT_CRITICAL(); - } + /* Remove compiler warning about unused variables when the port + optimised task selection is not being used. */ + ( void ) uxPriorityUsedOnEntry; + } + } + taskEXIT_CRITICAL(); + } #endif /* INCLUDE_vTaskPrioritySet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) - void vTaskSuspend( TaskHandle_t xTaskToSuspend ) - { - TCB_t *pxTCB; + void vTaskSuspend( TaskHandle_t xTaskToSuspend ) + { + TCB_t *pxTCB; - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the running task that is - being suspended. */ - pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the running task that is + being suspended. */ + pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); - traceTASK_SUSPEND( pxTCB ); + traceTASK_SUSPEND( pxTCB ); - /* Remove task from the ready/delayed list and place in the - suspended list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Remove task from the ready/delayed list and place in the + suspended list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); + vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - { - if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task was blocked to wait for a notification, but is - now suspended, so no notification was received. */ - pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - } - #endif - } - taskEXIT_CRITICAL(); + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + { + if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task was blocked to wait for a notification, but is + now suspended, so no notification was received. */ + pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + } + #endif + } + taskEXIT_CRITICAL(); - if( xSchedulerRunning != pdFALSE ) - { - /* Reset the next expected unblock time in case it referred to the - task that is now in the Suspended state. */ - taskENTER_CRITICAL(); - { - prvResetNextTaskUnblockTime(); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSchedulerRunning != pdFALSE ) + { + /* Reset the next expected unblock time in case it referred to the + task that is now in the Suspended state. */ + taskENTER_CRITICAL(); + { + prvResetNextTaskUnblockTime(); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( pxTCB == pxCurrentTCB ) - { - if( xSchedulerRunning != pdFALSE ) - { - /* The current task has just been suspended. */ - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - /* The scheduler is not running, but the task that was pointed - to by pxCurrentTCB has just been suspended and pxCurrentTCB - must be adjusted to point to a different task. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ - { - /* No other tasks are ready, so set pxCurrentTCB back to - NULL so when the next task is created pxCurrentTCB will - be set to point to it no matter what its relative priority - is. */ - pxCurrentTCB = NULL; - } - else - { - vTaskSwitchContext(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( pxTCB == pxCurrentTCB ) + { + if( xSchedulerRunning != pdFALSE ) + { + /* The current task has just been suspended. */ + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + /* The scheduler is not running, but the task that was pointed + to by pxCurrentTCB has just been suspended and pxCurrentTCB + must be adjusted to point to a different task. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ + { + /* No other tasks are ready, so set pxCurrentTCB back to + NULL so when the next task is created pxCurrentTCB will + be set to point to it no matter what its relative priority + is. */ + pxCurrentTCB = NULL; + } + else + { + vTaskSwitchContext(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskSuspend */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) - { - BaseType_t xReturn = pdFALSE; - const TCB_t * const pxTCB = xTask; + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) + { + BaseType_t xReturn = pdFALSE; + const TCB_t * const pxTCB = xTask; - /* Accesses xPendingReadyList so must be called from a critical - section. */ + /* Accesses xPendingReadyList so must be called from a critical + section. */ - /* It does not make sense to check if the calling task is suspended. */ - configASSERT( xTask ); + /* It does not make sense to check if the calling task is suspended. */ + configASSERT( xTask ); - /* Is the task being resumed actually in the suspended list? */ - if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* Has the task already been resumed from within an ISR? */ - if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) - { - /* Is it in the suspended list because it is in the Suspended - state, or because is is blocked with no timeout? */ - if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ - { - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task being resumed actually in the suspended list? */ + if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* Has the task already been resumed from within an ISR? */ + if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) + { + /* Is it in the suspended list because it is in the Suspended + state, or because is is blocked with no timeout? */ + if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ + { + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + return xReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ #endif /* INCLUDE_vTaskSuspend */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) - void vTaskResume( TaskHandle_t xTaskToResume ) - { - TCB_t * const pxTCB = xTaskToResume; + void vTaskResume( TaskHandle_t xTaskToResume ) + { + TCB_t * const pxTCB = xTaskToResume; - /* It does not make sense to resume the calling task. */ - configASSERT( xTaskToResume ); + /* It does not make sense to resume the calling task. */ + configASSERT( xTaskToResume ); - /* The parameter cannot be NULL as it is impossible to resume the - currently executing task. */ - if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) - { - taskENTER_CRITICAL(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME( pxTCB ); + /* The parameter cannot be NULL as it is impossible to resume the + currently executing task. */ + if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) + { + taskENTER_CRITICAL(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME( pxTCB ); - /* The ready list can be accessed even if the scheduler is - suspended because this is inside a critical section. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); + /* The ready list can be accessed even if the scheduler is + suspended because this is inside a critical section. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); - /* A higher priority task may have just been resumed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - /* This yield may not cause the task just resumed to run, - but will leave the lists in the correct state for the - next yield. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* A higher priority task may have just been resumed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + /* This yield may not cause the task just resumed to run, + but will leave the lists in the correct state for the + next yield. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskSuspend */ @@ -1894,72 +1894,72 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) #if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) - BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) - { - BaseType_t xYieldRequired = pdFALSE; - TCB_t * const pxTCB = xTaskToResume; - UBaseType_t uxSavedInterruptStatus; + BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) + { + BaseType_t xYieldRequired = pdFALSE; + TCB_t * const pxTCB = xTaskToResume; + UBaseType_t uxSavedInterruptStatus; - configASSERT( xTaskToResume ); + configASSERT( xTaskToResume ); - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - https://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME_FROM_ISR( pxTCB ); + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME_FROM_ISR( pxTCB ); - /* Check the ready lists can be accessed. */ - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Ready lists can be accessed so move the task from the - suspended list to the ready list directly. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Check the ready lists can be accessed. */ + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Ready lists can be accessed so move the task from the + suspended list to the ready list directly. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed or ready lists cannot be accessed so the task - is held in the pending ready list until the scheduler is - unsuspended. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed or ready lists cannot be accessed so the task + is held in the pending ready list until the scheduler is + unsuspended. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xYieldRequired; - } + return xYieldRequired; + } #endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ /*-----------------------------------------------------------*/ @@ -1968,205 +1968,205 @@ void vTaskStartScheduler( void ) { BaseType_t xReturn; - /* Add the idle task at the lowest priority. */ - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t *pxIdleTaskTCBBuffer = NULL; - StackType_t *pxIdleTaskStackBuffer = NULL; - uint32_t ulIdleTaskStackSize; + /* Add the idle task at the lowest priority. */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t *pxIdleTaskTCBBuffer = NULL; + StackType_t *pxIdleTaskStackBuffer = NULL; + uint32_t ulIdleTaskStackSize; - /* The Idle task is created using user provided RAM - obtain the - address of the RAM then create the idle task. */ - vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); - xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, - configIDLE_TASK_NAME, - ulIdleTaskStackSize, - ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ - portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ - pxIdleTaskStackBuffer, - pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + /* The Idle task is created using user provided RAM - obtain the + address of the RAM then create the idle task. */ + vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); + xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, + configIDLE_TASK_NAME, + ulIdleTaskStackSize, + ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + pxIdleTaskStackBuffer, + pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - if( xIdleTaskHandle != NULL ) - { - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - #else - { - /* The Idle task is being created using dynamically allocated RAM. */ - xReturn = xTaskCreate( prvIdleTask, - configIDLE_TASK_NAME, - configMINIMAL_STACK_SIZE, - ( void * ) NULL, - portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ - &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ + if( xIdleTaskHandle != NULL ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + #else + { + /* The Idle task is being created using dynamically allocated RAM. */ + xReturn = xTaskCreate( prvIdleTask, + configIDLE_TASK_NAME, + configMINIMAL_STACK_SIZE, + ( void * ) NULL, + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ - #if ( configUSE_TIMERS == 1 ) - { - if( xReturn == pdPASS ) - { - xReturn = xTimerCreateTimerTask(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TIMERS */ + #if ( configUSE_TIMERS == 1 ) + { + if( xReturn == pdPASS ) + { + xReturn = xTimerCreateTimerTask(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TIMERS */ - if( xReturn == pdPASS ) - { - /* freertos_tasks_c_additions_init() should only be called if the user - definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is - the only macro called by the function. */ - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - { - freertos_tasks_c_additions_init(); - } - #endif + if( xReturn == pdPASS ) + { + /* freertos_tasks_c_additions_init() should only be called if the user + definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is + the only macro called by the function. */ + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + { + freertos_tasks_c_additions_init(); + } + #endif - /* Interrupts are turned off here, to ensure a tick does not occur - before or during the call to xPortStartScheduler(). The stacks of - the created tasks contain a status word with interrupts switched on - so interrupts will automatically get re-enabled when the first task - starts to run. */ - portDISABLE_INTERRUPTS(); + /* Interrupts are turned off here, to ensure a tick does not occur + before or during the call to xPortStartScheduler(). The stacks of + the created tasks contain a status word with interrupts switched on + so interrupts will automatically get re-enabled when the first task + starts to run. */ + portDISABLE_INTERRUPTS(); - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - structure specific to the task that will run first. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + structure specific to the task that will run first. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ - xNextTaskUnblockTime = portMAX_DELAY; - xSchedulerRunning = pdTRUE; - xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; + xNextTaskUnblockTime = portMAX_DELAY; + xSchedulerRunning = pdTRUE; + xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; - /* If configGENERATE_RUN_TIME_STATS is defined then the following - macro must be defined to configure the timer/counter used to generate - the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS - is set to 0 and the following line fails to build then ensure you do not - have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your - FreeRTOSConfig.h file. */ - portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); + /* If configGENERATE_RUN_TIME_STATS is defined then the following + macro must be defined to configure the timer/counter used to generate + the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS + is set to 0 and the following line fails to build then ensure you do not + have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your + FreeRTOSConfig.h file. */ + portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); - traceTASK_SWITCHED_IN(); + traceTASK_SWITCHED_IN(); - /* Setting up the timer tick is hardware specific and thus in the - portable interface. */ - if( xPortStartScheduler() != pdFALSE ) - { - /* Should not reach here as if the scheduler is running the - function will not return. */ - } - else - { - /* Should only reach here if a task calls xTaskEndScheduler(). */ - } - } - else - { - /* This line will only be reached if the kernel could not be started, - because there was not enough FreeRTOS heap to create the idle task - or the timer task. */ - configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); - } + /* Setting up the timer tick is hardware specific and thus in the + portable interface. */ + if( xPortStartScheduler() != pdFALSE ) + { + /* Should not reach here as if the scheduler is running the + function will not return. */ + } + else + { + /* Should only reach here if a task calls xTaskEndScheduler(). */ + } + } + else + { + /* This line will only be reached if the kernel could not be started, + because there was not enough FreeRTOS heap to create the idle task + or the timer task. */ + configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); + } - /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, - meaning xIdleTaskHandle is not used anywhere else. */ - ( void ) xIdleTaskHandle; + /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, + meaning xIdleTaskHandle is not used anywhere else. */ + ( void ) xIdleTaskHandle; } /*-----------------------------------------------------------*/ void vTaskEndScheduler( void ) { - /* Stop the scheduler interrupts and call the portable scheduler end - routine so the original ISRs can be restored if necessary. The port - layer must ensure interrupts enable bit is left in the correct state. */ - portDISABLE_INTERRUPTS(); - xSchedulerRunning = pdFALSE; - vPortEndScheduler(); + /* Stop the scheduler interrupts and call the portable scheduler end + routine so the original ISRs can be restored if necessary. The port + layer must ensure interrupts enable bit is left in the correct state. */ + portDISABLE_INTERRUPTS(); + xSchedulerRunning = pdFALSE; + vPortEndScheduler(); } /*----------------------------------------------------------*/ void vTaskSuspendAll( void ) { - /* A critical section is not required as the variable is of type - BaseType_t. Please read Richard Barry's reply in the following link to a - post in the FreeRTOS support forum before reporting this as a bug! - - http://goo.gl/wu4acr */ - ++uxSchedulerSuspended; - portMEMORY_BARRIER(); + /* A critical section is not required as the variable is of type + BaseType_t. Please read Richard Barry's reply in the following link to a + post in the FreeRTOS support forum before reporting this as a bug! - + http://goo.gl/wu4acr */ + ++uxSchedulerSuspended; + portMEMORY_BARRIER(); } /*----------------------------------------------------------*/ #if ( configUSE_TICKLESS_IDLE != 0 ) - static TickType_t prvGetExpectedIdleTime( void ) - { - TickType_t xReturn; - UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; + static TickType_t prvGetExpectedIdleTime( void ) + { + TickType_t xReturn; + UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; - /* uxHigherPriorityReadyTasks takes care of the case where - configUSE_PREEMPTION is 0, so there may be tasks above the idle priority - task that are in the Ready state, even though the idle task is - running. */ - #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - { - if( uxTopReadyPriority > tskIDLE_PRIORITY ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #else - { - const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; + /* uxHigherPriorityReadyTasks takes care of the case where + configUSE_PREEMPTION is 0, so there may be tasks above the idle priority + task that are in the Ready state, even though the idle task is + running. */ + #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + { + if( uxTopReadyPriority > tskIDLE_PRIORITY ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #else + { + const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; - /* When port optimised task selection is used the uxTopReadyPriority - variable is used as a bit map. If bits other than the least - significant bit are set then there are tasks that have a priority - above the idle priority that are in the Ready state. This takes - care of the case where the co-operative scheduler is in use. */ - if( uxTopReadyPriority > uxLeastSignificantBit ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #endif + /* When port optimised task selection is used the uxTopReadyPriority + variable is used as a bit map. If bits other than the least + significant bit are set then there are tasks that have a priority + above the idle priority that are in the Ready state. This takes + care of the case where the co-operative scheduler is in use. */ + if( uxTopReadyPriority > uxLeastSignificantBit ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #endif - if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) - { - xReturn = 0; - } - else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) - { - /* There are other idle priority tasks in the ready state. If - time slicing is used then the very next tick interrupt must be - processed. */ - xReturn = 0; - } - else if( uxHigherPriorityReadyTasks != pdFALSE ) - { - /* There are tasks in the Ready state that have a priority above the - idle priority. This path can only be reached if - configUSE_PREEMPTION is 0. */ - xReturn = 0; - } - else - { - xReturn = xNextTaskUnblockTime - xTickCount; - } + if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) + { + xReturn = 0; + } + else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) + { + /* There are other idle priority tasks in the ready state. If + time slicing is used then the very next tick interrupt must be + processed. */ + xReturn = 0; + } + else if( uxHigherPriorityReadyTasks != pdFALSE ) + { + /* There are tasks in the Ready state that have a priority above the + idle priority. This path can only be reached if + configUSE_PREEMPTION is 0. */ + xReturn = 0; + } + else + { + xReturn = xNextTaskUnblockTime - xTickCount; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_TICKLESS_IDLE */ /*----------------------------------------------------------*/ @@ -2176,108 +2176,108 @@ BaseType_t xTaskResumeAll( void ) TCB_t *pxTCB = NULL; BaseType_t xAlreadyYielded = pdFALSE; - /* If uxSchedulerSuspended is zero then this function does not match a - previous call to vTaskSuspendAll(). */ - configASSERT( uxSchedulerSuspended ); + /* If uxSchedulerSuspended is zero then this function does not match a + previous call to vTaskSuspendAll(). */ + configASSERT( uxSchedulerSuspended ); - /* It is possible that an ISR caused a task to be removed from an event - list while the scheduler was suspended. If this was the case then the - removed task will have been added to the xPendingReadyList. Once the - scheduler has been resumed it is safe to move all the pending ready - tasks from this list into their appropriate ready list. */ - taskENTER_CRITICAL(); - { - --uxSchedulerSuspended; + /* It is possible that an ISR caused a task to be removed from an event + list while the scheduler was suspended. If this was the case then the + removed task will have been added to the xPendingReadyList. Once the + scheduler has been resumed it is safe to move all the pending ready + tasks from this list into their appropriate ready list. */ + taskENTER_CRITICAL(); + { + --uxSchedulerSuspended; - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) - { - /* Move any readied tasks from the pending list into the - appropriate ready list. */ - while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) - { - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) + { + /* Move any readied tasks from the pending list into the + appropriate ready list. */ + while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); - /* If the moved task has a priority higher than the current - task then a yield must be performed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* If the moved task has a priority higher than the current + task then a yield must be performed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - if( pxTCB != NULL ) - { - /* A task was unblocked while the scheduler was suspended, - which may have prevented the next unblock time from being - re-calculated, in which case re-calculate it now. Mainly - important for low power tickless implementations, where - this can prevent an unnecessary exit from low power - state. */ - prvResetNextTaskUnblockTime(); - } + if( pxTCB != NULL ) + { + /* A task was unblocked while the scheduler was suspended, + which may have prevented the next unblock time from being + re-calculated, in which case re-calculate it now. Mainly + important for low power tickless implementations, where + this can prevent an unnecessary exit from low power + state. */ + prvResetNextTaskUnblockTime(); + } - /* If any ticks occurred while the scheduler was suspended then - they should be processed now. This ensures the tick count does - not slip, and that any delayed tasks are resumed at the correct - time. */ - { - UBaseType_t uxPendedCounts = uxPendedTicks; /* Non-volatile copy. */ + /* If any ticks occurred while the scheduler was suspended then + they should be processed now. This ensures the tick count does + not slip, and that any delayed tasks are resumed at the correct + time. */ + { + UBaseType_t uxPendedCounts = uxPendedTicks; /* Non-volatile copy. */ - if( uxPendedCounts > ( UBaseType_t ) 0U ) - { - do - { - if( xTaskIncrementTick() != pdFALSE ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --uxPendedCounts; - } while( uxPendedCounts > ( UBaseType_t ) 0U ); + if( uxPendedCounts > ( UBaseType_t ) 0U ) + { + do + { + if( xTaskIncrementTick() != pdFALSE ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --uxPendedCounts; + } while( uxPendedCounts > ( UBaseType_t ) 0U ); - uxPendedTicks = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + uxPendedTicks = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - if( xYieldPending != pdFALSE ) - { - #if( configUSE_PREEMPTION != 0 ) - { - xAlreadyYielded = pdTRUE; - } - #endif - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + if( xYieldPending != pdFALSE ) + { + #if( configUSE_PREEMPTION != 0 ) + { + xAlreadyYielded = pdTRUE; + } + #endif + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - return xAlreadyYielded; + return xAlreadyYielded; } /*-----------------------------------------------------------*/ @@ -2285,27 +2285,27 @@ TickType_t xTaskGetTickCount( void ) { TickType_t xTicks; - /* Critical section required if running on a 16 bit processor. */ - portTICK_TYPE_ENTER_CRITICAL(); - { - xTicks = xTickCount; - } - portTICK_TYPE_EXIT_CRITICAL(); + /* Critical section required if running on a 16 bit processor. */ + portTICK_TYPE_ENTER_CRITICAL(); + { + xTicks = xTickCount; + } + portTICK_TYPE_EXIT_CRITICAL(); - return xTicks; + return xTicks; } BaseType_t xTaskGetTickCount2( TickType_t *ticks, BaseType_t *overflow ) { //FIXME TODO potential BUG for TICK count - portTICK_TYPE_ENTER_CRITICAL(); - { - *ticks = xTickCount; + portTICK_TYPE_ENTER_CRITICAL(); + { + *ticks = xTickCount; *overflow = xNumOfOverflows; - } - portTICK_TYPE_EXIT_CRITICAL(); + } + portTICK_TYPE_EXIT_CRITICAL(); - return pdTRUE; + return pdTRUE; } /*-----------------------------------------------------------*/ @@ -2314,37 +2314,37 @@ TickType_t xTaskGetTickCountFromISR( void ) TickType_t xReturn; UBaseType_t uxSavedInterruptStatus; - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: https://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); - { - xReturn = xTickCount; - } - portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = xTickCount; + } + portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ UBaseType_t uxTaskGetNumberOfTasks( void ) { - /* A critical section is not required because the variables are of type - BaseType_t. */ - return uxCurrentNumberOfTasks; + /* A critical section is not required because the variables are of type + BaseType_t. */ + return uxCurrentNumberOfTasks; } /*-----------------------------------------------------------*/ @@ -2352,230 +2352,230 @@ char *pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char t { TCB_t *pxTCB; - /* If null is passed in here then the name of the calling task is being - queried. */ - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - configASSERT( pxTCB ); - return &( pxTCB->pcTaskName[ 0 ] ); + /* If null is passed in here then the name of the calling task is being + queried. */ + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + configASSERT( pxTCB ); + return &( pxTCB->pcTaskName[ 0 ] ); } /*-----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetHandle == 1 ) - static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) - { - TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL; - UBaseType_t x; - char cNextChar; - BaseType_t xBreakLoop; + static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) + { + TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL; + UBaseType_t x; + char cNextChar; + BaseType_t xBreakLoop; - /* This function is called with the scheduler suspended. */ + /* This function is called with the scheduler suspended. */ - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - /* Check each character in the name looking for a match or - mismatch. */ - xBreakLoop = pdFALSE; - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - cNextChar = pxNextTCB->pcTaskName[ x ]; + /* Check each character in the name looking for a match or + mismatch. */ + xBreakLoop = pdFALSE; + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + cNextChar = pxNextTCB->pcTaskName[ x ]; - if( cNextChar != pcNameToQuery[ x ] ) - { - /* Characters didn't match. */ - xBreakLoop = pdTRUE; - } - else if( cNextChar == ( char ) 0x00 ) - { - /* Both strings terminated, a match must have been - found. */ - pxReturn = pxNextTCB; - xBreakLoop = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( cNextChar != pcNameToQuery[ x ] ) + { + /* Characters didn't match. */ + xBreakLoop = pdTRUE; + } + else if( cNextChar == ( char ) 0x00 ) + { + /* Both strings terminated, a match must have been + found. */ + pxReturn = pxNextTCB; + xBreakLoop = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xBreakLoop != pdFALSE ) - { - break; - } - } + if( xBreakLoop != pdFALSE ) + { + break; + } + } - if( pxReturn != NULL ) - { - /* The handle has been found. */ - break; - } + if( pxReturn != NULL ) + { + /* The handle has been found. */ + break; + } - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return pxReturn; - } + return pxReturn; + } #endif /* INCLUDE_xTaskGetHandle */ /*-----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetHandle == 1 ) - TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t uxQueue = configMAX_PRIORITIES; - TCB_t* pxTCB; + TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t uxQueue = configMAX_PRIORITIES; + TCB_t* pxTCB; - /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ - configASSERT( rtos_strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); + /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ + configASSERT( rtos_strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); - vTaskSuspendAll(); - { - /* Search the ready lists. */ - do - { - uxQueue--; - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); + vTaskSuspendAll(); + { + /* Search the ready lists. */ + do + { + uxQueue--; + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); - if( pxTCB != NULL ) - { - /* Found the handle. */ - break; - } + if( pxTCB != NULL ) + { + /* Found the handle. */ + break; + } - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - /* Search the delayed lists. */ - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); - } + /* Search the delayed lists. */ + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); + } - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); - } + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); + } - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the suspended list. */ - pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); - } - } - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the suspended list. */ + pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); + } + } + #endif - #if( INCLUDE_vTaskDelete == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the deleted list. */ - pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); - } - } - #endif - } - ( void ) xTaskResumeAll(); + #if( INCLUDE_vTaskDelete == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the deleted list. */ + pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); + } + } + #endif + } + ( void ) xTaskResumeAll(); - return pxTCB; - } + return pxTCB; + } #endif /* INCLUDE_xTaskGetHandle */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) - { - UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; + UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) + { + UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; - vTaskSuspendAll(); - { - /* Is there a space in the array for each task in the system? */ - if( uxArraySize >= uxCurrentNumberOfTasks ) - { - /* Fill in an TaskStatus_t structure with information on each - task in the Ready state. */ - do - { - uxQueue--; - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); + vTaskSuspendAll(); + { + /* Is there a space in the array for each task in the system? */ + if( uxArraySize >= uxCurrentNumberOfTasks ) + { + /* Fill in an TaskStatus_t structure with information on each + task in the Ready state. */ + do + { + uxQueue--; + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - /* Fill in an TaskStatus_t structure with information on each - task in the Blocked state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); + /* Fill in an TaskStatus_t structure with information on each + task in the Blocked state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); - #if( INCLUDE_vTaskDelete == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - each task that has been deleted but not yet cleaned up. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); - } - #endif + #if( INCLUDE_vTaskDelete == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + each task that has been deleted but not yet cleaned up. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); + } + #endif - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - each task in the Suspended state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); - } - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + each task in the Suspended state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); + } + #endif - #if ( configGENERATE_RUN_TIME_STATS == 1) - { - if( pulTotalRunTime != NULL ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); - #else - *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif - } - } - #else - { - if( pulTotalRunTime != NULL ) - { - *pulTotalRunTime = 0; - } - } - #endif - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); + #if ( configGENERATE_RUN_TIME_STATS == 1) + { + if( pulTotalRunTime != NULL ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); + #else + *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + } + } + #else + { + if( pulTotalRunTime != NULL ) + { + *pulTotalRunTime = 0; + } + } + #endif + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); - return uxTask; - } + return uxTask; + } #endif /* configUSE_TRACE_FACILITY */ /*----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) - TaskHandle_t xTaskGetIdleTaskHandle( void ) - { - /* If xTaskGetIdleTaskHandle() is called before the scheduler has been - started, then xIdleTaskHandle will be NULL. */ - configASSERT( ( xIdleTaskHandle != NULL ) ); - return xIdleTaskHandle; - } + TaskHandle_t xTaskGetIdleTaskHandle( void ) + { + /* If xTaskGetIdleTaskHandle() is called before the scheduler has been + started, then xIdleTaskHandle will be NULL. */ + configASSERT( ( xIdleTaskHandle != NULL ) ); + return xIdleTaskHandle; + } #endif /* INCLUDE_xTaskGetIdleTaskHandle */ /*----------------------------------------------------------*/ @@ -2586,91 +2586,91 @@ implementations require configUSE_TICKLESS_IDLE to be set to a value other than 1. */ #if ( configUSE_TICKLESS_IDLE != 0 ) - void vTaskStepTick( const TickType_t xTicksToJump ) - { - /* Correct the tick count value after a period during which the tick - was suppressed. Note this does *not* call the tick hook function for - each stepped tick. */ - configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); - xTickCount += xTicksToJump; - traceINCREASE_TICK_COUNT( xTicksToJump ); - } + void vTaskStepTick( const TickType_t xTicksToJump ) + { + /* Correct the tick count value after a period during which the tick + was suppressed. Note this does *not* call the tick hook function for + each stepped tick. */ + configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); + xTickCount += xTicksToJump; + traceINCREASE_TICK_COUNT( xTicksToJump ); + } #endif /* configUSE_TICKLESS_IDLE */ /*----------------------------------------------------------*/ #if ( INCLUDE_xTaskAbortDelay == 1 ) - BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) - { - TCB_t *pxTCB = xTask; - BaseType_t xReturn; + BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) + { + TCB_t *pxTCB = xTask; + BaseType_t xReturn; - configASSERT( pxTCB ); + configASSERT( pxTCB ); - vTaskSuspendAll(); - { - /* A task can only be prematurely removed from the Blocked state if - it is actually in the Blocked state. */ - if( eTaskGetState( xTask ) == eBlocked ) - { - xReturn = pdPASS; + vTaskSuspendAll(); + { + /* A task can only be prematurely removed from the Blocked state if + it is actually in the Blocked state. */ + if( eTaskGetState( xTask ) == eBlocked ) + { + xReturn = pdPASS; - /* Remove the reference to the task from the blocked list. An - interrupt won't touch the xStateListItem because the - scheduler is suspended. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + /* Remove the reference to the task from the blocked list. An + interrupt won't touch the xStateListItem because the + scheduler is suspended. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - /* Is the task waiting on an event also? If so remove it from - the event list too. Interrupts can touch the event list item, - even though the scheduler is suspended, so a critical section - is used. */ - taskENTER_CRITICAL(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - pxTCB->ucDelayAborted = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* Is the task waiting on an event also? If so remove it from + the event list too. Interrupts can touch the event list item, + even though the scheduler is suspended, so a critical section + is used. */ + taskENTER_CRITICAL(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + pxTCB->ucDelayAborted = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - /* Place the unblocked task into the appropriate ready list. */ - prvAddTaskToReadyList( pxTCB ); + /* Place the unblocked task into the appropriate ready list. */ + prvAddTaskToReadyList( pxTCB ); - /* A task being unblocked cannot cause an immediate context - switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should only be - performed if the unblocked task has a priority that is - equal to or higher than the currently executing task. */ - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Pend the yield to be performed when the scheduler - is unsuspended. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - else - { - xReturn = pdFAIL; - } - } - ( void ) xTaskResumeAll(); + /* A task being unblocked cannot cause an immediate context + switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should only be + performed if the unblocked task has a priority that is + equal to or higher than the currently executing task. */ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Pend the yield to be performed when the scheduler + is unsuspended. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + else + { + xReturn = pdFAIL; + } + } + ( void ) xTaskResumeAll(); - return xReturn; - } + return xReturn; + } #endif /* INCLUDE_xTaskAbortDelay */ /*----------------------------------------------------------*/ @@ -2681,425 +2681,425 @@ TCB_t * pxTCB; TickType_t xItemValue; BaseType_t xSwitchRequired = pdFALSE; - /* Called by the portable layer each time a tick interrupt occurs. - Increments the tick then checks to see if the new tick value will cause any - tasks to be unblocked. */ - traceTASK_INCREMENT_TICK( xTickCount ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; + /* Called by the portable layer each time a tick interrupt occurs. + Increments the tick then checks to see if the new tick value will cause any + tasks to be unblocked. */ + traceTASK_INCREMENT_TICK( xTickCount ); + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Minor optimisation. The tick count cannot change in this + block. */ + const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; - /* Increment the RTOS tick, switching the delayed and overflowed - delayed lists if it wraps to 0. */ - xTickCount = xConstTickCount; + /* Increment the RTOS tick, switching the delayed and overflowed + delayed lists if it wraps to 0. */ + xTickCount = xConstTickCount; - if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ - { - taskSWITCH_DELAYED_LISTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ + { + taskSWITCH_DELAYED_LISTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* See if this tick has made a timeout expire. Tasks are stored in - the queue in the order of their wake time - meaning once one task - has been found whose block time has not expired there is no need to - look any further down the list. */ - if( xConstTickCount >= xNextTaskUnblockTime ) - { - for( ;; ) - { - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The delayed list is empty. Set xNextTaskUnblockTime - to the maximum possible value so it is extremely - unlikely that the - if( xTickCount >= xNextTaskUnblockTime ) test will pass - next time through. */ - xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - break; - } - else - { - /* The delayed list is not empty, get the value of the - item at the head of the delayed list. This is the time - at which the task at the head of the delayed list must - be removed from the Blocked state. */ - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); + /* See if this tick has made a timeout expire. Tasks are stored in + the queue in the order of their wake time - meaning once one task + has been found whose block time has not expired there is no need to + look any further down the list. */ + if( xConstTickCount >= xNextTaskUnblockTime ) + { + for( ;; ) + { + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The delayed list is empty. Set xNextTaskUnblockTime + to the maximum possible value so it is extremely + unlikely that the + if( xTickCount >= xNextTaskUnblockTime ) test will pass + next time through. */ + xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + break; + } + else + { + /* The delayed list is not empty, get the value of the + item at the head of the delayed list. This is the time + at which the task at the head of the delayed list must + be removed from the Blocked state. */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); - if( xConstTickCount < xItemValue ) - { - /* It is not time to unblock this item yet, but the - item value is the time at which the task at the head - of the blocked list must be removed from the Blocked - state - so record the item value in - xNextTaskUnblockTime. */ - xNextTaskUnblockTime = xItemValue; - break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xConstTickCount < xItemValue ) + { + /* It is not time to unblock this item yet, but the + item value is the time at which the task at the head + of the blocked list must be removed from the Blocked + state - so record the item value in + xNextTaskUnblockTime. */ + xNextTaskUnblockTime = xItemValue; + break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* It is time to remove the item from the Blocked state. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + /* It is time to remove the item from the Blocked state. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - /* Is the task waiting on an event also? If so remove - it from the event list. */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task waiting on an event also? If so remove + it from the event list. */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Place the unblocked task into the appropriate ready - list. */ - prvAddTaskToReadyList( pxTCB ); + /* Place the unblocked task into the appropriate ready + list. */ + prvAddTaskToReadyList( pxTCB ); - /* A task being unblocked cannot cause an immediate - context switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should - only be performed if the unblocked task has a - priority that is equal to or higher than the - currently executing task. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - } - } + /* A task being unblocked cannot cause an immediate + context switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should + only be performed if the unblocked task has a + priority that is equal to or higher than the + currently executing task. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + } + } - /* Tasks of equal priority to the currently running task will share - processing time (time slice) if preemption is on, and the application - writer has not explicitly turned time slicing off. */ - #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) - { - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ + /* Tasks of equal priority to the currently running task will share + processing time (time slice) if preemption is on, and the application + writer has not explicitly turned time slicing off. */ + #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) + { + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ - #if ( configUSE_TICK_HOOK == 1 ) - { - /* Guard against the tick hook being called when the pended tick - count is being unwound (when the scheduler is being unlocked). */ - if( uxPendedTicks == ( UBaseType_t ) 0U ) - { - vApplicationTickHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICK_HOOK */ - } - else - { - ++uxPendedTicks; + #if ( configUSE_TICK_HOOK == 1 ) + { + /* Guard against the tick hook being called when the pended tick + count is being unwound (when the scheduler is being unlocked). */ + if( uxPendedTicks == ( UBaseType_t ) 0U ) + { + vApplicationTickHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICK_HOOK */ + } + else + { + ++uxPendedTicks; - /* The tick hook gets called at regular intervals, even if the - scheduler is locked. */ - #if ( configUSE_TICK_HOOK == 1 ) - { - vApplicationTickHook(); - } - #endif - } + /* The tick hook gets called at regular intervals, even if the + scheduler is locked. */ + #if ( configUSE_TICK_HOOK == 1 ) + { + vApplicationTickHook(); + } + #endif + } - #if ( configUSE_PREEMPTION == 1 ) - { - if( xYieldPending != pdFALSE ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ + #if ( configUSE_PREEMPTION == 1 ) + { + if( xYieldPending != pdFALSE ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ - return xSwitchRequired; + return xSwitchRequired; } /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) - { - TCB_t *xTCB; + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) + { + TCB_t *xTCB; - /* If xTask is NULL then it is the task hook of the calling task that is - getting set. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB; - } - else - { - xTCB = xTask; - } + /* If xTask is NULL then it is the task hook of the calling task that is + getting set. */ + if( xTask == NULL ) + { + xTCB = ( TCB_t * ) pxCurrentTCB; + } + else + { + xTCB = xTask; + } - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - { - xTCB->pxTaskTag = pxHookFunction; - } - taskEXIT_CRITICAL(); - } + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xTCB->pxTaskTag = pxHookFunction; + } + taskEXIT_CRITICAL(); + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - TaskHookFunction_t xReturn; + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + TaskHookFunction_t xReturn; - /* If xTask is NULL then set the calling task's hook. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - { - xReturn = pxTCB->pxTaskTag; - } - taskEXIT_CRITICAL(); + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xReturn = pxTCB->pxTaskTag; + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - TaskHookFunction_t xReturn; - UBaseType_t uxSavedInterruptStatus; + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + TaskHookFunction_t xReturn; + UBaseType_t uxSavedInterruptStatus; - /* If xTask is NULL then set the calling task's hook. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - xReturn = pxTCB->pxTaskTag; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = pxTCB->pxTaskTag; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; - } + return xReturn; + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) - { - TCB_t *xTCB; - BaseType_t xReturn; + BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) + { + TCB_t *xTCB; + BaseType_t xReturn; - /* If xTask is NULL then we are calling our own task hook. */ - if( xTask == NULL ) - { - xTCB = pxCurrentTCB; - } - else - { - xTCB = xTask; - } + /* If xTask is NULL then we are calling our own task hook. */ + if( xTask == NULL ) + { + xTCB = pxCurrentTCB; + } + else + { + xTCB = xTask; + } - if( xTCB->pxTaskTag != NULL ) - { - xReturn = xTCB->pxTaskTag( pvParameter ); - } - else - { - xReturn = pdFAIL; - } + if( xTCB->pxTaskTag != NULL ) + { + xReturn = xTCB->pxTaskTag( pvParameter ); + } + else + { + xReturn = pdFAIL; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ void vTaskSwitchContext( void ) { - if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) - { - /* The scheduler is currently suspended - do not allow a context - switch. */ - xYieldPending = pdTRUE; - } - else - { - xYieldPending = pdFALSE; - traceTASK_SWITCHED_OUT(); + if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) + { + /* The scheduler is currently suspended - do not allow a context + switch. */ + xYieldPending = pdTRUE; + } + else + { + xYieldPending = pdFALSE; + traceTASK_SWITCHED_OUT(); - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); - #else - ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); + #else + ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif - /* Add the amount of time the task has been running to the - accumulated time so far. The time the task started running was - stored in ulTaskSwitchedInTime. Note that there is no overflow - protection here so count values are only valid until the timer - overflows. The guard against negative values is to protect - against suspect run time stat counter implementations - which - are provided by the application, not the kernel. */ - if( ulTotalRunTime > ulTaskSwitchedInTime ) - { - pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - ulTaskSwitchedInTime = ulTotalRunTime; - } - #endif /* configGENERATE_RUN_TIME_STATS */ + /* Add the amount of time the task has been running to the + accumulated time so far. The time the task started running was + stored in ulTaskSwitchedInTime. Note that there is no overflow + protection here so count values are only valid until the timer + overflows. The guard against negative values is to protect + against suspect run time stat counter implementations - which + are provided by the application, not the kernel. */ + if( ulTotalRunTime > ulTaskSwitchedInTime ) + { + pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + ulTaskSwitchedInTime = ulTotalRunTime; + } + #endif /* configGENERATE_RUN_TIME_STATS */ - /* Check for stack overflow, if configured. */ - taskCHECK_FOR_STACK_OVERFLOW(); + /* Check for stack overflow, if configured. */ + taskCHECK_FOR_STACK_OVERFLOW(); - /* Before the currently running task is switched out, save its errno. */ - #if( configUSE_POSIX_ERRNO == 1 ) - { - pxCurrentTCB->iTaskErrno = FreeRTOS_errno; - } - #endif + /* Before the currently running task is switched out, save its errno. */ + #if( configUSE_POSIX_ERRNO == 1 ) + { + pxCurrentTCB->iTaskErrno = FreeRTOS_errno; + } + #endif - /* Select a new task to run using either the generic C or port - optimised asm code. */ - taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - traceTASK_SWITCHED_IN(); + /* Select a new task to run using either the generic C or port + optimised asm code. */ + taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + traceTASK_SWITCHED_IN(); - /* After the new task is switched in, update the global errno. */ - #if( configUSE_POSIX_ERRNO == 1 ) - { - FreeRTOS_errno = pxCurrentTCB->iTaskErrno; - } - #endif + /* After the new task is switched in, update the global errno. */ + #if( configUSE_POSIX_ERRNO == 1 ) + { + FreeRTOS_errno = pxCurrentTCB->iTaskErrno; + } + #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - structure specific to this task. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - } + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + structure specific to this task. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + } } /*-----------------------------------------------------------*/ void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) { - configASSERT( pxEventList ); + configASSERT( pxEventList ); - /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE - SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ + /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE + SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ - /* Place the event list item of the TCB in the appropriate event list. - This is placed in the list in priority order so the highest priority task - is the first to be woken by the event. The queue that contains the event - list is locked, preventing simultaneous access from interrupts. */ - vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + /* Place the event list item of the TCB in the appropriate event list. + This is placed in the list in priority order so the highest priority task + is the first to be woken by the event. The queue that contains the event + list is locked, preventing simultaneous access from interrupts. */ + vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); } /*-----------------------------------------------------------*/ void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) { - configASSERT( pxEventList ); + configASSERT( pxEventList ); - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event groups implementation. */ - configASSERT( uxSchedulerSuspended != 0 ); + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + the event groups implementation. */ + configASSERT( uxSchedulerSuspended != 0 ); - /* Store the item value in the event list item. It is safe to access the - event list item here as interrupts won't access the event list item of a - task that is not in the Blocked state. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + /* Store the item value in the event list item. It is safe to access the + event list item here as interrupts won't access the event list item of a + task that is not in the Blocked state. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - /* Place the event list item of the TCB at the end of the appropriate event - list. It is safe to access the event list here because it is part of an - event group implementation - and interrupts don't access event groups - directly (instead they access them indirectly by pending function calls to - the task level). */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + /* Place the event list item of the TCB at the end of the appropriate event + list. It is safe to access the event list here because it is part of an + event group implementation - and interrupts don't access event groups + directly (instead they access them indirectly by pending function calls to + the task level). */ + vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); } /*-----------------------------------------------------------*/ #if( configUSE_TIMERS == 1 ) - void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) - { - configASSERT( pxEventList ); + void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) + { + configASSERT( pxEventList ); - /* This function should not be called by application code hence the - 'Restricted' in its name. It is not part of the public API. It is - designed for use by kernel code, and has special calling requirements - - it should be called with the scheduler suspended. */ + /* This function should not be called by application code hence the + 'Restricted' in its name. It is not part of the public API. It is + designed for use by kernel code, and has special calling requirements - + it should be called with the scheduler suspended. */ - /* Place the event list item of the TCB in the appropriate event list. - In this case it is assume that this is the only task that is going to - be waiting on this event list, so the faster vListInsertEnd() function - can be used in place of vListInsert. */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + /* Place the event list item of the TCB in the appropriate event list. + In this case it is assume that this is the only task that is going to + be waiting on this event list, so the faster vListInsertEnd() function + can be used in place of vListInsert. */ + vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - /* If the task should block indefinitely then set the block time to a - value that will be recognised as an indefinite delay inside the - prvAddCurrentTaskToDelayedList() function. */ - if( xWaitIndefinitely != pdFALSE ) - { - xTicksToWait = portMAX_DELAY; - } + /* If the task should block indefinitely then set the block time to a + value that will be recognised as an indefinite delay inside the + prvAddCurrentTaskToDelayedList() function. */ + if( xWaitIndefinitely != pdFALSE ) + { + xTicksToWait = portMAX_DELAY; + } - traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); - } + traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); + prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); + } #endif /* configUSE_TIMERS */ /*-----------------------------------------------------------*/ @@ -3109,66 +3109,66 @@ BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) TCB_t *pxUnblockedTCB; BaseType_t xReturn; - /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be - called from a critical section within an ISR. */ + /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be + called from a critical section within an ISR. */ - /* The event list is sorted in priority order, so the first in the list can - be removed as it is known to be the highest priority. Remove the TCB from - the delayed list, and add it to the ready list. + /* The event list is sorted in priority order, so the first in the list can + be removed as it is known to be the highest priority. Remove the TCB from + the delayed list, and add it to the ready list. - If an event is for a queue that is locked then this function will never - get called - the lock count on the queue will get modified instead. This - means exclusive access to the event list is guaranteed here. + If an event is for a queue that is locked then this function will never + get called - the lock count on the queue will get modified instead. This + means exclusive access to the event list is guaranteed here. - This function assumes that a check has already been made to ensure that - pxEventList is not empty. */ - pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); + This function assumes that a check has already been made to ensure that + pxEventList is not empty. */ + pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); - #if( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked on a kernel object then xNextTaskUnblockTime - might be set to the blocked task's time out time. If the task is - unblocked for a reason other than a timeout xNextTaskUnblockTime is - normally left unchanged, because it is automatically reset to a new - value when the tick count equals xNextTaskUnblockTime. However if - tickless idling is used it might be more important to enter sleep mode - at the earliest possible time - so reset xNextTaskUnblockTime here to - ensure it is updated at the earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif - } - else - { - /* The delayed and ready lists cannot be accessed, so hold this task - pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); - } + #if( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + might be set to the blocked task's time out time. If the task is + unblocked for a reason other than a timeout xNextTaskUnblockTime is + normally left unchanged, because it is automatically reset to a new + value when the tick count equals xNextTaskUnblockTime. However if + tickless idling is used it might be more important to enter sleep mode + at the earliest possible time - so reset xNextTaskUnblockTime here to + ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + } + else + { + /* The delayed and ready lists cannot be accessed, so hold this task + pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); + } - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Return true if the task removed from the event list has a higher - priority than the calling task. This allows the calling task to know if - it should force a context switch now. */ - xReturn = pdTRUE; + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Return true if the task removed from the event list has a higher + priority than the calling task. This allows the calling task to know if + it should force a context switch now. */ + xReturn = pdTRUE; - /* Mark that a yield is pending in case the user is not using the - "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + /* Mark that a yield is pending in case the user is not using the + "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -3176,53 +3176,53 @@ void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const Tick { TCB_t *pxUnblockedTCB; - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event flags implementation. */ - configASSERT( uxSchedulerSuspended != pdFALSE ); + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + the event flags implementation. */ + configASSERT( uxSchedulerSuspended != pdFALSE ); - /* Store the new item value in the event list. */ - listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + /* Store the new item value in the event list. */ + listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - /* Remove the event list form the event flag. Interrupts do not access - event flags. */ - pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( pxEventListItem ); + /* Remove the event list form the event flag. Interrupts do not access + event flags. */ + pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + ( void ) uxListRemove( pxEventListItem ); - /* Remove the task from the delayed list and add it to the ready list. The - scheduler is suspended so interrupts will not be accessing the ready - lists. */ - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); + /* Remove the task from the delayed list and add it to the ready list. The + scheduler is suspended so interrupts will not be accessing the ready + lists. */ + ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The unblocked task has a priority above that of the calling task, so - a context switch is required. This function is called with the - scheduler suspended so xYieldPending is set so the context switch - occurs immediately that the scheduler is resumed (unsuspended). */ - xYieldPending = pdTRUE; - } + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The unblocked task has a priority above that of the calling task, so + a context switch is required. This function is called with the + scheduler suspended so xYieldPending is set so the context switch + occurs immediately that the scheduler is resumed (unsuspended). */ + xYieldPending = pdTRUE; + } } /*-----------------------------------------------------------*/ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) { - configASSERT( pxTimeOut ); - taskENTER_CRITICAL(); - { - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; - } - taskEXIT_CRITICAL(); + configASSERT( pxTimeOut ); + taskENTER_CRITICAL(); + { + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) { - /* For internal use only as it does not use a critical section. */ - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; + /* For internal use only as it does not use a critical section. */ + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; } /*-----------------------------------------------------------*/ @@ -3230,106 +3230,106 @@ BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const { BaseType_t xReturn; - configASSERT( pxTimeOut ); - configASSERT( pxTicksToWait ); + configASSERT( pxTimeOut ); + configASSERT( pxTicksToWait ); - taskENTER_CRITICAL(); - { - /* Minor optimisation. The tick count cannot change in this block. */ - const TickType_t xConstTickCount = xTickCount; - const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; + taskENTER_CRITICAL(); + { + /* Minor optimisation. The tick count cannot change in this block. */ + const TickType_t xConstTickCount = xTickCount; + const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; - #if( INCLUDE_xTaskAbortDelay == 1 ) - if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) - { - /* The delay was aborted, which is not the same as a time out, - but has the same result. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - xReturn = pdTRUE; - } - else - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) + { + /* The delay was aborted, which is not the same as a time out, + but has the same result. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + xReturn = pdTRUE; + } + else + #endif - #if ( INCLUDE_vTaskSuspend == 1 ) - if( *pxTicksToWait == portMAX_DELAY ) - { - /* If INCLUDE_vTaskSuspend is set to 1 and the block time - specified is the maximum block time then the task should block - indefinitely, and therefore never time out. */ - xReturn = pdFALSE; - } - else - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + if( *pxTicksToWait == portMAX_DELAY ) + { + /* If INCLUDE_vTaskSuspend is set to 1 and the block time + specified is the maximum block time then the task should block + indefinitely, and therefore never time out. */ + xReturn = pdFALSE; + } + else + #endif - if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ - { - /* The tick count is greater than the time at which - vTaskSetTimeout() was called, but has also overflowed since - vTaskSetTimeOut() was called. It must have wrapped all the way - around and gone past again. This passed since vTaskSetTimeout() - was called. */ - xReturn = pdTRUE; - } - else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ - { - /* Not a genuine timeout. Adjust parameters for time remaining. */ - *pxTicksToWait -= xElapsedTime; - vTaskInternalSetTimeOutState( pxTimeOut ); - xReturn = pdFALSE; - } - else - { - *pxTicksToWait = 0; - xReturn = pdTRUE; - } - } - taskEXIT_CRITICAL(); + if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ + { + /* The tick count is greater than the time at which + vTaskSetTimeout() was called, but has also overflowed since + vTaskSetTimeOut() was called. It must have wrapped all the way + around and gone past again. This passed since vTaskSetTimeout() + was called. */ + xReturn = pdTRUE; + } + else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ + { + /* Not a genuine timeout. Adjust parameters for time remaining. */ + *pxTicksToWait -= xElapsedTime; + vTaskInternalSetTimeOutState( pxTimeOut ); + xReturn = pdFALSE; + } + else + { + *pxTicksToWait = 0; + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ void vTaskMissedYield( void ) { - xYieldPending = pdTRUE; + xYieldPending = pdTRUE; } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) - { - UBaseType_t uxReturn; - TCB_t const *pxTCB; + UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) + { + UBaseType_t uxReturn; + TCB_t const *pxTCB; - if( xTask != NULL ) - { - pxTCB = xTask; - uxReturn = pxTCB->uxTaskNumber; - } - else - { - uxReturn = 0U; - } + if( xTask != NULL ) + { + pxTCB = xTask; + uxReturn = pxTCB->uxTaskNumber; + } + else + { + uxReturn = 0U; + } - return uxReturn; - } + return uxReturn; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) - { - TCB_t * pxTCB; + void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) + { + TCB_t * pxTCB; - if( xTask != NULL ) - { - pxTCB = xTask; - pxTCB->uxTaskNumber = uxHandle; - } - } + if( xTask != NULL ) + { + pxTCB = xTask; + pxTCB->uxTaskNumber = uxHandle; + } + } #endif /* configUSE_TRACE_FACILITY */ @@ -3346,212 +3346,212 @@ void vTaskMissedYield( void ) */ static portTASK_FUNCTION( prvIdleTask, pvParameters ) { - /* Stop warnings. */ - ( void ) pvParameters; + /* Stop warnings. */ + ( void ) pvParameters; - /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE - SCHEDULER IS STARTED. **/ + /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE + SCHEDULER IS STARTED. **/ - /* In case a task that has a secure context deletes itself, in which case - the idle task is responsible for deleting the task's secure context, if - any. */ - portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); + /* In case a task that has a secure context deletes itself, in which case + the idle task is responsible for deleting the task's secure context, if + any. */ + portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); - for( ;; ) - { - /* See if any tasks have deleted themselves - if so then the idle task - is responsible for freeing the deleted task's TCB and stack. */ - prvCheckTasksWaitingTermination(); + for( ;; ) + { + /* See if any tasks have deleted themselves - if so then the idle task + is responsible for freeing the deleted task's TCB and stack. */ + prvCheckTasksWaitingTermination(); - #if ( configUSE_PREEMPTION == 0 ) - { - /* If we are not using preemption we keep forcing a task switch to - see if any other task has become available. If we are using - preemption we don't need to do this as any task becoming available - will automatically get the processor anyway. */ - taskYIELD(); - } - #endif /* configUSE_PREEMPTION */ + #if ( configUSE_PREEMPTION == 0 ) + { + /* If we are not using preemption we keep forcing a task switch to + see if any other task has become available. If we are using + preemption we don't need to do this as any task becoming available + will automatically get the processor anyway. */ + taskYIELD(); + } + #endif /* configUSE_PREEMPTION */ - #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) - { - /* When using preemption tasks of equal priority will be - timesliced. If a task that is sharing the idle priority is ready - to run then the idle task should yield before the end of the - timeslice. + #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) + { + /* When using preemption tasks of equal priority will be + timesliced. If a task that is sharing the idle priority is ready + to run then the idle task should yield before the end of the + timeslice. - A critical region is not required here as we are just reading from - the list, and an occasional incorrect value will not matter. If - the ready list at the idle priority contains more than one task - then a task other than the idle task is ready to execute. */ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) - { - taskYIELD(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ + A critical region is not required here as we are just reading from + the list, and an occasional incorrect value will not matter. If + the ready list at the idle priority contains more than one task + then a task other than the idle task is ready to execute. */ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) + { + taskYIELD(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ - #if ( configUSE_IDLE_HOOK == 1 ) - { - extern void (*vApplicationIdleHook)( void ); + #if ( configUSE_IDLE_HOOK == 1 ) + { + extern void (*vApplicationIdleHook)( void ); - /* Call the user defined function from within the idle task. This - allows the application designer to add background functionality - without the overhead of a separate task. - NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, - CALL A FUNCTION THAT MIGHT BLOCK. */ - vApplicationIdleHook(); - } - #endif /* configUSE_IDLE_HOOK */ + /* Call the user defined function from within the idle task. This + allows the application designer to add background functionality + without the overhead of a separate task. + NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, + CALL A FUNCTION THAT MIGHT BLOCK. */ + vApplicationIdleHook(); + } + #endif /* configUSE_IDLE_HOOK */ - /* This conditional compilation should use inequality to 0, not equality - to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when - user defined low power mode implementations require - configUSE_TICKLESS_IDLE to be set to a value other than 1. */ - #if ( configUSE_TICKLESS_IDLE != 0 ) - { - TickType_t xExpectedIdleTime; + /* This conditional compilation should use inequality to 0, not equality + to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when + user defined low power mode implementations require + configUSE_TICKLESS_IDLE to be set to a value other than 1. */ + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + TickType_t xExpectedIdleTime; - /* It is not desirable to suspend then resume the scheduler on - each iteration of the idle task. Therefore, a preliminary - test of the expected idle time is performed without the - scheduler suspended. The result here is not necessarily - valid. */ - xExpectedIdleTime = prvGetExpectedIdleTime(); + /* It is not desirable to suspend then resume the scheduler on + each iteration of the idle task. Therefore, a preliminary + test of the expected idle time is performed without the + scheduler suspended. The result here is not necessarily + valid. */ + xExpectedIdleTime = prvGetExpectedIdleTime(); - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - vTaskSuspendAll(); - { - /* Now the scheduler is suspended, the expected idle - time can be sampled again, and this time its value can - be used. */ - configASSERT( xNextTaskUnblockTime >= xTickCount ); - xExpectedIdleTime = prvGetExpectedIdleTime(); + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + vTaskSuspendAll(); + { + /* Now the scheduler is suspended, the expected idle + time can be sampled again, and this time its value can + be used. */ + configASSERT( xNextTaskUnblockTime >= xTickCount ); + xExpectedIdleTime = prvGetExpectedIdleTime(); - /* Define the following macro to set xExpectedIdleTime to 0 - if the application does not want - portSUPPRESS_TICKS_AND_SLEEP() to be called. */ - configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); + /* Define the following macro to set xExpectedIdleTime to 0 + if the application does not want + portSUPPRESS_TICKS_AND_SLEEP() to be called. */ + configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - traceLOW_POWER_IDLE_BEGIN(); - portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); - traceLOW_POWER_IDLE_END(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICKLESS_IDLE */ - } + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + traceLOW_POWER_IDLE_BEGIN(); + portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); + traceLOW_POWER_IDLE_END(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICKLESS_IDLE */ + } } /*-----------------------------------------------------------*/ #if( configUSE_TICKLESS_IDLE != 0 ) - eSleepModeStatus eTaskConfirmSleepModeStatus( void ) - { - /* The idle task exists in addition to the application tasks. */ - const UBaseType_t uxNonApplicationTasks = 1; - eSleepModeStatus eReturn = eStandardSleep; + eSleepModeStatus eTaskConfirmSleepModeStatus( void ) + { + /* The idle task exists in addition to the application tasks. */ + const UBaseType_t uxNonApplicationTasks = 1; + eSleepModeStatus eReturn = eStandardSleep; - if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) - { - /* A task was made ready while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else if( xYieldPending != pdFALSE ) - { - /* A yield was pended while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else - { - /* If all the tasks are in the suspended list (which might mean they - have an infinite block time rather than actually being suspended) - then it is safe to turn all clocks off and just wait for external - interrupts. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) - { - eReturn = eNoTasksWaitingTimeout; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) + { + /* A task was made ready while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xYieldPending != pdFALSE ) + { + /* A yield was pended while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else + { + /* If all the tasks are in the suspended list (which might mean they + have an infinite block time rather than actually being suspended) + then it is safe to turn all clocks off and just wait for external + interrupts. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) + { + eReturn = eNoTasksWaitingTimeout; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - return eReturn; - } + return eReturn; + } #endif /* configUSE_TICKLESS_IDLE */ /*-----------------------------------------------------------*/ #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) - { - TCB_t *pxTCB; + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) + { + TCB_t *pxTCB; - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToSet ); - pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; - } - } + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToSet ); + pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; + } + } #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ /*-----------------------------------------------------------*/ #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) - { - void *pvReturn = NULL; - TCB_t *pxTCB; + void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) + { + void *pvReturn = NULL; + TCB_t *pxTCB; - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; - } - else - { - pvReturn = NULL; - } + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; + } + else + { + pvReturn = NULL; + } - return pvReturn; - } + return pvReturn; + } #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ /*-----------------------------------------------------------*/ #if ( portUSING_MPU_WRAPPERS == 1 ) - void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions ) - { - TCB_t *pxTCB; + void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions ) + { + TCB_t *pxTCB; - /* If null is passed in here then we are modifying the MPU settings of - the calling task. */ - pxTCB = prvGetTCBFromHandle( xTaskToModify ); + /* If null is passed in here then we are modifying the MPU settings of + the calling task. */ + pxTCB = prvGetTCBFromHandle( xTaskToModify ); - vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); - } + vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); + } #endif /* portUSING_MPU_WRAPPERS */ /*-----------------------------------------------------------*/ @@ -3560,332 +3560,332 @@ static void prvInitialiseTaskLists( void ) { UBaseType_t uxPriority; - for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) - { - vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); - } + for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) + { + vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); + } - vListInitialise( &xDelayedTaskList1 ); - vListInitialise( &xDelayedTaskList2 ); - vListInitialise( &xPendingReadyList ); + vListInitialise( &xDelayedTaskList1 ); + vListInitialise( &xDelayedTaskList2 ); + vListInitialise( &xPendingReadyList ); - #if ( INCLUDE_vTaskDelete == 1 ) - { - vListInitialise( &xTasksWaitingTermination ); - } - #endif /* INCLUDE_vTaskDelete */ + #if ( INCLUDE_vTaskDelete == 1 ) + { + vListInitialise( &xTasksWaitingTermination ); + } + #endif /* INCLUDE_vTaskDelete */ - #if ( INCLUDE_vTaskSuspend == 1 ) - { - vListInitialise( &xSuspendedTaskList ); - } - #endif /* INCLUDE_vTaskSuspend */ + #if ( INCLUDE_vTaskSuspend == 1 ) + { + vListInitialise( &xSuspendedTaskList ); + } + #endif /* INCLUDE_vTaskSuspend */ - /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList - using list2. */ - pxDelayedTaskList = &xDelayedTaskList1; - pxOverflowDelayedTaskList = &xDelayedTaskList2; + /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList + using list2. */ + pxDelayedTaskList = &xDelayedTaskList1; + pxOverflowDelayedTaskList = &xDelayedTaskList2; } /*-----------------------------------------------------------*/ static void prvCheckTasksWaitingTermination( void ) { - /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ + /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ - #if ( INCLUDE_vTaskDelete == 1 ) - { - TCB_t *pxTCB; + #if ( INCLUDE_vTaskDelete == 1 ) + { + TCB_t *pxTCB; - /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() - being called too often in the idle task. */ - while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) - { - taskENTER_CRITICAL(); - { - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - --uxCurrentNumberOfTasks; - --uxDeletedTasksWaitingCleanUp; - } - taskEXIT_CRITICAL(); + /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() + being called too often in the idle task. */ + while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) + { + taskENTER_CRITICAL(); + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + --uxCurrentNumberOfTasks; + --uxDeletedTasksWaitingCleanUp; + } + taskEXIT_CRITICAL(); - prvDeleteTCB( pxTCB ); - } - } - #endif /* INCLUDE_vTaskDelete */ + prvDeleteTCB( pxTCB ); + } + } + #endif /* INCLUDE_vTaskDelete */ } /*-----------------------------------------------------------*/ #if( configUSE_TRACE_FACILITY == 1 ) - void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) - { - TCB_t *pxTCB; + void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) + { + TCB_t *pxTCB; - /* xTask is NULL then get the state of the calling task. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* xTask is NULL then get the state of the calling task. */ + pxTCB = prvGetTCBFromHandle( xTask ); - pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; - pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] ); - pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; - pxTaskStatus->pxStackBase = pxTCB->pxStack; - pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; + pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; + pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] ); + pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; + pxTaskStatus->pxStackBase = pxTCB->pxStack; + pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; - #if ( configUSE_MUTEXES == 1 ) - { - pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; - } - #else - { - pxTaskStatus->uxBasePriority = 0; - } - #endif + #if ( configUSE_MUTEXES == 1 ) + { + pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; + } + #else + { + pxTaskStatus->uxBasePriority = 0; + } + #endif - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; - } - #else - { - pxTaskStatus->ulRunTimeCounter = 0; - } - #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; + } + #else + { + pxTaskStatus->ulRunTimeCounter = 0; + } + #endif - /* Obtaining the task state is a little fiddly, so is only done if the - value of eState passed into this function is eInvalid - otherwise the - state is just set to whatever is passed in. */ - if( eState != eInvalid ) - { - if( pxTCB == pxCurrentTCB ) - { - pxTaskStatus->eCurrentState = eRunning; - } - else - { - pxTaskStatus->eCurrentState = eState; + /* Obtaining the task state is a little fiddly, so is only done if the + value of eState passed into this function is eInvalid - otherwise the + state is just set to whatever is passed in. */ + if( eState != eInvalid ) + { + if( pxTCB == pxCurrentTCB ) + { + pxTaskStatus->eCurrentState = eRunning; + } + else + { + pxTaskStatus->eCurrentState = eState; - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* If the task is in the suspended list then there is a - chance it is actually just blocked indefinitely - so really - it should be reported as being in the Blocked state. */ - if( eState == eSuspended ) - { - vTaskSuspendAll(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - pxTaskStatus->eCurrentState = eBlocked; - } - } - ( void ) xTaskResumeAll(); - } - } - #endif /* INCLUDE_vTaskSuspend */ - } - } - else - { - pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); - } + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* If the task is in the suspended list then there is a + chance it is actually just blocked indefinitely - so really + it should be reported as being in the Blocked state. */ + if( eState == eSuspended ) + { + vTaskSuspendAll(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + pxTaskStatus->eCurrentState = eBlocked; + } + } + ( void ) xTaskResumeAll(); + } + } + #endif /* INCLUDE_vTaskSuspend */ + } + } + else + { + pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); + } - /* Obtaining the stack space takes some time, so the xGetFreeStackSpace - parameter is provided to allow it to be skipped. */ - if( xGetFreeStackSpace != pdFALSE ) - { - #if ( portSTACK_GROWTH > 0 ) - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); - } - #else - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); - } - #endif - } - else - { - pxTaskStatus->usStackHighWaterMark = 0; - } - } + /* Obtaining the stack space takes some time, so the xGetFreeStackSpace + parameter is provided to allow it to be skipped. */ + if( xGetFreeStackSpace != pdFALSE ) + { + #if ( portSTACK_GROWTH > 0 ) + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); + } + #else + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); + } + #endif + } + else + { + pxTaskStatus->usStackHighWaterMark = 0; + } + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) - { - configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB; - UBaseType_t uxTask = 0; + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) + { + configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB; + UBaseType_t uxTask = 0; - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - /* Populate an TaskStatus_t structure within the - pxTaskStatusArray array for each task that is referenced from - pxList. See the definition of TaskStatus_t in task.h for the - meaning of each TaskStatus_t structure member. */ - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); - uxTask++; - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Populate an TaskStatus_t structure within the + pxTaskStatusArray array for each task that is referenced from + pxList. See the definition of TaskStatus_t in task.h for the + meaning of each TaskStatus_t structure member. */ + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); + uxTask++; + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return uxTask; - } + return uxTask; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) - { - uint32_t ulCount = 0U; + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) + { + uint32_t ulCount = 0U; - while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) - { - pucStackByte -= portSTACK_GROWTH; - ulCount++; - } + while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) + { + pucStackByte -= portSTACK_GROWTH; + ulCount++; + } - ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ + ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ - return ( configSTACK_DEPTH_TYPE ) ulCount; - } + return ( configSTACK_DEPTH_TYPE ) ulCount; + } #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) - /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the - same except for their return type. Using configSTACK_DEPTH_TYPE allows the - user to determine the return type. It gets around the problem of the value - overflowing on 8-bit types without breaking backward compatibility for - applications that expect an 8-bit return type. */ - configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - uint8_t *pucEndOfStack; - configSTACK_DEPTH_TYPE uxReturn; + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + same except for their return type. Using configSTACK_DEPTH_TYPE allows the + user to determine the return type. It gets around the problem of the value + overflowing on 8-bit types without breaking backward compatibility for + applications that expect an 8-bit return type. */ + configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + uint8_t *pucEndOfStack; + configSTACK_DEPTH_TYPE uxReturn; - /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are - the same except for their return type. Using configSTACK_DEPTH_TYPE - allows the user to determine the return type. It gets around the - problem of the value overflowing on 8-bit types without breaking - backward compatibility for applications that expect an 8-bit return - type. */ + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are + the same except for their return type. Using configSTACK_DEPTH_TYPE + allows the user to determine the return type. It gets around the + problem of the value overflowing on 8-bit types without breaking + backward compatibility for applications that expect an 8-bit return + type. */ - pxTCB = prvGetTCBFromHandle( xTask ); + pxTCB = prvGetTCBFromHandle( xTask ); - #if portSTACK_GROWTH < 0 - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; - } - #else - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; - } - #endif + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif - uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); + uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) - UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - uint8_t *pucEndOfStack; - UBaseType_t uxReturn; + UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + uint8_t *pucEndOfStack; + UBaseType_t uxReturn; - pxTCB = prvGetTCBFromHandle( xTask ); + pxTCB = prvGetTCBFromHandle( xTask ); - #if portSTACK_GROWTH < 0 - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; - } - #else - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; - } - #endif + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif - uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); + uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskGetStackHighWaterMark */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelete == 1 ) - static void prvDeleteTCB( TCB_t *pxTCB ) - { - /* This call is required specifically for the TriCore port. It must be - above the vPortFree() calls. The call is also used by ports/demos that - want to allocate and clean RAM statically. */ - portCLEAN_UP_TCB( pxTCB ); + static void prvDeleteTCB( TCB_t *pxTCB ) + { + /* This call is required specifically for the TriCore port. It must be + above the vPortFree() calls. The call is also used by ports/demos that + want to allocate and clean RAM statically. */ + portCLEAN_UP_TCB( pxTCB ); - /* Free up the memory allocated by the scheduler for the task. It is up - to the task to free any memory allocated at the application level. */ - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - _reclaim_reent( &( pxTCB->xNewLib_reent ) ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ + /* Free up the memory allocated by the scheduler for the task. It is up + to the task to free any memory allocated at the application level. */ + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + _reclaim_reent( &( pxTCB->xNewLib_reent ) ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) - { - /* The task can only have been allocated dynamically - free both - the stack and TCB. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - { - /* The task could have been allocated statically or dynamically, so - check what was statically allocated before trying to free the - memory. */ - if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) - { - /* Both the stack and TCB were allocated dynamically, so both - must be freed. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) - { - /* Only the stack was statically allocated, so the TCB is the - only memory that must be freed. */ - vPortFree( pxTCB ); - } - else - { - /* Neither the stack nor the TCB were allocated dynamically, so - nothing needs to be freed. */ - configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) + { + /* The task can only have been allocated dynamically - free both + the stack and TCB. */ + vPortFree( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* The task could have been allocated statically or dynamically, so + check what was statically allocated before trying to free the + memory. */ + if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) + { + /* Both the stack and TCB were allocated dynamically, so both + must be freed. */ + vPortFree( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) + { + /* Only the stack was statically allocated, so the TCB is the + only memory that must be freed. */ + vPortFree( pxTCB ); + } + else + { + /* Neither the stack nor the TCB were allocated dynamically, so + nothing needs to be freed. */ + configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } #endif /* INCLUDE_vTaskDelete */ /*-----------------------------------------------------------*/ @@ -3894,651 +3894,651 @@ static void prvResetNextTaskUnblockTime( void ) { TCB_t *pxTCB; - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The new current delayed list is empty. Set xNextTaskUnblockTime to - the maximum possible value so it is extremely unlikely that the - if( xTickCount >= xNextTaskUnblockTime ) test will pass until - there is an item in the delayed list. */ - xNextTaskUnblockTime = portMAX_DELAY; - } - else - { - /* The new current delayed list is not empty, get the value of - the item at the head of the delayed list. This is the time at - which the task at the head of the delayed list should be removed - from the Blocked state. */ - ( pxTCB ) = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); - } + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The new current delayed list is empty. Set xNextTaskUnblockTime to + the maximum possible value so it is extremely unlikely that the + if( xTickCount >= xNextTaskUnblockTime ) test will pass until + there is an item in the delayed list. */ + xNextTaskUnblockTime = portMAX_DELAY; + } + else + { + /* The new current delayed list is not empty, get the value of + the item at the head of the delayed list. This is the time at + which the task at the head of the delayed list should be removed + from the Blocked state. */ + ( pxTCB ) = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); + } } /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) - TaskHandle_t xTaskGetCurrentTaskHandle( void ) - { - TaskHandle_t xReturn; + TaskHandle_t xTaskGetCurrentTaskHandle( void ) + { + TaskHandle_t xReturn; - /* A critical section is not required as this is not called from - an interrupt and the current TCB will always be the same for any - individual execution thread. */ - xReturn = pxCurrentTCB; + /* A critical section is not required as this is not called from + an interrupt and the current TCB will always be the same for any + individual execution thread. */ + xReturn = pxCurrentTCB; - return xReturn; - } + return xReturn; + } #endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - BaseType_t xTaskGetSchedulerState( void ) - { - BaseType_t xReturn; + BaseType_t xTaskGetSchedulerState( void ) + { + BaseType_t xReturn; - if( xSchedulerRunning == pdFALSE ) - { - xReturn = taskSCHEDULER_NOT_STARTED; - } - else - { - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - xReturn = taskSCHEDULER_RUNNING; - } - else - { - xReturn = taskSCHEDULER_SUSPENDED; - } - } + if( xSchedulerRunning == pdFALSE ) + { + xReturn = taskSCHEDULER_NOT_STARTED; + } + else + { + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + xReturn = taskSCHEDULER_RUNNING; + } + else + { + xReturn = taskSCHEDULER_SUSPENDED; + } + } - return xReturn; - } + return xReturn; + } #endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxMutexHolderTCB = pxMutexHolder; - BaseType_t xReturn = pdFALSE; + BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxMutexHolderTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; - /* If the mutex was given back by an interrupt while the queue was - locked then the mutex holder might now be NULL. _RB_ Is this still - needed as interrupts can no longer use mutexes? */ - if( pxMutexHolder != NULL ) - { - /* If the holder of the mutex has a priority below the priority of - the task attempting to obtain the mutex then it will temporarily - inherit the priority of the task attempting to obtain the mutex. */ - if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) - { - /* Adjust the mutex holder state to account for its new - priority. Only reset the event list item value if the value is - not being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the mutex was given back by an interrupt while the queue was + locked then the mutex holder might now be NULL. _RB_ Is this still + needed as interrupts can no longer use mutexes? */ + if( pxMutexHolder != NULL ) + { + /* If the holder of the mutex has a priority below the priority of + the task attempting to obtain the mutex then it will temporarily + inherit the priority of the task attempting to obtain the mutex. */ + if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) + { + /* Adjust the mutex holder state to account for its new + priority. Only reset the event list item value if the value is + not being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* If the task being modified is in the ready state it will need - to be moved into a new list. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the task being modified is in the ready state it will need + to be moved into a new list. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Inherit the priority before being moved into the new list. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - prvAddTaskToReadyList( pxMutexHolderTCB ); - } - else - { - /* Just inherit the priority. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - } + /* Inherit the priority before being moved into the new list. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + prvAddTaskToReadyList( pxMutexHolderTCB ); + } + else + { + /* Just inherit the priority. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + } - traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); + traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); - /* Inheritance occurred. */ - xReturn = pdTRUE; - } - else - { - if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) - { - /* The base priority of the mutex holder is lower than the - priority of the task attempting to take the mutex, but the - current priority of the mutex holder is not lower than the - priority of the task attempting to take the mutex. - Therefore the mutex holder must have already inherited a - priority, but inheritance would have occurred if that had - not been the case. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Inheritance occurred. */ + xReturn = pdTRUE; + } + else + { + if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) + { + /* The base priority of the mutex holder is lower than the + priority of the task attempting to take the mutex, but the + current priority of the mutex holder is not lower than the + priority of the task attempting to take the mutex. + Therefore the mutex holder must have already inherited a + priority, but inheritance would have occurred if that had + not been the case. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxTCB = pxMutexHolder; - BaseType_t xReturn = pdFALSE; + BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; - if( pxMutexHolder != NULL ) - { - /* A task can only have an inherited priority if it holds the mutex. - If the mutex is held by a task then it cannot be given from an - interrupt, and if a mutex is given by the holding task then it must - be the running state task. */ - configASSERT( pxTCB == pxCurrentTCB ); - configASSERT( pxTCB->uxMutexesHeld ); - ( pxTCB->uxMutexesHeld )--; + if( pxMutexHolder != NULL ) + { + /* A task can only have an inherited priority if it holds the mutex. + If the mutex is held by a task then it cannot be given from an + interrupt, and if a mutex is given by the holding task then it must + be the running state task. */ + configASSERT( pxTCB == pxCurrentTCB ); + configASSERT( pxTCB->uxMutexesHeld ); + ( pxTCB->uxMutexesHeld )--; - /* Has the holder of the mutex inherited the priority of another - task? */ - if( pxTCB->uxPriority != pxTCB->uxBasePriority ) - { - /* Only disinherit if no other mutexes are held. */ - if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) - { - /* A task can only have an inherited priority if it holds - the mutex. If the mutex is held by a task then it cannot be - given from an interrupt, and if a mutex is given by the - holding task then it must be the running state task. Remove - the holding task from the ready list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Has the holder of the mutex inherited the priority of another + task? */ + if( pxTCB->uxPriority != pxTCB->uxBasePriority ) + { + /* Only disinherit if no other mutexes are held. */ + if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) + { + /* A task can only have an inherited priority if it holds + the mutex. If the mutex is held by a task then it cannot be + given from an interrupt, and if a mutex is given by the + holding task then it must be the running state task. Remove + the holding task from the ready list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Disinherit the priority before adding the task into the - new ready list. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); - pxTCB->uxPriority = pxTCB->uxBasePriority; + /* Disinherit the priority before adding the task into the + new ready list. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + pxTCB->uxPriority = pxTCB->uxBasePriority; - /* Reset the event list item value. It cannot be in use for - any other purpose if this task is running, and it must be - running to give back the mutex. */ - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - prvAddTaskToReadyList( pxTCB ); + /* Reset the event list item value. It cannot be in use for + any other purpose if this task is running, and it must be + running to give back the mutex. */ + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + prvAddTaskToReadyList( pxTCB ); - /* Return true to indicate that a context switch is required. - This is only actually required in the corner case whereby - multiple mutexes were held and the mutexes were given back - in an order different to that in which they were taken. - If a context switch did not occur when the first mutex was - returned, even if a task was waiting on it, then a context - switch should occur when the last mutex is returned whether - a task is waiting on it or not. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Return true to indicate that a context switch is required. + This is only actually required in the corner case whereby + multiple mutexes were held and the mutexes were given back + in an order different to that in which they were taken. + If a context switch did not occur when the first mutex was + returned, even if a task was waiting on it, then a context + switch should occur when the last mutex is returned whether + a task is waiting on it or not. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) - { - TCB_t * const pxTCB = pxMutexHolder; - UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; - const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; + void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) + { + TCB_t * const pxTCB = pxMutexHolder; + UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; + const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; - if( pxMutexHolder != NULL ) - { - /* If pxMutexHolder is not NULL then the holder must hold at least - one mutex. */ - configASSERT( pxTCB->uxMutexesHeld ); + if( pxMutexHolder != NULL ) + { + /* If pxMutexHolder is not NULL then the holder must hold at least + one mutex. */ + configASSERT( pxTCB->uxMutexesHeld ); - /* Determine the priority to which the priority of the task that - holds the mutex should be set. This will be the greater of the - holding task's base priority and the priority of the highest - priority task that is waiting to obtain the mutex. */ - if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) - { - uxPriorityToUse = uxHighestPriorityWaitingTask; - } - else - { - uxPriorityToUse = pxTCB->uxBasePriority; - } + /* Determine the priority to which the priority of the task that + holds the mutex should be set. This will be the greater of the + holding task's base priority and the priority of the highest + priority task that is waiting to obtain the mutex. */ + if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) + { + uxPriorityToUse = uxHighestPriorityWaitingTask; + } + else + { + uxPriorityToUse = pxTCB->uxBasePriority; + } - /* Does the priority need to change? */ - if( pxTCB->uxPriority != uxPriorityToUse ) - { - /* Only disinherit if no other mutexes are held. This is a - simplification in the priority inheritance implementation. If - the task that holds the mutex is also holding other mutexes then - the other mutexes may have caused the priority inheritance. */ - if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) - { - /* If a task has timed out because it already holds the - mutex it was trying to obtain then it cannot of inherited - its own priority. */ - configASSERT( pxTCB != pxCurrentTCB ); + /* Does the priority need to change? */ + if( pxTCB->uxPriority != uxPriorityToUse ) + { + /* Only disinherit if no other mutexes are held. This is a + simplification in the priority inheritance implementation. If + the task that holds the mutex is also holding other mutexes then + the other mutexes may have caused the priority inheritance. */ + if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) + { + /* If a task has timed out because it already holds the + mutex it was trying to obtain then it cannot of inherited + its own priority. */ + configASSERT( pxTCB != pxCurrentTCB ); - /* Disinherit the priority, remembering the previous - priority to facilitate determining the subject task's - state. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); - uxPriorityUsedOnEntry = pxTCB->uxPriority; - pxTCB->uxPriority = uxPriorityToUse; + /* Disinherit the priority, remembering the previous + priority to facilitate determining the subject task's + state. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + uxPriorityUsedOnEntry = pxTCB->uxPriority; + pxTCB->uxPriority = uxPriorityToUse; - /* Only reset the event list item value if the value is not - being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Only reset the event list item value if the value is not + being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* If the running task is not the task that holds the mutex - then the task that holds the mutex could be in either the - Ready, Blocked or Suspended states. Only remove the task - from its current state list if it is in the Ready state as - the task's priority is going to change and there is one - Ready list per priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the running task is not the task that holds the mutex + then the task that holds the mutex could be in either the + Ready, Blocked or Suspended states. Only remove the task + from its current state list if it is in the Ready state as + the task's priority is going to change and there is one + Ready list per priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - void vTaskEnterCritical( void ) - { - portDISABLE_INTERRUPTS(); + void vTaskEnterCritical( void ) + { + portDISABLE_INTERRUPTS(); - if( xSchedulerRunning != pdFALSE ) - { - ( pxCurrentTCB->uxCriticalNesting )++; + if( xSchedulerRunning != pdFALSE ) + { + ( pxCurrentTCB->uxCriticalNesting )++; - /* This is not the interrupt safe version of the enter critical - function so assert() if it is being called from an interrupt - context. Only API functions that end in "FromISR" can be used in an - interrupt. Only assert if the critical nesting count is 1 to - protect against recursive calls if the assert function also uses a - critical section. */ - if( pxCurrentTCB->uxCriticalNesting == 1 ) - { - portASSERT_IF_IN_ISR(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* This is not the interrupt safe version of the enter critical + function so assert() if it is being called from an interrupt + context. Only API functions that end in "FromISR" can be used in an + interrupt. Only assert if the critical nesting count is 1 to + protect against recursive calls if the assert function also uses a + critical section. */ + if( pxCurrentTCB->uxCriticalNesting == 1 ) + { + portASSERT_IF_IN_ISR(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* portCRITICAL_NESTING_IN_TCB */ /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - void vTaskExitCritical( void ) - { - if( xSchedulerRunning != pdFALSE ) - { - if( pxCurrentTCB->uxCriticalNesting > 0U ) - { - ( pxCurrentTCB->uxCriticalNesting )--; + void vTaskExitCritical( void ) + { + if( xSchedulerRunning != pdFALSE ) + { + if( pxCurrentTCB->uxCriticalNesting > 0U ) + { + ( pxCurrentTCB->uxCriticalNesting )--; - if( pxCurrentTCB->uxCriticalNesting == 0U ) - { - portENABLE_INTERRUPTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( pxCurrentTCB->uxCriticalNesting == 0U ) + { + portENABLE_INTERRUPTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* portCRITICAL_NESTING_IN_TCB */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) - { - size_t x; + static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) + { + size_t x; - /* Start by copying the entire string. */ - rtos_strcpy_ptr( pcBuffer, pcTaskName ); + /* Start by copying the entire string. */ + rtos_strcpy_ptr( pcBuffer, pcTaskName ); - /* Pad the end of the string with spaces to ensure columns line up when - printed out. */ - for( x = rtos_strlen_ptr( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) - { - pcBuffer[ x ] = ' '; - } + /* Pad the end of the string with spaces to ensure columns line up when + printed out. */ + for( x = rtos_strlen_ptr( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) + { + pcBuffer[ x ] = ' '; + } - /* Terminate. */ - pcBuffer[ x ] = ( char ) 0x00; + /* Terminate. */ + pcBuffer[ x ] = ( char ) 0x00; - /* Return the new end of string. */ - return &( pcBuffer[ x ] ); - } + /* Return the new end of string. */ + return &( pcBuffer[ x ] ); + } #endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - void vTaskList( char * pcWriteBuffer ) - { - TaskStatus_t *pxTaskStatusArray; - UBaseType_t uxArraySize, x; - char cStatus; + void vTaskList( char * pcWriteBuffer ) + { + TaskStatus_t *pxTaskStatusArray; + UBaseType_t uxArraySize, x; + char cStatus; - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskList() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that - * displays task names, states and stack usage. - * - * vTaskList() has a dependency on the sprintf() C library function that - * might bloat the code size, use a lot of stack, and provide different - * results on different platforms. An alternative, tiny, third party, - * and limited functionality implementation of sprintf() is provided in - * many of the FreeRTOS/Demo sub-directories in a file called - * printf-stdarg.c (note printf-stdarg.c does not provide a full - * snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskList(). - */ + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that + * displays task names, states and stack usage. + * + * vTaskList() has a dependency on the sprintf() C library function that + * might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, + * and limited functionality implementation of sprintf() is provided in + * many of the FreeRTOS/Demo sub-directories in a file called + * printf-stdarg.c (note printf-stdarg.c does not provide a full + * snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskList(). + */ - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = ( char ) 0x00; + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; - /* Take a snapshot of the number of tasks in case it changes while this - function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; + /* Take a snapshot of the number of tasks in case it changes while this + function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; - /* Allocate an array index for each task. NOTE! if - configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + /* Allocate an array index for each task. NOTE! if + configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - switch( pxTaskStatusArray[ x ].eCurrentState ) - { - case eRunning: cStatus = tskRUNNING_CHAR; - break; + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + switch( pxTaskStatusArray[ x ].eCurrentState ) + { + case eRunning: cStatus = tskRUNNING_CHAR; + break; - case eReady: cStatus = tskREADY_CHAR; - break; + case eReady: cStatus = tskREADY_CHAR; + break; - case eBlocked: cStatus = tskBLOCKED_CHAR; - break; + case eBlocked: cStatus = tskBLOCKED_CHAR; + break; - case eSuspended: cStatus = tskSUSPENDED_CHAR; - break; + case eSuspended: cStatus = tskSUSPENDED_CHAR; + break; - case eDeleted: cStatus = tskDELETED_CHAR; - break; + case eDeleted: cStatus = tskDELETED_CHAR; + break; - case eInvalid: /* Fall through. */ - default: /* Should not get here, but it is included - to prevent static checking errors. */ - cStatus = ( char ) 0x00; - break; - } + case eInvalid: /* Fall through. */ + default: /* Should not get here, but it is included + to prevent static checking errors. */ + cStatus = ( char ) 0x00; + break; + } - /* Write the task name to the string, padding with spaces so it - can be printed in tabular form more easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + /* Write the task name to the string, padding with spaces so it + can be printed in tabular form more easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - /* Write the rest of the string. */ - rtos_sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - pcWriteBuffer += rtos_strlen_ptr( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ - } + /* Write the rest of the string. */ + rtos_sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + pcWriteBuffer += rtos_strlen_ptr( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*----------------------------------------------------------*/ #if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - void vTaskGetRunTimeStats( char *pcWriteBuffer ) - { - TaskStatus_t *pxTaskStatusArray; - UBaseType_t uxArraySize, x; - uint32_t ulTotalTime, ulStatsAsPercentage; + void vTaskGetRunTimeStats( char *pcWriteBuffer ) + { + TaskStatus_t *pxTaskStatusArray; + UBaseType_t uxArraySize, x; + uint32_t ulTotalTime, ulStatsAsPercentage; - #if( configUSE_TRACE_FACILITY != 1 ) - { - #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). - } - #endif + #if( configUSE_TRACE_FACILITY != 1 ) + { + #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). + } + #endif - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part - * of the uxTaskGetSystemState() output into a human readable table that - * displays the amount of time each task has spent in the Running state - * in both absolute and percentage terms. - * - * vTaskGetRunTimeStats() has a dependency on the sprintf() C library - * function that might bloat the code size, use a lot of stack, and - * provide different results on different platforms. An alternative, - * tiny, third party, and limited functionality implementation of - * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in - * a file called printf-stdarg.c (note printf-stdarg.c does not provide - * a full snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskGetRunTimeStats(). - */ + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part + * of the uxTaskGetSystemState() output into a human readable table that + * displays the amount of time each task has spent in the Running state + * in both absolute and percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the sprintf() C library + * function that might bloat the code size, use a lot of stack, and + * provide different results on different platforms. An alternative, + * tiny, third party, and limited functionality implementation of + * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in + * a file called printf-stdarg.c (note printf-stdarg.c does not provide + * a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskGetRunTimeStats(). + */ - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = ( char ) 0x00; + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; - /* Take a snapshot of the number of tasks in case it changes while this - function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; + /* Take a snapshot of the number of tasks in case it changes while this + function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; - /* Allocate an array index for each task. NOTE! If - configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + /* Allocate an array index for each task. NOTE! If + configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); - /* For percentage calculations. */ - ulTotalTime /= 100UL; + /* For percentage calculations. */ + ulTotalTime /= 100UL; - /* Avoid divide by zero errors. */ - if( ulTotalTime > 0UL ) - { - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - /* What percentage of the total run time has the task used? - This will always be rounded down to the nearest integer. - ulTotalRunTimeDiv100 has already been divided by 100. */ - ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; + /* Avoid divide by zero errors. */ + if( ulTotalTime > 0UL ) + { + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + /* What percentage of the total run time has the task used? + This will always be rounded down to the nearest integer. + ulTotalRunTimeDiv100 has already been divided by 100. */ + ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; - /* Write the task name to the string, padding with - spaces so it can be printed in tabular form more - easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + /* Write the task name to the string, padding with + spaces so it can be printed in tabular form more + easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - if( ulStatsAsPercentage > 0UL ) - { - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - } - #endif - } - else - { - /* If the percentage is zero here then the task has - consumed less than 1% of the total run time. */ - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - } - #endif - } + if( ulStatsAsPercentage > 0UL ) + { + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } + else + { + /* If the percentage is zero here then the task has + consumed less than 1% of the total run time. */ + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } - pcWriteBuffer += rtos_strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + pcWriteBuffer += rtos_strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ @@ -4547,506 +4547,506 @@ TickType_t uxTaskResetEventItemValue( void ) { TickType_t uxReturn; - uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); + uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); - /* Reset the event list item to its normal value - so it can be used with - queues and semaphores. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + /* Reset the event list item to its normal value - so it can be used with + queues and semaphores. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - TaskHandle_t pvTaskIncrementMutexHeldCount( void ) - { - /* If xSemaphoreCreateMutex() is called before any tasks have been created - then pxCurrentTCB will be NULL. */ - if( pxCurrentTCB != NULL ) - { - ( pxCurrentTCB->uxMutexesHeld )++; - } + TaskHandle_t pvTaskIncrementMutexHeldCount( void ) + { + /* If xSemaphoreCreateMutex() is called before any tasks have been created + then pxCurrentTCB will be NULL. */ + if( pxCurrentTCB != NULL ) + { + ( pxCurrentTCB->uxMutexesHeld )++; + } - return pxCurrentTCB; - } + return pxCurrentTCB; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) - { - uint32_t ulReturn; + uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) + { + uint32_t ulReturn; - taskENTER_CRITICAL(); - { - /* Only block if the notification count is not already non-zero. */ - if( pxCurrentTCB->ulNotifiedValue == 0UL ) - { - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; + taskENTER_CRITICAL(); + { + /* Only block if the notification count is not already non-zero. */ + if( pxCurrentTCB->ulNotifiedValue == 0UL ) + { + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_TAKE_BLOCK(); + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_TAKE_BLOCK(); - /* All ports are written to allow a yield in a critical - section (some will yield immediately, others wait until the - critical section exits) - but it is not something that - application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* All ports are written to allow a yield in a critical + section (some will yield immediately, others wait until the + critical section exits) - but it is not something that + application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_TAKE(); - ulReturn = pxCurrentTCB->ulNotifiedValue; + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_TAKE(); + ulReturn = pxCurrentTCB->ulNotifiedValue; - if( ulReturn != 0UL ) - { - if( xClearCountOnExit != pdFALSE ) - { - pxCurrentTCB->ulNotifiedValue = 0UL; - } - else - { - pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( ulReturn != 0UL ) + { + if( xClearCountOnExit != pdFALSE ) + { + pxCurrentTCB->ulNotifiedValue = 0UL; + } + else + { + pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); + pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); - return ulReturn; - } + return ulReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) - { - BaseType_t xReturn; + BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) + { + BaseType_t xReturn; - taskENTER_CRITICAL(); - { - /* Only block if a notification is not already pending. */ - if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) - { - /* Clear bits in the task's notification value as bits may get - set by the notifying task or interrupt. This can be used to - clear the value to zero. */ - pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry; + taskENTER_CRITICAL(); + { + /* Only block if a notification is not already pending. */ + if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) + { + /* Clear bits in the task's notification value as bits may get + set by the notifying task or interrupt. This can be used to + clear the value to zero. */ + pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry; - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_WAIT_BLOCK(); + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_WAIT_BLOCK(); - /* All ports are written to allow a yield in a critical - section (some will yield immediately, others wait until the - critical section exits) - but it is not something that - application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* All ports are written to allow a yield in a critical + section (some will yield immediately, others wait until the + critical section exits) - but it is not something that + application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_WAIT(); + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_WAIT(); - if( pulNotificationValue != NULL ) - { - /* Output the current notification value, which may or may not - have changed. */ - *pulNotificationValue = pxCurrentTCB->ulNotifiedValue; - } + if( pulNotificationValue != NULL ) + { + /* Output the current notification value, which may or may not + have changed. */ + *pulNotificationValue = pxCurrentTCB->ulNotifiedValue; + } - /* If ucNotifyValue is set then either the task never entered the - blocked state (because a notification was already pending) or the - task unblocked because of a notification. Otherwise the task - unblocked because of a timeout. */ - if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) - { - /* A notification was not received. */ - xReturn = pdFALSE; - } - else - { - /* A notification was already pending or a notification was - received while the task was waiting. */ - pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit; - xReturn = pdTRUE; - } + /* If ucNotifyValue is set then either the task never entered the + blocked state (because a notification was already pending) or the + task unblocked because of a notification. Otherwise the task + unblocked because of a timeout. */ + if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) + { + /* A notification was not received. */ + xReturn = pdFALSE; + } + else + { + /* A notification was already pending or a notification was + received while the task was waiting. */ + pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit; + xReturn = pdTRUE; + } - pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); + pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) - { - TCB_t * pxTCB; - BaseType_t xReturn = pdPASS; - uint8_t ucOriginalNotifyState; + BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) + { + TCB_t * pxTCB; + BaseType_t xReturn = pdPASS; + uint8_t ucOriginalNotifyState; - configASSERT( xTaskToNotify ); - pxTCB = xTaskToNotify; + configASSERT( xTaskToNotify ); + pxTCB = xTaskToNotify; - taskENTER_CRITICAL(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; - } + taskENTER_CRITICAL(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; + } - ucOriginalNotifyState = pxTCB->ucNotifyState; + ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - switch( eAction ) - { - case eSetBits : - pxTCB->ulNotifiedValue |= ulValue; - break; + switch( eAction ) + { + case eSetBits : + pxTCB->ulNotifiedValue |= ulValue; + break; - case eIncrement : - ( pxTCB->ulNotifiedValue )++; - break; + case eIncrement : + ( pxTCB->ulNotifiedValue )++; + break; - case eSetValueWithOverwrite : - pxTCB->ulNotifiedValue = ulValue; - break; + case eSetValueWithOverwrite : + pxTCB->ulNotifiedValue = ulValue; + break; - case eSetValueWithoutOverwrite : - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - break; + case eSetValueWithoutOverwrite : + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + break; - case eNoAction: - /* The task is being notified without its notify value being - updated. */ - break; + case eNoAction: + /* The task is being notified without its notify value being + updated. */ + break; - default: - /* Should not get here if all enums are handled. - Artificially force an assert by testing a value the - compiler can't assume is const. */ - configASSERT( pxTCB->ulNotifiedValue == ~0UL ); + default: + /* Should not get here if all enums are handled. + Artificially force an assert by testing a value the + compiler can't assume is const. */ + configASSERT( pxTCB->ulNotifiedValue == ~0UL ); - break; - } + break; + } - traceTASK_NOTIFY(); + traceTASK_NOTIFY(); - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - #if( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked waiting for a notification then - xNextTaskUnblockTime might be set to the blocked task's time - out time. If the task is unblocked for a reason other than - a timeout xNextTaskUnblockTime is normally left unchanged, - because it will automatically get reset to a new value when - the tick count equals xNextTaskUnblockTime. However if - tickless idling is used it might be more important to enter - sleep mode at the earliest possible time - so reset - xNextTaskUnblockTime here to ensure it is updated at the - earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif + #if( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked waiting for a notification then + xNextTaskUnblockTime might be set to the blocked task's time + out time. If the task is unblocked for a reason other than + a timeout xNextTaskUnblockTime is normally left unchanged, + because it will automatically get reset to a new value when + the tick count equals xNextTaskUnblockTime. However if + tickless idling is used it might be more important to enter + sleep mode at the earliest possible time - so reset + xNextTaskUnblockTime here to ensure it is updated at the + earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - BaseType_t xReturn = pdPASS; - UBaseType_t uxSavedInterruptStatus; + BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + BaseType_t xReturn = pdPASS; + UBaseType_t uxSavedInterruptStatus; - configASSERT( xTaskToNotify ); + configASSERT( xTaskToNotify ); - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - pxTCB = xTaskToNotify; + pxTCB = xTaskToNotify; - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; - } + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; + } - ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + ucOriginalNotifyState = pxTCB->ucNotifyState; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - switch( eAction ) - { - case eSetBits : - pxTCB->ulNotifiedValue |= ulValue; - break; + switch( eAction ) + { + case eSetBits : + pxTCB->ulNotifiedValue |= ulValue; + break; - case eIncrement : - ( pxTCB->ulNotifiedValue )++; - break; + case eIncrement : + ( pxTCB->ulNotifiedValue )++; + break; - case eSetValueWithOverwrite : - pxTCB->ulNotifiedValue = ulValue; - break; + case eSetValueWithOverwrite : + pxTCB->ulNotifiedValue = ulValue; + break; - case eSetValueWithoutOverwrite : - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - break; + case eSetValueWithoutOverwrite : + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + break; - case eNoAction : - /* The task is being notified without its notify value being - updated. */ - break; + case eNoAction : + /* The task is being notified without its notify value being + updated. */ + break; - default: - /* Should not get here if all enums are handled. - Artificially force an assert by testing a value the - compiler can't assume is const. */ - configASSERT( pxTCB->ulNotifiedValue == ~0UL ); - break; - } + default: + /* Should not get here if all enums are handled. + Artificially force an assert by testing a value the + compiler can't assume is const. */ + configASSERT( pxTCB->ulNotifiedValue == ~0UL ); + break; + } - traceTASK_NOTIFY_FROM_ISR(); + traceTASK_NOTIFY_FROM_ISR(); - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + this task pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } - /* Mark that a yield is pending in case the user is not - using the "xHigherPriorityTaskWoken" parameter to an ISR - safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + /* Mark that a yield is pending in case the user is not + using the "xHigherPriorityTaskWoken" parameter to an ISR + safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - UBaseType_t uxSavedInterruptStatus; + void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + UBaseType_t uxSavedInterruptStatus; - configASSERT( xTaskToNotify ); + configASSERT( xTaskToNotify ); - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - pxTCB = xTaskToNotify; + pxTCB = xTaskToNotify; - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + ucOriginalNotifyState = pxTCB->ucNotifyState; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - /* 'Giving' is equivalent to incrementing a count in a counting - semaphore. */ - ( pxTCB->ulNotifiedValue )++; + /* 'Giving' is equivalent to incrementing a count in a counting + semaphore. */ + ( pxTCB->ulNotifiedValue )++; - traceTASK_NOTIFY_GIVE_FROM_ISR(); + traceTASK_NOTIFY_GIVE_FROM_ISR(); - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + this task pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } - /* Mark that a yield is pending in case the user is not - using the "xHigherPriorityTaskWoken" parameter in an ISR - safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - } + /* Mark that a yield is pending in case the user is not + using the "xHigherPriorityTaskWoken" parameter in an ISR + safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + } #endif /* configUSE_TASK_NOTIFICATIONS */ @@ -5054,40 +5054,40 @@ TickType_t uxReturn; #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - BaseType_t xReturn; + BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + BaseType_t xReturn; - /* If null is passed in here then it is the calling task that is having - its notification state cleared. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* If null is passed in here then it is the calling task that is having + its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); - taskENTER_CRITICAL(); - { - if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED ) - { - pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED ) + { + pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) - TickType_t xTaskGetIdleRunTimeCounter( void ) - { - return xIdleTaskHandle->ulRunTimeCounter; - } + TickType_t xTaskGetIdleRunTimeCounter( void ) + { + return xIdleTaskHandle->ulRunTimeCounter; + } #endif /*-----------------------------------------------------------*/ @@ -5096,110 +5096,110 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT TickType_t xTimeToWake; const TickType_t xConstTickCount = xTickCount; - #if( INCLUDE_xTaskAbortDelay == 1 ) - { - /* About to enter a delayed list, so ensure the ucDelayAborted flag is - reset to pdFALSE so it can be detected as having been set to pdTRUE - when the task leaves the Blocked state. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - } - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + { + /* About to enter a delayed list, so ensure the ucDelayAborted flag is + reset to pdFALSE so it can be detected as having been set to pdTRUE + when the task leaves the Blocked state. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + } + #endif - /* Remove the task from the ready list before adding it to the blocked list - as the same list item is used for both lists. */ - if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* The current task must be in a ready list, so there is no need to - check, and the port reset macro can be called directly. */ - portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Remove the task from the ready list before adding it to the blocked list + as the same list item is used for both lists. */ + if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* The current task must be in a ready list, so there is no need to + check, and the port reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) - { - /* Add the task to the suspended task list instead of a delayed task - list to ensure it is not woken by a timing event. It will block - indefinitely. */ - vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* Calculate the time at which the task should be woken if the event - does not occur. This may overflow but this doesn't matter, the - kernel will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) + { + /* Add the task to the suspended task list instead of a delayed task + list to ensure it is not woken by a timing event. It will block + indefinitely. */ + vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* Calculate the time at which the task should be woken if the event + does not occur. This may overflow but this doesn't matter, the + kernel will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow - list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list - is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow + list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list + is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - /* If the task entering the blocked state was placed at the - head of the list of blocked tasks then xNextTaskUnblockTime - needs to be updated too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - } - #else /* INCLUDE_vTaskSuspend */ - { - /* Calculate the time at which the task should be woken if the event - does not occur. This may overflow but this doesn't matter, the kernel - will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; + /* If the task entering the blocked state was placed at the + head of the list of blocked tasks then xNextTaskUnblockTime + needs to be updated too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + } + #else /* INCLUDE_vTaskSuspend */ + { + /* Calculate the time at which the task should be woken if the event + does not occur. This may overflow but this doesn't matter, the kernel + will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - /* If the task entering the blocked state was placed at the head of the - list of blocked tasks then xNextTaskUnblockTime needs to be updated - too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* If the task entering the blocked state was placed at the head of the + list of blocked tasks then xNextTaskUnblockTime needs to be updated + too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ - ( void ) xCanBlockIndefinitely; - } - #endif /* INCLUDE_vTaskSuspend */ + /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ + ( void ) xCanBlockIndefinitely; + } + #endif /* INCLUDE_vTaskSuspend */ } /* Code below here allows additional code to be inserted into this source file, @@ -5207,20 +5207,20 @@ especially where access to file scope functions and data is needed (for example when performing module tests). */ #ifdef FREERTOS_MODULE_TEST - #include "tasks_test_access_functions.h" + #include "tasks_test_access_functions.h" #endif #if( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) - #include "freertos_tasks_c_additions.h" + #include "freertos_tasks_c_additions.h" - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - static void freertos_tasks_c_additions_init( void ) - { - FREERTOS_TASKS_C_ADDITIONS_INIT(); - } - #endif + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + static void freertos_tasks_c_additions_init( void ) + { + FREERTOS_TASKS_C_ADDITIONS_INIT(); + } + #endif #endif diff --git a/components/bl602/freertos_riscv/timers.c b/components/bl602/freertos_riscv/timers.c index aa9f53ce..964dadc9 100644 --- a/components/bl602/freertos_riscv/timers.c +++ b/components/bl602/freertos_riscv/timers.c @@ -39,7 +39,7 @@ task.h is included from an application file. */ #include "timers.h" #if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) - #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. + #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. #endif /* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified @@ -56,31 +56,31 @@ configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ #if ( configUSE_TIMERS == 1 ) /* Misc definitions. */ -#define tmrNO_DELAY ( TickType_t ) 0U +#define tmrNO_DELAY ( TickType_t ) 0U /* The name assigned to the timer service task. This can be overridden by defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ #ifndef configTIMER_SERVICE_TASK_NAME - #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" + #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" #endif /* Bit definitions used in the ucStatus member of a timer structure. */ -#define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 ) -#define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 ) -#define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 ) +#define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 ) +#define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 ) +#define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 ) /* The definition of the timers themselves. */ typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */ { - const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ - TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ - void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ - TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ - #endif - uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ + const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ + TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ + void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ + TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ + #endif + uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ } xTIMER; /* The old xTIMER name is maintained above then typedefed to the new Timer_t @@ -94,33 +94,33 @@ two message types are defined in two separate structures, xTimerParametersType and xCallbackParametersType respectively. */ typedef struct tmrTimerParameters { - TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ - Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ + TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ + Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ } TimerParameter_t; typedef struct tmrCallbackParameters { - PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ - void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */ - uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ + PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ + void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */ + uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ } CallbackParameters_t; /* The structure that contains the two message types, along with an identifier that is used to determine which message type is valid. */ typedef struct tmrTimerQueueMessage { - BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ - union - { - TimerParameter_t xTimerParameters; + BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ + union + { + TimerParameter_t xTimerParameters; - /* Don't include xCallbackParameters if it is not going to be used as - it makes the structure (and therefore the timer queue) larger. */ - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - CallbackParameters_t xCallbackParameters; - #endif /* INCLUDE_xTimerPendFunctionCall */ - } u; + /* Don't include xCallbackParameters if it is not going to be used as + it makes the structure (and therefore the timer queue) larger. */ + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + CallbackParameters_t xCallbackParameters; + #endif /* INCLUDE_xTimerPendFunctionCall */ + } u; } DaemonTaskMessage_t; /*lint -save -e956 A manual analysis and inspection has been used to determine @@ -147,11 +147,11 @@ PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL; #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - /* If static allocation is supported then the application must provide the - following callback function - which enables the application to optionally - provide the memory that will be used by the timer task as the task's stack - and TCB. */ - extern void (*vApplicationGetTimerTaskMemory)( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ); + /* If static allocation is supported then the application must provide the + following callback function - which enables the application to optionally + provide the memory that will be used by the timer task as the task's stack + and TCB. */ + extern void (*vApplicationGetTimerTaskMemory)( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ); #endif @@ -216,165 +216,165 @@ static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseTy * Called after a Timer_t structure has been allocated either statically or * dynamically to fill in the structure's members. */ -static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION; +static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION; /*-----------------------------------------------------------*/ BaseType_t xTimerCreateTimerTask( void ) { BaseType_t xReturn = pdFAIL; - /* This function is called when the scheduler is started if - configUSE_TIMERS is set to 1. Check that the infrastructure used by the - timer service task has been created/initialised. If timers have already - been created then the initialisation will already have been performed. */ - prvCheckForValidListAndQueue(); + /* This function is called when the scheduler is started if + configUSE_TIMERS is set to 1. Check that the infrastructure used by the + timer service task has been created/initialised. If timers have already + been created then the initialisation will already have been performed. */ + prvCheckForValidListAndQueue(); - if( xTimerQueue != NULL ) - { - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t *pxTimerTaskTCBBuffer = NULL; - StackType_t *pxTimerTaskStackBuffer = NULL; - uint32_t ulTimerTaskStackSize; + if( xTimerQueue != NULL ) + { + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t *pxTimerTaskTCBBuffer = NULL; + StackType_t *pxTimerTaskStackBuffer = NULL; + uint32_t ulTimerTaskStackSize; - vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); - xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - ulTimerTaskStackSize, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - pxTimerTaskStackBuffer, - pxTimerTaskTCBBuffer ); + vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); + xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + ulTimerTaskStackSize, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + pxTimerTaskStackBuffer, + pxTimerTaskTCBBuffer ); - if( xTimerTaskHandle != NULL ) - { - xReturn = pdPASS; - } - } - #else - { - xReturn = xTaskCreate( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - configTIMER_TASK_STACK_DEPTH, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - &xTimerTaskHandle ); - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xTimerTaskHandle != NULL ) + { + xReturn = pdPASS; + } + } + #else + { + xReturn = xTaskCreate( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + configTIMER_TASK_STACK_DEPTH, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + &xTimerTaskHandle ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - configASSERT( xReturn ); - return xReturn; + configASSERT( xReturn ); + return xReturn; } /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) - { - Timer_t *pxNewTimer; + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) + { + Timer_t *pxNewTimer; - pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ + pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ - if( pxNewTimer != NULL ) - { - /* Status is thus far zero as the timer is not created statically - and has not been started. The autoreload bit may get set in - prvInitialiseNewTimer. */ - pxNewTimer->ucStatus = 0x00; - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - } + if( pxNewTimer != NULL ) + { + /* Status is thus far zero as the timer is not created statically + and has not been started. The autoreload bit may get set in + prvInitialiseNewTimer. */ + pxNewTimer->ucStatus = 0x00; + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } - return pxNewTimer; - } + return pxNewTimer; + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t *pxTimerBuffer ) - { - Timer_t *pxNewTimer; + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t *pxTimerBuffer ) + { + Timer_t *pxNewTimer; - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticTimer_t equals the size of the real timer - structure. */ - volatile size_t xSize = sizeof( StaticTimer_t ); - configASSERT( xSize == sizeof( Timer_t ) ); - ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ - } - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticTimer_t equals the size of the real timer + structure. */ + volatile size_t xSize = sizeof( StaticTimer_t ); + configASSERT( xSize == sizeof( Timer_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ - /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ - configASSERT( pxTimerBuffer ); - pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ + /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ + configASSERT( pxTimerBuffer ); + pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ - if( pxNewTimer != NULL ) - { - /* Timers can be created statically or dynamically so note this - timer was created statically in case it is later deleted. The - autoreload bit may get set in prvInitialiseNewTimer(). */ - pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; + if( pxNewTimer != NULL ) + { + /* Timers can be created statically or dynamically so note this + timer was created statically in case it is later deleted. The + autoreload bit may get set in prvInitialiseNewTimer(). */ + pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - } + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } - return pxNewTimer; - } + return pxNewTimer; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ -static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t *pxNewTimer ) +static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t *pxNewTimer ) { - /* 0 is not a valid value for xTimerPeriodInTicks. */ - configASSERT( ( xTimerPeriodInTicks > 0 ) ); + /* 0 is not a valid value for xTimerPeriodInTicks. */ + configASSERT( ( xTimerPeriodInTicks > 0 ) ); - if( pxNewTimer != NULL ) - { - /* Ensure the infrastructure used by the timer service task has been - created/initialised. */ - prvCheckForValidListAndQueue(); + if( pxNewTimer != NULL ) + { + /* Ensure the infrastructure used by the timer service task has been + created/initialised. */ + prvCheckForValidListAndQueue(); - /* Initialise the timer structure members using the function - parameters. */ - pxNewTimer->pcTimerName = pcTimerName; - pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; - pxNewTimer->pvTimerID = pvTimerID; - pxNewTimer->pxCallbackFunction = pxCallbackFunction; - vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); - if( uxAutoReload != pdFALSE ) - { - pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; - } - traceTIMER_CREATE( pxNewTimer ); - } + /* Initialise the timer structure members using the function + parameters. */ + pxNewTimer->pcTimerName = pcTimerName; + pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; + pxNewTimer->pvTimerID = pvTimerID; + pxNewTimer->pxCallbackFunction = pxCallbackFunction; + vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); + if( uxAutoReload != pdFALSE ) + { + pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + traceTIMER_CREATE( pxNewTimer ); + } } /*-----------------------------------------------------------*/ @@ -383,50 +383,50 @@ BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommand BaseType_t xReturn = pdFAIL; DaemonTaskMessage_t xMessage; - configASSERT( xTimer ); + configASSERT( xTimer ); - /* Send a message to the timer service task to perform a particular action - on a particular timer definition. */ - if( xTimerQueue != NULL ) - { - /* Send a command to the timer service task to start the xTimer timer. */ - xMessage.xMessageID = xCommandID; - xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; - xMessage.u.xTimerParameters.pxTimer = xTimer; + /* Send a message to the timer service task to perform a particular action + on a particular timer definition. */ + if( xTimerQueue != NULL ) + { + /* Send a command to the timer service task to start the xTimer timer. */ + xMessage.xMessageID = xCommandID; + xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; + xMessage.u.xTimerParameters.pxTimer = xTimer; - if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) - { - if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - } - else - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); - } - } - else - { - xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - } + if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) + { + if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + } + else + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); + } + } + else + { + xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + } - traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) { - /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been - started, then xTimerTaskHandle will be NULL. */ - configASSERT( ( xTimerTaskHandle != NULL ) ); - return xTimerTaskHandle; + /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been + started, then xTimerTaskHandle will be NULL. */ + configASSERT( ( xTimerTaskHandle != NULL ) ); + return xTimerTaskHandle; } /*-----------------------------------------------------------*/ @@ -434,8 +434,8 @@ TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) { Timer_t *pxTimer = xTimer; - configASSERT( xTimer ); - return pxTimer->xTimerPeriodInTicks; + configASSERT( xTimer ); + return pxTimer->xTimerPeriodInTicks; } /*-----------------------------------------------------------*/ @@ -443,19 +443,19 @@ void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ) { Timer_t * pxTimer = xTimer; - configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - if( uxAutoReload != pdFALSE ) - { - pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; - } - } - taskEXIT_CRITICAL(); + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( uxAutoReload != pdFALSE ) + { + pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; + } + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ @@ -464,9 +464,9 @@ TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) Timer_t * pxTimer = xTimer; TickType_t xReturn; - configASSERT( xTimer ); - xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); - return xReturn; + configASSERT( xTimer ); + xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); + return xReturn; } /*-----------------------------------------------------------*/ @@ -474,8 +474,8 @@ const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified cha { Timer_t *pxTimer = xTimer; - configASSERT( xTimer ); - return pxTimer->pcTimerName; + configASSERT( xTimer ); + return pxTimer->pcTimerName; } /*-----------------------------------------------------------*/ @@ -484,39 +484,39 @@ static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const Tick BaseType_t xResult; Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - /* Remove the timer from the list of active timers. A check has already - been performed to ensure the list is not empty. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); + /* Remove the timer from the list of active timers. A check has already + been performed to ensure the list is not empty. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + traceTIMER_EXPIRED( pxTimer ); - /* If the timer is an auto reload timer then calculate the next - expiry time and re-insert the timer in the list of active timers. */ - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - /* The timer is inserted into a list using a time relative to anything - other than the current time. It will therefore be inserted into the - correct list relative to the time this task thinks it is now. */ - if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) - { - /* The timer expired before it was added to the active timer - list. Reload it now. */ - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - mtCOVERAGE_TEST_MARKER(); - } + /* If the timer is an auto reload timer then calculate the next + expiry time and re-insert the timer in the list of active timers. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + /* The timer is inserted into a list using a time relative to anything + other than the current time. It will therefore be inserted into the + correct list relative to the time this task thinks it is now. */ + if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) + { + /* The timer expired before it was added to the active timer + list. Reload it now. */ + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + mtCOVERAGE_TEST_MARKER(); + } - /* Call the timer callback. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + /* Call the timer callback. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); } /*-----------------------------------------------------------*/ @@ -525,34 +525,34 @@ static portTASK_FUNCTION( prvTimerTask, pvParameters ) TickType_t xNextExpireTime; BaseType_t xListWasEmpty; - /* Just to avoid compiler warnings. */ - ( void ) pvParameters; + /* Just to avoid compiler warnings. */ + ( void ) pvParameters; - #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) - { - extern void vApplicationDaemonTaskStartupHook( void ); + #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) + { + extern void vApplicationDaemonTaskStartupHook( void ); - /* Allow the application writer to execute some code in the context of - this task at the point the task starts executing. This is useful if the - application includes initialisation code that would benefit from - executing after the scheduler has been started. */ - vApplicationDaemonTaskStartupHook(); - } - #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ + /* Allow the application writer to execute some code in the context of + this task at the point the task starts executing. This is useful if the + application includes initialisation code that would benefit from + executing after the scheduler has been started. */ + vApplicationDaemonTaskStartupHook(); + } + #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ - for( ;; ) - { - /* Query the timers list to see if it contains any timers, and if so, - obtain the time at which the next timer will expire. */ - xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); + for( ;; ) + { + /* Query the timers list to see if it contains any timers, and if so, + obtain the time at which the next timer will expire. */ + xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); - /* If a timer has expired, process it. Otherwise, block this task - until either a timer does expire, or a command is received. */ - prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); + /* If a timer has expired, process it. Otherwise, block this task + until either a timer does expire, or a command is received. */ + prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); - /* Empty the command queue. */ - prvProcessReceivedCommands(); - } + /* Empty the command queue. */ + prvProcessReceivedCommands(); + } } /*-----------------------------------------------------------*/ @@ -561,58 +561,58 @@ static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseTy TickType_t xTimeNow; BaseType_t xTimerListsWereSwitched; - vTaskSuspendAll(); - { - /* Obtain the time now to make an assessment as to whether the timer - has expired or not. If obtaining the time causes the lists to switch - then don't process this timer as any timers that remained in the list - when the lists were switched will have been processed within the - prvSampleTimeNow() function. */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - if( xTimerListsWereSwitched == pdFALSE ) - { - /* The tick count has not overflowed, has the timer expired? */ - if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) - { - ( void ) xTaskResumeAll(); - prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); - } - else - { - /* The tick count has not overflowed, and the next expire - time has not been reached yet. This task should therefore - block to wait for the next expire time or a command to be - received - whichever comes first. The following line cannot - be reached unless xNextExpireTime > xTimeNow, except in the - case when the current timer list is empty. */ - if( xListWasEmpty != pdFALSE ) - { - /* The current timer list is empty - is the overflow list - also empty? */ - xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); - } + vTaskSuspendAll(); + { + /* Obtain the time now to make an assessment as to whether the timer + has expired or not. If obtaining the time causes the lists to switch + then don't process this timer as any timers that remained in the list + when the lists were switched will have been processed within the + prvSampleTimeNow() function. */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + if( xTimerListsWereSwitched == pdFALSE ) + { + /* The tick count has not overflowed, has the timer expired? */ + if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) + { + ( void ) xTaskResumeAll(); + prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); + } + else + { + /* The tick count has not overflowed, and the next expire + time has not been reached yet. This task should therefore + block to wait for the next expire time or a command to be + received - whichever comes first. The following line cannot + be reached unless xNextExpireTime > xTimeNow, except in the + case when the current timer list is empty. */ + if( xListWasEmpty != pdFALSE ) + { + /* The current timer list is empty - is the overflow list + also empty? */ + xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); + } - vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); + vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); - if( xTaskResumeAll() == pdFALSE ) - { - /* Yield to wait for either a command to arrive, or the - block time to expire. If a command arrived between the - critical section being exited and this yield then the yield - will not cause the task to block. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - ( void ) xTaskResumeAll(); - } - } + if( xTaskResumeAll() == pdFALSE ) + { + /* Yield to wait for either a command to arrive, or the + block time to expire. If a command arrived between the + critical section being exited and this yield then the yield + will not cause the task to block. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + ( void ) xTaskResumeAll(); + } + } } /*-----------------------------------------------------------*/ @@ -620,25 +620,25 @@ static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) { TickType_t xNextExpireTime; - /* Timers are listed in expiry time order, with the head of the list - referencing the task that will expire first. Obtain the time at which - the timer with the nearest expiry time will expire. If there are no - active timers then just set the next expire time to 0. That will cause - this task to unblock when the tick count overflows, at which point the - timer lists will be switched and the next expiry time can be - re-assessed. */ - *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); - if( *pxListWasEmpty == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - } - else - { - /* Ensure the task unblocks when the tick count rolls over. */ - xNextExpireTime = ( TickType_t ) 0U; - } + /* Timers are listed in expiry time order, with the head of the list + referencing the task that will expire first. Obtain the time at which + the timer with the nearest expiry time will expire. If there are no + active timers then just set the next expire time to 0. That will cause + this task to unblock when the tick count overflows, at which point the + timer lists will be switched and the next expiry time can be + re-assessed. */ + *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); + if( *pxListWasEmpty == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + } + else + { + /* Ensure the task unblocks when the tick count rolls over. */ + xNextExpireTime = ( TickType_t ) 0U; + } - return xNextExpireTime; + return xNextExpireTime; } /*-----------------------------------------------------------*/ @@ -647,21 +647,21 @@ static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched TickType_t xTimeNow; PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */ - xTimeNow = xTaskGetTickCount(); + xTimeNow = xTaskGetTickCount(); - if( xTimeNow < xLastTime ) - { - prvSwitchTimerLists(); - *pxTimerListsWereSwitched = pdTRUE; - } - else - { - *pxTimerListsWereSwitched = pdFALSE; - } + if( xTimeNow < xLastTime ) + { + prvSwitchTimerLists(); + *pxTimerListsWereSwitched = pdTRUE; + } + else + { + *pxTimerListsWereSwitched = pdFALSE; + } - xLastTime = xTimeNow; + xLastTime = xTimeNow; - return xTimeNow; + return xTimeNow; } /*-----------------------------------------------------------*/ @@ -669,188 +669,188 @@ static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const Tic { BaseType_t xProcessTimerNow = pdFALSE; - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - if( xNextExpiryTime <= xTimeNow ) - { - /* Has the expiry time elapsed between the command to start/reset a - timer was issued, and the time the command was processed? */ - if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - { - /* The time between a command being issued and the command being - processed actually exceeds the timers period. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); - } - } - else - { - if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) - { - /* If, since the command was issued, the tick count has overflowed - but the expiry time has not, then the timer must have already passed - its expiry time and should be processed immediately. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - } + if( xNextExpiryTime <= xTimeNow ) + { + /* Has the expiry time elapsed between the command to start/reset a + timer was issued, and the time the command was processed? */ + if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + { + /* The time between a command being issued and the command being + processed actually exceeds the timers period. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); + } + } + else + { + if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) + { + /* If, since the command was issued, the tick count has overflowed + but the expiry time has not, then the timer must have already passed + its expiry time and should be processed immediately. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + } - return xProcessTimerNow; + return xProcessTimerNow; } /*-----------------------------------------------------------*/ -static void prvProcessReceivedCommands( void ) +static void prvProcessReceivedCommands( void ) { DaemonTaskMessage_t xMessage; Timer_t *pxTimer; BaseType_t xTimerListsWereSwitched, xResult; TickType_t xTimeNow; - while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ - { - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - { - /* Negative commands are pended function calls rather than timer - commands. */ - if( xMessage.xMessageID < ( BaseType_t ) 0 ) - { - const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); + while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ + { + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + { + /* Negative commands are pended function calls rather than timer + commands. */ + if( xMessage.xMessageID < ( BaseType_t ) 0 ) + { + const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); - /* The timer uses the xCallbackParameters member to request a - callback be executed. Check the callback is not NULL. */ - configASSERT( pxCallback ); + /* The timer uses the xCallbackParameters member to request a + callback be executed. Check the callback is not NULL. */ + configASSERT( pxCallback ); - /* Call the function. */ - pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* INCLUDE_xTimerPendFunctionCall */ + /* Call the function. */ + pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* INCLUDE_xTimerPendFunctionCall */ - /* Commands that are positive are timer commands rather than pended - function calls. */ - if( xMessage.xMessageID >= ( BaseType_t ) 0 ) - { - /* The messages uses the xTimerParameters member to work on a - software timer. */ - pxTimer = xMessage.u.xTimerParameters.pxTimer; + /* Commands that are positive are timer commands rather than pended + function calls. */ + if( xMessage.xMessageID >= ( BaseType_t ) 0 ) + { + /* The messages uses the xTimerParameters member to work on a + software timer. */ + pxTimer = xMessage.u.xTimerParameters.pxTimer; - if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ - { - /* The timer is in a list, remove it. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ + { + /* The timer is in a list, remove it. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); + traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); - /* In this case the xTimerListsWereSwitched parameter is not used, but - it must be present in the function call. prvSampleTimeNow() must be - called after the message is received from xTimerQueue so there is no - possibility of a higher priority task adding a message to the message - queue with a time that is ahead of the timer daemon task (because it - pre-empted the timer daemon task after the xTimeNow value was set). */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + /* In this case the xTimerListsWereSwitched parameter is not used, but + it must be present in the function call. prvSampleTimeNow() must be + called after the message is received from xTimerQueue so there is no + possibility of a higher priority task adding a message to the message + queue with a time that is ahead of the timer daemon task (because it + pre-empted the timer daemon task after the xTimeNow value was set). */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - switch( xMessage.xMessageID ) - { - case tmrCOMMAND_START : - case tmrCOMMAND_START_FROM_ISR : - case tmrCOMMAND_RESET : - case tmrCOMMAND_RESET_FROM_ISR : - case tmrCOMMAND_START_DONT_TRACE : - /* Start or restart a timer. */ - pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; - if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) - { - /* The timer expired before it was added to the active - timer list. Process it now. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - traceTIMER_EXPIRED( pxTimer ); + switch( xMessage.xMessageID ) + { + case tmrCOMMAND_START : + case tmrCOMMAND_START_FROM_ISR : + case tmrCOMMAND_RESET : + case tmrCOMMAND_RESET_FROM_ISR : + case tmrCOMMAND_START_DONT_TRACE : + /* Start or restart a timer. */ + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) + { + /* The timer expired before it was added to the active + timer list. Process it now. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + traceTIMER_EXPIRED( pxTimer ); - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - break; + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + break; - case tmrCOMMAND_STOP : - case tmrCOMMAND_STOP_FROM_ISR : - /* The timer has already been removed from the active list. */ - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - break; + case tmrCOMMAND_STOP : + case tmrCOMMAND_STOP_FROM_ISR : + /* The timer has already been removed from the active list. */ + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + break; - case tmrCOMMAND_CHANGE_PERIOD : - case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR : - pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; - pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; - configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); + case tmrCOMMAND_CHANGE_PERIOD : + case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR : + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; + configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); - /* The new period does not really have a reference, and can - be longer or shorter than the old one. The command time is - therefore set to the current time, and as the period cannot - be zero the next expiry time can only be in the future, - meaning (unlike for the xTimerStart() case above) there is - no fail case that needs to be handled here. */ - ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); - break; + /* The new period does not really have a reference, and can + be longer or shorter than the old one. The command time is + therefore set to the current time, and as the period cannot + be zero the next expiry time can only be in the future, + meaning (unlike for the xTimerStart() case above) there is + no fail case that needs to be handled here. */ + ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); + break; - case tmrCOMMAND_DELETE : - #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* The timer has already been removed from the active list, - just free up the memory if the memory was dynamically - allocated. */ - if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) - { - vPortFree( pxTimer ); - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - } - } - #else - { - /* If dynamic allocation is not enabled, the memory - could not have been dynamically allocated. So there is - no need to free the memory - just mark the timer as - "not active". */ - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - break; + case tmrCOMMAND_DELETE : + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* The timer has already been removed from the active list, + just free up the memory if the memory was dynamically + allocated. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) + { + vPortFree( pxTimer ); + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + } + } + #else + { + /* If dynamic allocation is not enabled, the memory + could not have been dynamically allocated. So there is + no need to free the memory - just mark the timer as + "not active". */ + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + break; - default : - /* Don't expect to get here. */ - break; - } - } - } + default : + /* Don't expect to get here. */ + break; + } + } + } } /*-----------------------------------------------------------*/ @@ -861,106 +861,106 @@ List_t *pxTemp; Timer_t *pxTimer; BaseType_t xResult; - /* The tick count has overflowed. The timer lists must be switched. - If there are any timers still referenced from the current timer list - then they must have expired and should be processed before the lists - are switched. */ - while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + /* The tick count has overflowed. The timer lists must be switched. + If there are any timers still referenced from the current timer list + then they must have expired and should be processed before the lists + are switched. */ + while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - /* Remove the timer from the list. */ - pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); + /* Remove the timer from the list. */ + pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + traceTIMER_EXPIRED( pxTimer ); - /* Execute its callback, then send a command to restart the timer if - it is an auto-reload timer. It cannot be restarted here as the lists - have not yet been switched. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + /* Execute its callback, then send a command to restart the timer if + it is an auto-reload timer. It cannot be restarted here as the lists + have not yet been switched. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - /* Calculate the reload value, and if the reload value results in - the timer going into the same timer list then it has already expired - and the timer should be re-inserted into the current list so it is - processed again within this loop. Otherwise a command should be sent - to restart the timer to ensure it is only inserted into a list after - the lists have been swapped. */ - xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); - if( xReloadTime > xNextExpireTime ) - { - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - else - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + /* Calculate the reload value, and if the reload value results in + the timer going into the same timer list then it has already expired + and the timer should be re-inserted into the current list so it is + processed again within this loop. Otherwise a command should be sent + to restart the timer to ensure it is only inserted into a list after + the lists have been swapped. */ + xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); + if( xReloadTime > xNextExpireTime ) + { + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + else + { + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - pxTemp = pxCurrentTimerList; - pxCurrentTimerList = pxOverflowTimerList; - pxOverflowTimerList = pxTemp; + pxTemp = pxCurrentTimerList; + pxCurrentTimerList = pxOverflowTimerList; + pxOverflowTimerList = pxTemp; } /*-----------------------------------------------------------*/ static void prvCheckForValidListAndQueue( void ) { - /* Check that the list from which active timers are referenced, and the - queue used to communicate with the timer service, have been - initialised. */ - taskENTER_CRITICAL(); - { - if( xTimerQueue == NULL ) - { - vListInitialise( &xActiveTimerList1 ); - vListInitialise( &xActiveTimerList2 ); - pxCurrentTimerList = &xActiveTimerList1; - pxOverflowTimerList = &xActiveTimerList2; + /* Check that the list from which active timers are referenced, and the + queue used to communicate with the timer service, have been + initialised. */ + taskENTER_CRITICAL(); + { + if( xTimerQueue == NULL ) + { + vListInitialise( &xActiveTimerList1 ); + vListInitialise( &xActiveTimerList2 ); + pxCurrentTimerList = &xActiveTimerList1; + pxOverflowTimerList = &xActiveTimerList2; - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* The timer queue is allocated statically in case - configSUPPORT_DYNAMIC_ALLOCATION is 0. */ - static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* The timer queue is allocated statically in case + configSUPPORT_DYNAMIC_ALLOCATION is 0. */ + static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); - } - #else - { - xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); - } - #endif + xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); + } + #else + { + xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); + } + #endif - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - if( xTimerQueue != NULL ) - { - vQueueAddToRegistry( xTimerQueue, "TmrQ" ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configQUEUE_REGISTRY_SIZE */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + if( xTimerQueue != NULL ) + { + vQueueAddToRegistry( xTimerQueue, "TmrQ" ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configQUEUE_REGISTRY_SIZE */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ @@ -969,23 +969,23 @@ BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) BaseType_t xReturn; Timer_t *pxTimer = xTimer; - configASSERT( xTimer ); + configASSERT( xTimer ); - /* Is the timer in the list of active timers? */ - taskENTER_CRITICAL(); - { - if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) - { - xReturn = pdFALSE; - } - else - { - xReturn = pdTRUE; - } - } - taskEXIT_CRITICAL(); + /* Is the timer in the list of active timers? */ + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*lint !e818 Can't be pointer to const due to the typedef. */ /*-----------------------------------------------------------*/ @@ -994,15 +994,15 @@ void *pvTimerGetTimerID( const TimerHandle_t xTimer ) Timer_t * const pxTimer = xTimer; void *pvReturn; - configASSERT( xTimer ); + configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - pvReturn = pxTimer->pvTimerID; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + pvReturn = pxTimer->pvTimerID; + } + taskEXIT_CRITICAL(); - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ @@ -1010,85 +1010,85 @@ void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) { Timer_t * const pxTimer = xTimer; - configASSERT( xTimer ); + configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - pxTimer->pvTimerID = pvNewID; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + pxTimer->pvTimerID = pvNewID; + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ #if( INCLUDE_xTimerPendFunctionCall == 1 ) - BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; + BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; - /* Complete the message with the function parameters and post it to the - daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + /* Complete the message with the function parameters and post it to the + daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - return xReturn; - } + return xReturn; + } #endif /* INCLUDE_xTimerPendFunctionCall */ /*-----------------------------------------------------------*/ #if( INCLUDE_xTimerPendFunctionCall == 1 ) - BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; + BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; - /* This function can only be called after a timer has been created or - after the scheduler has been started because, until then, the timer - queue does not exist. */ - configASSERT( xTimerQueue ); + /* This function can only be called after a timer has been created or + after the scheduler has been started because, until then, the timer + queue does not exist. */ + configASSERT( xTimerQueue ); - /* Complete the message with the function parameters and post it to the - daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + /* Complete the message with the function parameters and post it to the + daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - return xReturn; - } + return xReturn; + } #endif /* INCLUDE_xTimerPendFunctionCall */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) - { - return ( ( Timer_t * ) xTimer )->uxTimerNumber; - } + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) + { + return ( ( Timer_t * ) xTimer )->uxTimerNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) - { - ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; - } + void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) + { + ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv_ram/config/FreeRTOS.h b/components/bl602/freertos_riscv_ram/config/FreeRTOS.h index 9d09d91a..a3796364 100644 --- a/components/bl602/freertos_riscv_ram/config/FreeRTOS.h +++ b/components/bl602/freertos_riscv_ram/config/FreeRTOS.h @@ -63,12 +63,12 @@ extern "C" { /* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ #ifndef configUSE_NEWLIB_REENTRANT - #define configUSE_NEWLIB_REENTRANT 0 + #define configUSE_NEWLIB_REENTRANT 0 #endif /* Required if struct _reent is used. */ #if ( configUSE_NEWLIB_REENTRANT == 1 ) - #include + #include #endif /* * Check all the required application specific macros have been defined. @@ -77,479 +77,479 @@ extern "C" { */ #ifndef configMINIMAL_STACK_SIZE - #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. + #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. #endif #ifndef configMAX_PRIORITIES - #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. #endif #if configMAX_PRIORITIES < 1 - #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. + #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. #endif #ifndef configUSE_PREEMPTION - #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_IDLE_HOOK - #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_TICK_HOOK - #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_16_BIT_TICKS - #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. + #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_CO_ROUTINES - #define configUSE_CO_ROUTINES 0 + #define configUSE_CO_ROUTINES 0 #endif #ifndef INCLUDE_vTaskPrioritySet - #define INCLUDE_vTaskPrioritySet 0 + #define INCLUDE_vTaskPrioritySet 0 #endif #ifndef INCLUDE_uxTaskPriorityGet - #define INCLUDE_uxTaskPriorityGet 0 + #define INCLUDE_uxTaskPriorityGet 0 #endif #ifndef INCLUDE_vTaskDelete - #define INCLUDE_vTaskDelete 0 + #define INCLUDE_vTaskDelete 0 #endif #ifndef INCLUDE_vTaskSuspend - #define INCLUDE_vTaskSuspend 0 + #define INCLUDE_vTaskSuspend 0 #endif #ifndef INCLUDE_vTaskDelayUntil - #define INCLUDE_vTaskDelayUntil 0 + #define INCLUDE_vTaskDelayUntil 0 #endif #ifndef INCLUDE_vTaskDelay - #define INCLUDE_vTaskDelay 0 + #define INCLUDE_vTaskDelay 0 #endif #ifndef INCLUDE_xTaskGetIdleTaskHandle - #define INCLUDE_xTaskGetIdleTaskHandle 0 + #define INCLUDE_xTaskGetIdleTaskHandle 0 #endif #ifndef INCLUDE_xTaskAbortDelay - #define INCLUDE_xTaskAbortDelay 0 + #define INCLUDE_xTaskAbortDelay 0 #endif #ifndef INCLUDE_xQueueGetMutexHolder - #define INCLUDE_xQueueGetMutexHolder 0 + #define INCLUDE_xQueueGetMutexHolder 0 #endif #ifndef INCLUDE_xSemaphoreGetMutexHolder - #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder + #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder #endif #ifndef INCLUDE_xTaskGetHandle - #define INCLUDE_xTaskGetHandle 0 + #define INCLUDE_xTaskGetHandle 0 #endif #ifndef INCLUDE_uxTaskGetStackHighWaterMark - #define INCLUDE_uxTaskGetStackHighWaterMark 0 + #define INCLUDE_uxTaskGetStackHighWaterMark 0 #endif #ifndef INCLUDE_uxTaskGetStackHighWaterMark2 - #define INCLUDE_uxTaskGetStackHighWaterMark2 0 + #define INCLUDE_uxTaskGetStackHighWaterMark2 0 #endif #ifndef INCLUDE_eTaskGetState - #define INCLUDE_eTaskGetState 0 + #define INCLUDE_eTaskGetState 0 #endif #ifndef INCLUDE_xTaskResumeFromISR - #define INCLUDE_xTaskResumeFromISR 1 + #define INCLUDE_xTaskResumeFromISR 1 #endif #ifndef INCLUDE_xTimerPendFunctionCall - #define INCLUDE_xTimerPendFunctionCall 0 + #define INCLUDE_xTimerPendFunctionCall 0 #endif #ifndef INCLUDE_xTaskGetSchedulerState - #define INCLUDE_xTaskGetSchedulerState 0 + #define INCLUDE_xTaskGetSchedulerState 0 #endif #ifndef INCLUDE_xTaskGetCurrentTaskHandle - #define INCLUDE_xTaskGetCurrentTaskHandle 0 + #define INCLUDE_xTaskGetCurrentTaskHandle 0 #endif #if configUSE_CO_ROUTINES != 0 - #ifndef configMAX_CO_ROUTINE_PRIORITIES - #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. - #endif + #ifndef configMAX_CO_ROUTINE_PRIORITIES + #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. + #endif #endif #ifndef configUSE_DAEMON_TASK_STARTUP_HOOK - #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 + #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 #endif #ifndef configUSE_APPLICATION_TASK_TAG - #define configUSE_APPLICATION_TASK_TAG 0 + #define configUSE_APPLICATION_TASK_TAG 0 #endif #ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS - #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 + #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 #endif #ifndef configUSE_RECURSIVE_MUTEXES - #define configUSE_RECURSIVE_MUTEXES 0 + #define configUSE_RECURSIVE_MUTEXES 0 #endif #ifndef configUSE_MUTEXES - #define configUSE_MUTEXES 0 + #define configUSE_MUTEXES 0 #endif #ifndef configUSE_TIMERS - #define configUSE_TIMERS 0 + #define configUSE_TIMERS 0 #endif #ifndef configUSE_COUNTING_SEMAPHORES - #define configUSE_COUNTING_SEMAPHORES 0 + #define configUSE_COUNTING_SEMAPHORES 0 #endif #ifndef configUSE_ALTERNATIVE_API - #define configUSE_ALTERNATIVE_API 0 + #define configUSE_ALTERNATIVE_API 0 #endif #ifndef portCRITICAL_NESTING_IN_TCB - #define portCRITICAL_NESTING_IN_TCB 0 + #define portCRITICAL_NESTING_IN_TCB 0 #endif #ifndef configMAX_TASK_NAME_LEN - #define configMAX_TASK_NAME_LEN 16 + #define configMAX_TASK_NAME_LEN 16 #endif #ifndef configIDLE_SHOULD_YIELD - #define configIDLE_SHOULD_YIELD 1 + #define configIDLE_SHOULD_YIELD 1 #endif #if configMAX_TASK_NAME_LEN < 1 - #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h + #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h #endif #ifndef configASSERT - #define configASSERT( x ) - #define configASSERT_DEFINED 0 + #define configASSERT( x ) + #define configASSERT_DEFINED 0 #else - #define configASSERT_DEFINED 1 + #define configASSERT_DEFINED 1 #endif #ifndef portMEMORY_BARRIER - #define portMEMORY_BARRIER() + #define portMEMORY_BARRIER() #endif /* The timers module relies on xTaskGetSchedulerState(). */ #if configUSE_TIMERS == 1 - #ifndef configTIMER_TASK_PRIORITY - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. - #endif /* configTIMER_TASK_PRIORITY */ + #ifndef configTIMER_TASK_PRIORITY + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. + #endif /* configTIMER_TASK_PRIORITY */ - #ifndef configTIMER_QUEUE_LENGTH - #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. - #endif /* configTIMER_QUEUE_LENGTH */ + #ifndef configTIMER_QUEUE_LENGTH + #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. + #endif /* configTIMER_QUEUE_LENGTH */ - #ifndef configTIMER_TASK_STACK_DEPTH - #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. - #endif /* configTIMER_TASK_STACK_DEPTH */ + #ifndef configTIMER_TASK_STACK_DEPTH + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. + #endif /* configTIMER_TASK_STACK_DEPTH */ #endif /* configUSE_TIMERS */ #ifndef portSET_INTERRUPT_MASK_FROM_ISR - #define portSET_INTERRUPT_MASK_FROM_ISR() 0 + #define portSET_INTERRUPT_MASK_FROM_ISR() 0 #endif #ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR - #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue + #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue #endif #ifndef portCLEAN_UP_TCB - #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB + #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef portPRE_TASK_DELETE_HOOK - #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) + #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) #endif #ifndef portSETUP_TCB - #define portSETUP_TCB( pxTCB ) ( void ) pxTCB + #define portSETUP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef configQUEUE_REGISTRY_SIZE - #define configQUEUE_REGISTRY_SIZE 0U + #define configQUEUE_REGISTRY_SIZE 0U #endif #if ( configQUEUE_REGISTRY_SIZE < 1 ) - #define vQueueAddToRegistry( xQueue, pcName ) - #define vQueueUnregisterQueue( xQueue ) - #define pcQueueGetName( xQueue ) + #define vQueueAddToRegistry( xQueue, pcName ) + #define vQueueUnregisterQueue( xQueue ) + #define pcQueueGetName( xQueue ) #endif #ifndef portPOINTER_SIZE_TYPE - #define portPOINTER_SIZE_TYPE uint32_t + #define portPOINTER_SIZE_TYPE uint32_t #endif /* Remove any unused trace macros. */ #ifndef traceSTART - /* Used to perform any necessary initialisation - for example, open a file - into which trace is to be written. */ - #define traceSTART() + /* Used to perform any necessary initialisation - for example, open a file + into which trace is to be written. */ + #define traceSTART() #endif #ifndef traceEND - /* Use to close a trace, for example close a file into which trace has been - written. */ - #define traceEND() + /* Use to close a trace, for example close a file into which trace has been + written. */ + #define traceEND() #endif #ifndef traceTASK_SWITCHED_IN - /* Called after a task has been selected to run. pxCurrentTCB holds a pointer - to the task control block of the selected task. */ - #define traceTASK_SWITCHED_IN() + /* Called after a task has been selected to run. pxCurrentTCB holds a pointer + to the task control block of the selected task. */ + #define traceTASK_SWITCHED_IN() #endif #ifndef traceINCREASE_TICK_COUNT - /* Called before stepping the tick count after waking from tickless idle - sleep. */ - #define traceINCREASE_TICK_COUNT( x ) + /* Called before stepping the tick count after waking from tickless idle + sleep. */ + #define traceINCREASE_TICK_COUNT( x ) #endif #ifndef traceLOW_POWER_IDLE_BEGIN - /* Called immediately before entering tickless idle. */ - #define traceLOW_POWER_IDLE_BEGIN() + /* Called immediately before entering tickless idle. */ + #define traceLOW_POWER_IDLE_BEGIN() #endif -#ifndef traceLOW_POWER_IDLE_END - /* Called when returning to the Idle task after a tickless idle. */ - #define traceLOW_POWER_IDLE_END() +#ifndef traceLOW_POWER_IDLE_END + /* Called when returning to the Idle task after a tickless idle. */ + #define traceLOW_POWER_IDLE_END() #endif #ifndef traceTASK_SWITCHED_OUT - /* Called before a task has been selected to run. pxCurrentTCB holds a pointer - to the task control block of the task being switched out. */ - #define traceTASK_SWITCHED_OUT() + /* Called before a task has been selected to run. pxCurrentTCB holds a pointer + to the task control block of the task being switched out. */ + #define traceTASK_SWITCHED_OUT() #endif #ifndef traceTASK_PRIORITY_INHERIT - /* Called when a task attempts to take a mutex that is already held by a - lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task - that holds the mutex. uxInheritedPriority is the priority the mutex holder - will inherit (the priority of the task that is attempting to obtain the - muted. */ - #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) + /* Called when a task attempts to take a mutex that is already held by a + lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task + that holds the mutex. uxInheritedPriority is the priority the mutex holder + will inherit (the priority of the task that is attempting to obtain the + muted. */ + #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) #endif #ifndef traceTASK_PRIORITY_DISINHERIT - /* Called when a task releases a mutex, the holding of which had resulted in - the task inheriting the priority of a higher priority task. - pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the - mutex. uxOriginalPriority is the task's configured (base) priority. */ - #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) + /* Called when a task releases a mutex, the holding of which had resulted in + the task inheriting the priority of a higher priority task. + pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the + mutex. uxOriginalPriority is the task's configured (base) priority. */ + #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) #endif #ifndef traceBLOCKING_ON_QUEUE_RECEIVE - /* Task is about to block because it cannot read from a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the read was attempted. pxCurrentTCB points to the TCB of the - task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) + /* Task is about to block because it cannot read from a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the read was attempted. pxCurrentTCB points to the TCB of the + task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) #endif #ifndef traceBLOCKING_ON_QUEUE_PEEK - /* Task is about to block because it cannot read from a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the read was attempted. pxCurrentTCB points to the TCB of the - task that attempted the read. */ - #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) + /* Task is about to block because it cannot read from a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the read was attempted. pxCurrentTCB points to the TCB of the + task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) #endif #ifndef traceBLOCKING_ON_QUEUE_SEND - /* Task is about to block because it cannot write to a - queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore - upon which the write was attempted. pxCurrentTCB points to the TCB of the - task that attempted the write. */ - #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) + /* Task is about to block because it cannot write to a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the write was attempted. pxCurrentTCB points to the TCB of the + task that attempted the write. */ + #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) #endif #ifndef configCHECK_FOR_STACK_OVERFLOW - #define configCHECK_FOR_STACK_OVERFLOW 0 + #define configCHECK_FOR_STACK_OVERFLOW 0 #endif #ifndef configRECORD_STACK_HIGH_ADDRESS - #define configRECORD_STACK_HIGH_ADDRESS 0 + #define configRECORD_STACK_HIGH_ADDRESS 0 #endif #ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H - #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 + #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 #endif /* The following event macros are embedded in the kernel API calls. */ #ifndef traceMOVED_TASK_TO_READY_STATE - #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) + #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) #endif #ifndef tracePOST_MOVED_TASK_TO_READY_STATE - #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) + #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) #endif #ifndef traceQUEUE_CREATE - #define traceQUEUE_CREATE( pxNewQueue ) + #define traceQUEUE_CREATE( pxNewQueue ) #endif #ifndef traceQUEUE_CREATE_FAILED - #define traceQUEUE_CREATE_FAILED( ucQueueType ) + #define traceQUEUE_CREATE_FAILED( ucQueueType ) #endif #ifndef traceCREATE_MUTEX - #define traceCREATE_MUTEX( pxNewQueue ) + #define traceCREATE_MUTEX( pxNewQueue ) #endif #ifndef traceCREATE_MUTEX_FAILED - #define traceCREATE_MUTEX_FAILED() + #define traceCREATE_MUTEX_FAILED() #endif #ifndef traceGIVE_MUTEX_RECURSIVE - #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) + #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceGIVE_MUTEX_RECURSIVE_FAILED - #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) + #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE - #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) + #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE_FAILED - #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) + #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceCREATE_COUNTING_SEMAPHORE - #define traceCREATE_COUNTING_SEMAPHORE() + #define traceCREATE_COUNTING_SEMAPHORE() #endif #ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED - #define traceCREATE_COUNTING_SEMAPHORE_FAILED() + #define traceCREATE_COUNTING_SEMAPHORE_FAILED() #endif #ifndef traceQUEUE_SEND - #define traceQUEUE_SEND( pxQueue ) + #define traceQUEUE_SEND( pxQueue ) #endif #ifndef traceQUEUE_SEND_FAILED - #define traceQUEUE_SEND_FAILED( pxQueue ) + #define traceQUEUE_SEND_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE - #define traceQUEUE_RECEIVE( pxQueue ) + #define traceQUEUE_RECEIVE( pxQueue ) #endif #ifndef traceQUEUE_PEEK - #define traceQUEUE_PEEK( pxQueue ) + #define traceQUEUE_PEEK( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FAILED - #define traceQUEUE_PEEK_FAILED( pxQueue ) + #define traceQUEUE_PEEK_FAILED( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR - #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) + #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FAILED - #define traceQUEUE_RECEIVE_FAILED( pxQueue ) + #define traceQUEUE_RECEIVE_FAILED( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR - #define traceQUEUE_SEND_FROM_ISR( pxQueue ) + #define traceQUEUE_SEND_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR_FAILED - #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) + #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR - #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) + #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED - #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) + #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR_FAILED - #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) + #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_DELETE - #define traceQUEUE_DELETE( pxQueue ) + #define traceQUEUE_DELETE( pxQueue ) #endif #ifndef traceTASK_CREATE - #define traceTASK_CREATE( pxNewTCB ) + #define traceTASK_CREATE( pxNewTCB ) #endif #ifndef traceTASK_CREATE_FAILED - #define traceTASK_CREATE_FAILED() + #define traceTASK_CREATE_FAILED() #endif #ifndef traceTASK_DELETE - #define traceTASK_DELETE( pxTaskToDelete ) + #define traceTASK_DELETE( pxTaskToDelete ) #endif #ifndef traceTASK_DELAY_UNTIL - #define traceTASK_DELAY_UNTIL( x ) + #define traceTASK_DELAY_UNTIL( x ) #endif #ifndef traceTASK_DELAY - #define traceTASK_DELAY() + #define traceTASK_DELAY() #endif #ifndef traceTASK_PRIORITY_SET - #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) + #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) #endif #ifndef traceTASK_SUSPEND - #define traceTASK_SUSPEND( pxTaskToSuspend ) + #define traceTASK_SUSPEND( pxTaskToSuspend ) #endif #ifndef traceTASK_RESUME - #define traceTASK_RESUME( pxTaskToResume ) + #define traceTASK_RESUME( pxTaskToResume ) #endif #ifndef traceTASK_RESUME_FROM_ISR - #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) + #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) #endif #ifndef traceTASK_INCREMENT_TICK - #define traceTASK_INCREMENT_TICK( xTickCount ) + #define traceTASK_INCREMENT_TICK( xTickCount ) #endif #ifndef traceTIMER_CREATE - #define traceTIMER_CREATE( pxNewTimer ) + #define traceTIMER_CREATE( pxNewTimer ) #endif #ifndef traceTIMER_CREATE_FAILED - #define traceTIMER_CREATE_FAILED() + #define traceTIMER_CREATE_FAILED() #endif #ifndef traceTIMER_COMMAND_SEND - #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) + #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) #endif #ifndef traceTIMER_EXPIRED - #define traceTIMER_EXPIRED( pxTimer ) + #define traceTIMER_EXPIRED( pxTimer ) #endif #ifndef traceTIMER_COMMAND_RECEIVED - #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) + #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) #endif #ifndef traceMALLOC @@ -561,397 +561,397 @@ extern "C" { #endif #ifndef traceEVENT_GROUP_CREATE - #define traceEVENT_GROUP_CREATE( xEventGroup ) + #define traceEVENT_GROUP_CREATE( xEventGroup ) #endif #ifndef traceEVENT_GROUP_CREATE_FAILED - #define traceEVENT_GROUP_CREATE_FAILED() + #define traceEVENT_GROUP_CREATE_FAILED() #endif #ifndef traceEVENT_GROUP_SYNC_BLOCK - #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) + #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_SYNC_END - #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred + #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK - #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) + #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_WAIT_BITS_END - #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred + #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_CLEAR_BITS - #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) + #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR - #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) + #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_SET_BITS - #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) + #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR - #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) + #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_DELETE - #define traceEVENT_GROUP_DELETE( xEventGroup ) + #define traceEVENT_GROUP_DELETE( xEventGroup ) #endif #ifndef tracePEND_FUNC_CALL - #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) + #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef tracePEND_FUNC_CALL_FROM_ISR - #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) + #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef traceQUEUE_REGISTRY_ADD - #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) + #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) #endif #ifndef traceTASK_NOTIFY_TAKE_BLOCK - #define traceTASK_NOTIFY_TAKE_BLOCK() + #define traceTASK_NOTIFY_TAKE_BLOCK() #endif #ifndef traceTASK_NOTIFY_TAKE - #define traceTASK_NOTIFY_TAKE() + #define traceTASK_NOTIFY_TAKE() #endif #ifndef traceTASK_NOTIFY_WAIT_BLOCK - #define traceTASK_NOTIFY_WAIT_BLOCK() + #define traceTASK_NOTIFY_WAIT_BLOCK() #endif #ifndef traceTASK_NOTIFY_WAIT - #define traceTASK_NOTIFY_WAIT() + #define traceTASK_NOTIFY_WAIT() #endif #ifndef traceTASK_NOTIFY - #define traceTASK_NOTIFY() + #define traceTASK_NOTIFY() #endif #ifndef traceTASK_NOTIFY_FROM_ISR - #define traceTASK_NOTIFY_FROM_ISR() + #define traceTASK_NOTIFY_FROM_ISR() #endif #ifndef traceTASK_NOTIFY_GIVE_FROM_ISR - #define traceTASK_NOTIFY_GIVE_FROM_ISR() + #define traceTASK_NOTIFY_GIVE_FROM_ISR() #endif #ifndef traceSTREAM_BUFFER_CREATE_FAILED - #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) + #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED - #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) + #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_CREATE - #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) + #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_DELETE - #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) + #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RESET - #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) + #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) #endif #ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND - #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) + #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_SEND - #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) + #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) #endif #ifndef traceSTREAM_BUFFER_SEND_FAILED - #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) + #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_SEND_FROM_ISR - #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) + #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) #endif #ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE - #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) + #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE - #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) + #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE_FAILED - #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) + #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR - #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) + #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) #endif #ifndef configGENERATE_RUN_TIME_STATS - #define configGENERATE_RUN_TIME_STATS 0 + #define configGENERATE_RUN_TIME_STATS 0 #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) - #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. - #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ + #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. + #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ - #ifndef portGET_RUN_TIME_COUNTER_VALUE - #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE - #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. - #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ - #endif /* portGET_RUN_TIME_COUNTER_VALUE */ + #ifndef portGET_RUN_TIME_COUNTER_VALUE + #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE + #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. + #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ + #endif /* portGET_RUN_TIME_COUNTER_VALUE */ #endif /* configGENERATE_RUN_TIME_STATS */ #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS - #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() + #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() #endif #ifndef configUSE_MALLOC_FAILED_HOOK - #define configUSE_MALLOC_FAILED_HOOK 0 + #define configUSE_MALLOC_FAILED_HOOK 0 #endif #ifndef portPRIVILEGE_BIT - #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) + #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) #endif #ifndef portYIELD_WITHIN_API - #define portYIELD_WITHIN_API portYIELD + #define portYIELD_WITHIN_API portYIELD #endif #ifndef portSUPPRESS_TICKS_AND_SLEEP - #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) + #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) #endif #ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP - #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 + #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 #endif #if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 - #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 + #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 #endif #ifndef configUSE_TICKLESS_IDLE - #define configUSE_TICKLESS_IDLE 0 + #define configUSE_TICKLESS_IDLE 0 #endif #ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING - #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) + #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) #endif #ifndef configPRE_SLEEP_PROCESSING - #define configPRE_SLEEP_PROCESSING( x ) + #define configPRE_SLEEP_PROCESSING( x ) #endif #ifndef configPOST_SLEEP_PROCESSING - #define configPOST_SLEEP_PROCESSING( x ) + #define configPOST_SLEEP_PROCESSING( x ) #endif #ifndef configUSE_QUEUE_SETS - #define configUSE_QUEUE_SETS 0 + #define configUSE_QUEUE_SETS 0 #endif #ifndef portTASK_USES_FLOATING_POINT - #define portTASK_USES_FLOATING_POINT() + #define portTASK_USES_FLOATING_POINT() #endif #ifndef portALLOCATE_SECURE_CONTEXT - #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) + #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) #endif #ifndef portDONT_DISCARD - #define portDONT_DISCARD + #define portDONT_DISCARD #endif #ifndef configUSE_TIME_SLICING - #define configUSE_TIME_SLICING 1 + #define configUSE_TIME_SLICING 1 #endif #ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS - #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 + #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 #endif #ifndef configUSE_STATS_FORMATTING_FUNCTIONS - #define configUSE_STATS_FORMATTING_FUNCTIONS 0 + #define configUSE_STATS_FORMATTING_FUNCTIONS 0 #endif #ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID - #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() + #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() #endif #ifndef configUSE_TRACE_FACILITY - #define configUSE_TRACE_FACILITY 0 + #define configUSE_TRACE_FACILITY 0 #endif #ifndef mtCOVERAGE_TEST_MARKER - #define mtCOVERAGE_TEST_MARKER() + #define mtCOVERAGE_TEST_MARKER() #endif #ifndef mtCOVERAGE_TEST_DELAY - #define mtCOVERAGE_TEST_DELAY() + #define mtCOVERAGE_TEST_DELAY() #endif #ifndef portASSERT_IF_IN_ISR - #define portASSERT_IF_IN_ISR() + #define portASSERT_IF_IN_ISR() #endif #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 #endif #ifndef configAPPLICATION_ALLOCATED_HEAP - #define configAPPLICATION_ALLOCATED_HEAP 0 + #define configAPPLICATION_ALLOCATED_HEAP 0 #endif #ifndef configUSE_TASK_NOTIFICATIONS - #define configUSE_TASK_NOTIFICATIONS 1 + #define configUSE_TASK_NOTIFICATIONS 1 #endif #ifndef configUSE_POSIX_ERRNO - #define configUSE_POSIX_ERRNO 0 + #define configUSE_POSIX_ERRNO 0 #endif #ifndef portTICK_TYPE_IS_ATOMIC - #define portTICK_TYPE_IS_ATOMIC 0 + #define portTICK_TYPE_IS_ATOMIC 0 #endif #ifndef configSUPPORT_STATIC_ALLOCATION - /* Defaults to 0 for backward compatibility. */ - #define configSUPPORT_STATIC_ALLOCATION 0 + /* Defaults to 0 for backward compatibility. */ + #define configSUPPORT_STATIC_ALLOCATION 0 #endif #ifndef configSUPPORT_DYNAMIC_ALLOCATION - /* Defaults to 1 for backward compatibility. */ - #define configSUPPORT_DYNAMIC_ALLOCATION 1 + /* Defaults to 1 for backward compatibility. */ + #define configSUPPORT_DYNAMIC_ALLOCATION 1 #endif #ifndef configSTACK_DEPTH_TYPE - /* Defaults to uint16_t for backward compatibility, but can be overridden - in FreeRTOSConfig.h if uint16_t is too restrictive. */ - #define configSTACK_DEPTH_TYPE uint16_t + /* Defaults to uint16_t for backward compatibility, but can be overridden + in FreeRTOSConfig.h if uint16_t is too restrictive. */ + #define configSTACK_DEPTH_TYPE uint16_t #endif #ifndef configMESSAGE_BUFFER_LENGTH_TYPE - /* Defaults to size_t for backward compatibility, but can be overridden - in FreeRTOSConfig.h if lengths will always be less than the number of bytes - in a size_t. */ - #define configMESSAGE_BUFFER_LENGTH_TYPE size_t + /* Defaults to size_t for backward compatibility, but can be overridden + in FreeRTOSConfig.h if lengths will always be less than the number of bytes + in a size_t. */ + #define configMESSAGE_BUFFER_LENGTH_TYPE size_t #endif /* Sanity check the configuration. */ #if( configUSE_TICKLESS_IDLE != 0 ) - #if( INCLUDE_vTaskSuspend != 1 ) - #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 - #endif /* INCLUDE_vTaskSuspend */ + #if( INCLUDE_vTaskSuspend != 1 ) + #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 + #endif /* INCLUDE_vTaskSuspend */ #endif /* configUSE_TICKLESS_IDLE */ #if( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) - #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. + #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. #endif #if( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) - #error configUSE_MUTEXES must be set to 1 to use recursive mutexes + #error configUSE_MUTEXES must be set to 1 to use recursive mutexes #endif #ifndef configINITIAL_TICK_COUNT - #define configINITIAL_TICK_COUNT 0 + #define configINITIAL_TICK_COUNT 0 #endif #if( portTICK_TYPE_IS_ATOMIC == 0 ) - /* Either variables of tick type cannot be read atomically, or - portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when - the tick count is returned to the standard critical section macros. */ - #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) + /* Either variables of tick type cannot be read atomically, or + portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when + the tick count is returned to the standard critical section macros. */ + #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) #else - /* The tick type can be read atomically, so critical sections used when the - tick count is returned can be defined away. */ - #define portTICK_TYPE_ENTER_CRITICAL() - #define portTICK_TYPE_EXIT_CRITICAL() - #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 - #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x + /* The tick type can be read atomically, so critical sections used when the + tick count is returned can be defined away. */ + #define portTICK_TYPE_ENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x #endif /* Definitions to allow backward compatibility with FreeRTOS versions prior to V8 if desired. */ #ifndef configENABLE_BACKWARD_COMPATIBILITY - #define configENABLE_BACKWARD_COMPATIBILITY 1 + #define configENABLE_BACKWARD_COMPATIBILITY 1 #endif #ifndef configPRINTF - /* configPRINTF() was not defined, so define it away to nothing. To use - configPRINTF() then define it as follows (where MyPrintFunction() is - provided by the application writer): + /* configPRINTF() was not defined, so define it away to nothing. To use + configPRINTF() then define it as follows (where MyPrintFunction() is + provided by the application writer): - void MyPrintFunction(const char *pcFormat, ... ); - #define configPRINTF( X ) MyPrintFunction X + void MyPrintFunction(const char *pcFormat, ... ); + #define configPRINTF( X ) MyPrintFunction X - Then call like a standard printf() function, but placing brackets around - all parameters so they are passed as a single parameter. For example: - configPRINTF( ("Value = %d", MyVariable) ); */ - #define configPRINTF( X ) + Then call like a standard printf() function, but placing brackets around + all parameters so they are passed as a single parameter. For example: + configPRINTF( ("Value = %d", MyVariable) ); */ + #define configPRINTF( X ) #endif #ifndef configMAX - /* The application writer has not provided their own MAX macro, so define - the following generic implementation. */ - #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) + /* The application writer has not provided their own MAX macro, so define + the following generic implementation. */ + #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) #endif #ifndef configMIN - /* The application writer has not provided their own MAX macro, so define - the following generic implementation. */ - #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) + /* The application writer has not provided their own MAX macro, so define + the following generic implementation. */ + #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) #endif #if configENABLE_BACKWARD_COMPATIBILITY == 1 - #define eTaskStateGet eTaskGetState - #define portTickType TickType_t - #define xTaskHandle TaskHandle_t - #define xQueueHandle QueueHandle_t - #define xSemaphoreHandle SemaphoreHandle_t - #define xQueueSetHandle QueueSetHandle_t - #define xQueueSetMemberHandle QueueSetMemberHandle_t - #define xTimeOutType TimeOut_t - #define xMemoryRegion MemoryRegion_t - #define xTaskParameters TaskParameters_t - #define xTaskStatusType TaskStatus_t - #define xTimerHandle TimerHandle_t - #define xCoRoutineHandle CoRoutineHandle_t - #define pdTASK_HOOK_CODE TaskHookFunction_t - #define portTICK_RATE_MS portTICK_PERIOD_MS - #define pcTaskGetTaskName pcTaskGetName - #define pcTimerGetTimerName pcTimerGetName - #define pcQueueGetQueueName pcQueueGetName - #define vTaskGetTaskInfo vTaskGetInfo + #define eTaskStateGet eTaskGetState + #define portTickType TickType_t + #define xTaskHandle TaskHandle_t + #define xQueueHandle QueueHandle_t + #define xSemaphoreHandle SemaphoreHandle_t + #define xQueueSetHandle QueueSetHandle_t + #define xQueueSetMemberHandle QueueSetMemberHandle_t + #define xTimeOutType TimeOut_t + #define xMemoryRegion MemoryRegion_t + #define xTaskParameters TaskParameters_t + #define xTaskStatusType TaskStatus_t + #define xTimerHandle TimerHandle_t + #define xCoRoutineHandle CoRoutineHandle_t + #define pdTASK_HOOK_CODE TaskHookFunction_t + #define portTICK_RATE_MS portTICK_PERIOD_MS + #define pcTaskGetTaskName pcTaskGetName + #define pcTimerGetTimerName pcTimerGetName + #define pcQueueGetQueueName pcQueueGetName + #define vTaskGetTaskInfo vTaskGetInfo - /* Backward compatibility within the scheduler code only - these definitions - are not really required but are included for completeness. */ - #define tmrTIMER_CALLBACK TimerCallbackFunction_t - #define pdTASK_CODE TaskFunction_t - #define xListItem ListItem_t - #define xList List_t + /* Backward compatibility within the scheduler code only - these definitions + are not really required but are included for completeness. */ + #define tmrTIMER_CALLBACK TimerCallbackFunction_t + #define pdTASK_CODE TaskFunction_t + #define xListItem ListItem_t + #define xList List_t - /* For libraries that break the list data hiding, and access list structure - members directly (which is not supposed to be done). */ - #define pxContainer pvContainer + /* For libraries that break the list data hiding, and access list structure + members directly (which is not supposed to be done). */ + #define pxContainer pvContainer #endif /* configENABLE_BACKWARD_COMPATIBILITY */ #if( configUSE_ALTERNATIVE_API != 0 ) - #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 + #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 #endif /* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even @@ -959,31 +959,31 @@ if floating point hardware is otherwise supported by the FreeRTOS port in use. This constant is not supported by all FreeRTOS ports that include floating point support. */ #ifndef configUSE_TASK_FPU_SUPPORT - #define configUSE_TASK_FPU_SUPPORT 1 + #define configUSE_TASK_FPU_SUPPORT 1 #endif /* Set configENABLE_MPU to 1 to enable MPU support and 0 to disable it. This is currently used in ARMv8M ports. */ #ifndef configENABLE_MPU - #define configENABLE_MPU 0 + #define configENABLE_MPU 0 #endif /* Set configENABLE_FPU to 1 to enable FPU support and 0 to disable it. This is currently used in ARMv8M ports. */ #ifndef configENABLE_FPU - #define configENABLE_FPU 1 + #define configENABLE_FPU 1 #endif /* Set configENABLE_TRUSTZONE to 1 enable TrustZone support and 0 to disable it. This is currently used in ARMv8M ports. */ #ifndef configENABLE_TRUSTZONE - #define configENABLE_TRUSTZONE 1 + #define configENABLE_TRUSTZONE 1 #endif /* Set configRUN_FREERTOS_SECURE_ONLY to 1 to run the FreeRTOS ARMv8M port on the Secure Side only. */ #ifndef configRUN_FREERTOS_SECURE_ONLY - #define configRUN_FREERTOS_SECURE_ONLY 0 + #define configRUN_FREERTOS_SECURE_ONLY 0 #endif /* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using @@ -1028,8 +1028,8 @@ the Secure Side only. */ * | | | | xTaskCreateRestrictedStatic | | | | * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ */ -#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ - ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) +#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ + ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) /* * In line with software engineering best practice, FreeRTOS implements a strict @@ -1043,40 +1043,40 @@ the Secure Side only. */ */ struct xSTATIC_LIST_ITEM { - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - TickType_t xDummy2; - void *pvDummy3[ 4 ]; - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy4; - #endif + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void *pvDummy3[ 4 ]; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy4; + #endif }; typedef struct xSTATIC_LIST_ITEM StaticListItem_t; /* See the comments above the struct xSTATIC_LIST_ITEM definition. */ struct xSTATIC_MINI_LIST_ITEM { - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - TickType_t xDummy2; - void *pvDummy3[ 2 ]; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void *pvDummy3[ 2 ]; }; typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; /* See the comments above the struct xSTATIC_LIST_ITEM definition. */ typedef struct xSTATIC_LIST { - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy1; - #endif - UBaseType_t uxDummy2; - void *pvDummy3; - StaticMiniListItem_t xDummy4; - #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) - TickType_t xDummy5; - #endif + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + UBaseType_t uxDummy2; + void *pvDummy3; + StaticMiniListItem_t xDummy4; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy5; + #endif } StaticList_t; /* @@ -1094,52 +1094,52 @@ typedef struct xSTATIC_LIST */ typedef struct xSTATIC_TCB { - void *pxDummy1; - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xDummy2; - #endif - StaticListItem_t xDummy3[ 2 ]; - UBaseType_t uxDummy5; - void *pxDummy6; - uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - void *pxDummy8; - #endif - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxDummy9; - #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy10[ 2 ]; - #endif - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxDummy12[ 2 ]; - #endif - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - void *pxDummy14; - #endif - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void *pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulDummy16; - #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - struct _reent xDummy17; - #endif - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - uint32_t ulDummy18; - uint8_t ucDummy19; - #endif - #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - uint8_t uxDummy20; - #endif + void *pxDummy1; + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xDummy2; + #endif + StaticListItem_t xDummy3[ 2 ]; + UBaseType_t uxDummy5; + void *pxDummy6; + uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + void *pxDummy8; + #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxDummy9; + #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy10[ 2 ]; + #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxDummy12[ 2 ]; + #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + void *pxDummy14; + #endif + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void *pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + uint32_t ulDummy16; + #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + struct _reent xDummy17; + #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + uint32_t ulDummy18; + uint8_t ucDummy19; + #endif + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + uint8_t uxDummy20; + #endif - #if( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDummy21; - #endif - #if ( configUSE_POSIX_ERRNO == 1 ) - int iDummy22; - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDummy21; + #endif + #if ( configUSE_POSIX_ERRNO == 1 ) + int iDummy22; + #endif } StaticTask_t; /* @@ -1158,30 +1158,30 @@ typedef struct xSTATIC_TCB */ typedef struct xSTATIC_QUEUE { - void *pvDummy1[ 3 ]; + void *pvDummy1[ 3 ]; - union - { - void *pvDummy2; - UBaseType_t uxDummy2; - } u; + union + { + void *pvDummy2; + UBaseType_t uxDummy2; + } u; - StaticList_t xDummy3[ 2 ]; - UBaseType_t uxDummy4[ 3 ]; - uint8_t ucDummy5[ 2 ]; + StaticList_t xDummy3[ 2 ]; + UBaseType_t uxDummy4[ 3 ]; + uint8_t ucDummy5[ 2 ]; - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy6; - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy6; + #endif - #if ( configUSE_QUEUE_SETS == 1 ) - void *pvDummy7; - #endif + #if ( configUSE_QUEUE_SETS == 1 ) + void *pvDummy7; + #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy8; - uint8_t ucDummy9; - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy8; + uint8_t ucDummy9; + #endif } StaticQueue_t; typedef StaticQueue_t StaticSemaphore_t; @@ -1202,16 +1202,16 @@ typedef StaticQueue_t StaticSemaphore_t; */ typedef struct xSTATIC_EVENT_GROUP { - TickType_t xDummy1; - StaticList_t xDummy2; + TickType_t xDummy1; + StaticList_t xDummy2; - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy3; - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy3; + #endif - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucDummy4; - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy4; + #endif } StaticEventGroup_t; @@ -1231,15 +1231,15 @@ typedef struct xSTATIC_EVENT_GROUP */ typedef struct xSTATIC_TIMER { - void *pvDummy1; - StaticListItem_t xDummy2; - TickType_t xDummy3; - void *pvDummy5; - TaskFunction_t pvDummy6; - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy7; - #endif - uint8_t ucDummy8; + void *pvDummy1; + StaticListItem_t xDummy2; + TickType_t xDummy3; + void *pvDummy5; + TaskFunction_t pvDummy6; + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy7; + #endif + uint8_t ucDummy8; } StaticTimer_t; @@ -1259,12 +1259,12 @@ typedef struct xSTATIC_TIMER */ typedef struct xSTATIC_STREAM_BUFFER { - size_t uxDummy1[ 4 ]; - void * pvDummy2[ 3 ]; - uint8_t ucDummy3; - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxDummy4; - #endif + size_t uxDummy1[ 4 ]; + void * pvDummy2[ 3 ]; + uint8_t ucDummy3; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy4; + #endif } StaticStreamBuffer_t; /* Message buffers are built on stream buffers. */ diff --git a/components/bl602/freertos_riscv_ram/config/FreeRTOSConfig.h b/components/bl602/freertos_riscv_ram/config/FreeRTOSConfig.h index b694171a..309bc5b5 100644 --- a/components/bl602/freertos_riscv_ram/config/FreeRTOSConfig.h +++ b/components/bl602/freertos_riscv_ram/config/FreeRTOSConfig.h @@ -87,61 +87,61 @@ #define configSUPPORT_STATIC_ALLOCATION 1 -#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR -#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) -#define configUSE_PREEMPTION 1 -#define configUSE_IDLE_HOOK 1 -#define configUSE_TICK_HOOK 0 +#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR +#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 0 #ifndef configUSE_TICKLESS_IDLE //Maybe Compile flags is passed by command line -#define configUSE_TICKLESS_IDLE 1 +#define configUSE_TICKLESS_IDLE 1 #endif -#define configCPU_CLOCK_HZ ( 10 * 1000 * 1000 ) /*QEMU*/ -#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) -#define configMAX_PRIORITIES ( 32 ) -#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 96 ) -#define configTOTAL_HEAP_SIZE ( ( size_t ) 14100 ) -#define configMAX_TASK_NAME_LEN ( 16 ) -#define configUSE_TRACE_FACILITY 1 +#define configCPU_CLOCK_HZ ( 10 * 1000 * 1000 ) /*QEMU*/ +#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) +#define configMAX_PRIORITIES ( 32 ) +#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 96 ) +#define configTOTAL_HEAP_SIZE ( ( size_t ) 14100 ) +#define configMAX_TASK_NAME_LEN ( 16 ) +#define configUSE_TRACE_FACILITY 1 #define configUSE_STATS_FORMATTING_FUNCTIONS 1 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_MUTEXES 1 -#define configQUEUE_REGISTRY_SIZE 8 -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_MALLOC_FAILED_HOOK 1 -#define configUSE_APPLICATION_TASK_TAG 0 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 0 #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 /* Co-routine definitions. */ -#define configUSE_CO_ROUTINES 0 +#define configUSE_CO_ROUTINES 0 #define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) /* Software timer definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) -#define configTIMER_QUEUE_LENGTH 4 -#define configTIMER_TASK_STACK_DEPTH ( 400 ) +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH ( 400 ) /* Task priorities. Allow these to be overridden. */ #ifndef uartPRIMARY_PRIORITY - #define uartPRIMARY_PRIORITY ( configMAX_PRIORITIES - 3 ) + #define uartPRIMARY_PRIORITY ( configMAX_PRIORITIES - 3 ) #endif /* Set the following definitions to 1 to include the API function, or zero to exclude the API function. */ -#define INCLUDE_vTaskPrioritySet 1 -#define INCLUDE_uxTaskPriorityGet 1 -#define INCLUDE_vTaskDelete 1 -#define INCLUDE_vTaskCleanUpResources 1 -#define INCLUDE_vTaskSuspend 1 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_eTaskGetState 1 -#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 #define INCLUDE_uxTaskGetStackHighWaterMark 1 /* Normal assert() semantics without relying on the provision of an assert.h diff --git a/components/bl602/freertos_riscv_ram/config/StackMacros.h b/components/bl602/freertos_riscv_ram/config/StackMacros.h index 3ed8b22d..d3e79464 100644 --- a/components/bl602/freertos_riscv_ram/config/StackMacros.h +++ b/components/bl602/freertos_riscv_ram/config/StackMacros.h @@ -29,7 +29,7 @@ #define STACK_MACROS_H #ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ - #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. + #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. #endif /* @@ -50,81 +50,81 @@ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + /* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) - /* Only the current stack state is to be checked. */ - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - \ - /* Is the currently saved stack pointer within the stack limit? */ \ - if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + /* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ - const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ - \ - if( ( pulStack[ 0 ] != ulCheckValue ) || \ - ( pulStack[ 1 ] != ulCheckValue ) || \ - ( pulStack[ 2 ] != ulCheckValue ) || \ - ( pulStack[ 3 ] != ulCheckValue ) ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ + const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ + \ + if( ( pulStack[ 0 ] != ulCheckValue ) || \ + ( pulStack[ 1 ] != ulCheckValue ) || \ + ( pulStack[ 2 ] != ulCheckValue ) || \ + ( pulStack[ 3 ] != ulCheckValue ) ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) - #define taskCHECK_FOR_STACK_OVERFLOW() \ - { \ - int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ - static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ - tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ - \ - \ - pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ - \ - /* Has the extremity of the task stack ever been written over? */ \ - if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ - { \ - vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ - } \ - } + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ + static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ + \ + \ + pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ + \ + /* Has the extremity of the task stack ever been written over? */ \ + if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ /* Remove stack overflow macro if not being used. */ #ifndef taskCHECK_FOR_STACK_OVERFLOW - #define taskCHECK_FOR_STACK_OVERFLOW() + #define taskCHECK_FOR_STACK_OVERFLOW() #endif diff --git a/components/bl602/freertos_riscv_ram/config/croutine.h b/components/bl602/freertos_riscv_ram/config/croutine.h index 8b3b41b9..8de53088 100644 --- a/components/bl602/freertos_riscv_ram/config/croutine.h +++ b/components/bl602/freertos_riscv_ram/config/croutine.h @@ -29,7 +29,7 @@ #define CO_ROUTINE_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include croutine.h" + #error "include FreeRTOS.h must appear in source files before include croutine.h" #endif #include "list.h" @@ -48,12 +48,12 @@ typedef void (*crCOROUTINE_CODE)( CoRoutineHandle_t, UBaseType_t ); typedef struct corCoRoutineControlBlock { - crCOROUTINE_CODE pxCoRoutineFunction; - ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ - ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ - UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ - UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ - uint16_t uxState; /*< Used internally by the co-routine implementation. */ + crCOROUTINE_CODE pxCoRoutineFunction; + ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ + ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ + UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ + UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ + uint16_t uxState; /*< Used internally by the co-routine implementation. */ } CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ /** @@ -153,7 +153,7 @@ BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPri // The rest of the idle task will execute between co-routine calls. void vApplicationIdleHook( void ) { - vCoRoutineSchedule(); + vCoRoutineSchedule(); } // Alternatively, if you do not require any other part of the idle task to @@ -287,12 +287,12 @@ void vCoRoutineSchedule( void ); * \defgroup crDELAY crDELAY * \ingroup Tasks */ -#define crDELAY( xHandle, xTicksToDelay ) \ - if( ( xTicksToDelay ) > 0 ) \ - { \ - vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ - } \ - crSET_STATE0( ( xHandle ) ); +#define crDELAY( xHandle, xTicksToDelay ) \ + if( ( xTicksToDelay ) > 0 ) \ + { \ + vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ + } \ + crSET_STATE0( ( xHandle ) ); /** *
@@ -377,19 +377,19 @@ void vCoRoutineSchedule( void );
  * \defgroup crQUEUE_SEND crQUEUE_SEND
  * \ingroup Tasks
  */
-#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult )			\
-{																						\
-	*( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) );	\
-	if( *( pxResult ) == errQUEUE_BLOCKED )												\
-	{																					\
-		crSET_STATE0( ( xHandle ) );													\
-		*pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 );					\
-	}																					\
-	if( *pxResult == errQUEUE_YIELD )													\
-	{																					\
-		crSET_STATE1( ( xHandle ) );													\
-		*pxResult = pdPASS;																\
-	}																					\
+#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult )         \
+{                                                                                       \
+    *( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) );   \
+    if( *( pxResult ) == errQUEUE_BLOCKED )                                             \
+    {                                                                                   \
+        crSET_STATE0( ( xHandle ) );                                                    \
+        *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 );                  \
+    }                                                                                   \
+    if( *pxResult == errQUEUE_YIELD )                                                   \
+    {                                                                                   \
+        crSET_STATE1( ( xHandle ) );                                                    \
+        *pxResult = pdPASS;                                                             \
+    }                                                                                   \
 }
 
 /**
@@ -469,19 +469,19 @@ void vCoRoutineSchedule( void );
  * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE
  * \ingroup Tasks
  */
-#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult )			\
-{																						\
-	*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) );		\
-	if( *( pxResult ) == errQUEUE_BLOCKED ) 											\
-	{																					\
-		crSET_STATE0( ( xHandle ) );													\
-		*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 );				\
-	}																					\
-	if( *( pxResult ) == errQUEUE_YIELD )												\
-	{																					\
-		crSET_STATE1( ( xHandle ) );													\
-		*( pxResult ) = pdPASS;															\
-	}																					\
+#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult )           \
+{                                                                                       \
+    *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) );     \
+    if( *( pxResult ) == errQUEUE_BLOCKED )                                             \
+    {                                                                                   \
+        crSET_STATE0( ( xHandle ) );                                                    \
+        *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 );                \
+    }                                                                                   \
+    if( *( pxResult ) == errQUEUE_YIELD )                                               \
+    {                                                                                   \
+        crSET_STATE1( ( xHandle ) );                                                    \
+        *( pxResult ) = pdPASS;                                                         \
+    }                                                                                   \
 }
 
 /**
@@ -645,25 +645,25 @@ void vCoRoutineSchedule( void );
          {
              // The character was successfully posted to the queue.
          }
-		 else
-		 {
-			// Could not post the character to the queue.
-		 }
+         else
+         {
+            // Could not post the character to the queue.
+         }
 
          // Enable the UART Tx interrupt to cause an interrupt in this
-		 // hypothetical UART.  The interrupt will obtain the character
-		 // from the queue and send it.
-		 ENABLE_RX_INTERRUPT();
+         // hypothetical UART.  The interrupt will obtain the character
+         // from the queue and send it.
+         ENABLE_RX_INTERRUPT();
 
-		 // Increment to the next character then block for a fixed period.
-		 // cCharToTx will maintain its value across the delay as it is
-		 // declared static.
-		 cCharToTx++;
-		 if( cCharToTx > 'x' )
-		 {
-			cCharToTx = 'a';
-		 }
-		 crDELAY( 100 );
+         // Increment to the next character then block for a fixed period.
+         // cCharToTx will maintain its value across the delay as it is
+         // declared static.
+         cCharToTx++;
+         if( cCharToTx > 'x' )
+         {
+            cCharToTx = 'a';
+         }
+         crDELAY( 100 );
      }
 
      // All co-routines must end with a call to crEND().
@@ -679,13 +679,13 @@ void vCoRoutineSchedule( void );
      while( UART_TX_REG_EMPTY() )
      {
          // Are there any characters in the queue waiting to be sent?
-		 // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
-		 // is woken by the post - ensuring that only a single co-routine is
-		 // woken no matter how many times we go around this loop.
+         // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
+         // is woken by the post - ensuring that only a single co-routine is
+         // woken no matter how many times we go around this loop.
          if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
-		 {
-			 SEND_CHARACTER( cCharToTx );
-		 }
+         {
+             SEND_CHARACTER( cCharToTx );
+         }
      }
  }
* \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR diff --git a/components/bl602/freertos_riscv_ram/config/deprecated_definitions.h b/components/bl602/freertos_riscv_ram/config/deprecated_definitions.h index 9cece988..20e6efee 100644 --- a/components/bl602/freertos_riscv_ram/config/deprecated_definitions.h +++ b/components/bl602/freertos_riscv_ram/config/deprecated_definitions.h @@ -39,149 +39,149 @@ definitions below remain in the code for backward compatibility only. New projects should not use them. */ #ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT - #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" - typedef void ( __interrupt __far *pxISR )(); + #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" + typedef void ( __interrupt __far *pxISR )(); #endif #ifdef OPEN_WATCOM_FLASH_LITE_186_PORT - #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" - typedef void ( __interrupt __far *pxISR )(); + #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" + typedef void ( __interrupt __far *pxISR )(); #endif #ifdef GCC_MEGA_AVR - #include "../portable/GCC/ATMega323/portmacro.h" + #include "../portable/GCC/ATMega323/portmacro.h" #endif #ifdef IAR_MEGA_AVR - #include "../portable/IAR/ATMega323/portmacro.h" + #include "../portable/IAR/ATMega323/portmacro.h" #endif #ifdef MPLAB_PIC24_PORT - #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" #endif #ifdef MPLAB_DSPIC_PORT - #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" #endif #ifdef MPLAB_PIC18F_PORT - #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" + #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" #endif #ifdef MPLAB_PIC32MX_PORT - #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" + #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" #endif #ifdef _FEDPICC - #include "libFreeRTOS/Include/portmacro.h" + #include "libFreeRTOS/Include/portmacro.h" #endif #ifdef SDCC_CYGNAL - #include "../../Source/portable/SDCC/Cygnal/portmacro.h" + #include "../../Source/portable/SDCC/Cygnal/portmacro.h" #endif #ifdef GCC_ARM7 - #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" + #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" #endif #ifdef GCC_ARM7_ECLIPSE - #include "portmacro.h" + #include "portmacro.h" #endif #ifdef ROWLEY_LPC23xx - #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" + #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" #endif #ifdef IAR_MSP430 - #include "..\..\Source\portable\IAR\MSP430\portmacro.h" + #include "..\..\Source\portable\IAR\MSP430\portmacro.h" #endif #ifdef GCC_MSP430 - #include "../../Source/portable/GCC/MSP430F449/portmacro.h" + #include "../../Source/portable/GCC/MSP430F449/portmacro.h" #endif #ifdef ROWLEY_MSP430 - #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" + #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" #endif #ifdef ARM7_LPC21xx_KEIL_RVDS - #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" + #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" #endif #ifdef SAM7_GCC - #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" + #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" #endif #ifdef SAM7_IAR - #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" + #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" #endif #ifdef SAM9XE_IAR - #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" + #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" #endif #ifdef LPC2000_IAR - #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" + #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" #endif #ifdef STR71X_IAR - #include "..\..\Source\portable\IAR\STR71x\portmacro.h" + #include "..\..\Source\portable\IAR\STR71x\portmacro.h" #endif #ifdef STR75X_IAR - #include "..\..\Source\portable\IAR\STR75x\portmacro.h" + #include "..\..\Source\portable\IAR\STR75x\portmacro.h" #endif #ifdef STR75X_GCC - #include "..\..\Source\portable\GCC\STR75x\portmacro.h" + #include "..\..\Source\portable\GCC\STR75x\portmacro.h" #endif #ifdef STR91X_IAR - #include "..\..\Source\portable\IAR\STR91x\portmacro.h" + #include "..\..\Source\portable\IAR\STR91x\portmacro.h" #endif #ifdef GCC_H8S - #include "../../Source/portable/GCC/H8S2329/portmacro.h" + #include "../../Source/portable/GCC/H8S2329/portmacro.h" #endif #ifdef GCC_AT91FR40008 - #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" + #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" #endif #ifdef RVDS_ARMCM3_LM3S102 - #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" + #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" #endif #ifdef GCC_ARMCM3_LM3S102 - #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" #endif #ifdef GCC_ARMCM3 - #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" #endif #ifdef IAR_ARM_CM3 - #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" #endif #ifdef IAR_ARMCM3_LM - #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" #endif #ifdef HCS12_CODE_WARRIOR - #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" + #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" #endif #ifdef MICROBLAZE_GCC - #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" + #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" #endif #ifdef TERN_EE - #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" + #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" #endif #ifdef GCC_HCS12 - #include "../../Source/portable/GCC/HCS12/portmacro.h" + #include "../../Source/portable/GCC/HCS12/portmacro.h" #endif #ifdef GCC_MCF5235 @@ -189,90 +189,90 @@ projects should not use them. */ #endif #ifdef COLDFIRE_V2_GCC - #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" + #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" #endif #ifdef COLDFIRE_V2_CODEWARRIOR - #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" + #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" #endif #ifdef GCC_PPC405 - #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" + #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" #endif #ifdef GCC_PPC440 - #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" + #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" #endif #ifdef _16FX_SOFTUNE - #include "..\..\Source\portable\Softune\MB96340\portmacro.h" + #include "..\..\Source\portable\Softune\MB96340\portmacro.h" #endif #ifdef BCC_INDUSTRIAL_PC_PORT - /* A short file name has to be used in place of the normal - FreeRTOSConfig.h when using the Borland compiler. */ - #include "frconfig.h" - #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" + /* A short file name has to be used in place of the normal + FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef BCC_FLASH_LITE_186_PORT - /* A short file name has to be used in place of the normal - FreeRTOSConfig.h when using the Borland compiler. */ - #include "frconfig.h" - #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" + /* A short file name has to be used in place of the normal + FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" typedef void ( __interrupt __far *pxISR )(); #endif #ifdef __GNUC__ #ifdef __AVR32_AVR32A__ - #include "portmacro.h" + #include "portmacro.h" #endif #endif #ifdef __ICCAVR32__ #ifdef __CORE__ #if __CORE__ == __AVR32A__ - #include "portmacro.h" + #include "portmacro.h" #endif #endif #endif #ifdef __91467D - #include "portmacro.h" + #include "portmacro.h" #endif #ifdef __96340 - #include "portmacro.h" + #include "portmacro.h" #endif #ifdef __IAR_V850ES_Fx3__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx3__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx3_L__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Jx2__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_V850ES_Hx2__ - #include "../../Source/portable/IAR/V850ES/portmacro.h" + #include "../../Source/portable/IAR/V850ES/portmacro.h" #endif #ifdef __IAR_78K0R_Kx3__ - #include "../../Source/portable/IAR/78K0R/portmacro.h" + #include "../../Source/portable/IAR/78K0R/portmacro.h" #endif #ifdef __IAR_78K0R_Kx3L__ - #include "../../Source/portable/IAR/78K0R/portmacro.h" + #include "../../Source/portable/IAR/78K0R/portmacro.h" #endif #endif /* DEPRECATED_DEFINITIONS_H */ diff --git a/components/bl602/freertos_riscv_ram/config/event_groups.h b/components/bl602/freertos_riscv_ram/config/event_groups.h index 1f38bdb7..056152b4 100644 --- a/components/bl602/freertos_riscv_ram/config/event_groups.h +++ b/components/bl602/freertos_riscv_ram/config/event_groups.h @@ -29,7 +29,7 @@ #define EVENT_GROUPS_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" + #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" #endif /* FreeRTOS includes. */ @@ -123,28 +123,28 @@ typedef TickType_t EventBits_t; * * Example usage:
-	// Declare a variable to hold the created event group.
-	EventGroupHandle_t xCreatedEventGroup;
+    // Declare a variable to hold the created event group.
+    EventGroupHandle_t xCreatedEventGroup;
 
-	// Attempt to create the event group.
-	xCreatedEventGroup = xEventGroupCreate();
+    // Attempt to create the event group.
+    xCreatedEventGroup = xEventGroupCreate();
 
-	// Was the event group created successfully?
-	if( xCreatedEventGroup == NULL )
-	{
-		// The event group was not created because there was insufficient
-		// FreeRTOS heap available.
-	}
-	else
-	{
-		// The event group was created.
-	}
+    // Was the event group created successfully?
+    if( xCreatedEventGroup == NULL )
+    {
+        // The event group was not created because there was insufficient
+        // FreeRTOS heap available.
+    }
+    else
+    {
+        // The event group was created.
+    }
    
* \defgroup xEventGroupCreate xEventGroupCreate * \ingroup EventGroup */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION; + EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION; #endif /** @@ -182,32 +182,32 @@ typedef TickType_t EventBits_t; * * Example usage:
-	// StaticEventGroup_t is a publicly accessible structure that has the same
-	// size and alignment requirements as the real event group structure.  It is
-	// provided as a mechanism for applications to know the size of the event
-	// group (which is dependent on the architecture and configuration file
-	// settings) without breaking the strict data hiding policy by exposing the
-	// real event group internals.  This StaticEventGroup_t variable is passed
-	// into the xSemaphoreCreateEventGroupStatic() function and is used to store
-	// the event group's data structures
-	StaticEventGroup_t xEventGroupBuffer;
+    // StaticEventGroup_t is a publicly accessible structure that has the same
+    // size and alignment requirements as the real event group structure.  It is
+    // provided as a mechanism for applications to know the size of the event
+    // group (which is dependent on the architecture and configuration file
+    // settings) without breaking the strict data hiding policy by exposing the
+    // real event group internals.  This StaticEventGroup_t variable is passed
+    // into the xSemaphoreCreateEventGroupStatic() function and is used to store
+    // the event group's data structures
+    StaticEventGroup_t xEventGroupBuffer;
 
-	// Create the event group without dynamically allocating any memory.
-	xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer );
+    // Create the event group without dynamically allocating any memory.
+    xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer );
    
*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION; + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION; #endif /** * event_groups.h *
-	EventBits_t xEventGroupWaitBits( 	EventGroupHandle_t xEventGroup,
-										const EventBits_t uxBitsToWaitFor,
-										const BaseType_t xClearOnExit,
-										const BaseType_t xWaitForAllBits,
-										const TickType_t xTicksToWait );
+    EventBits_t xEventGroupWaitBits(    EventGroupHandle_t xEventGroup,
+                                        const EventBits_t uxBitsToWaitFor,
+                                        const BaseType_t xClearOnExit,
+                                        const BaseType_t xWaitForAllBits,
+                                        const TickType_t xTicksToWait );
  
* * [Potentially] block to wait for one or more bits to be set within a @@ -253,40 +253,40 @@ typedef TickType_t EventBits_t; * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    void aFunction( EventGroupHandle_t xEventGroup )
    {
    EventBits_t uxBits;
    const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
 
-		// Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
-		// the event group.  Clear the bits before exiting.
-		uxBits = xEventGroupWaitBits(
-					xEventGroup,	// The event group being tested.
-					BIT_0 | BIT_4,	// The bits within the event group to wait for.
-					pdTRUE,			// BIT_0 and BIT_4 should be cleared before returning.
-					pdFALSE,		// Don't wait for both bits, either bit will do.
-					xTicksToWait );	// Wait a maximum of 100ms for either bit to be set.
+        // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
+        // the event group.  Clear the bits before exiting.
+        uxBits = xEventGroupWaitBits(
+                    xEventGroup,    // The event group being tested.
+                    BIT_0 | BIT_4,  // The bits within the event group to wait for.
+                    pdTRUE,         // BIT_0 and BIT_4 should be cleared before returning.
+                    pdFALSE,        // Don't wait for both bits, either bit will do.
+                    xTicksToWait ); // Wait a maximum of 100ms for either bit to be set.
 
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// xEventGroupWaitBits() returned because both bits were set.
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// xEventGroupWaitBits() returned because just BIT_0 was set.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// xEventGroupWaitBits() returned because just BIT_4 was set.
-		}
-		else
-		{
-			// xEventGroupWaitBits() returned because xTicksToWait ticks passed
-			// without either BIT_0 or BIT_4 becoming set.
-		}
+        if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+        {
+            // xEventGroupWaitBits() returned because both bits were set.
+        }
+        else if( ( uxBits & BIT_0 ) != 0 )
+        {
+            // xEventGroupWaitBits() returned because just BIT_0 was set.
+        }
+        else if( ( uxBits & BIT_4 ) != 0 )
+        {
+            // xEventGroupWaitBits() returned because just BIT_4 was set.
+        }
+        else
+        {
+            // xEventGroupWaitBits() returned because xTicksToWait ticks passed
+            // without either BIT_0 or BIT_4 becoming set.
+        }
    }
    
* \defgroup xEventGroupWaitBits xEventGroupWaitBits @@ -297,7 +297,7 @@ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits /** * event_groups.h *
-	EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
+    EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
  
* * Clear bits within an event group. This function cannot be called from an @@ -313,37 +313,37 @@ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    void aFunction( EventGroupHandle_t xEventGroup )
    {
    EventBits_t uxBits;
 
-		// Clear bit 0 and bit 4 in xEventGroup.
-		uxBits = xEventGroupClearBits(
-								xEventGroup,	// The event group being updated.
-								BIT_0 | BIT_4 );// The bits being cleared.
+        // Clear bit 0 and bit 4 in xEventGroup.
+        uxBits = xEventGroupClearBits(
+                                xEventGroup,    // The event group being updated.
+                                BIT_0 | BIT_4 );// The bits being cleared.
 
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// Both bit 0 and bit 4 were set before xEventGroupClearBits() was
-			// called.  Both will now be clear (not set).
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// Bit 0 was set before xEventGroupClearBits() was called.  It will
-			// now be clear.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// Bit 4 was set before xEventGroupClearBits() was called.  It will
-			// now be clear.
-		}
-		else
-		{
-			// Neither bit 0 nor bit 4 were set in the first place.
-		}
+        if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+        {
+            // Both bit 0 and bit 4 were set before xEventGroupClearBits() was
+            // called.  Both will now be clear (not set).
+        }
+        else if( ( uxBits & BIT_0 ) != 0 )
+        {
+            // Bit 0 was set before xEventGroupClearBits() was called.  It will
+            // now be clear.
+        }
+        else if( ( uxBits & BIT_4 ) != 0 )
+        {
+            // Bit 4 was set before xEventGroupClearBits() was called.  It will
+            // now be clear.
+        }
+        else
+        {
+            // Neither bit 0 nor bit 4 were set in the first place.
+        }
    }
    
* \defgroup xEventGroupClearBits xEventGroupClearBits @@ -354,7 +354,7 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit /** * event_groups.h *
-	BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+    BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
  
* * A version of xEventGroupClearBits() that can be called from an interrupt. @@ -381,8 +381,8 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    // An event group which it is assumed has already been created by a call to
    // xEventGroupCreate().
@@ -390,30 +390,30 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit
 
    void anInterruptHandler( void )
    {
-		// Clear bit 0 and bit 4 in xEventGroup.
-		xResult = xEventGroupClearBitsFromISR(
-							xEventGroup,	 // The event group being updated.
-							BIT_0 | BIT_4 ); // The bits being set.
+        // Clear bit 0 and bit 4 in xEventGroup.
+        xResult = xEventGroupClearBitsFromISR(
+                            xEventGroup,     // The event group being updated.
+                            BIT_0 | BIT_4 ); // The bits being set.
 
-		if( xResult == pdPASS )
-		{
-			// The message was posted successfully.
-		}
+        if( xResult == pdPASS )
+        {
+            // The message was posted successfully.
+        }
   }
    
* \defgroup xEventGroupClearBitsFromISR xEventGroupClearBitsFromISR * \ingroup EventGroup */ #if( configUSE_TRACE_FACILITY == 1 ) - BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; #else - #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) + #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) #endif /** * event_groups.h *
-	EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+    EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
  
* * Set bits within an event group. @@ -441,42 +441,42 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    void aFunction( EventGroupHandle_t xEventGroup )
    {
    EventBits_t uxBits;
 
-		// Set bit 0 and bit 4 in xEventGroup.
-		uxBits = xEventGroupSetBits(
-							xEventGroup,	// The event group being updated.
-							BIT_0 | BIT_4 );// The bits being set.
+        // Set bit 0 and bit 4 in xEventGroup.
+        uxBits = xEventGroupSetBits(
+                            xEventGroup,    // The event group being updated.
+                            BIT_0 | BIT_4 );// The bits being set.
 
-		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
-		{
-			// Both bit 0 and bit 4 remained set when the function returned.
-		}
-		else if( ( uxBits & BIT_0 ) != 0 )
-		{
-			// Bit 0 remained set when the function returned, but bit 4 was
-			// cleared.  It might be that bit 4 was cleared automatically as a
-			// task that was waiting for bit 4 was removed from the Blocked
-			// state.
-		}
-		else if( ( uxBits & BIT_4 ) != 0 )
-		{
-			// Bit 4 remained set when the function returned, but bit 0 was
-			// cleared.  It might be that bit 0 was cleared automatically as a
-			// task that was waiting for bit 0 was removed from the Blocked
-			// state.
-		}
-		else
-		{
-			// Neither bit 0 nor bit 4 remained set.  It might be that a task
-			// was waiting for both of the bits to be set, and the bits were
-			// cleared as the task left the Blocked state.
-		}
+        if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+        {
+            // Both bit 0 and bit 4 remained set when the function returned.
+        }
+        else if( ( uxBits & BIT_0 ) != 0 )
+        {
+            // Bit 0 remained set when the function returned, but bit 4 was
+            // cleared.  It might be that bit 4 was cleared automatically as a
+            // task that was waiting for bit 4 was removed from the Blocked
+            // state.
+        }
+        else if( ( uxBits & BIT_4 ) != 0 )
+        {
+            // Bit 4 remained set when the function returned, but bit 0 was
+            // cleared.  It might be that bit 0 was cleared automatically as a
+            // task that was waiting for bit 0 was removed from the Blocked
+            // state.
+        }
+        else
+        {
+            // Neither bit 0 nor bit 4 remained set.  It might be that a task
+            // was waiting for both of the bits to be set, and the bits were
+            // cleared as the task left the Blocked state.
+        }
    }
    
* \defgroup xEventGroupSetBits xEventGroupSetBits @@ -487,7 +487,7 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_ /** * event_groups.h *
-	BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
+    BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
  
* * A version of xEventGroupSetBits() that can be called from an interrupt. @@ -522,8 +522,8 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_ * * Example usage:
-   #define BIT_0	( 1 << 0 )
-   #define BIT_4	( 1 << 4 )
+   #define BIT_0    ( 1 << 0 )
+   #define BIT_4    ( 1 << 4 )
 
    // An event group which it is assumed has already been created by a call to
    // xEventGroupCreate().
@@ -533,42 +533,42 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_
    {
    BaseType_t xHigherPriorityTaskWoken, xResult;
 
-		// xHigherPriorityTaskWoken must be initialised to pdFALSE.
-		xHigherPriorityTaskWoken = pdFALSE;
+        // xHigherPriorityTaskWoken must be initialised to pdFALSE.
+        xHigherPriorityTaskWoken = pdFALSE;
 
-		// Set bit 0 and bit 4 in xEventGroup.
-		xResult = xEventGroupSetBitsFromISR(
-							xEventGroup,	// The event group being updated.
-							BIT_0 | BIT_4   // The bits being set.
-							&xHigherPriorityTaskWoken );
+        // Set bit 0 and bit 4 in xEventGroup.
+        xResult = xEventGroupSetBitsFromISR(
+                            xEventGroup,    // The event group being updated.
+                            BIT_0 | BIT_4   // The bits being set.
+                            &xHigherPriorityTaskWoken );
 
-		// Was the message posted successfully?
-		if( xResult == pdPASS )
-		{
-			// If xHigherPriorityTaskWoken is now set to pdTRUE then a context
-			// switch should be requested.  The macro used is port specific and
-			// will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
-			// refer to the documentation page for the port being used.
-			portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
-		}
+        // Was the message posted successfully?
+        if( xResult == pdPASS )
+        {
+            // If xHigherPriorityTaskWoken is now set to pdTRUE then a context
+            // switch should be requested.  The macro used is port specific and
+            // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
+            // refer to the documentation page for the port being used.
+            portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
+        }
   }
    
* \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR * \ingroup EventGroup */ #if( configUSE_TRACE_FACILITY == 1 ) - BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; #else - #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) + #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) #endif /** * event_groups.h *
-	EventBits_t xEventGroupSync(	EventGroupHandle_t xEventGroup,
-									const EventBits_t uxBitsToSet,
-									const EventBits_t uxBitsToWaitFor,
-									TickType_t xTicksToWait );
+    EventBits_t xEventGroupSync(    EventGroupHandle_t xEventGroup,
+                                    const EventBits_t uxBitsToSet,
+                                    const EventBits_t uxBitsToWaitFor,
+                                    TickType_t xTicksToWait );
  
* * Atomically set bits within an event group, then wait for a combination of @@ -610,9 +610,9 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_ * Example usage:
  // Bits used by the three tasks.
- #define TASK_0_BIT		( 1 << 0 )
- #define TASK_1_BIT		( 1 << 1 )
- #define TASK_2_BIT		( 1 << 2 )
+ #define TASK_0_BIT     ( 1 << 0 )
+ #define TASK_1_BIT     ( 1 << 1 )
+ #define TASK_2_BIT     ( 1 << 2 )
 
  #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
 
@@ -625,61 +625,61 @@ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_
  EventBits_t uxReturn;
  TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
 
-	 for( ;; )
-	 {
-		// Perform task functionality here.
+     for( ;; )
+     {
+        // Perform task functionality here.
 
-		// Set bit 0 in the event flag to note this task has reached the
-		// sync point.  The other two tasks will set the other two bits defined
-		// by ALL_SYNC_BITS.  All three tasks have reached the synchronisation
-		// point when all the ALL_SYNC_BITS are set.  Wait a maximum of 100ms
-		// for this to happen.
-		uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
+        // Set bit 0 in the event flag to note this task has reached the
+        // sync point.  The other two tasks will set the other two bits defined
+        // by ALL_SYNC_BITS.  All three tasks have reached the synchronisation
+        // point when all the ALL_SYNC_BITS are set.  Wait a maximum of 100ms
+        // for this to happen.
+        uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
 
-		if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
-		{
-			// All three tasks reached the synchronisation point before the call
-			// to xEventGroupSync() timed out.
-		}
-	}
+        if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
+        {
+            // All three tasks reached the synchronisation point before the call
+            // to xEventGroupSync() timed out.
+        }
+    }
  }
 
  void vTask1( void *pvParameters )
  {
-	 for( ;; )
-	 {
-		// Perform task functionality here.
+     for( ;; )
+     {
+        // Perform task functionality here.
 
-		// Set bit 1 in the event flag to note this task has reached the
-		// synchronisation point.  The other two tasks will set the other two
-		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
-		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
-		// indefinitely for this to happen.
-		xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+        // Set bit 1 in the event flag to note this task has reached the
+        // synchronisation point.  The other two tasks will set the other two
+        // bits defined by ALL_SYNC_BITS.  All three tasks have reached the
+        // synchronisation point when all the ALL_SYNC_BITS are set.  Wait
+        // indefinitely for this to happen.
+        xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
 
-		// xEventGroupSync() was called with an indefinite block time, so
-		// this task will only reach here if the syncrhonisation was made by all
-		// three tasks, so there is no need to test the return value.
-	 }
+        // xEventGroupSync() was called with an indefinite block time, so
+        // this task will only reach here if the syncrhonisation was made by all
+        // three tasks, so there is no need to test the return value.
+     }
  }
 
  void vTask2( void *pvParameters )
  {
-	 for( ;; )
-	 {
-		// Perform task functionality here.
+     for( ;; )
+     {
+        // Perform task functionality here.
 
-		// Set bit 2 in the event flag to note this task has reached the
-		// synchronisation point.  The other two tasks will set the other two
-		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
-		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
-		// indefinitely for this to happen.
-		xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+        // Set bit 2 in the event flag to note this task has reached the
+        // synchronisation point.  The other two tasks will set the other two
+        // bits defined by ALL_SYNC_BITS.  All three tasks have reached the
+        // synchronisation point when all the ALL_SYNC_BITS are set.  Wait
+        // indefinitely for this to happen.
+        xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
 
-		// xEventGroupSync() was called with an indefinite block time, so
-		// this task will only reach here if the syncrhonisation was made by all
-		// three tasks, so there is no need to test the return value.
-	}
+        // xEventGroupSync() was called with an indefinite block time, so
+        // this task will only reach here if the syncrhonisation was made by all
+        // three tasks, so there is no need to test the return value.
+    }
  }
 
  
@@ -692,7 +692,7 @@ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t u /** * event_groups.h *
-	EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
+    EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
  
* * Returns the current value of the bits in an event group. This function @@ -710,7 +710,7 @@ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t u /** * event_groups.h *
-	EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
+    EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
  
* * A version of xEventGroupGetBits() that can be called from an ISR. @@ -727,7 +727,7 @@ EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEG /** * event_groups.h *
-	void xEventGroupDelete( EventGroupHandle_t xEventGroup );
+    void xEventGroupDelete( EventGroupHandle_t xEventGroup );
  
* * Delete an event group that was previously created by a call to @@ -744,8 +744,8 @@ void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToCl #if (configUSE_TRACE_FACILITY == 1) - UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) PRIVILEGED_FUNCTION; - void vEventGroupSetNumber( void* xEventGroup, UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) PRIVILEGED_FUNCTION; + void vEventGroupSetNumber( void* xEventGroup, UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; #endif #ifdef __cplusplus diff --git a/components/bl602/freertos_riscv_ram/config/list.h b/components/bl602/freertos_riscv_ram/config/list.h index 2fb6775f..fe90782a 100644 --- a/components/bl602/freertos_riscv_ram/config/list.h +++ b/components/bl602/freertos_riscv_ram/config/list.h @@ -54,7 +54,7 @@ */ #ifndef INC_FREERTOS_H - #error FreeRTOS.h must be included before list.h + #error FreeRTOS.h must be included before list.h #endif #ifndef LIST_H @@ -89,7 +89,7 @@ * "#define configLIST_VOLATILE volatile" */ #ifndef configLIST_VOLATILE - #define configLIST_VOLATILE + #define configLIST_VOLATILE #endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ #ifdef __cplusplus @@ -102,34 +102,34 @@ the application. These may catch the list data structures being overwritten in memory. They will not catch data errors caused by incorrect configuration or use of FreeRTOS.*/ #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) - /* Define the macros to do nothing. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) - #define listTEST_LIST_INTEGRITY( pxList ) + /* Define the macros to do nothing. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) + #define listTEST_LIST_INTEGRITY( pxList ) #else - /* Define macros that add new members into the list structures. */ - #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; - #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; - #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; - #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; + /* Define macros that add new members into the list structures. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; - /* Define macros that set the new structure members to known values. */ - #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE - #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + /* Define macros that set the new structure members to known values. */ + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE - /* Define macros that will assert if one of the structure members does not - contain its expected value. */ - #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) - #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + /* Define macros that will assert if one of the structure members does not + contain its expected value. */ + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) #endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ @@ -139,22 +139,22 @@ use of FreeRTOS.*/ struct xLIST; struct xLIST_ITEM { - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ - struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ - void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ - struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ - listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ + struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ + void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ + struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ + listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ }; -typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ +typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ struct xMINI_LIST_ITEM { - listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - configLIST_VOLATILE TickType_t xItemValue; - struct xLIST_ITEM * configLIST_VOLATILE pxNext; - struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; + struct xLIST_ITEM * configLIST_VOLATILE pxNext; + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; }; typedef struct xMINI_LIST_ITEM MiniListItem_t; @@ -163,11 +163,11 @@ typedef struct xMINI_LIST_ITEM MiniListItem_t; */ typedef struct xLIST { - listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - volatile UBaseType_t uxNumberOfItems; - ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ - MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ - listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + volatile UBaseType_t uxNumberOfItems; + ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ + MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ + listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ } List_t; /* @@ -177,7 +177,7 @@ typedef struct xLIST * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER * \ingroup LinkedList */ -#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) +#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) /* * Access macro to get the owner of a list item. The owner of a list item @@ -186,7 +186,7 @@ typedef struct xLIST * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER * \ingroup LinkedList */ -#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) +#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) /* * Access macro to set the value of the list item. In most cases the value is @@ -195,7 +195,7 @@ typedef struct xLIST * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE * \ingroup LinkedList */ -#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) +#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) /* * Access macro to retrieve the value of the list item. The value can @@ -205,7 +205,7 @@ typedef struct xLIST * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE * \ingroup LinkedList */ -#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) +#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) /* * Access macro to retrieve the value of the list item at the head of a given @@ -214,7 +214,7 @@ typedef struct xLIST * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE * \ingroup LinkedList */ -#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) +#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) /* * Return the list item at the head of the list. @@ -222,7 +222,7 @@ typedef struct xLIST * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY * \ingroup LinkedList */ -#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) +#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) /* * Return the list item at the head of the list. @@ -230,7 +230,7 @@ typedef struct xLIST * \page listGET_NEXT listGET_NEXT * \ingroup LinkedList */ -#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) +#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) /* * Return the list item that marks the end of the list @@ -238,7 +238,7 @@ typedef struct xLIST * \page listGET_END_MARKER listGET_END_MARKER * \ingroup LinkedList */ -#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) +#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) /* * Access macro to determine if a list contains any items. The macro will @@ -247,12 +247,12 @@ typedef struct xLIST * \page listLIST_IS_EMPTY listLIST_IS_EMPTY * \ingroup LinkedList */ -#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) +#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) /* * Access macro to return the number of items in the list. */ -#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) +#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) /* * Access function to obtain the owner of the next entry in a list. @@ -274,17 +274,17 @@ typedef struct xLIST * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY * \ingroup LinkedList */ -#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ -{ \ -List_t * const pxConstList = ( pxList ); \ - /* Increment the index to the next item and return the item, ensuring */ \ - /* we don't return the marker used at the end of the list. */ \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ - { \ - ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ - } \ - ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ +#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ +{ \ +List_t * const pxConstList = ( pxList ); \ + /* Increment the index to the next item and return the item, ensuring */ \ + /* we don't return the marker used at the end of the list. */ \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ + { \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + } \ + ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ } diff --git a/components/bl602/freertos_riscv_ram/config/message_buffer.h b/components/bl602/freertos_riscv_ram/config/message_buffer.h index 88f38d25..04b6efec 100644 --- a/components/bl602/freertos_riscv_ram/config/message_buffer.h +++ b/components/bl602/freertos_riscv_ram/config/message_buffer.h @@ -795,4 +795,4 @@ BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xStreamB } /* extern "C" */ #endif -#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ +#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/components/bl602/freertos_riscv_ram/config/mpu_wrappers.h b/components/bl602/freertos_riscv_ram/config/mpu_wrappers.h index 711393f6..a4e19741 100644 --- a/components/bl602/freertos_riscv_ram/config/mpu_wrappers.h +++ b/components/bl602/freertos_riscv_ram/config/mpu_wrappers.h @@ -32,152 +32,152 @@ only for ports that are using the MPU. */ #ifdef portUSING_MPU_WRAPPERS - /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is - included from queue.c or task.c to prevent it from having an effect within - those files. */ - #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is + included from queue.c or task.c to prevent it from having an effect within + those files. */ + #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE - /* - * Map standard (non MPU) API functions to equivalents that start - * "MPU_". This will cause the application code to call the MPU_ - * version, which wraps the non-MPU version with privilege promoting - * then demoting code, so the kernel code always runs will full - * privileges. - */ + /* + * Map standard (non MPU) API functions to equivalents that start + * "MPU_". This will cause the application code to call the MPU_ + * version, which wraps the non-MPU version with privilege promoting + * then demoting code, so the kernel code always runs will full + * privileges. + */ - /* Map standard tasks.h API functions to the MPU equivalents. */ - #define xTaskCreate MPU_xTaskCreate - #define xTaskCreateStatic MPU_xTaskCreateStatic - #define xTaskCreateRestricted MPU_xTaskCreateRestricted - #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions - #define vTaskDelete MPU_vTaskDelete - #define vTaskDelay MPU_vTaskDelay - #define vTaskDelayUntil MPU_vTaskDelayUntil - #define xTaskAbortDelay MPU_xTaskAbortDelay - #define uxTaskPriorityGet MPU_uxTaskPriorityGet - #define eTaskGetState MPU_eTaskGetState - #define vTaskGetInfo MPU_vTaskGetInfo - #define vTaskPrioritySet MPU_vTaskPrioritySet - #define vTaskSuspend MPU_vTaskSuspend - #define vTaskResume MPU_vTaskResume - #define vTaskSuspendAll MPU_vTaskSuspendAll - #define xTaskResumeAll MPU_xTaskResumeAll - #define xTaskGetTickCount MPU_xTaskGetTickCount - #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks - #define pcTaskGetName MPU_pcTaskGetName - #define xTaskGetHandle MPU_xTaskGetHandle - #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark - #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 - #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag - #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag - #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer - #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer - #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook - #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle - #define uxTaskGetSystemState MPU_uxTaskGetSystemState - #define vTaskList MPU_vTaskList - #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats - #define xTaskGetIdleRunTimeCounter MPU_xTaskGetIdleRunTimeCounter - #define xTaskGenericNotify MPU_xTaskGenericNotify - #define xTaskNotifyWait MPU_xTaskNotifyWait - #define ulTaskNotifyTake MPU_ulTaskNotifyTake - #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear + /* Map standard tasks.h API functions to the MPU equivalents. */ + #define xTaskCreate MPU_xTaskCreate + #define xTaskCreateStatic MPU_xTaskCreateStatic + #define xTaskCreateRestricted MPU_xTaskCreateRestricted + #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions + #define vTaskDelete MPU_vTaskDelete + #define vTaskDelay MPU_vTaskDelay + #define vTaskDelayUntil MPU_vTaskDelayUntil + #define xTaskAbortDelay MPU_xTaskAbortDelay + #define uxTaskPriorityGet MPU_uxTaskPriorityGet + #define eTaskGetState MPU_eTaskGetState + #define vTaskGetInfo MPU_vTaskGetInfo + #define vTaskPrioritySet MPU_vTaskPrioritySet + #define vTaskSuspend MPU_vTaskSuspend + #define vTaskResume MPU_vTaskResume + #define vTaskSuspendAll MPU_vTaskSuspendAll + #define xTaskResumeAll MPU_xTaskResumeAll + #define xTaskGetTickCount MPU_xTaskGetTickCount + #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks + #define pcTaskGetName MPU_pcTaskGetName + #define xTaskGetHandle MPU_xTaskGetHandle + #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark + #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 + #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag + #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag + #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer + #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer + #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook + #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle + #define uxTaskGetSystemState MPU_uxTaskGetSystemState + #define vTaskList MPU_vTaskList + #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats + #define xTaskGetIdleRunTimeCounter MPU_xTaskGetIdleRunTimeCounter + #define xTaskGenericNotify MPU_xTaskGenericNotify + #define xTaskNotifyWait MPU_xTaskNotifyWait + #define ulTaskNotifyTake MPU_ulTaskNotifyTake + #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear - #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle - #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState - #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut - #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState + #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle + #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState + #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut + #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState - /* Map standard queue.h API functions to the MPU equivalents. */ - #define xQueueGenericSend MPU_xQueueGenericSend - #define xQueueReceive MPU_xQueueReceive - #define xQueuePeek MPU_xQueuePeek - #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake - #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting - #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable - #define vQueueDelete MPU_vQueueDelete - #define xQueueCreateMutex MPU_xQueueCreateMutex - #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic - #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore - #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic - #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder - #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive - #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive - #define xQueueGenericCreate MPU_xQueueGenericCreate - #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic - #define xQueueCreateSet MPU_xQueueCreateSet - #define xQueueAddToSet MPU_xQueueAddToSet - #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet - #define xQueueSelectFromSet MPU_xQueueSelectFromSet - #define xQueueGenericReset MPU_xQueueGenericReset + /* Map standard queue.h API functions to the MPU equivalents. */ + #define xQueueGenericSend MPU_xQueueGenericSend + #define xQueueReceive MPU_xQueueReceive + #define xQueuePeek MPU_xQueuePeek + #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake + #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting + #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable + #define vQueueDelete MPU_vQueueDelete + #define xQueueCreateMutex MPU_xQueueCreateMutex + #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic + #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore + #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic + #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder + #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive + #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive + #define xQueueGenericCreate MPU_xQueueGenericCreate + #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic + #define xQueueCreateSet MPU_xQueueCreateSet + #define xQueueAddToSet MPU_xQueueAddToSet + #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet + #define xQueueSelectFromSet MPU_xQueueSelectFromSet + #define xQueueGenericReset MPU_xQueueGenericReset - #if( configQUEUE_REGISTRY_SIZE > 0 ) - #define vQueueAddToRegistry MPU_vQueueAddToRegistry - #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue - #define pcQueueGetName MPU_pcQueueGetName - #endif + #if( configQUEUE_REGISTRY_SIZE > 0 ) + #define vQueueAddToRegistry MPU_vQueueAddToRegistry + #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue + #define pcQueueGetName MPU_pcQueueGetName + #endif - /* Map standard timer.h API functions to the MPU equivalents. */ - #define xTimerCreate MPU_xTimerCreate - #define xTimerCreateStatic MPU_xTimerCreateStatic - #define pvTimerGetTimerID MPU_pvTimerGetTimerID - #define vTimerSetTimerID MPU_vTimerSetTimerID - #define xTimerIsTimerActive MPU_xTimerIsTimerActive - #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle - #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall - #define pcTimerGetName MPU_pcTimerGetName - #define vTimerSetReloadMode MPU_vTimerSetReloadMode - #define xTimerGetPeriod MPU_xTimerGetPeriod - #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime - #define xTimerGenericCommand MPU_xTimerGenericCommand + /* Map standard timer.h API functions to the MPU equivalents. */ + #define xTimerCreate MPU_xTimerCreate + #define xTimerCreateStatic MPU_xTimerCreateStatic + #define pvTimerGetTimerID MPU_pvTimerGetTimerID + #define vTimerSetTimerID MPU_vTimerSetTimerID + #define xTimerIsTimerActive MPU_xTimerIsTimerActive + #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle + #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall + #define pcTimerGetName MPU_pcTimerGetName + #define vTimerSetReloadMode MPU_vTimerSetReloadMode + #define xTimerGetPeriod MPU_xTimerGetPeriod + #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime + #define xTimerGenericCommand MPU_xTimerGenericCommand - /* Map standard event_group.h API functions to the MPU equivalents. */ - #define xEventGroupCreate MPU_xEventGroupCreate - #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic - #define xEventGroupWaitBits MPU_xEventGroupWaitBits - #define xEventGroupClearBits MPU_xEventGroupClearBits - #define xEventGroupSetBits MPU_xEventGroupSetBits - #define xEventGroupSync MPU_xEventGroupSync - #define vEventGroupDelete MPU_vEventGroupDelete + /* Map standard event_group.h API functions to the MPU equivalents. */ + #define xEventGroupCreate MPU_xEventGroupCreate + #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic + #define xEventGroupWaitBits MPU_xEventGroupWaitBits + #define xEventGroupClearBits MPU_xEventGroupClearBits + #define xEventGroupSetBits MPU_xEventGroupSetBits + #define xEventGroupSync MPU_xEventGroupSync + #define vEventGroupDelete MPU_vEventGroupDelete - /* Map standard message/stream_buffer.h API functions to the MPU - equivalents. */ - #define xStreamBufferSend MPU_xStreamBufferSend - #define xStreamBufferReceive MPU_xStreamBufferReceive - #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes - #define vStreamBufferDelete MPU_vStreamBufferDelete - #define xStreamBufferIsFull MPU_xStreamBufferIsFull - #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty - #define xStreamBufferReset MPU_xStreamBufferReset - #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable - #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable - #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel - #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate - #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic + /* Map standard message/stream_buffer.h API functions to the MPU + equivalents. */ + #define xStreamBufferSend MPU_xStreamBufferSend + #define xStreamBufferReceive MPU_xStreamBufferReceive + #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes + #define vStreamBufferDelete MPU_vStreamBufferDelete + #define xStreamBufferIsFull MPU_xStreamBufferIsFull + #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty + #define xStreamBufferReset MPU_xStreamBufferReset + #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable + #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable + #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel + #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate + #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic - /* Remove the privileged function macro, but keep the PRIVILEGED_DATA - macro so applications can place data in privileged access sections - (useful when using statically allocated objects). */ - #define PRIVILEGED_FUNCTION - #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) - #define FREERTOS_SYSTEM_CALL + /* Remove the privileged function macro, but keep the PRIVILEGED_DATA + macro so applications can place data in privileged access sections + (useful when using statically allocated objects). */ + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL - #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ - /* Ensure API functions go in the privileged execution section. */ - #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) - #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) - #define FREERTOS_SYSTEM_CALL __attribute__((section( "freertos_system_calls"))) + /* Ensure API functions go in the privileged execution section. */ + #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL __attribute__((section( "freertos_system_calls"))) - #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ #else /* portUSING_MPU_WRAPPERS */ - #define PRIVILEGED_FUNCTION - #define PRIVILEGED_DATA - #define FREERTOS_SYSTEM_CALL - #define portUSING_MPU_WRAPPERS 0 + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA + #define FREERTOS_SYSTEM_CALL + #define portUSING_MPU_WRAPPERS 0 #endif /* portUSING_MPU_WRAPPERS */ diff --git a/components/bl602/freertos_riscv_ram/config/portable.h b/components/bl602/freertos_riscv_ram/config/portable.h index 59e81694..a6e65b0d 100644 --- a/components/bl602/freertos_riscv_ram/config/portable.h +++ b/components/bl602/freertos_riscv_ram/config/portable.h @@ -49,47 +49,47 @@ did not result in a portmacro.h header file being included - and it should be included here. In this case the path to the correct portmacro.h header file must be set in the compiler's include path. */ #ifndef portENTER_CRITICAL - #include "portmacro.h" + #include "portmacro.h" #endif #if portBYTE_ALIGNMENT == 32 - #define portBYTE_ALIGNMENT_MASK ( 0x001f ) + #define portBYTE_ALIGNMENT_MASK ( 0x001f ) #endif #if portBYTE_ALIGNMENT == 16 - #define portBYTE_ALIGNMENT_MASK ( 0x000f ) + #define portBYTE_ALIGNMENT_MASK ( 0x000f ) #endif #if portBYTE_ALIGNMENT == 8 - #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) #endif #if portBYTE_ALIGNMENT == 4 - #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) #endif #if portBYTE_ALIGNMENT == 2 - #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) #endif #if portBYTE_ALIGNMENT == 1 - #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) + #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) #endif #ifndef portBYTE_ALIGNMENT_MASK - #error "Invalid portBYTE_ALIGNMENT definition" + #error "Invalid portBYTE_ALIGNMENT definition" #endif #ifndef portNUM_CONFIGURABLE_REGIONS - #define portNUM_CONFIGURABLE_REGIONS 1 + #define portNUM_CONFIGURABLE_REGIONS 1 #endif #ifndef portHAS_STACK_OVERFLOW_CHECKING - #define portHAS_STACK_OVERFLOW_CHECKING 0 + #define portHAS_STACK_OVERFLOW_CHECKING 0 #endif #ifndef portARCH_NAME - #define portARCH_NAME NULL + #define portARCH_NAME NULL #endif #ifdef __cplusplus @@ -105,24 +105,24 @@ extern "C" { * */ #if( portUSING_MPU_WRAPPERS == 1 ) - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; - #else - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; - #endif + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #endif #else - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; - #else - StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; - #endif + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #endif #endif /* Used by heap_5.c. */ typedef struct HeapRegion { - uint8_t *pucStartAddress; - size_t xSizeInBytes; + uint8_t *pucStartAddress; + size_t xSizeInBytes; } HeapRegion_t; /* @@ -169,8 +169,8 @@ void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; * contained in xRegions. */ #if( portUSING_MPU_WRAPPERS == 1 ) - struct xMEMORY_REGION; - void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; + struct xMEMORY_REGION; + void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; #endif #ifdef __cplusplus diff --git a/components/bl602/freertos_riscv_ram/config/projdefs.h b/components/bl602/freertos_riscv_ram/config/projdefs.h index e0458619..d33f145b 100644 --- a/components/bl602/freertos_riscv_ram/config/projdefs.h +++ b/components/bl602/freertos_riscv_ram/config/projdefs.h @@ -38,84 +38,84 @@ typedef void (*TaskFunction_t)( void * ); overridden by a macro of the same name defined in FreeRTOSConfig.h in case the definition here is not suitable for your application. */ #ifndef pdMS_TO_TICKS - #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) + #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) #endif -#define pdFALSE ( ( BaseType_t ) 0 ) -#define pdTRUE ( ( BaseType_t ) 1 ) +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) -#define pdPASS ( pdTRUE ) -#define pdFAIL ( pdFALSE ) -#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) -#define errQUEUE_FULL ( ( BaseType_t ) 0 ) +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) +#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) +#define errQUEUE_FULL ( ( BaseType_t ) 0 ) /* FreeRTOS error definitions. */ -#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) -#define errQUEUE_BLOCKED ( -4 ) -#define errQUEUE_YIELD ( -5 ) +#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) +#define errQUEUE_BLOCKED ( -4 ) +#define errQUEUE_YIELD ( -5 ) /* Macros used for basic data corruption checks. */ #ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES - #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 + #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 #endif #if( configUSE_16_BIT_TICKS == 1 ) - #define pdINTEGRITY_CHECK_VALUE 0x5a5a + #define pdINTEGRITY_CHECK_VALUE 0x5a5a #else - #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL #endif /* The following errno values are used by FreeRTOS+ components, not FreeRTOS itself. */ -#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ -#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ -#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ -#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ -#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ -#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ -#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ -#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ -#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ -#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ -#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ -#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ -#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ -#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ -#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ -#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ -#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ -#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ -#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ -#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ -#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ -#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ -#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ -#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ -#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ -#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ -#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ -#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ -#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ -#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ -#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ -#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ -#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ -#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ -#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ -#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ -#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ -#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ -#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ +#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ +#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ +#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ +#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ +#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ +#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ +#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ +#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ +#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ +#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ +#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ +#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ +#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ +#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ +#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ +#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ +#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ +#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ +#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ +#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ +#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ +#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ +#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ +#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ +#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ +#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ +#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ +#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ +#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ +#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ +#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ +#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ +#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ +#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ +#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ +#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ +#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ +#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ +#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ /* The following endian values are used by FreeRTOS+ components, not FreeRTOS itself. */ -#define pdFREERTOS_LITTLE_ENDIAN 0 -#define pdFREERTOS_BIG_ENDIAN 1 +#define pdFREERTOS_LITTLE_ENDIAN 0 +#define pdFREERTOS_BIG_ENDIAN 1 /* Re-defining endian values for generic naming. */ -#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN -#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN +#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN +#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN #endif /* PROJDEFS_H */ diff --git a/components/bl602/freertos_riscv_ram/config/queue.h b/components/bl602/freertos_riscv_ram/config/queue.h index 3b9da937..2ce0415c 100644 --- a/components/bl602/freertos_riscv_ram/config/queue.h +++ b/components/bl602/freertos_riscv_ram/config/queue.h @@ -30,7 +30,7 @@ #define QUEUE_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include queue.h" + #error "include FreeRTOS.h" must appear in source files before "include queue.h" #endif #ifdef __cplusplus @@ -62,25 +62,25 @@ typedef struct QueueDefinition * QueueSetHandle_t; typedef struct QueueDefinition * QueueSetMemberHandle_t; /* For internal use only. */ -#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) -#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) -#define queueOVERWRITE ( ( BaseType_t ) 2 ) +#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) +#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) +#define queueOVERWRITE ( ( BaseType_t ) 2 ) /* For internal use only. These definitions *must* match those in queue.c. */ -#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) -#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) -#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) -#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) -#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) -#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) +#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) +#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) +#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) +#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) /** * queue. h *
  QueueHandle_t xQueueCreate(
-							  UBaseType_t uxQueueLength,
-							  UBaseType_t uxItemSize
-						  );
+                              UBaseType_t uxQueueLength,
+                              UBaseType_t uxItemSize
+                          );
  * 
* * Creates a new queue instance, and returns a handle by which the new queue @@ -113,48 +113,48 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  };
 
  void vATask( void *pvParameters )
  {
  QueueHandle_t xQueue1, xQueue2;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
-	if( xQueue1 == 0 )
-	{
-		// Queue was not created and must not be used.
-	}
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    if( xQueue1 == 0 )
+    {
+        // Queue was not created and must not be used.
+    }
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue2 == 0 )
-	{
-		// Queue was not created and must not be used.
-	}
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    if( xQueue2 == 0 )
+    {
+        // Queue was not created and must not be used.
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueCreate xQueueCreate * \ingroup QueueManagement */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) + #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) #endif /** * queue. h *
  QueueHandle_t xQueueCreateStatic(
-							  UBaseType_t uxQueueLength,
-							  UBaseType_t uxItemSize,
-							  uint8_t *pucQueueStorageBuffer,
-							  StaticQueue_t *pxQueueBuffer
-						  );
+                              UBaseType_t uxQueueLength,
+                              UBaseType_t uxItemSize,
+                              uint8_t *pucQueueStorageBuffer,
+                              StaticQueue_t *pxQueueBuffer
+                          );
  * 
* * Creates a new queue instance, and returns a handle by which the new queue @@ -195,8 +195,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  };
 
  #define QUEUE_LENGTH 10
@@ -213,33 +213,33 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  {
  QueueHandle_t xQueue1;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold.
-							ITEM_SIZE	  // The size of each item in the queue
-							&( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue.
-							&xQueueBuffer ); // The buffer that will hold the queue structure.
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold.
+                            ITEM_SIZE     // The size of each item in the queue
+                            &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue.
+                            &xQueueBuffer ); // The buffer that will hold the queue structure.
 
-	// The queue is guaranteed to be created successfully as no dynamic memory
-	// allocation is used.  Therefore xQueue1 is now a handle to a valid queue.
+    // The queue is guaranteed to be created successfully as no dynamic memory
+    // allocation is used.  Therefore xQueue1 is now a handle to a valid queue.
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueCreateStatic xQueueCreateStatic * \ingroup QueueManagement */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) + #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * queue. h *
  BaseType_t xQueueSendToToFront(
-								   QueueHandle_t	xQueue,
-								   const void		*pvItemToQueue,
-								   TickType_t		xTicksToWait
-							   );
+                                   QueueHandle_t    xQueue,
+                                   const void       *pvItemToQueue,
+                                   TickType_t       xTicksToWait
+                               );
  * 
* * Post an item to the front of a queue. The item is queued by copy, not by @@ -266,8 +266,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -277,34 +277,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -316,10 +316,10 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueSendToBack(
-								   QueueHandle_t	xQueue,
-								   const void		*pvItemToQueue,
-								   TickType_t		xTicksToWait
-							   );
+                                   QueueHandle_t    xQueue,
+                                   const void       *pvItemToQueue,
+                                   TickType_t       xTicksToWait
+                               );
  * 
* * This is a macro that calls xQueueGenericSend(). @@ -348,8 +348,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -359,34 +359,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -398,10 +398,10 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueSend(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue,
-							  TickType_t xTicksToWait
-						 );
+                              QueueHandle_t xQueue,
+                              const void * pvItemToQueue,
+                              TickType_t xTicksToWait
+                         );
  * 
* * This is a macro that calls xQueueGenericSend(). It is included for @@ -432,8 +432,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -443,34 +443,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -482,9 +482,9 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueOverwrite(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue
-						 );
+                              QueueHandle_t xQueue,
+                              const void * pvItemToQueue
+                         );
  * 
* * Only for use with queues that have a length of one - so the queue is either @@ -516,44 +516,44 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; QueueHandle_t xQueue; uint32_t ulVarToSend, ulValReceived; - // Create a queue to hold one uint32_t value. It is strongly - // recommended *not* to use xQueueOverwrite() on queues that can - // contain more than one value, and doing so will trigger an assertion - // if configASSERT() is defined. - xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + // Create a queue to hold one uint32_t value. It is strongly + // recommended *not* to use xQueueOverwrite() on queues that can + // contain more than one value, and doing so will trigger an assertion + // if configASSERT() is defined. + xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); - // Write the value 10 to the queue using xQueueOverwrite(). - ulVarToSend = 10; - xQueueOverwrite( xQueue, &ulVarToSend ); + // Write the value 10 to the queue using xQueueOverwrite(). + ulVarToSend = 10; + xQueueOverwrite( xQueue, &ulVarToSend ); - // Peeking the queue should now return 10, but leave the value 10 in - // the queue. A block time of zero is used as it is known that the - // queue holds a value. - ulValReceived = 0; - xQueuePeek( xQueue, &ulValReceived, 0 ); + // Peeking the queue should now return 10, but leave the value 10 in + // the queue. A block time of zero is used as it is known that the + // queue holds a value. + ulValReceived = 0; + xQueuePeek( xQueue, &ulValReceived, 0 ); - if( ulValReceived != 10 ) - { - // Error unless the item was removed by a different task. - } + if( ulValReceived != 10 ) + { + // Error unless the item was removed by a different task. + } - // The queue is still full. Use xQueueOverwrite() to overwrite the - // value held in the queue with 100. - ulVarToSend = 100; - xQueueOverwrite( xQueue, &ulVarToSend ); + // The queue is still full. Use xQueueOverwrite() to overwrite the + // value held in the queue with 100. + ulVarToSend = 100; + xQueueOverwrite( xQueue, &ulVarToSend ); - // This time read from the queue, leaving the queue empty once more. - // A block time of 0 is used again. - xQueueReceive( xQueue, &ulValReceived, 0 ); + // This time read from the queue, leaving the queue empty once more. + // A block time of 0 is used again. + xQueueReceive( xQueue, &ulValReceived, 0 ); - // The value read should be the last value written, even though the - // queue was already full when the value was written. - if( ulValReceived != 100 ) - { - // Error! - } + // The value read should be the last value written, even though the + // queue was already full when the value was written. + if( ulValReceived != 100 ) + { + // Error! + } - // ... + // ... } * \defgroup xQueueOverwrite xQueueOverwrite @@ -566,11 +566,11 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t; * queue. h *
  BaseType_t xQueueGenericSend(
-									QueueHandle_t xQueue,
-									const void * pvItemToQueue,
-									TickType_t xTicksToWait
-									BaseType_t xCopyPosition
-								);
+                                    QueueHandle_t xQueue,
+                                    const void * pvItemToQueue,
+                                    TickType_t xTicksToWait
+                                    BaseType_t xCopyPosition
+                                );
  * 
* * It is preferred that the macros xQueueSend(), xQueueSendToFront() and @@ -603,8 +603,8 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  uint32_t ulVar = 10UL;
@@ -614,34 +614,34 @@ typedef struct QueueDefinition * QueueSetMemberHandle_t;
  QueueHandle_t xQueue1, xQueue2;
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 uint32_t values.
-	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+    // Create a queue capable of containing 10 uint32_t values.
+    xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
 
-	// ...
+    // ...
 
-	if( xQueue1 != 0 )
-	{
-		// Send an uint32_t.  Wait for 10 ticks for space to become
-		// available if necessary.
-		if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS )
-		{
-			// Failed to post the message, even after 10 ticks.
-		}
-	}
+    if( xQueue1 != 0 )
+    {
+        // Send an uint32_t.  Wait for 10 ticks for space to become
+        // available if necessary.
+        if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS )
+        {
+            // Failed to post the message, even after 10 ticks.
+        }
+    }
 
-	if( xQueue2 != 0 )
-	{
-		// Send a pointer to a struct AMessage object.  Don't block if the
-		// queue is already full.
-		pxMessage = & xMessage;
-		xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK );
-	}
+    if( xQueue2 != 0 )
+    {
+        // Send a pointer to a struct AMessage object.  Don't block if the
+        // queue is already full.
+        pxMessage = & xMessage;
+        xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK );
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueSend xQueueSend @@ -653,10 +653,10 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ * queue. h *
  BaseType_t xQueuePeek(
-							 QueueHandle_t xQueue,
-							 void * const pvBuffer,
-							 TickType_t xTicksToWait
-						 );
+ QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait + ); * * Receive an item from a queue without removing the item from the queue. * The item is received by copy so a buffer of adequate size must be @@ -678,7 +678,7 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ * * @param xTicksToWait The maximum amount of time the task should block * waiting for an item to receive should the queue be empty at the time - * of the call. The time is defined in tick periods so the constant + * of the call. The time is defined in tick periods so the constant * portTICK_PERIOD_MS should be used to convert to real time if this is required. * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue * is empty. @@ -690,8 +690,8 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  QueueHandle_t xQueue;
@@ -701,22 +701,22 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ
  {
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue == 0 )
-	{
-		// Failed to create the queue.
-	}
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    if( xQueue == 0 )
+    {
+        // Failed to create the queue.
+    }
 
-	// ...
+    // ...
 
-	// Send a pointer to a struct AMessage object.  Don't block if the
-	// queue is already full.
-	pxMessage = & xMessage;
-	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    // Send a pointer to a struct AMessage object.  Don't block if the
+    // queue is already full.
+    pxMessage = & xMessage;
+    xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
 
  // Task to peek the data from the queue.
@@ -724,18 +724,18 @@ BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQ
  {
  struct AMessage *pxRxedMessage;
 
-	if( xQueue != 0 )
-	{
-		// Peek a message on the created queue.  Block for 10 ticks if a
-		// message is not immediately available.
-		if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
-		{
-			// pcRxedMessage now points to the struct AMessage variable posted
-			// by vATask, but the item still remains on the queue.
-		}
-	}
+    if( xQueue != 0 )
+    {
+        // Peek a message on the created queue.  Block for 10 ticks if a
+        // message is not immediately available.
+        if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+        {
+            // pcRxedMessage now points to the struct AMessage variable posted
+            // by vATask, but the item still remains on the queue.
+        }
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueuePeek xQueuePeek @@ -747,9 +747,9 @@ BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t x * queue. h *
  BaseType_t xQueuePeekFromISR(
-									QueueHandle_t xQueue,
-									void *pvBuffer,
-								);
+ QueueHandle_t xQueue, + void *pvBuffer, + ); * * A version of xQueuePeek() that can be called from an interrupt service * routine (ISR). @@ -780,10 +780,10 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV * queue. h *
  BaseType_t xQueueReceive(
-								 QueueHandle_t xQueue,
-								 void *pvBuffer,
-								 TickType_t xTicksToWait
-							);
+ QueueHandle_t xQueue, + void *pvBuffer, + TickType_t xTicksToWait + ); * * Receive an item from a queue. The item is received by copy so a buffer of * adequate size must be provided. The number of bytes copied into the buffer @@ -802,7 +802,7 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV * * @param xTicksToWait The maximum amount of time the task should block * waiting for an item to receive should the queue be empty at the time - * of the call. xQueueReceive() will return immediately if xTicksToWait + * of the call. xQueueReceive() will return immediately if xTicksToWait * is zero and the queue is empty. The time is defined in tick periods so the * constant portTICK_PERIOD_MS should be used to convert to real time if this is * required. @@ -814,8 +814,8 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV
  struct AMessage
  {
-	char ucMessageID;
-	char ucData[ 20 ];
+    char ucMessageID;
+    char ucData[ 20 ];
  } xMessage;
 
  QueueHandle_t xQueue;
@@ -825,22 +825,22 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV
  {
  struct AMessage *pxMessage;
 
-	// Create a queue capable of containing 10 pointers to AMessage structures.
-	// These should be passed by pointer as they contain a lot of data.
-	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
-	if( xQueue == 0 )
-	{
-		// Failed to create the queue.
-	}
+    // Create a queue capable of containing 10 pointers to AMessage structures.
+    // These should be passed by pointer as they contain a lot of data.
+    xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+    if( xQueue == 0 )
+    {
+        // Failed to create the queue.
+    }
 
-	// ...
+    // ...
 
-	// Send a pointer to a struct AMessage object.  Don't block if the
-	// queue is already full.
-	pxMessage = & xMessage;
-	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+    // Send a pointer to a struct AMessage object.  Don't block if the
+    // queue is already full.
+    pxMessage = & xMessage;
+    xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
 
  // Task to receive from the queue.
@@ -848,18 +848,18 @@ BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIV
  {
  struct AMessage *pxRxedMessage;
 
-	if( xQueue != 0 )
-	{
-		// Receive a message on the created queue.  Block for 10 ticks if a
-		// message is not immediately available.
-		if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
-		{
-			// pcRxedMessage now points to the struct AMessage variable posted
-			// by vATask.
-		}
-	}
+    if( xQueue != 0 )
+    {
+        // Receive a message on the created queue.  Block for 10 ticks if a
+        // message is not immediately available.
+        if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+        {
+            // pcRxedMessage now points to the struct AMessage variable posted
+            // by vATask.
+        }
+    }
 
-	// ... Rest of task code.
+    // ... Rest of task code.
  }
  
* \defgroup xQueueReceive xQueueReceive @@ -917,10 +917,10 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * queue. h *
  BaseType_t xQueueSendToFrontFromISR(
-										 QueueHandle_t xQueue,
-										 const void *pvItemToQueue,
-										 BaseType_t *pxHigherPriorityTaskWoken
-									  );
+                                         QueueHandle_t xQueue,
+                                         const void *pvItemToQueue,
+                                         BaseType_t *pxHigherPriorityTaskWoken
+                                      );
  
* * This is a macro that calls xQueueGenericSendFromISR(). @@ -956,25 +956,25 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; char cIn; BaseType_t xHigherPrioritTaskWoken; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWoken = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post the byte. - xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + // Post the byte. + xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. - if( xHigherPriorityTaskWoken ) - { - taskYIELD (); - } + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + taskYIELD (); + } } * @@ -988,10 +988,10 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * queue. h *
  BaseType_t xQueueSendToBackFromISR(
-										 QueueHandle_t xQueue,
-										 const void *pvItemToQueue,
-										 BaseType_t *pxHigherPriorityTaskWoken
-									  );
+                                         QueueHandle_t xQueue,
+                                         const void *pvItemToQueue,
+                                         BaseType_t *pxHigherPriorityTaskWoken
+                                      );
  
* * This is a macro that calls xQueueGenericSendFromISR(). @@ -1027,25 +1027,25 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; char cIn; BaseType_t xHigherPriorityTaskWoken; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWoken = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post the byte. - xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + // Post the byte. + xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. - if( xHigherPriorityTaskWoken ) - { - taskYIELD (); - } + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + taskYIELD (); + } } * @@ -1058,10 +1058,10 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; * queue. h *
  BaseType_t xQueueOverwriteFromISR(
-							  QueueHandle_t xQueue,
-							  const void * pvItemToQueue,
-							  BaseType_t *pxHigherPriorityTaskWoken
-						 );
+                              QueueHandle_t xQueue,
+                              const void * pvItemToQueue,
+                              BaseType_t *pxHigherPriorityTaskWoken
+                         );
  * 
* * A version of xQueueOverwrite() that can be used in an interrupt service @@ -1099,11 +1099,11 @@ void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; void vFunction( void *pvParameters ) { - // Create a queue to hold one uint32_t value. It is strongly - // recommended *not* to use xQueueOverwriteFromISR() on queues that can - // contain more than one value, and doing so will trigger an assertion - // if configASSERT() is defined. - xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + // Create a queue to hold one uint32_t value. It is strongly + // recommended *not* to use xQueueOverwriteFromISR() on queues that can + // contain more than one value, and doing so will trigger an assertion + // if configASSERT() is defined. + xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); } void vAnInterruptHandler( void ) @@ -1112,28 +1112,28 @@ void vAnInterruptHandler( void ) BaseType_t xHigherPriorityTaskWoken = pdFALSE; uint32_t ulVarToSend, ulValReceived; - // Write the value 10 to the queue using xQueueOverwriteFromISR(). - ulVarToSend = 10; - xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + // Write the value 10 to the queue using xQueueOverwriteFromISR(). + ulVarToSend = 10; + xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); - // The queue is full, but calling xQueueOverwriteFromISR() again will still - // pass because the value held in the queue will be overwritten with the - // new value. - ulVarToSend = 100; - xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + // The queue is full, but calling xQueueOverwriteFromISR() again will still + // pass because the value held in the queue will be overwritten with the + // new value. + ulVarToSend = 100; + xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); - // Reading from the queue will now return 100. + // Reading from the queue will now return 100. - // ... + // ... - if( xHigherPrioritytaskWoken == pdTRUE ) - { - // Writing to the queue caused a task to unblock and the unblocked task - // has a priority higher than or equal to the priority of the currently - // executing task (the task this interrupt interrupted). Perform a context - // switch so this interrupt returns directly to the unblocked task. - portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. - } + if( xHigherPrioritytaskWoken == pdTRUE ) + { + // Writing to the queue caused a task to unblock and the unblocked task + // has a priority higher than or equal to the priority of the currently + // executing task (the task this interrupt interrupted). Perform a context + // switch so this interrupt returns directly to the unblocked task. + portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. + } } * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR @@ -1145,10 +1145,10 @@ uint32_t ulVarToSend, ulValReceived; * queue. h *
  BaseType_t xQueueSendFromISR(
-									 QueueHandle_t xQueue,
-									 const void *pvItemToQueue,
-									 BaseType_t *pxHigherPriorityTaskWoken
-								);
+                                     QueueHandle_t xQueue,
+                                     const void *pvItemToQueue,
+                                     BaseType_t *pxHigherPriorityTaskWoken
+                                );
  
* * This is a macro that calls xQueueGenericSendFromISR(). It is included @@ -1187,26 +1187,26 @@ uint32_t ulVarToSend, ulValReceived; char cIn; BaseType_t xHigherPriorityTaskWoken; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWoken = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post the byte. - xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + // Post the byte. + xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. - if( xHigherPriorityTaskWoken ) - { - // Actual macro used here is port specific. - portYIELD_FROM_ISR (); - } + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + // Actual macro used here is port specific. + portYIELD_FROM_ISR (); + } } * @@ -1219,11 +1219,11 @@ uint32_t ulVarToSend, ulValReceived; * queue. h *
  BaseType_t xQueueGenericSendFromISR(
-										   QueueHandle_t		xQueue,
-										   const	void	*pvItemToQueue,
-										   BaseType_t	*pxHigherPriorityTaskWoken,
-										   BaseType_t	xCopyPosition
-									   );
+                                           QueueHandle_t        xQueue,
+                                           const    void    *pvItemToQueue,
+                                           BaseType_t   *pxHigherPriorityTaskWoken,
+                                           BaseType_t   xCopyPosition
+                                       );
  
* * It is preferred that the macros xQueueSendFromISR(), @@ -1266,26 +1266,26 @@ uint32_t ulVarToSend, ulValReceived; char cIn; BaseType_t xHigherPriorityTaskWokenByPost; - // We have not woken a task at the start of the ISR. - xHigherPriorityTaskWokenByPost = pdFALSE; + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWokenByPost = pdFALSE; - // Loop until the buffer is empty. - do - { - // Obtain a byte from the buffer. - cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); - // Post each byte. - xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); + // Post each byte. + xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); - } while( portINPUT_BYTE( BUFFER_COUNT ) ); + } while( portINPUT_BYTE( BUFFER_COUNT ) ); - // Now the buffer is empty we can switch context if necessary. Note that the - // name of the yield function required is port specific. - if( xHigherPriorityTaskWokenByPost ) - { - taskYIELD_YIELD_FROM_ISR(); - } + // Now the buffer is empty we can switch context if necessary. Note that the + // name of the yield function required is port specific. + if( xHigherPriorityTaskWokenByPost ) + { + taskYIELD_YIELD_FROM_ISR(); + } } * @@ -1299,10 +1299,10 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherP * queue. h *
  BaseType_t xQueueReceiveFromISR(
-									   QueueHandle_t	xQueue,
-									   void	*pvBuffer,
-									   BaseType_t *pxTaskWoken
-								   );
+                                       QueueHandle_t    xQueue,
+                                       void *pvBuffer,
+                                       BaseType_t *pxTaskWoken
+                                   );
  * 
* * Receive an item from a queue. It is safe to use this function from within an @@ -1333,27 +1333,27 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherP char cValueToPost; const TickType_t xTicksToWait = ( TickType_t )0xff; - // Create a queue capable of containing 10 characters. - xQueue = xQueueCreate( 10, sizeof( char ) ); - if( xQueue == 0 ) - { - // Failed to create the queue. - } + // Create a queue capable of containing 10 characters. + xQueue = xQueueCreate( 10, sizeof( char ) ); + if( xQueue == 0 ) + { + // Failed to create the queue. + } - // ... + // ... - // Post some characters that will be used within an ISR. If the queue - // is full then this task will block for xTicksToWait ticks. - cValueToPost = 'a'; - xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); - cValueToPost = 'b'; - xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + // Post some characters that will be used within an ISR. If the queue + // is full then this task will block for xTicksToWait ticks. + cValueToPost = 'a'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + cValueToPost = 'b'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); - // ... keep posting characters ... this task may block when the queue - // becomes full. + // ... keep posting characters ... this task may block when the queue + // becomes full. - cValueToPost = 'c'; - xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + cValueToPost = 'c'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); } // ISR that outputs all the characters received on the queue. @@ -1362,21 +1362,21 @@ BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherP BaseType_t xTaskWokenByReceive = pdFALSE; char cRxedChar; - while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) - { - // A character was received. Output the character now. - vOutputCharacter( cRxedChar ); + while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) + { + // A character was received. Output the character now. + vOutputCharacter( cRxedChar ); - // If removing the character from the queue woke the task that was - // posting onto the queue cTaskWokenByReceive will have been set to - // pdTRUE. No matter how many times this loop iterates only one - // task will be woken. - } + // If removing the character from the queue woke the task that was + // posting onto the queue cTaskWokenByReceive will have been set to + // pdTRUE. No matter how many times this loop iterates only one + // task will be woken. + } - if( cTaskWokenByPost != ( char ) pdFALSE; - { - taskYIELD (); - } + if( cTaskWokenByPost != ( char ) pdFALSE; + { + taskYIELD (); + } } * \defgroup xQueueReceiveFromISR xQueueReceiveFromISR @@ -1455,7 +1455,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * preferably in ROM/Flash), not on the stack. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ #endif /* @@ -1469,7 +1469,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * @param xQueue The handle of the queue being removed from the registry. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; #endif /* @@ -1484,7 +1484,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * returned. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) - const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ #endif /* @@ -1493,7 +1493,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * RTOS objects that use the queue structure as their base. */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; #endif /* @@ -1502,7 +1502,7 @@ BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; * RTOS objects that use the queue structure as their base. */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; #endif /* diff --git a/components/bl602/freertos_riscv_ram/config/semphr.h b/components/bl602/freertos_riscv_ram/config/semphr.h index 2c106eac..db258aef 100644 --- a/components/bl602/freertos_riscv_ram/config/semphr.h +++ b/components/bl602/freertos_riscv_ram/config/semphr.h @@ -29,16 +29,16 @@ #define SEMAPHORE_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h" must appear in source files before "include semphr.h" + #error "include FreeRTOS.h" must appear in source files before "include semphr.h" #endif #include "queue.h" typedef QueueHandle_t SemaphoreHandle_t; -#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) -#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) -#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) +#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) +#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) +#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) /** @@ -91,14 +91,14 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define vSemaphoreCreateBinary( xSemaphore ) \ - { \ - ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ - if( ( xSemaphore ) != NULL ) \ - { \ - ( void ) xSemaphoreGive( ( xSemaphore ) ); \ - } \ - } + #define vSemaphoreCreateBinary( xSemaphore ) \ + { \ + ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ + if( ( xSemaphore ) != NULL ) \ + { \ + ( void ) xSemaphoreGive( ( xSemaphore ) ); \ + } \ + } #endif /** @@ -159,7 +159,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) + #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) #endif /** @@ -218,7 +218,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) + #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) #endif /* configSUPPORT_STATIC_ALLOCATION */ /** @@ -286,7 +286,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \defgroup xSemaphoreTake xSemaphoreTake * \ingroup Semaphores */ -#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) +#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) /** * semphr. h @@ -380,7 +380,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) + #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) #endif /** @@ -444,7 +444,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \defgroup xSemaphoreGive xSemaphoreGive * \ingroup Semaphores */ -#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) +#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) /** * semphr. h @@ -498,24 +498,24 @@ typedef QueueHandle_t SemaphoreHandle_t; // ... // For some reason due to the nature of the code further calls to - // xSemaphoreTakeRecursive() are made on the same mutex. In real - // code these would not be just sequential calls as this would make - // no sense. Instead the calls are likely to be buried inside - // a more complex call structure. + // xSemaphoreTakeRecursive() are made on the same mutex. In real + // code these would not be just sequential calls as this would make + // no sense. Instead the calls are likely to be buried inside + // a more complex call structure. xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); // The mutex has now been 'taken' three times, so will not be - // available to another task until it has also been given back - // three times. Again it is unlikely that real code would have - // these calls sequentially, it would be more likely that the calls - // to xSemaphoreGiveRecursive() would be called as a call stack - // unwound. This is just for demonstrative purposes. + // available to another task until it has also been given back + // three times. Again it is unlikely that real code would have + // these calls sequentially, it would be more likely that the calls + // to xSemaphoreGiveRecursive() would be called as a call stack + // unwound. This is just for demonstrative purposes. + xSemaphoreGiveRecursive( xMutex ); + xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); - xSemaphoreGiveRecursive( xMutex ); - xSemaphoreGiveRecursive( xMutex ); - // Now the mutex can be taken by other tasks. + // Now the mutex can be taken by other tasks. } else { @@ -529,7 +529,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * \ingroup Semaphores */ #if( configUSE_RECURSIVE_MUTEXES == 1 ) - #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) + #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) #endif /** @@ -562,7 +562,7 @@ typedef QueueHandle_t SemaphoreHandle_t; * Example usage:
  \#define LONG_TIME 0xffff
- \#define TICKS_TO_WAIT	10
+ \#define TICKS_TO_WAIT 10
  SemaphoreHandle_t xSemaphore = NULL;
 
  // Repetitive task.
@@ -583,7 +583,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
             // We have finished our task.  Return to the top of the loop where
             // we will block on the semaphore until it is time to execute
             // again.  Note when using the semaphore for synchronisation with an
-			// ISR in this manner there is no need to 'give' the semaphore back.
+            // ISR in this manner there is no need to 'give' the semaphore back.
         }
     }
  }
@@ -599,7 +599,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
     // ... Do other time functions.
 
     // Is it time for vATask () to run?
-	xHigherPriorityTaskWoken = pdFALSE;
+    xHigherPriorityTaskWoken = pdFALSE;
     ucLocalTickCount++;
     if( ucLocalTickCount >= TICKS_TO_WAIT )
     {
@@ -621,7 +621,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR
  * \ingroup Semaphores
  */
-#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken )	xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) )
+#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken )  xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) )
 
 /**
  * semphr. h
@@ -655,7 +655,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * @return pdTRUE if the semaphore was successfully taken, otherwise
  * pdFALSE
  */
-#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken )	xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) )
+#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken )  xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) )
 
 /**
  * semphr. h
@@ -713,7 +713,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )
+    #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )
 #endif
 
 /**
@@ -774,7 +774,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
  #if( configSUPPORT_STATIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) )
+    #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) )
 #endif /* configSUPPORT_STATIC_ALLOCATION */
 
 
@@ -842,7 +842,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) )
-	#define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
+    #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
 #endif
 
 /**
@@ -915,7 +915,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) )
-	#define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore )
+    #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore )
 #endif /* configSUPPORT_STATIC_ALLOCATION */
 
 /**
@@ -995,7 +995,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )
+    #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )
 #endif
 
 /**
@@ -1080,7 +1080,7 @@ typedef QueueHandle_t SemaphoreHandle_t;
  * \ingroup Semaphores
  */
 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
-	#define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) )
+    #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) )
 #endif /* configSUPPORT_STATIC_ALLOCATION */
 
 /**
diff --git a/components/bl602/freertos_riscv_ram/config/stack_macros.h b/components/bl602/freertos_riscv_ram/config/stack_macros.h
index 18406bbf..60a95370 100644
--- a/components/bl602/freertos_riscv_ram/config/stack_macros.h
+++ b/components/bl602/freertos_riscv_ram/config/stack_macros.h
@@ -46,81 +46,81 @@
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) )
 
-	/* Only the current stack state is to be checked. */
-	#define taskCHECK_FOR_STACK_OVERFLOW()																\
-	{																									\
-		/* Is the currently saved stack pointer within the stack limit? */								\
-		if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack )										\
-		{																								\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
-		}																								\
-	}
+    /* Only the current stack state is to be checked. */
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                              \
+    {                                                                                                   \
+        /* Is the currently saved stack pointer within the stack limit? */                              \
+        if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack )                                       \
+        {                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );   \
+        }                                                                                               \
+    }
 
 #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
 /*-----------------------------------------------------------*/
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) )
 
-	/* Only the current stack state is to be checked. */
-	#define taskCHECK_FOR_STACK_OVERFLOW()																\
-	{																									\
-																										\
-		/* Is the currently saved stack pointer within the stack limit? */								\
-		if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack )									\
-		{																								\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
-		}																								\
-	}
+    /* Only the current stack state is to be checked. */
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                              \
+    {                                                                                                   \
+                                                                                                        \
+        /* Is the currently saved stack pointer within the stack limit? */                              \
+        if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack )                                  \
+        {                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );   \
+        }                                                                                               \
+    }
 
 #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
 /*-----------------------------------------------------------*/
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) )
 
-	#define taskCHECK_FOR_STACK_OVERFLOW()																\
-	{																									\
-		const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack;							\
-		const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5;											\
-																										\
-		if( ( pulStack[ 0 ] != ulCheckValue ) ||														\
-			( pulStack[ 1 ] != ulCheckValue ) ||														\
-			( pulStack[ 2 ] != ulCheckValue ) ||														\
-			( pulStack[ 3 ] != ulCheckValue ) )															\
-		{																								\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
-		}																								\
-	}
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                              \
+    {                                                                                                   \
+        const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack;                         \
+        const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5;                                          \
+                                                                                                        \
+        if( ( pulStack[ 0 ] != ulCheckValue ) ||                                                        \
+            ( pulStack[ 1 ] != ulCheckValue ) ||                                                        \
+            ( pulStack[ 2 ] != ulCheckValue ) ||                                                        \
+            ( pulStack[ 3 ] != ulCheckValue ) )                                                         \
+        {                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );   \
+        }                                                                                               \
+    }
 
 #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
 /*-----------------------------------------------------------*/
 
 #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) )
 
-	#define taskCHECK_FOR_STACK_OVERFLOW()																								\
-	{																																	\
-	int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack;																		\
-	static const uint8_t ucExpectedStackBytes[] = {	tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
-													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE };	\
-																																		\
-																																		\
-		pcEndOfStack -= sizeof( ucExpectedStackBytes );																					\
-																																		\
-		/* Has the extremity of the task stack ever been written over? */																\
-		if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 )					\
-		{																																\
-			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );									\
-		}																																\
-	}
+    #define taskCHECK_FOR_STACK_OVERFLOW()                                                                                              \
+    {                                                                                                                                   \
+    int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack;                                                                     \
+    static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,     \
+                                                    tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE };   \
+                                                                                                                                        \
+                                                                                                                                        \
+        pcEndOfStack -= sizeof( ucExpectedStackBytes );                                                                                 \
+                                                                                                                                        \
+        /* Has the extremity of the task stack ever been written over? */                                                               \
+        if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 )                   \
+        {                                                                                                                               \
+            vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );                                   \
+        }                                                                                                                               \
+    }
 
 #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
 /*-----------------------------------------------------------*/
 
 /* Remove stack overflow macro if not being used. */
 #ifndef taskCHECK_FOR_STACK_OVERFLOW
-	#define taskCHECK_FOR_STACK_OVERFLOW()
+    #define taskCHECK_FOR_STACK_OVERFLOW()
 #endif
 
 
diff --git a/components/bl602/freertos_riscv_ram/config/stream_buffer.h b/components/bl602/freertos_riscv_ram/config/stream_buffer.h
index 0f00119e..2dd7e7fe 100644
--- a/components/bl602/freertos_riscv_ram/config/stream_buffer.h
+++ b/components/bl602/freertos_riscv_ram/config/stream_buffer.h
@@ -306,9 +306,9 @@ const TickType_t x100ms = pdMS_TO_TICKS( 100 );
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
-						  const void *pvTxData,
-						  size_t xDataLengthBytes,
-						  TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+                          const void *pvTxData,
+                          size_t xDataLengthBytes,
+                          TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -407,9 +407,9 @@ BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
-								 const void *pvTxData,
-								 size_t xDataLengthBytes,
-								 BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+                                 const void *pvTxData,
+                                 size_t xDataLengthBytes,
+                                 BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -496,9 +496,9 @@ const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
-							 void *pvRxData,
-							 size_t xBufferLengthBytes,
-							 TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+                             void *pvRxData,
+                             size_t xBufferLengthBytes,
+                             TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -582,9 +582,9 @@ BaseType_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.
  * \ingroup StreamBufferManagement
  */
 size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
-									void *pvRxData,
-									size_t xBufferLengthBytes,
-									BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+                                    void *pvRxData,
+                                    size_t xBufferLengthBytes,
+                                    BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
 
 /**
  * stream_buffer.h
@@ -831,25 +831,25 @@ BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuf
 
 /* Functions below here are not part of the public API. */
 StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,
-												 size_t xTriggerLevelBytes,
-												 BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION;
+                                                 size_t xTriggerLevelBytes,
+                                                 BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION;
 
 StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes,
-													   size_t xTriggerLevelBytes,
-													   BaseType_t xIsMessageBuffer,
-													   uint8_t * const pucStreamBufferStorageArea,
-													   StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION;
+                                                       size_t xTriggerLevelBytes,
+                                                       BaseType_t xIsMessageBuffer,
+                                                       uint8_t * const pucStreamBufferStorageArea,
+                                                       StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION;
 
 size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
 
 #if( configUSE_TRACE_FACILITY == 1 )
-	void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION;
-	UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
-	uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
+    void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION;
+    UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
+    uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
 #endif
 
 #if defined( __cplusplus )
 }
 #endif
 
-#endif	/* !defined( STREAM_BUFFER_H ) */
+#endif  /* !defined( STREAM_BUFFER_H ) */
diff --git a/components/bl602/freertos_riscv_ram/config/task.h b/components/bl602/freertos_riscv_ram/config/task.h
index 64ccb190..15628fd5 100644
--- a/components/bl602/freertos_riscv_ram/config/task.h
+++ b/components/bl602/freertos_riscv_ram/config/task.h
@@ -30,7 +30,7 @@
 #define INC_TASK_H
 
 #ifndef INC_FREERTOS_H
-	#error "include FreeRTOS.h must appear in source files before include task.h"
+    #error "include FreeRTOS.h must appear in source files before include task.h"
 #endif
 
 #include "list.h"
@@ -50,11 +50,11 @@ extern "C" {
 
 /* MPU region parameters passed in ulParameters
  * of MemoryRegion_t struct. */
-#define tskMPU_REGION_READ_ONLY			( 1UL << 0UL )
-#define tskMPU_REGION_READ_WRITE		( 1UL << 1UL )
-#define tskMPU_REGION_EXECUTE_NEVER		( 1UL << 2UL )
-#define tskMPU_REGION_NORMAL_MEMORY		( 1UL << 3UL )
-#define tskMPU_REGION_DEVICE_MEMORY		( 1UL << 4UL )
+#define tskMPU_REGION_READ_ONLY         ( 1UL << 0UL )
+#define tskMPU_REGION_READ_WRITE        ( 1UL << 1UL )
+#define tskMPU_REGION_EXECUTE_NEVER     ( 1UL << 2UL )
+#define tskMPU_REGION_NORMAL_MEMORY     ( 1UL << 3UL )
+#define tskMPU_REGION_DEVICE_MEMORY     ( 1UL << 4UL )
 
 /**
  * task. h
@@ -78,22 +78,22 @@ typedef BaseType_t (*TaskHookFunction_t)( void * );
 /* Task states returned by eTaskGetState. */
 typedef enum
 {
-	eRunning = 0,	/* A task is querying the state of itself, so must be running. */
-	eReady,			/* The task being queried is in a read or pending ready list. */
-	eBlocked,		/* The task being queried is in the Blocked state. */
-	eSuspended,		/* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
-	eDeleted,		/* The task being queried has been deleted, but its TCB has not yet been freed. */
-	eInvalid		/* Used as an 'invalid state' value. */
+    eRunning = 0,   /* A task is querying the state of itself, so must be running. */
+    eReady,         /* The task being queried is in a read or pending ready list. */
+    eBlocked,       /* The task being queried is in the Blocked state. */
+    eSuspended,     /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
+    eDeleted,       /* The task being queried has been deleted, but its TCB has not yet been freed. */
+    eInvalid        /* Used as an 'invalid state' value. */
 } eTaskState;
 
 /* Actions that can be performed when vTaskNotify() is called. */
 typedef enum
 {
-	eNoAction = 0,				/* Notify the task without updating its notify value. */
-	eSetBits,					/* Set bits in the task's notification value. */
-	eIncrement,					/* Increment the task's notification value. */
-	eSetValueWithOverwrite,		/* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */
-	eSetValueWithoutOverwrite	/* Set the task's notification value if the previous value has been read by the task. */
+    eNoAction = 0,              /* Notify the task without updating its notify value. */
+    eSetBits,                   /* Set bits in the task's notification value. */
+    eIncrement,                 /* Increment the task's notification value. */
+    eSetValueWithOverwrite,     /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */
+    eSetValueWithoutOverwrite   /* Set the task's notification value if the previous value has been read by the task. */
 } eNotifyAction;
 
 /*
@@ -101,8 +101,8 @@ typedef enum
  */
 typedef struct xTIME_OUT
 {
-	BaseType_t xOverflowCount;
-	TickType_t xTimeOnEntering;
+    BaseType_t xOverflowCount;
+    TickType_t xTimeOnEntering;
 } TimeOut_t;
 
 /*
@@ -110,9 +110,9 @@ typedef struct xTIME_OUT
  */
 typedef struct xMEMORY_REGION
 {
-	void *pvBaseAddress;
-	uint32_t ulLengthInBytes;
-	uint32_t ulParameters;
+    void *pvBaseAddress;
+    uint32_t ulLengthInBytes;
+    uint32_t ulParameters;
 } MemoryRegion_t;
 
 /*
@@ -120,39 +120,39 @@ typedef struct xMEMORY_REGION
  */
 typedef struct xTASK_PARAMETERS
 {
-	TaskFunction_t pvTaskCode;
-	const char * const pcName;	/*lint !e971 Unqualified char types are allowed for strings and single characters only. */
-	configSTACK_DEPTH_TYPE usStackDepth;
-	void *pvParameters;
-	UBaseType_t uxPriority;
-	StackType_t *puxStackBuffer;
-	MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
-	#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
-		StaticTask_t * const pxTaskBuffer;
-	#endif
+    TaskFunction_t pvTaskCode;
+    const char * const pcName;  /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+    configSTACK_DEPTH_TYPE usStackDepth;
+    void *pvParameters;
+    UBaseType_t uxPriority;
+    StackType_t *puxStackBuffer;
+    MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
+    #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
+        StaticTask_t * const pxTaskBuffer;
+    #endif
 } TaskParameters_t;
 
 /* Used with the uxTaskGetSystemState() function to return the state of each task
 in the system. */
 typedef struct xTASK_STATUS
 {
-	TaskHandle_t xHandle;			/* The handle of the task to which the rest of the information in the structure relates. */
-	const char *pcTaskName;			/* A pointer to the task's name.  This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
-	UBaseType_t xTaskNumber;		/* A number unique to the task. */
-	eTaskState eCurrentState;		/* The state in which the task existed when the structure was populated. */
-	UBaseType_t uxCurrentPriority;	/* The priority at which the task was running (may be inherited) when the structure was populated. */
-	UBaseType_t uxBasePriority;		/* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex.  Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */
-	uint32_t ulRunTimeCounter;		/* The total run time allocated to the task so far, as defined by the run time stats clock.  See http://www.freertos.org/rtos-run-time-stats.html.  Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */
-	StackType_t *pxStackBase;		/* Points to the lowest address of the task's stack area. */
-	configSTACK_DEPTH_TYPE usStackHighWaterMark;	/* The minimum amount of stack space that has remained for the task since the task was created.  The closer this value is to zero the closer the task has come to overflowing its stack. */
+    TaskHandle_t xHandle;           /* The handle of the task to which the rest of the information in the structure relates. */
+    const char *pcTaskName;         /* A pointer to the task's name.  This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+    UBaseType_t xTaskNumber;        /* A number unique to the task. */
+    eTaskState eCurrentState;       /* The state in which the task existed when the structure was populated. */
+    UBaseType_t uxCurrentPriority;  /* The priority at which the task was running (may be inherited) when the structure was populated. */
+    UBaseType_t uxBasePriority;     /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex.  Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */
+    uint32_t ulRunTimeCounter;      /* The total run time allocated to the task so far, as defined by the run time stats clock.  See http://www.freertos.org/rtos-run-time-stats.html.  Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */
+    StackType_t *pxStackBase;       /* Points to the lowest address of the task's stack area. */
+    configSTACK_DEPTH_TYPE usStackHighWaterMark;    /* The minimum amount of stack space that has remained for the task since the task was created.  The closer this value is to zero the closer the task has come to overflowing its stack. */
 } TaskStatus_t;
 
 /* Possible return values for eTaskConfirmSleepModeStatus(). */
 typedef enum
 {
-	eAbortSleep = 0,		/* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */
-	eStandardSleep,			/* Enter a sleep mode that will not last any longer than the expected idle time. */
-	eNoTasksWaitingTimeout	/* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */
+    eAbortSleep = 0,        /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */
+    eStandardSleep,         /* Enter a sleep mode that will not last any longer than the expected idle time. */
+    eNoTasksWaitingTimeout  /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */
 } eSleepModeStatus;
 
 /**
@@ -160,7 +160,7 @@ typedef enum
  *
  * \ingroup TaskUtils
  */
-#define tskIDLE_PRIORITY			( ( UBaseType_t ) 0U )
+#define tskIDLE_PRIORITY            ( ( UBaseType_t ) 0U )
 
 /**
  * task. h
@@ -170,7 +170,7 @@ typedef enum
  * \defgroup taskYIELD taskYIELD
  * \ingroup SchedulerControl
  */
-#define taskYIELD()					portYIELD()
+#define taskYIELD()                 portYIELD()
 
 /**
  * task. h
@@ -184,7 +184,7 @@ typedef enum
  * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL
  * \ingroup SchedulerControl
  */
-#define taskENTER_CRITICAL()		portENTER_CRITICAL()
+#define taskENTER_CRITICAL()        portENTER_CRITICAL()
 #define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR()
 
 /**
@@ -199,7 +199,7 @@ typedef enum
  * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL
  * \ingroup SchedulerControl
  */
-#define taskEXIT_CRITICAL()			portEXIT_CRITICAL()
+#define taskEXIT_CRITICAL()         portEXIT_CRITICAL()
 #define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x )
 /**
  * task. h
@@ -209,7 +209,7 @@ typedef enum
  * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS
  * \ingroup SchedulerControl
  */
-#define taskDISABLE_INTERRUPTS()	portDISABLE_INTERRUPTS()
+#define taskDISABLE_INTERRUPTS()    portDISABLE_INTERRUPTS()
 
 /**
  * task. h
@@ -219,14 +219,14 @@ typedef enum
  * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS
  * \ingroup SchedulerControl
  */
-#define taskENABLE_INTERRUPTS()		portENABLE_INTERRUPTS()
+#define taskENABLE_INTERRUPTS()     portENABLE_INTERRUPTS()
 
 /* Definitions returned by xTaskGetSchedulerState().  taskSCHEDULER_SUSPENDED is
 0 to generate more optimal code when configASSERT() is defined as the constant
 is used in assert() statements. */
-#define taskSCHEDULER_SUSPENDED		( ( BaseType_t ) 0 )
-#define taskSCHEDULER_NOT_STARTED	( ( BaseType_t ) 1 )
-#define taskSCHEDULER_RUNNING		( ( BaseType_t ) 2 )
+#define taskSCHEDULER_SUSPENDED     ( ( BaseType_t ) 0 )
+#define taskSCHEDULER_NOT_STARTED   ( ( BaseType_t ) 1 )
+#define taskSCHEDULER_RUNNING       ( ( BaseType_t ) 2 )
 
 
 /*-----------------------------------------------------------
@@ -237,13 +237,13 @@ is used in assert() statements. */
  * task. h
  *
  BaseType_t xTaskCreate(
-							  TaskFunction_t pvTaskCode,
-							  const char * const pcName,
-							  configSTACK_DEPTH_TYPE usStackDepth,
-							  void *pvParameters,
-							  UBaseType_t uxPriority,
-							  TaskHandle_t *pvCreatedTask
-						  );
+ TaskFunction_t pvTaskCode, + const char * const pcName, + configSTACK_DEPTH_TYPE usStackDepth, + void *pvParameters, + UBaseType_t uxPriority, + TaskHandle_t *pvCreatedTask + );
* * Create a new task and add it to the list of tasks that are ready to run. * @@ -297,10 +297,10 @@ is used in assert() statements. */ // Task to be created. void vTaskCode( void * pvParameters ) { - for( ;; ) - { - // Task code goes here. - } + for( ;; ) + { + // Task code goes here. + } } // Function that creates a task. @@ -309,17 +309,17 @@ is used in assert() statements. */ static uint8_t ucParameterToPass; TaskHandle_t xHandle = NULL; - // Create the task, storing the handle. Note that the passed parameter ucParameterToPass - // must exist for the lifetime of the task, so in this case is declared static. If it was just an - // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time - // the new task attempts to access it. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); + // Create the task, storing the handle. Note that the passed parameter ucParameterToPass + // must exist for the lifetime of the task, so in this case is declared static. If it was just an + // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time + // the new task attempts to access it. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); configASSERT( xHandle ); - // Use the handle to delete the task. + // Use the handle to delete the task. if( xHandle != NULL ) { - vTaskDelete( xHandle ); + vTaskDelete( xHandle ); } } @@ -327,24 +327,24 @@ is used in assert() statements. */ * \ingroup Tasks */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; #endif /** * task. h *
  TaskHandle_t xTaskCreateStatic( TaskFunction_t pvTaskCode,
-								 const char * const pcName,
-								 uint32_t ulStackDepth,
-								 void *pvParameters,
-								 UBaseType_t uxPriority,
-								 StackType_t *pxStackBuffer,
-								 StaticTask_t *pxTaskBuffer );
+ const char * const pcName, + uint32_t ulStackDepth, + void *pvParameters, + UBaseType_t uxPriority, + StackType_t *pxStackBuffer, + StaticTask_t *pxTaskBuffer ); * * Create a new task and add it to the list of tasks that are ready to run. * @@ -443,13 +443,13 @@ is used in assert() statements. */ * \ingroup Tasks */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; #endif /* configSUPPORT_STATIC_ALLOCATION */ /** @@ -485,47 +485,47 @@ is used in assert() statements. */ // Create an TaskParameters_t structure that defines the task to be created. static const TaskParameters_t xCheckTaskParameters = { - vATask, // pvTaskCode - the function that implements the task. - "ATask", // pcName - just a text name for the task to assist debugging. - 100, // usStackDepth - the stack size DEFINED IN WORDS. - NULL, // pvParameters - passed into the task function as the function parameters. - ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. - cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + vATask, // pvTaskCode - the function that implements the task. + "ATask", // pcName - just a text name for the task to assist debugging. + 100, // usStackDepth - the stack size DEFINED IN WORDS. + NULL, // pvParameters - passed into the task function as the function parameters. + ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. - // xRegions - Allocate up to three separate memory regions for access by - // the task, with appropriate access permissions. Different processors have - // different memory alignment requirements - refer to the FreeRTOS documentation - // for full information. - { - // Base address Length Parameters - { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, - { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, - { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } - } + // xRegions - Allocate up to three separate memory regions for access by + // the task, with appropriate access permissions. Different processors have + // different memory alignment requirements - refer to the FreeRTOS documentation + // for full information. + { + // Base address Length Parameters + { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + } }; int main( void ) { TaskHandle_t xHandle; - // Create a task from the const structure defined above. The task handle - // is requested (the second parameter is not NULL) but in this case just for - // demonstration purposes as its not actually used. - xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + // Create a task from the const structure defined above. The task handle + // is requested (the second parameter is not NULL) but in this case just for + // demonstration purposes as its not actually used. + xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); - // Start the scheduler. - vTaskStartScheduler(); + // Start the scheduler. + vTaskStartScheduler(); - // Will only get here if there was insufficient memory to create the idle - // and/or timer task. - for( ;; ); + // Will only get here if there was insufficient memory to create the idle + // and/or timer task. + for( ;; ); } * \defgroup xTaskCreateRestricted xTaskCreateRestricted * \ingroup Tasks */ #if( portUSING_MPU_WRAPPERS == 1 ) - BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; #endif /** @@ -571,49 +571,49 @@ TaskHandle_t xHandle; static PRIVILEGED_DATA StaticTask_t xTaskBuffer; static const TaskParameters_t xCheckTaskParameters = { - vATask, // pvTaskCode - the function that implements the task. - "ATask", // pcName - just a text name for the task to assist debugging. - 100, // usStackDepth - the stack size DEFINED IN WORDS. - NULL, // pvParameters - passed into the task function as the function parameters. - ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. - cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + vATask, // pvTaskCode - the function that implements the task. + "ATask", // pcName - just a text name for the task to assist debugging. + 100, // usStackDepth - the stack size DEFINED IN WORDS. + NULL, // pvParameters - passed into the task function as the function parameters. + ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. - // xRegions - Allocate up to three separate memory regions for access by - // the task, with appropriate access permissions. Different processors have - // different memory alignment requirements - refer to the FreeRTOS documentation - // for full information. - { - // Base address Length Parameters - { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, - { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, - { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } - } + // xRegions - Allocate up to three separate memory regions for access by + // the task, with appropriate access permissions. Different processors have + // different memory alignment requirements - refer to the FreeRTOS documentation + // for full information. + { + // Base address Length Parameters + { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + } - &xTaskBuffer; // Holds the task's data structure. + &xTaskBuffer; // Holds the task's data structure. }; int main( void ) { TaskHandle_t xHandle; - // Create a task from the const structure defined above. The task handle - // is requested (the second parameter is not NULL) but in this case just for - // demonstration purposes as its not actually used. - xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + // Create a task from the const structure defined above. The task handle + // is requested (the second parameter is not NULL) but in this case just for + // demonstration purposes as its not actually used. + xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); - // Start the scheduler. - vTaskStartScheduler(); + // Start the scheduler. + vTaskStartScheduler(); - // Will only get here if there was insufficient memory to create the idle - // and/or timer task. - for( ;; ); + // Will only get here if there was insufficient memory to create the idle + // and/or timer task. + for( ;; ); } * \defgroup xTaskCreateRestrictedStatic xTaskCreateRestrictedStatic * \ingroup Tasks */ #if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; #endif /** @@ -638,25 +638,25 @@ TaskHandle_t xHandle; // unused so set to zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = { - // Base address Length Parameters - { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, - { 0, 0, 0 }, - { 0, 0, 0 } + // Base address Length Parameters + { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, + { 0, 0, 0 }, + { 0, 0, 0 } }; void vATask( void *pvParameters ) { - // This task was created such that it has access to certain regions of - // memory as defined by the MPU configuration. At some point it is - // desired that these MPU regions are replaced with that defined in the - // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() - // for this purpose. NULL is used as the task handle to indicate that this - // function should modify the MPU regions of the calling task. - vTaskAllocateMPURegions( NULL, xAltRegions ); + // This task was created such that it has access to certain regions of + // memory as defined by the MPU configuration. At some point it is + // desired that these MPU regions are replaced with that defined in the + // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() + // for this purpose. NULL is used as the task handle to indicate that this + // function should modify the MPU regions of the calling task. + vTaskAllocateMPURegions( NULL, xAltRegions ); - // Now the task can continue its function, but from this point on can only - // access its stack and the ucOneKByte array (unless any other statically - // defined or shared regions have been declared elsewhere). + // Now the task can continue its function, but from this point on can only + // access its stack and the ucOneKByte array (unless any other statically + // defined or shared regions have been declared elsewhere). } * \defgroup xTaskCreateRestricted xTaskCreateRestricted @@ -693,11 +693,11 @@ void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const p { TaskHandle_t xHandle; - // Create the task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create the task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // Use the handle to delete the task. - vTaskDelete( xHandle ); + // Use the handle to delete the task. + vTaskDelete( xHandle ); } * \defgroup vTaskDelete vTaskDelete @@ -744,12 +744,12 @@ void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; // Block for 500ms. const TickType_t xDelay = 500 / portTICK_PERIOD_MS; - for( ;; ) - { - // Simply toggle the LED every 500ms, blocking between each toggle. - vToggleLED(); - vTaskDelay( xDelay ); - } + for( ;; ) + { + // Simply toggle the LED every 500ms, blocking between each toggle. + vToggleLED(); + vTaskDelay( xDelay ); + } } * \defgroup vTaskDelay vTaskDelay @@ -800,15 +800,15 @@ void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; TickType_t xLastWakeTime; const TickType_t xFrequency = 10; - // Initialise the xLastWakeTime variable with the current time. - xLastWakeTime = xTaskGetTickCount (); - for( ;; ) - { - // Wait for the next cycle. - vTaskDelayUntil( &xLastWakeTime, xFrequency ); + // Initialise the xLastWakeTime variable with the current time. + xLastWakeTime = xTaskGetTickCount (); + for( ;; ) + { + // Wait for the next cycle. + vTaskDelayUntil( &xLastWakeTime, xFrequency ); - // Perform action here. - } + // Perform action here. + } } * \defgroup vTaskDelayUntil vTaskDelayUntil @@ -861,26 +861,26 @@ BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to obtain the priority of the created task. - // It was created with tskIDLE_PRIORITY, but may have changed - // it itself. - if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) - { - // The task has changed it's priority. - } + // Use the handle to obtain the priority of the created task. + // It was created with tskIDLE_PRIORITY, but may have changed + // it itself. + if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) + { + // The task has changed it's priority. + } - // ... + // ... - // Is our priority higher than the created task? - if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) - { - // Our priority (obtained using NULL handle) is higher. - } + // Is our priority higher than the created task? + if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) + { + // Our priority (obtained using NULL handle) is higher. + } } * \defgroup uxTaskPriorityGet uxTaskPriorityGet @@ -993,18 +993,18 @@ void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xG { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to raise the priority of the created task. - vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); + // Use the handle to raise the priority of the created task. + vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); - // ... + // ... - // Use a NULL handle to raise our priority to the same value. - vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); + // Use a NULL handle to raise our priority to the same value. + vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); } * \defgroup vTaskPrioritySet vTaskPrioritySet @@ -1035,27 +1035,27 @@ void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGE { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to suspend the created task. - vTaskSuspend( xHandle ); + // Use the handle to suspend the created task. + vTaskSuspend( xHandle ); - // ... + // ... - // The created task will not run during this period, unless - // another task calls vTaskResume( xHandle ). + // The created task will not run during this period, unless + // another task calls vTaskResume( xHandle ). - //... + //... - // Suspend ourselves. - vTaskSuspend( NULL ); + // Suspend ourselves. + vTaskSuspend( NULL ); - // We cannot get here unless another task calls vTaskResume - // with our handle as the parameter. + // We cannot get here unless another task calls vTaskResume + // with our handle as the parameter. } * \defgroup vTaskSuspend vTaskSuspend @@ -1084,27 +1084,27 @@ void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; { TaskHandle_t xHandle; - // Create a task, storing the handle. - xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); - // ... + // ... - // Use the handle to suspend the created task. - vTaskSuspend( xHandle ); + // Use the handle to suspend the created task. + vTaskSuspend( xHandle ); - // ... + // ... - // The created task will not run during this period, unless - // another task calls vTaskResume( xHandle ). + // The created task will not run during this period, unless + // another task calls vTaskResume( xHandle ). - //... + //... - // Resume the suspended task ourselves. - vTaskResume( xHandle ); + // Resume the suspended task ourselves. + vTaskResume( xHandle ); - // The created task will once again get microcontroller processing - // time in accordance with its priority within the system. + // The created task will once again get microcontroller processing + // time in accordance with its priority within the system. } * \defgroup vTaskResume vTaskResume @@ -1159,13 +1159,13 @@ BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
  void vAFunction( void )
  {
-	 // Create at least one task before starting the kernel.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+     // Create at least one task before starting the kernel.
+     xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
 
-	 // Start the real time kernel with preemption.
-	 vTaskStartScheduler ();
+     // Start the real time kernel with preemption.
+     vTaskStartScheduler ();
 
-	 // Will not get here unless a task calls vTaskEndScheduler ()
+     // Will not get here unless a task calls vTaskEndScheduler ()
  }
    
* @@ -1201,27 +1201,27 @@ void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;
  void vTaskCode( void * pvParameters )
  {
-	 for( ;; )
-	 {
-		 // Task code goes here.
+     for( ;; )
+     {
+         // Task code goes here.
 
-		 // At some point we want to end the real time kernel processing
-		 // so call ...
-		 vTaskEndScheduler ();
-	 }
+         // At some point we want to end the real time kernel processing
+         // so call ...
+         vTaskEndScheduler ();
+     }
  }
 
  void vAFunction( void )
  {
-	 // Create at least one task before starting the kernel.
-	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+     // Create at least one task before starting the kernel.
+     xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
 
-	 // Start the real time kernel with preemption.
-	 vTaskStartScheduler ();
+     // Start the real time kernel with preemption.
+     vTaskStartScheduler ();
 
-	 // Will only get here when the vTaskCode () task has called
-	 // vTaskEndScheduler ().  When we get here we are back to single task
-	 // execution.
+     // Will only get here when the vTaskCode () task has called
+     // vTaskEndScheduler ().  When we get here we are back to single task
+     // execution.
  }
    
* @@ -1249,31 +1249,31 @@ void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;
  void vTask1( void * pvParameters )
  {
-	 for( ;; )
-	 {
-		 // Task code goes here.
+     for( ;; )
+     {
+         // Task code goes here.
 
-		 // ...
+         // ...
 
-		 // At some point the task wants to perform a long operation during
-		 // which it does not want to get swapped out.  It cannot use
-		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
-		 // operation may cause interrupts to be missed - including the
-		 // ticks.
+         // At some point the task wants to perform a long operation during
+         // which it does not want to get swapped out.  It cannot use
+         // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+         // operation may cause interrupts to be missed - including the
+         // ticks.
 
-		 // Prevent the real time kernel swapping out the task.
-		 vTaskSuspendAll ();
+         // Prevent the real time kernel swapping out the task.
+         vTaskSuspendAll ();
 
-		 // Perform the operation here.  There is no need to use critical
-		 // sections as we have all the microcontroller processing time.
-		 // During this time interrupts will still operate and the kernel
-		 // tick count will be maintained.
+         // Perform the operation here.  There is no need to use critical
+         // sections as we have all the microcontroller processing time.
+         // During this time interrupts will still operate and the kernel
+         // tick count will be maintained.
 
-		 // ...
+         // ...
 
-		 // The operation is complete.  Restart the kernel.
-		 xTaskResumeAll ();
-	 }
+         // The operation is complete.  Restart the kernel.
+         xTaskResumeAll ();
+     }
  }
    
* \defgroup vTaskSuspendAll vTaskSuspendAll @@ -1292,42 +1292,42 @@ void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; * that were previously suspended by a call to vTaskSuspend(). * * @return If resuming the scheduler caused a context switch then pdTRUE is - * returned, otherwise pdFALSE is returned. + * returned, otherwise pdFALSE is returned. * * Example usage:
  void vTask1( void * pvParameters )
  {
-	 for( ;; )
-	 {
-		 // Task code goes here.
+     for( ;; )
+     {
+         // Task code goes here.
 
-		 // ...
+         // ...
 
-		 // At some point the task wants to perform a long operation during
-		 // which it does not want to get swapped out.  It cannot use
-		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
-		 // operation may cause interrupts to be missed - including the
-		 // ticks.
+         // At some point the task wants to perform a long operation during
+         // which it does not want to get swapped out.  It cannot use
+         // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+         // operation may cause interrupts to be missed - including the
+         // ticks.
 
-		 // Prevent the real time kernel swapping out the task.
-		 vTaskSuspendAll ();
+         // Prevent the real time kernel swapping out the task.
+         vTaskSuspendAll ();
 
-		 // Perform the operation here.  There is no need to use critical
-		 // sections as we have all the microcontroller processing time.
-		 // During this time interrupts will still operate and the real
-		 // time kernel tick count will be maintained.
+         // Perform the operation here.  There is no need to use critical
+         // sections as we have all the microcontroller processing time.
+         // During this time interrupts will still operate and the real
+         // time kernel tick count will be maintained.
 
-		 // ...
+         // ...
 
-		 // The operation is complete.  Restart the kernel.  We want to force
-		 // a context switch - but there is no point if resuming the scheduler
-		 // caused a context switch already.
-		 if( !xTaskResumeAll () )
-		 {
-			  taskYIELD ();
-		 }
-	 }
+         // The operation is complete.  Restart the kernel.  We want to force
+         // a context switch - but there is no point if resuming the scheduler
+         // caused a context switch already.
+         if( !xTaskResumeAll () )
+         {
+              taskYIELD ();
+         }
+     }
  }
    
* \defgroup xTaskResumeAll xTaskResumeAll @@ -1471,47 +1471,47 @@ fixed by simply guarding against the inclusion of these two prototypes unless they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration constant. */ #ifdef configUSE_APPLICATION_TASK_TAG - #if configUSE_APPLICATION_TASK_TAG == 1 - /** - * task.h - *
void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );
- * - * Sets pxHookFunction to be the task hook function used by the task xTask. - * Passing xTask as NULL has the effect of setting the calling tasks hook - * function. - */ - void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; + #if configUSE_APPLICATION_TASK_TAG == 1 + /** + * task.h + *
void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );
+ * + * Sets pxHookFunction to be the task hook function used by the task xTask. + * Passing xTask as NULL has the effect of setting the calling tasks hook + * function. + */ + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; - /** - * task.h - *
void xTaskGetApplicationTaskTag( TaskHandle_t xTask );
- * - * Returns the pxHookFunction value assigned to the task xTask. Do not - * call from an interrupt service routine - call - * xTaskGetApplicationTaskTagFromISR() instead. - */ - TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + /** + * task.h + *
void xTaskGetApplicationTaskTag( TaskHandle_t xTask );
+ * + * Returns the pxHookFunction value assigned to the task xTask. Do not + * call from an interrupt service routine - call + * xTaskGetApplicationTaskTagFromISR() instead. + */ + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - /** - * task.h - *
void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask );
- * - * Returns the pxHookFunction value assigned to the task xTask. Can - * be called from an interrupt service routine. - */ - TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; - #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ + /** + * task.h + *
void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask );
+ * + * Returns the pxHookFunction value assigned to the task xTask. Can + * be called from an interrupt service routine. + */ + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ #endif /* ifdef configUSE_APPLICATION_TASK_TAG */ #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - /* Each task contains an array of pointers that is dimensioned by the - configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The - kernel does not use the pointers itself, so the application writer can use - the pointers for any purpose they wish. The following two functions are - used to set and query a pointer respectively. */ - void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION; - void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION; + /* Each task contains an array of pointers that is dimensioned by the + configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The + kernel does not use the pointers itself, so the application writer can use + the pointers for any purpose they wish. The following two functions are + used to set and query a pointer respectively. */ + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION; + void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION; #endif @@ -1574,65 +1574,65 @@ TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; * Example usage:
     // This example demonstrates how a human readable table of run time stats
-	// information is generated from raw data provided by uxTaskGetSystemState().
-	// The human readable table is written to pcWriteBuffer
-	void vTaskGetRunTimeStats( char *pcWriteBuffer )
-	{
-	TaskStatus_t *pxTaskStatusArray;
-	volatile UBaseType_t uxArraySize, x;
-	uint32_t ulTotalRunTime, ulStatsAsPercentage;
+    // information is generated from raw data provided by uxTaskGetSystemState().
+    // The human readable table is written to pcWriteBuffer
+    void vTaskGetRunTimeStats( char *pcWriteBuffer )
+    {
+    TaskStatus_t *pxTaskStatusArray;
+    volatile UBaseType_t uxArraySize, x;
+    uint32_t ulTotalRunTime, ulStatsAsPercentage;
 
-		// Make sure the write buffer does not contain a string.
-		*pcWriteBuffer = 0x00;
+        // Make sure the write buffer does not contain a string.
+        *pcWriteBuffer = 0x00;
 
-		// Take a snapshot of the number of tasks in case it changes while this
-		// function is executing.
-		uxArraySize = uxTaskGetNumberOfTasks();
+        // Take a snapshot of the number of tasks in case it changes while this
+        // function is executing.
+        uxArraySize = uxTaskGetNumberOfTasks();
 
-		// Allocate a TaskStatus_t structure for each task.  An array could be
-		// allocated statically at compile time.
-		pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
+        // Allocate a TaskStatus_t structure for each task.  An array could be
+        // allocated statically at compile time.
+        pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
 
-		if( pxTaskStatusArray != NULL )
-		{
-			// Generate raw status information about each task.
-			uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
+        if( pxTaskStatusArray != NULL )
+        {
+            // Generate raw status information about each task.
+            uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
 
-			// For percentage calculations.
-			ulTotalRunTime /= 100UL;
+            // For percentage calculations.
+            ulTotalRunTime /= 100UL;
 
-			// Avoid divide by zero errors.
-			if( ulTotalRunTime > 0 )
-			{
-				// For each populated position in the pxTaskStatusArray array,
-				// format the raw data as human readable ASCII data
-				for( x = 0; x < uxArraySize; x++ )
-				{
-					// What percentage of the total run time has the task used?
-					// This will always be rounded down to the nearest integer.
-					// ulTotalRunTimeDiv100 has already been divided by 100.
-					ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
+            // Avoid divide by zero errors.
+            if( ulTotalRunTime > 0 )
+            {
+                // For each populated position in the pxTaskStatusArray array,
+                // format the raw data as human readable ASCII data
+                for( x = 0; x < uxArraySize; x++ )
+                {
+                    // What percentage of the total run time has the task used?
+                    // This will always be rounded down to the nearest integer.
+                    // ulTotalRunTimeDiv100 has already been divided by 100.
+                    ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
 
-					if( ulStatsAsPercentage > 0UL )
-					{
-						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
-					}
-					else
-					{
-						// If the percentage is zero here then the task has
-						// consumed less than 1% of the total run time.
-						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
-					}
+                    if( ulStatsAsPercentage > 0UL )
+                    {
+                        sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
+                    }
+                    else
+                    {
+                        // If the percentage is zero here then the task has
+                        // consumed less than 1% of the total run time.
+                        sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
+                    }
 
-					pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
-				}
-			}
+                    pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
+                }
+            }
 
-			// The array is no longer needed, free the memory it consumes.
-			vPortFree( pxTaskStatusArray );
-		}
-	}
-	
+ // The array is no longer needed, free the memory it consumes. + vPortFree( pxTaskStatusArray ); + } + } + */ UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) PRIVILEGED_FUNCTION; diff --git a/components/bl602/freertos_riscv_ram/config/timers.h b/components/bl602/freertos_riscv_ram/config/timers.h index cb721797..67a238c3 100644 --- a/components/bl602/freertos_riscv_ram/config/timers.h +++ b/components/bl602/freertos_riscv_ram/config/timers.h @@ -30,7 +30,7 @@ #define TIMERS_H #ifndef INC_FREERTOS_H - #error "include FreeRTOS.h must appear in source files before include timers.h" + #error "include FreeRTOS.h must appear in source files before include timers.h" #endif /*lint -save -e537 This headers are only multiply included if the application code @@ -51,20 +51,20 @@ be used solely through the macros that make up the public software timer API, as defined below. The commands that are sent from interrupts must use the highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task or interrupt version of the queue send function should be used. */ -#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) -#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) -#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) -#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) -#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) -#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) -#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) -#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) +#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) +#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) +#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) +#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) +#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) +#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) +#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) +#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) -#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) -#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) -#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) -#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) -#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) +#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) +#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) +#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) /** @@ -88,11 +88,11 @@ typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer ); typedef void (*PendedFunction_t)( void *, uint32_t ); /** - * TimerHandle_t xTimerCreate( const char * const pcTimerName, - * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, - * void * pvTimerID, - * TimerCallbackFunction_t pxCallbackFunction ); + * TimerHandle_t xTimerCreate( const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction ); * * Creates a new software timer instance, and returns a handle by which the * created software timer can be referenced. @@ -135,7 +135,7 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * * @param pxCallbackFunction The function to call when the timer expires. * Callback functions must have the prototype defined by TimerCallbackFunction_t, - * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * which is "void vCallbackFunction( TimerHandle_t xTimer );". * * @return If the timer is successfully created then a handle to the newly * created timer is returned. If the timer cannot be created (because either @@ -161,8 +161,8 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * int32_t lArrayIndex; * const int32_t xMaxExpiryCountBeforeStopping = 10; * - * // Optionally do something if the pxTimer parameter is NULL. - * configASSERT( pxTimer ); + * // Optionally do something if the pxTimer parameter is NULL. + * configASSERT( pxTimer ); * * // Which timer expired? * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); @@ -225,20 +225,20 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * @endverbatim */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; #endif /** * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, - * TickType_t xTimerPeriodInTicks, - * UBaseType_t uxAutoReload, - * void * pvTimerID, - * TimerCallbackFunction_t pxCallbackFunction, - * StaticTimer_t *pxTimerBuffer ); + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction, + * StaticTimer_t *pxTimerBuffer ); * * Creates a new software timer instance, and returns a handle by which the * created software timer can be referenced. @@ -355,12 +355,12 @@ typedef void (*PendedFunction_t)( void *, uint32_t ); * @endverbatim */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t *pxTimerBuffer ) PRIVILEGED_FUNCTION; + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t *pxTimerBuffer ) PRIVILEGED_FUNCTION; #endif /* configSUPPORT_STATIC_ALLOCATION */ /** @@ -546,9 +546,9 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerStop( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) /** - * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, - * TickType_t xNewPeriod, - * TickType_t xTicksToWait ); + * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * TickType_t xTicksToWait ); * * Timer functionality is provided by a timer service/daemon task. Many of the * public FreeRTOS timer API functions send commands to the timer service task @@ -788,8 +788,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerReset( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) /** - * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerStart() that can be called from an interrupt service * routine. @@ -874,8 +874,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) /** - * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerStop() that can be called from an interrupt service * routine. @@ -938,8 +938,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; /** * BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, - * TickType_t xNewPeriod, - * BaseType_t *pxHigherPriorityTaskWoken ); + * TickType_t xNewPeriod, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerChangePeriod() that can be called from an interrupt * service routine. @@ -1010,8 +1010,8 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; #define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) /** - * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, - * BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); * * A version of xTimerReset() that can be called from an interrupt service * routine. @@ -1146,42 +1146,42 @@ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; * Example usage: * @verbatim * - * // The callback function that will execute in the context of the daemon task. + * // The callback function that will execute in the context of the daemon task. * // Note callback functions must all use this same prototype. * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) - * { - * BaseType_t xInterfaceToService; + * { + * BaseType_t xInterfaceToService; * - * // The interface that requires servicing is passed in the second + * // The interface that requires servicing is passed in the second * // parameter. The first parameter is not used in this case. - * xInterfaceToService = ( BaseType_t ) ulParameter2; + * xInterfaceToService = ( BaseType_t ) ulParameter2; * - * // ...Perform the processing here... - * } + * // ...Perform the processing here... + * } * - * // An ISR that receives data packets from multiple interfaces + * // An ISR that receives data packets from multiple interfaces * void vAnISR( void ) - * { - * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; + * { + * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; * - * // Query the hardware to determine which interface needs processing. - * xInterfaceToService = prvCheckInterfaces(); + * // Query the hardware to determine which interface needs processing. + * xInterfaceToService = prvCheckInterfaces(); * * // The actual processing is to be deferred to a task. Request the * // vProcessInterface() callback function is executed, passing in the - * // number of the interface that needs processing. The interface to - * // service is passed in the second parameter. The first parameter is - * // not used in this case. - * xHigherPriorityTaskWoken = pdFALSE; - * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); + * // number of the interface that needs processing. The interface to + * // service is passed in the second parameter. The first parameter is + * // not used in this case. + * xHigherPriorityTaskWoken = pdFALSE; + * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); * - * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context - * // switch should be requested. The macro used is port specific and will - * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to - * // the documentation page for the port being used. - * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and will + * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to + * // the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); * - * } + * } * @endverbatim */ BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; @@ -1282,8 +1282,8 @@ BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; #if( configUSE_TRACE_FACILITY == 1 ) - void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; - UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; #endif #ifdef __cplusplus diff --git a/components/bl602/freertos_riscv_ram/croutine.c b/components/bl602/freertos_riscv_ram/croutine.c index 56c8ac29..07df1cd8 100644 --- a/components/bl602/freertos_riscv_ram/croutine.c +++ b/components/bl602/freertos_riscv_ram/croutine.c @@ -37,17 +37,17 @@ * than file scope. */ #ifdef portREMOVE_STATIC_QUALIFIER - #define static + #define static #endif /* Lists for ready and blocked co-routines. --------------------*/ -static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ -static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ -static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ -static List_t * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */ -static List_t * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ -static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ +static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ +static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ +static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ +static List_t * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */ +static List_t * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ +static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ /* Other file private variables. --------------------------------*/ CRCB_t * pxCurrentCoRoutine = NULL; @@ -55,7 +55,7 @@ static UBaseType_t uxTopCoRoutineReadyPriority = 0; static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; /* The initial state of the co-routine when it is created. */ -#define corINITIAL_STATE ( 0 ) +#define corINITIAL_STATE ( 0 ) /* * Place the co-routine represented by pxCRCB into the appropriate ready queue @@ -64,13 +64,13 @@ static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; * This macro accesses the co-routine ready lists and therefore must not be * used from within an ISR. */ -#define prvAddCoRoutineToReadyQueue( pxCRCB ) \ -{ \ - if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ - { \ - uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ - } \ - vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ +#define prvAddCoRoutineToReadyQueue( pxCRCB ) \ +{ \ + if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ + { \ + uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ + } \ + vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ } /* @@ -104,55 +104,55 @@ BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPri BaseType_t xReturn; CRCB_t *pxCoRoutine; - /* Allocate the memory that will store the co-routine control block. */ - pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); - if( pxCoRoutine ) - { - /* If pxCurrentCoRoutine is NULL then this is the first co-routine to - be created and the co-routine data structures need initialising. */ - if( pxCurrentCoRoutine == NULL ) - { - pxCurrentCoRoutine = pxCoRoutine; - prvInitialiseCoRoutineLists(); - } + /* Allocate the memory that will store the co-routine control block. */ + pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); + if( pxCoRoutine ) + { + /* If pxCurrentCoRoutine is NULL then this is the first co-routine to + be created and the co-routine data structures need initialising. */ + if( pxCurrentCoRoutine == NULL ) + { + pxCurrentCoRoutine = pxCoRoutine; + prvInitialiseCoRoutineLists(); + } - /* Check the priority is within limits. */ - if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) - { - uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; - } + /* Check the priority is within limits. */ + if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) + { + uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; + } - /* Fill out the co-routine control block from the function parameters. */ - pxCoRoutine->uxState = corINITIAL_STATE; - pxCoRoutine->uxPriority = uxPriority; - pxCoRoutine->uxIndex = uxIndex; - pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; + /* Fill out the co-routine control block from the function parameters. */ + pxCoRoutine->uxState = corINITIAL_STATE; + pxCoRoutine->uxPriority = uxPriority; + pxCoRoutine->uxIndex = uxIndex; + pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; - /* Initialise all the other co-routine control block parameters. */ - vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); - vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); + /* Initialise all the other co-routine control block parameters. */ + vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); + vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); - /* Set the co-routine control block as a link back from the ListItem_t. - This is so we can get back to the containing CRCB from a generic item - in a list. */ - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); - listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); + /* Set the co-routine control block as a link back from the ListItem_t. + This is so we can get back to the containing CRCB from a generic item + in a list. */ + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); - /* Now the co-routine has been initialised it can be added to the ready - list at the correct priority. */ - prvAddCoRoutineToReadyQueue( pxCoRoutine ); + /* Now the co-routine has been initialised it can be added to the ready + list at the correct priority. */ + prvAddCoRoutineToReadyQueue( pxCoRoutine ); - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -160,60 +160,60 @@ void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList ) { TickType_t xTimeToWake; - /* Calculate the time to wake - this may overflow but this is - not a problem. */ - xTimeToWake = xCoRoutineTickCount + xTicksToDelay; + /* Calculate the time to wake - this may overflow but this is + not a problem. */ + xTimeToWake = xCoRoutineTickCount + xTicksToDelay; - /* We must remove ourselves from the ready list before adding - ourselves to the blocked list as the same list item is used for - both lists. */ - ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + /* We must remove ourselves from the ready list before adding + ourselves to the blocked list as the same list item is used for + both lists. */ + ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); - if( xTimeToWake < xCoRoutineTickCount ) - { - /* Wake time has overflowed. Place this item in the - overflow list. */ - vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } - else - { - /* The wake time has not overflowed, so we can use the - current block list. */ - vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); - } + if( xTimeToWake < xCoRoutineTickCount ) + { + /* Wake time has overflowed. Place this item in the + overflow list. */ + vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + else + { + /* The wake time has not overflowed, so we can use the + current block list. */ + vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } - if( pxEventList ) - { - /* Also add the co-routine to an event list. If this is done then the - function must be called with interrupts disabled. */ - vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); - } + if( pxEventList ) + { + /* Also add the co-routine to an event list. If this is done then the + function must be called with interrupts disabled. */ + vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); + } } /*-----------------------------------------------------------*/ static void prvCheckPendingReadyList( void ) { - /* Are there any co-routines waiting to get moved to the ready list? These - are co-routines that have been readied by an ISR. The ISR cannot access - the ready lists itself. */ - while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) - { - CRCB_t *pxUnblockedCRCB; + /* Are there any co-routines waiting to get moved to the ready list? These + are co-routines that have been readied by an ISR. The ISR cannot access + the ready lists itself. */ + while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) + { + CRCB_t *pxUnblockedCRCB; - /* The pending ready list can be accessed by an ISR. */ - portDISABLE_INTERRUPTS(); - { - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - } - portENABLE_INTERRUPTS(); + /* The pending ready list can be accessed by an ISR. */ + portDISABLE_INTERRUPTS(); + { + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + } + portENABLE_INTERRUPTS(); - ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); - prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); - } + ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); + prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); + } } /*-----------------------------------------------------------*/ @@ -221,87 +221,87 @@ static void prvCheckDelayedList( void ) { CRCB_t *pxCRCB; - xPassedTicks = xTaskGetTickCount() - xLastTickCount; - while( xPassedTicks ) - { - xCoRoutineTickCount++; - xPassedTicks--; + xPassedTicks = xTaskGetTickCount() - xLastTickCount; + while( xPassedTicks ) + { + xCoRoutineTickCount++; + xPassedTicks--; - /* If the tick count has overflowed we need to swap the ready lists. */ - if( xCoRoutineTickCount == 0 ) - { - List_t * pxTemp; + /* If the tick count has overflowed we need to swap the ready lists. */ + if( xCoRoutineTickCount == 0 ) + { + List_t * pxTemp; - /* Tick count has overflowed so we need to swap the delay lists. If there are - any items in pxDelayedCoRoutineList here then there is an error! */ - pxTemp = pxDelayedCoRoutineList; - pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; - pxOverflowDelayedCoRoutineList = pxTemp; - } + /* Tick count has overflowed so we need to swap the delay lists. If there are + any items in pxDelayedCoRoutineList here then there is an error! */ + pxTemp = pxDelayedCoRoutineList; + pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; + pxOverflowDelayedCoRoutineList = pxTemp; + } - /* See if this tick has made a timeout expire. */ - while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) - { - pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); + /* See if this tick has made a timeout expire. */ + while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) + { + pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); - if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) - { - /* Timeout not yet expired. */ - break; - } + if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) + { + /* Timeout not yet expired. */ + break; + } - portDISABLE_INTERRUPTS(); - { - /* The event could have occurred just before this critical - section. If this is the case then the generic list item will - have been moved to the pending ready list and the following - line is still valid. Also the pvContainer parameter will have - been set to NULL so the following lines are also valid. */ - ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); + portDISABLE_INTERRUPTS(); + { + /* The event could have occurred just before this critical + section. If this is the case then the generic list item will + have been moved to the pending ready list and the following + line is still valid. Also the pvContainer parameter will have + been set to NULL so the following lines are also valid. */ + ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); - /* Is the co-routine waiting on an event also? */ - if( pxCRCB->xEventListItem.pxContainer ) - { - ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); - } - } - portENABLE_INTERRUPTS(); + /* Is the co-routine waiting on an event also? */ + if( pxCRCB->xEventListItem.pxContainer ) + { + ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); + } + } + portENABLE_INTERRUPTS(); - prvAddCoRoutineToReadyQueue( pxCRCB ); - } - } + prvAddCoRoutineToReadyQueue( pxCRCB ); + } + } - xLastTickCount = xCoRoutineTickCount; + xLastTickCount = xCoRoutineTickCount; } /*-----------------------------------------------------------*/ void vCoRoutineSchedule( void ) { - /* See if any co-routines readied by events need moving to the ready lists. */ - prvCheckPendingReadyList(); + /* See if any co-routines readied by events need moving to the ready lists. */ + prvCheckPendingReadyList(); - /* See if any delayed co-routines have timed out. */ - prvCheckDelayedList(); + /* See if any delayed co-routines have timed out. */ + prvCheckDelayedList(); - /* Find the highest priority queue that contains ready co-routines. */ - while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) - { - if( uxTopCoRoutineReadyPriority == 0 ) - { - /* No more co-routines to check. */ - return; - } - --uxTopCoRoutineReadyPriority; - } + /* Find the highest priority queue that contains ready co-routines. */ + while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) + { + if( uxTopCoRoutineReadyPriority == 0 ) + { + /* No more co-routines to check. */ + return; + } + --uxTopCoRoutineReadyPriority; + } - /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines - of the same priority get an equal share of the processor time. */ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); + /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines + of the same priority get an equal share of the processor time. */ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); - /* Call the co-routine. */ - ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); + /* Call the co-routine. */ + ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); - return; + return; } /*-----------------------------------------------------------*/ @@ -309,19 +309,19 @@ static void prvInitialiseCoRoutineLists( void ) { UBaseType_t uxPriority; - for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) - { - vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); - } + for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) + { + vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); + } - vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); - vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); - vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); + vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); + vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); + vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); - /* Start with pxDelayedCoRoutineList using list1 and the - pxOverflowDelayedCoRoutineList using list2. */ - pxDelayedCoRoutineList = &xDelayedCoRoutineList1; - pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; + /* Start with pxDelayedCoRoutineList using list1 and the + pxOverflowDelayedCoRoutineList using list2. */ + pxDelayedCoRoutineList = &xDelayedCoRoutineList1; + pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; } /*-----------------------------------------------------------*/ @@ -330,23 +330,23 @@ BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList ) CRCB_t *pxUnblockedCRCB; BaseType_t xReturn; - /* This function is called from within an interrupt. It can only access - event lists and the pending ready list. This function assumes that a - check has already been made to ensure pxEventList is not empty. */ - pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); - ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); - vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); + /* This function is called from within an interrupt. It can only access + event lists and the pending ready list. This function assumes that a + check has already been made to ensure pxEventList is not empty. */ + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); - if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } #endif /* configUSE_CO_ROUTINES == 0 */ diff --git a/components/bl602/freertos_riscv_ram/event_groups.c b/components/bl602/freertos_riscv_ram/event_groups.c index 65a5ff25..155fc187 100644 --- a/components/bl602/freertos_riscv_ram/event_groups.c +++ b/components/bl602/freertos_riscv_ram/event_groups.c @@ -49,29 +49,29 @@ correct privileged Vs unprivileged linkage and placement. */ item value. It is important they don't clash with the taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */ #if configUSE_16_BIT_TICKS == 1 - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U - #define eventWAIT_FOR_ALL_BITS 0x0400U - #define eventEVENT_BITS_CONTROL_BYTES 0xff00U + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U + #define eventWAIT_FOR_ALL_BITS 0x0400U + #define eventEVENT_BITS_CONTROL_BYTES 0xff00U #else - #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL - #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL - #define eventWAIT_FOR_ALL_BITS 0x04000000UL - #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL + #define eventWAIT_FOR_ALL_BITS 0x04000000UL + #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL #endif typedef struct EventGroupDef_t { - EventBits_t uxEventBits; - List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ + EventBits_t uxEventBits; + List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxEventGroupNumber; - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxEventGroupNumber; + #endif - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ + #endif } EventGroup_t; /*-----------------------------------------------------------*/ @@ -90,100 +90,100 @@ static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, co #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) - { - EventGroup_t *pxEventBits; + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) + { + EventGroup_t *pxEventBits; - /* A StaticEventGroup_t object must be provided. */ - configASSERT( pxEventGroupBuffer ); + /* A StaticEventGroup_t object must be provided. */ + configASSERT( pxEventGroupBuffer ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticEventGroup_t equals the size of the real - event group structure. */ - volatile size_t xSize = sizeof( StaticEventGroup_t ); - configASSERT( xSize == sizeof( EventGroup_t ) ); - } /*lint !e529 xSize is referenced if configASSERT() is defined. */ - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticEventGroup_t equals the size of the real + event group structure. */ + volatile size_t xSize = sizeof( StaticEventGroup_t ); + configASSERT( xSize == sizeof( EventGroup_t ) ); + } /*lint !e529 xSize is referenced if configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ - /* The user has provided a statically allocated event group - use it. */ - pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ + /* The user has provided a statically allocated event group - use it. */ + pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note that - this event group was created statically in case the event group - is later deleted. */ - pxEventBits->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note that + this event group was created statically in case the event group + is later deleted. */ + pxEventBits->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - /* xEventGroupCreateStatic should only ever be called with - pxEventGroupBuffer pointing to a pre-allocated (compile time - allocated) StaticEventGroup_t variable. */ - traceEVENT_GROUP_CREATE_FAILED(); - } + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + /* xEventGroupCreateStatic should only ever be called with + pxEventGroupBuffer pointing to a pre-allocated (compile time + allocated) StaticEventGroup_t variable. */ + traceEVENT_GROUP_CREATE_FAILED(); + } - return pxEventBits; - } + return pxEventBits; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - EventGroupHandle_t xEventGroupCreate( void ) - { - EventGroup_t *pxEventBits; + EventGroupHandle_t xEventGroupCreate( void ) + { + EventGroup_t *pxEventBits; - /* Allocate the event group. Justification for MISRA deviation as - follows: pvPortMalloc() always ensures returned memory blocks are - aligned per the requirements of the MCU stack. In this case - pvPortMalloc() must return a pointer that is guaranteed to meet the - alignment requirements of the EventGroup_t structure - which (if you - follow it through) is the alignment requirements of the TickType_t type - (EventBits_t being of TickType_t itself). Therefore, whenever the - stack alignment requirements are greater than or equal to the - TickType_t alignment requirements the cast is safe. In other cases, - where the natural word size of the architecture is less than - sizeof( TickType_t ), the TickType_t variables will be accessed in two - or more reads operations, and the alignment requirements is only that - of each individual read. */ - pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */ + /* Allocate the event group. Justification for MISRA deviation as + follows: pvPortMalloc() always ensures returned memory blocks are + aligned per the requirements of the MCU stack. In this case + pvPortMalloc() must return a pointer that is guaranteed to meet the + alignment requirements of the EventGroup_t structure - which (if you + follow it through) is the alignment requirements of the TickType_t type + (EventBits_t being of TickType_t itself). Therefore, whenever the + stack alignment requirements are greater than or equal to the + TickType_t alignment requirements the cast is safe. In other cases, + where the natural word size of the architecture is less than + sizeof( TickType_t ), the TickType_t variables will be accessed in two + or more reads operations, and the alignment requirements is only that + of each individual read. */ + pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */ - if( pxEventBits != NULL ) - { - pxEventBits->uxEventBits = 0; - vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Both static and dynamic allocation can be used, so note this - event group was allocated statically in case the event group is - later deleted. */ - pxEventBits->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note this + event group was allocated statically in case the event group is + later deleted. */ + pxEventBits->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ - traceEVENT_GROUP_CREATE( pxEventBits ); - } - else - { - traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */ - } + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */ + } - return pxEventBits; - } + return pxEventBits; + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ @@ -195,116 +195,116 @@ EventGroup_t *pxEventBits = xEventGroup; BaseType_t xAlreadyYielded; BaseType_t xTimeoutOccurred = pdFALSE; - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - vTaskSuspendAll(); - { - uxOriginalBitValue = pxEventBits->uxEventBits; + vTaskSuspendAll(); + { + uxOriginalBitValue = pxEventBits->uxEventBits; - ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); + ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); - if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - /* All the rendezvous bits are now set - no need to block. */ - uxReturn = ( uxOriginalBitValue | uxBitsToSet ); + if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + /* All the rendezvous bits are now set - no need to block. */ + uxReturn = ( uxOriginalBitValue | uxBitsToSet ); - /* Rendezvous always clear the bits. They will have been cleared - already unless this is the only task in the rendezvous. */ - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + /* Rendezvous always clear the bits. They will have been cleared + already unless this is the only task in the rendezvous. */ + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - xTicksToWait = 0; - } - else - { - if( xTicksToWait != ( TickType_t ) 0 ) - { - traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); + xTicksToWait = 0; + } + else + { + if( xTicksToWait != ( TickType_t ) 0 ) + { + traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); - /* Store the bits that the calling task is waiting for in the - task's event list item so the kernel knows when a match is - found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); + /* Store the bits that the calling task is waiting for in the + task's event list item so the kernel knows when a match is + found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); - /* This assignment is obsolete as uxReturn will get set after - the task unblocks, but some compilers mistakenly generate a - warning about uxReturn being returned without being set if the - assignment is omitted. */ - uxReturn = 0; - } - else - { - /* The rendezvous bits were not set, but no block time was - specified - just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; - xTimeoutOccurred = pdTRUE; - } - } - } - xAlreadyYielded = xTaskResumeAll(); + /* This assignment is obsolete as uxReturn will get set after + the task unblocks, but some compilers mistakenly generate a + warning about uxReturn being returned without being set if the + assignment is omitted. */ + uxReturn = 0; + } + else + { + /* The rendezvous bits were not set, but no block time was + specified - just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + xTimeoutOccurred = pdTRUE; + } + } + } + xAlreadyYielded = xTaskResumeAll(); - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The task blocked to wait for its required bits to be set - at this - point either the required bits were set or the block time expired. If - the required bits were set they will have been stored in the task's - event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); + /* The task blocked to wait for its required bits to be set - at this + point either the required bits were set or the block time expired. If + the required bits were set they will have been stored in the task's + event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - /* The task timed out, just return the current event bit value. */ - taskENTER_CRITICAL(); - { - uxReturn = pxEventBits->uxEventBits; + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + /* The task timed out, just return the current event bit value. */ + taskENTER_CRITICAL(); + { + uxReturn = pxEventBits->uxEventBits; - /* Although the task got here because it timed out before the - bits it was waiting for were set, it is possible that since it - unblocked another task has set the bits. If this is the case - then it needs to clear the bits before exiting. */ - if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* Although the task got here because it timed out before the + bits it was waiting for were set, it is possible that since it + unblocked another task has set the bits. If this is the case + then it needs to clear the bits before exiting. */ + if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task unblocked because the bits were set. */ - } + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task unblocked because the bits were set. */ + } - /* Control bits might be set as the task had blocked should not be - returned. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } + /* Control bits might be set as the task had blocked should not be + returned. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } - traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); + traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ @@ -315,146 +315,146 @@ EventBits_t uxReturn, uxControlBits = 0; BaseType_t xWaitConditionMet, xAlreadyYielded; BaseType_t xTimeoutOccurred = pdFALSE; - /* Check the user is not attempting to wait on the bits used by the kernel - itself, and that at least one bit is being requested. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - configASSERT( uxBitsToWaitFor != 0 ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Check the user is not attempting to wait on the bits used by the kernel + itself, and that at least one bit is being requested. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - vTaskSuspendAll(); - { - const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; + vTaskSuspendAll(); + { + const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; - /* Check to see if the wait condition is already met or not. */ - xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); + /* Check to see if the wait condition is already met or not. */ + xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); - if( xWaitConditionMet != pdFALSE ) - { - /* The wait condition has already been met so there is no need to - block. */ - uxReturn = uxCurrentEventBits; - xTicksToWait = ( TickType_t ) 0; + if( xWaitConditionMet != pdFALSE ) + { + /* The wait condition has already been met so there is no need to + block. */ + uxReturn = uxCurrentEventBits; + xTicksToWait = ( TickType_t ) 0; - /* Clear the wait bits if requested to do so. */ - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The wait condition has not been met, but no block time was - specified, so just return the current value. */ - uxReturn = uxCurrentEventBits; - xTimeoutOccurred = pdTRUE; - } - else - { - /* The task is going to block to wait for its required bits to be - set. uxControlBits are used to remember the specified behaviour of - this call to xEventGroupWaitBits() - for use when the event bits - unblock the task. */ - if( xClearOnExit != pdFALSE ) - { - uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Clear the wait bits if requested to do so. */ + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The wait condition has not been met, but no block time was + specified, so just return the current value. */ + uxReturn = uxCurrentEventBits; + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task is going to block to wait for its required bits to be + set. uxControlBits are used to remember the specified behaviour of + this call to xEventGroupWaitBits() - for use when the event bits + unblock the task. */ + if( xClearOnExit != pdFALSE ) + { + uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xWaitForAllBits != pdFALSE ) - { - uxControlBits |= eventWAIT_FOR_ALL_BITS; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xWaitForAllBits != pdFALSE ) + { + uxControlBits |= eventWAIT_FOR_ALL_BITS; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Store the bits that the calling task is waiting for in the - task's event list item so the kernel knows when a match is - found. Then enter the blocked state. */ - vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); + /* Store the bits that the calling task is waiting for in the + task's event list item so the kernel knows when a match is + found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); - /* This is obsolete as it will get set after the task unblocks, but - some compilers mistakenly generate a warning about the variable - being returned without being set if it is not done. */ - uxReturn = 0; + /* This is obsolete as it will get set after the task unblocks, but + some compilers mistakenly generate a warning about the variable + being returned without being set if it is not done. */ + uxReturn = 0; - traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); - } - } - xAlreadyYielded = xTaskResumeAll(); + traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); + } + } + xAlreadyYielded = xTaskResumeAll(); - if( xTicksToWait != ( TickType_t ) 0 ) - { - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The task blocked to wait for its required bits to be set - at this - point either the required bits were set or the block time expired. If - the required bits were set they will have been stored in the task's - event list item, and they should now be retrieved then cleared. */ - uxReturn = uxTaskResetEventItemValue(); + /* The task blocked to wait for its required bits to be set - at this + point either the required bits were set or the block time expired. If + the required bits were set they will have been stored in the task's + event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); - if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) - { - taskENTER_CRITICAL(); - { - /* The task timed out, just return the current event bit value. */ - uxReturn = pxEventBits->uxEventBits; + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + taskENTER_CRITICAL(); + { + /* The task timed out, just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; - /* It is possible that the event bits were updated between this - task leaving the Blocked state and running again. */ - if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) - { - if( xClearOnExit != pdFALSE ) - { - pxEventBits->uxEventBits &= ~uxBitsToWaitFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - xTimeoutOccurred = pdTRUE; - } - taskEXIT_CRITICAL(); - } - else - { - /* The task unblocked because the bits were set. */ - } + /* It is possible that the event bits were updated between this + task leaving the Blocked state and running again. */ + if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) + { + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + xTimeoutOccurred = pdTRUE; + } + taskEXIT_CRITICAL(); + } + else + { + /* The task unblocked because the bits were set. */ + } - /* The task blocked so control bits may have been set. */ - uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; - } - traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); + /* The task blocked so control bits may have been set. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); - /* Prevent compiler warnings when trace macros are not used. */ - ( void ) xTimeoutOccurred; + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ @@ -463,39 +463,39 @@ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBit EventGroup_t *pxEventBits = xEventGroup; EventBits_t uxReturn; - /* Check the user is not attempting to clear the bits used by the kernel - itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + /* Check the user is not attempting to clear the bits used by the kernel + itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - taskENTER_CRITICAL(); - { - traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); + taskENTER_CRITICAL(); + { + traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); - /* The value returned is the event group value prior to the bits being - cleared. */ - uxReturn = pxEventBits->uxEventBits; + /* The value returned is the event group value prior to the bits being + cleared. */ + uxReturn = pxEventBits->uxEventBits; - /* Clear the bits. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - taskEXIT_CRITICAL(); + /* Clear the bits. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + taskEXIT_CRITICAL(); - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) - { - BaseType_t xReturn; + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) + { + BaseType_t xReturn; - traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ - return xReturn; - } + return xReturn; + } #endif /*-----------------------------------------------------------*/ @@ -506,13 +506,13 @@ UBaseType_t uxSavedInterruptStatus; EventGroup_t const * const pxEventBits = xEventGroup; EventBits_t uxReturn; - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - uxReturn = pxEventBits->uxEventBits; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + uxReturn = pxEventBits->uxEventBits; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return uxReturn; + return uxReturn; } /*lint !e818 EventGroupHandle_t is a typedef used in other functions to so can't be pointer to const. */ /*-----------------------------------------------------------*/ @@ -525,88 +525,88 @@ EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits; EventGroup_t *pxEventBits = xEventGroup; BaseType_t xMatchFound = pdFALSE; - /* Check the user is not attempting to set the bits used by the kernel - itself. */ - configASSERT( xEventGroup ); - configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + /* Check the user is not attempting to set the bits used by the kernel + itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); - pxList = &( pxEventBits->xTasksWaitingForBits ); - pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - vTaskSuspendAll(); - { - traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); + pxList = &( pxEventBits->xTasksWaitingForBits ); + pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + vTaskSuspendAll(); + { + traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); - pxListItem = listGET_HEAD_ENTRY( pxList ); + pxListItem = listGET_HEAD_ENTRY( pxList ); - /* Set the bits. */ - pxEventBits->uxEventBits |= uxBitsToSet; + /* Set the bits. */ + pxEventBits->uxEventBits |= uxBitsToSet; - /* See if the new bit value should unblock any tasks. */ - while( pxListItem != pxListEnd ) - { - pxNext = listGET_NEXT( pxListItem ); - uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); - xMatchFound = pdFALSE; + /* See if the new bit value should unblock any tasks. */ + while( pxListItem != pxListEnd ) + { + pxNext = listGET_NEXT( pxListItem ); + uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); + xMatchFound = pdFALSE; - /* Split the bits waited for from the control bits. */ - uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; - uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; + /* Split the bits waited for from the control bits. */ + uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; + uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; - if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) - { - /* Just looking for single bit being set. */ - if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) - { - xMatchFound = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) - { - /* All bits are set. */ - xMatchFound = pdTRUE; - } - else - { - /* Need all bits to be set, but not all the bits were set. */ - } + if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) + { + /* Just looking for single bit being set. */ + if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) + { + xMatchFound = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) + { + /* All bits are set. */ + xMatchFound = pdTRUE; + } + else + { + /* Need all bits to be set, but not all the bits were set. */ + } - if( xMatchFound != pdFALSE ) - { - /* The bits match. Should the bits be cleared on exit? */ - if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) - { - uxBitsToClear |= uxBitsWaitedFor; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xMatchFound != pdFALSE ) + { + /* The bits match. Should the bits be cleared on exit? */ + if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) + { + uxBitsToClear |= uxBitsWaitedFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Store the actual event flag value in the task's event list - item before removing the task from the event list. The - eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows - that is was unblocked due to its required bits matching, rather - than because it timed out. */ - vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); - } + /* Store the actual event flag value in the task's event list + item before removing the task from the event list. The + eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows + that is was unblocked due to its required bits matching, rather + than because it timed out. */ + vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); + } - /* Move onto the next list item. Note pxListItem->pxNext is not - used here as the list item may have been removed from the event list - and inserted into the ready/pending reading list. */ - pxListItem = pxNext; - } + /* Move onto the next list item. Note pxListItem->pxNext is not + used here as the list item may have been removed from the event list + and inserted into the ready/pending reading list. */ + pxListItem = pxNext; + } - /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT - bit was set in the control word. */ - pxEventBits->uxEventBits &= ~uxBitsToClear; - } - ( void ) xTaskResumeAll(); + /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT + bit was set in the control word. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + ( void ) xTaskResumeAll(); - return pxEventBits->uxEventBits; + return pxEventBits->uxEventBits; } /*-----------------------------------------------------------*/ @@ -615,40 +615,40 @@ void vEventGroupDelete( EventGroupHandle_t xEventGroup ) EventGroup_t *pxEventBits = xEventGroup; const List_t *pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); - vTaskSuspendAll(); - { - traceEVENT_GROUP_DELETE( xEventGroup ); + vTaskSuspendAll(); + { + traceEVENT_GROUP_DELETE( xEventGroup ); - while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) - { - /* Unblock the task, returning 0 as the event list is being deleted - and cannot therefore have any bits set. */ - configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); - vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); - } + while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) + { + /* Unblock the task, returning 0 as the event list is being deleted + and cannot therefore have any bits set. */ + configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); + vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); + } - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The event group can only have been allocated dynamically - free - it again. */ - vPortFree( pxEventBits ); - } - #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The event group could have been allocated statically or - dynamically, so check before attempting to free the memory. */ - if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxEventBits ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } - ( void ) xTaskResumeAll(); + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The event group can only have been allocated dynamically - free + it again. */ + vPortFree( pxEventBits ); + } + #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The event group could have been allocated statically or + dynamically, so check before attempting to free the memory. */ + if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxEventBits ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } + ( void ) xTaskResumeAll(); } /*-----------------------------------------------------------*/ @@ -656,7 +656,7 @@ const List_t *pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); an interrupt. */ void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet ) { - ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ + ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ } /*-----------------------------------------------------------*/ @@ -664,7 +664,7 @@ void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet an interrupt. */ void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear ) { - ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ + ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ } /*-----------------------------------------------------------*/ @@ -672,80 +672,80 @@ static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, co { BaseType_t xWaitConditionMet = pdFALSE; - if( xWaitForAllBits == pdFALSE ) - { - /* Task only has to wait for one bit within uxBitsToWaitFor to be - set. Is one already set? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Task has to wait for all the bits in uxBitsToWaitFor to be set. - Are they set already? */ - if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) - { - xWaitConditionMet = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( xWaitForAllBits == pdFALSE ) + { + /* Task only has to wait for one bit within uxBitsToWaitFor to be + set. Is one already set? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Task has to wait for all the bits in uxBitsToWaitFor to be set. + Are they set already? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - return xWaitConditionMet; + return xWaitConditionMet; } /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) - BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) - { - BaseType_t xReturn; + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) + { + BaseType_t xReturn; - traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); - xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ - return xReturn; - } + return xReturn; + } #endif /*-----------------------------------------------------------*/ #if (configUSE_TRACE_FACILITY == 1) - UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) - { - UBaseType_t xReturn; - EventGroup_t const *pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) + { + UBaseType_t xReturn; + EventGroup_t const *pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ - if( xEventGroup == NULL ) - { - xReturn = 0; - } - else - { - xReturn = pxEventBits->uxEventGroupNumber; - } + if( xEventGroup == NULL ) + { + xReturn = 0; + } + else + { + xReturn = pxEventBits->uxEventGroupNumber; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vEventGroupSetNumber( void * xEventGroup, UBaseType_t uxEventGroupNumber ) - { - ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ - } + void vEventGroupSetNumber( void * xEventGroup, UBaseType_t uxEventGroupNumber ) + { + ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv_ram/list.c b/components/bl602/freertos_riscv_ram/list.c index 21dabdec..98855882 100644 --- a/components/bl602/freertos_riscv_ram/list.c +++ b/components/bl602/freertos_riscv_ram/list.c @@ -36,38 +36,38 @@ void vListInitialise( List_t * const pxList ) { - /* The list structure contains a list item which is used to mark the - end of the list. To initialise the list the list end is inserted - as the only list entry. */ - pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + /* The list structure contains a list item which is used to mark the + end of the list. To initialise the list the list end is inserted + as the only list entry. */ + pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - /* The list end value is the highest possible value in the list to - ensure it remains at the end of the list. */ - pxList->xListEnd.xItemValue = portMAX_DELAY; + /* The list end value is the highest possible value in the list to + ensure it remains at the end of the list. */ + pxList->xListEnd.xItemValue = portMAX_DELAY; - /* The list end next and previous pointers point to itself so we know - when the list is empty. */ - pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + /* The list end next and previous pointers point to itself so we know + when the list is empty. */ + pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ - pxList->uxNumberOfItems = ( UBaseType_t ) 0U; + pxList->uxNumberOfItems = ( UBaseType_t ) 0U; - /* Write known values into the list if - configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); - listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); + /* Write known values into the list if + configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); + listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); } /*-----------------------------------------------------------*/ void vListInitialiseItem( ListItem_t * const pxItem ) { - /* Make sure the list item is not recorded as being on a list. */ - pxItem->pxContainer = NULL; + /* Make sure the list item is not recorded as being on a list. */ + pxItem->pxContainer = NULL; - /* Write known values into the list item if - configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ - listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); - listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + /* Write known values into the list item if + configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); } /*-----------------------------------------------------------*/ @@ -75,28 +75,28 @@ void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem ) { ListItem_t * const pxIndex = pxList->pxIndex; - /* Only effective when configASSERT() is also defined, these tests may catch - the list data structures being overwritten in memory. They will not catch - data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + /* Only effective when configASSERT() is also defined, these tests may catch + the list data structures being overwritten in memory. They will not catch + data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - /* Insert a new list item into pxList, but rather than sort the list, - makes the new list item the last item to be removed by a call to - listGET_OWNER_OF_NEXT_ENTRY(). */ - pxNewListItem->pxNext = pxIndex; - pxNewListItem->pxPrevious = pxIndex->pxPrevious; + /* Insert a new list item into pxList, but rather than sort the list, + makes the new list item the last item to be removed by a call to + listGET_OWNER_OF_NEXT_ENTRY(). */ + pxNewListItem->pxNext = pxIndex; + pxNewListItem->pxPrevious = pxIndex->pxPrevious; - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); - pxIndex->pxPrevious->pxNext = pxNewListItem; - pxIndex->pxPrevious = pxNewListItem; + pxIndex->pxPrevious->pxNext = pxNewListItem; + pxIndex->pxPrevious = pxNewListItem; - /* Remember which list the item is in. */ - pxNewListItem->pxContainer = pxList; + /* Remember which list the item is in. */ + pxNewListItem->pxContainer = pxList; - ( pxList->uxNumberOfItems )++; + ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ @@ -105,65 +105,65 @@ void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem ) ListItem_t *pxIterator; const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; - /* Only effective when configASSERT() is also defined, these tests may catch - the list data structures being overwritten in memory. They will not catch - data errors caused by incorrect configuration or use of FreeRTOS. */ - listTEST_LIST_INTEGRITY( pxList ); - listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + /* Only effective when configASSERT() is also defined, these tests may catch + the list data structures being overwritten in memory. They will not catch + data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); - /* Insert the new list item into the list, sorted in xItemValue order. + /* Insert the new list item into the list, sorted in xItemValue order. - If the list already contains a list item with the same item value then the - new list item should be placed after it. This ensures that TCBs which are - stored in ready lists (all of which have the same xItemValue value) get a - share of the CPU. However, if the xItemValue is the same as the back marker - the iteration loop below will not end. Therefore the value is checked - first, and the algorithm slightly modified if necessary. */ - if( xValueOfInsertion == portMAX_DELAY ) - { - pxIterator = pxList->xListEnd.pxPrevious; - } - else - { - /* *** NOTE *********************************************************** - If you find your application is crashing here then likely causes are - listed below. In addition see https://www.freertos.org/FAQHelp.html for - more tips, and ensure configASSERT() is defined! - https://www.freertos.org/a00110.html#configASSERT + If the list already contains a list item with the same item value then the + new list item should be placed after it. This ensures that TCBs which are + stored in ready lists (all of which have the same xItemValue value) get a + share of the CPU. However, if the xItemValue is the same as the back marker + the iteration loop below will not end. Therefore the value is checked + first, and the algorithm slightly modified if necessary. */ + if( xValueOfInsertion == portMAX_DELAY ) + { + pxIterator = pxList->xListEnd.pxPrevious; + } + else + { + /* *** NOTE *********************************************************** + If you find your application is crashing here then likely causes are + listed below. In addition see https://www.freertos.org/FAQHelp.html for + more tips, and ensure configASSERT() is defined! + https://www.freertos.org/a00110.html#configASSERT - 1) Stack overflow - - see https://www.freertos.org/Stacks-and-stack-overflow-checking.html - 2) Incorrect interrupt priority assignment, especially on Cortex-M - parts where numerically high priority values denote low actual - interrupt priorities, which can seem counter intuitive. See - https://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition - of configMAX_SYSCALL_INTERRUPT_PRIORITY on - https://www.freertos.org/a00110.html - 3) Calling an API function from within a critical section or when - the scheduler is suspended, or calling an API function that does - not end in "FromISR" from an interrupt. - 4) Using a queue or semaphore before it has been initialised or - before the scheduler has been started (are interrupts firing - before vTaskStartScheduler() has been called?). - **********************************************************************/ + 1) Stack overflow - + see https://www.freertos.org/Stacks-and-stack-overflow-checking.html + 2) Incorrect interrupt priority assignment, especially on Cortex-M + parts where numerically high priority values denote low actual + interrupt priorities, which can seem counter intuitive. See + https://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition + of configMAX_SYSCALL_INTERRUPT_PRIORITY on + https://www.freertos.org/a00110.html + 3) Calling an API function from within a critical section or when + the scheduler is suspended, or calling an API function that does + not end in "FromISR" from an interrupt. + 4) Using a queue or semaphore before it has been initialised or + before the scheduler has been started (are interrupts firing + before vTaskStartScheduler() has been called?). + **********************************************************************/ - for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */ - { - /* There is nothing to do here, just iterating to the wanted - insertion position. */ - } - } + for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */ + { + /* There is nothing to do here, just iterating to the wanted + insertion position. */ + } + } - pxNewListItem->pxNext = pxIterator->pxNext; - pxNewListItem->pxNext->pxPrevious = pxNewListItem; - pxNewListItem->pxPrevious = pxIterator; - pxIterator->pxNext = pxNewListItem; + pxNewListItem->pxNext = pxIterator->pxNext; + pxNewListItem->pxNext->pxPrevious = pxNewListItem; + pxNewListItem->pxPrevious = pxIterator; + pxIterator->pxNext = pxNewListItem; - /* Remember which list the item is in. This allows fast removal of the - item later. */ - pxNewListItem->pxContainer = pxList; + /* Remember which list the item is in. This allows fast removal of the + item later. */ + pxNewListItem->pxContainer = pxList; - ( pxList->uxNumberOfItems )++; + ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ @@ -173,26 +173,26 @@ UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) item. */ List_t * const pxList = pxItemToRemove->pxContainer; - pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; - pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; + pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; + pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; - /* Only used during decision coverage testing. */ - mtCOVERAGE_TEST_DELAY(); + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); - /* Make sure the index is left pointing to a valid item. */ - if( pxList->pxIndex == pxItemToRemove ) - { - pxList->pxIndex = pxItemToRemove->pxPrevious; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Make sure the index is left pointing to a valid item. */ + if( pxList->pxIndex == pxItemToRemove ) + { + pxList->pxIndex = pxItemToRemove->pxPrevious; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxItemToRemove->pxContainer = NULL; - ( pxList->uxNumberOfItems )--; + pxItemToRemove->pxContainer = NULL; + ( pxList->uxNumberOfItems )--; - return pxList->uxNumberOfItems; + return pxList->uxNumberOfItems; } /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv_ram/panic/panic.h b/components/bl602/freertos_riscv_ram/panic/panic.h index 86a80472..0d67e951 100644 --- a/components/bl602/freertos_riscv_ram/panic/panic.h +++ b/components/bl602/freertos_riscv_ram/panic/panic.h @@ -1,7 +1,7 @@ -#ifndef _PANIC_H_ -#define _PANIC_H_ - -int backtrace_now(int (*print_func)(const char *fmt, ...), uintptr_t *regs); -int backtrace_now_app(int (*print_func)(const char *fmt, ...)); - -#endif +#ifndef _PANIC_H_ +#define _PANIC_H_ + +int backtrace_now(int (*print_func)(const char *fmt, ...), uintptr_t *regs); +int backtrace_now_app(int (*print_func)(const char *fmt, ...)); + +#endif diff --git a/components/bl602/freertos_riscv_ram/panic/panic_c.c b/components/bl602/freertos_riscv_ram/panic/panic_c.c index d0980407..b104300f 100644 --- a/components/bl602/freertos_riscv_ram/panic/panic_c.c +++ b/components/bl602/freertos_riscv_ram/panic/panic_c.c @@ -146,7 +146,7 @@ int backtrace_now_app(int (*print_func)(const char *fmt, ...)) { #if defined(__GNUC__) __asm__("add %0, x0, fp" - : "=r"(fp)); + : "=r"(fp)); #else #error "Compiler is not gcc!" #endif diff --git a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h index ef954846..5fb31a71 100644 --- a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h +++ b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/Pulpino_Vega_RV32M1RM/freertos_risc_v_chip_specific_extensions.h @@ -62,48 +62,48 @@ #define portasmHAS_CLINT 0 /* Constants to define the additional registers found on the Pulpino RI5KY. */ -#define lpstart0 0x7b0 -#define lpend0 0x7b1 -#define lpcount0 0x7b2 -#define lpstart1 0x7b4 -#define lpend1 0x7b5 -#define lpcount1 0x7b6 +#define lpstart0 0x7b0 +#define lpend0 0x7b1 +#define lpcount0 0x7b2 +#define lpstart1 0x7b4 +#define lpend1 0x7b5 +#define lpcount1 0x7b6 /* Six additional registers to save and restore, as per the #defines above. */ #define portasmADDITIONAL_CONTEXT_SIZE 6 /* Must be even number on 32-bit cores. */ /* Save additional registers found on the Pulpino. */ .macro portasmSAVE_ADDITIONAL_REGISTERS - addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) /* Make room for the additional registers. */ - csrr t0, lpstart0 /* Load additional registers into accessible temporary registers. */ - csrr t1, lpend0 - csrr t2, lpcount0 - csrr t3, lpstart1 - csrr t4, lpend1 - csrr t5, lpcount1 - sw t0, 1 * portWORD_SIZE( sp ) - sw t1, 2 * portWORD_SIZE( sp ) - sw t2, 3 * portWORD_SIZE( sp ) - sw t3, 4 * portWORD_SIZE( sp ) - sw t4, 5 * portWORD_SIZE( sp ) - sw t5, 6 * portWORD_SIZE( sp ) - .endm + addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) /* Make room for the additional registers. */ + csrr t0, lpstart0 /* Load additional registers into accessible temporary registers. */ + csrr t1, lpend0 + csrr t2, lpcount0 + csrr t3, lpstart1 + csrr t4, lpend1 + csrr t5, lpcount1 + sw t0, 1 * portWORD_SIZE( sp ) + sw t1, 2 * portWORD_SIZE( sp ) + sw t2, 3 * portWORD_SIZE( sp ) + sw t3, 4 * portWORD_SIZE( sp ) + sw t4, 5 * portWORD_SIZE( sp ) + sw t5, 6 * portWORD_SIZE( sp ) + .endm /* Restore the additional registers found on the Pulpino. */ .macro portasmRESTORE_ADDITIONAL_REGISTERS - lw t0, 1 * portWORD_SIZE( sp ) /* Load additional registers into accessible temporary registers. */ - lw t1, 2 * portWORD_SIZE( sp ) - lw t2, 3 * portWORD_SIZE( sp ) - lw t3, 4 * portWORD_SIZE( sp ) - lw t4, 5 * portWORD_SIZE( sp ) - lw t5, 6 * portWORD_SIZE( sp ) - csrw lpstart0, t0 - csrw lpend0, t1 - csrw lpcount0, t2 - csrw lpstart1, t3 - csrw lpend1, t4 - csrw lpcount1, t5 - addi sp, sp, (portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE )/* Remove space added for additional registers. */ - .endm + lw t0, 1 * portWORD_SIZE( sp ) /* Load additional registers into accessible temporary registers. */ + lw t1, 2 * portWORD_SIZE( sp ) + lw t2, 3 * portWORD_SIZE( sp ) + lw t3, 4 * portWORD_SIZE( sp ) + lw t4, 5 * portWORD_SIZE( sp ) + lw t5, 6 * portWORD_SIZE( sp ) + csrw lpstart0, t0 + csrw lpend0, t1 + csrw lpcount0, t2 + csrw lpstart1, t3 + csrw lpend1, t4 + csrw lpcount1, t5 + addi sp, sp, (portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE )/* Remove space added for additional registers. */ + .endm #endif /* __FREERTOS_RISC_V_EXTENSIONS_H__ */ diff --git a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h index b3562abe..e0849880 100644 --- a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h +++ b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h @@ -57,12 +57,12 @@ #define portasmADDITIONAL_CONTEXT_SIZE 0 /* Must be even number on 32-bit cores. */ .macro portasmSAVE_ADDITIONAL_REGISTERS - /* No additional registers to save, so this macro does nothing. */ - .endm + /* No additional registers to save, so this macro does nothing. */ + .endm /* Restore the additional registers found on the Pulpino. */ .macro portasmRESTORE_ADDITIONAL_REGISTERS - /* No additional registers to restore, so this macro does nothing. */ - .endm + /* No additional registers to restore, so this macro does nothing. */ + .endm #endif /* __FREERTOS_RISC_V_EXTENSIONS_H__ */ diff --git a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/port.c b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/port.c index 9a342f3f..d8de3c4e 100644 --- a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/port.c +++ b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/port.c @@ -35,16 +35,16 @@ #include "portmacro.h" #ifndef configCLINT_BASE_ADDRESS - #warning configCLINT_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a Core Local Interrupter (CLINT) then set configCLINT_BASE_ADDRESS to the CLINT base address. Otherwise set configCLINT_BASE_ADDRESS to 0. + #warning configCLINT_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a Core Local Interrupter (CLINT) then set configCLINT_BASE_ADDRESS to the CLINT base address. Otherwise set configCLINT_BASE_ADDRESS to 0. #endif /* Let the user override the pre-loading of the initial LR with the address of prvTaskExitError() in case it messes up unwinding of the stack in the debugger. */ #ifdef configTASK_RETURN_ADDRESS - #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS + #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS #else - #define portTASK_RETURN_ADDRESS prvTaskExitError + #define portTASK_RETURN_ADDRESS prvTaskExitError #endif /* The stack used by interrupt service routines. Set configISR_STACK_SIZE_WORDS @@ -55,11 +55,11 @@ of the stack used by main. Using the linker script method will repurpose the stack that was used by main before the scheduler was started for use as the interrupt stack after the scheduler has started. */ #ifdef configISR_STACK_SIZE_WORDS - static __attribute__ ((aligned(16))) StackType_t xISRStack[ configISR_STACK_SIZE_WORDS ] = { 0 }; - const StackType_t xISRStackTop = ( StackType_t ) &( xISRStack[ ( configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK ) - 1 ] ); + static __attribute__ ((aligned(16))) StackType_t xISRStack[ configISR_STACK_SIZE_WORDS ] = { 0 }; + const StackType_t xISRStackTop = ( StackType_t ) &( xISRStack[ ( configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK ) - 1 ] ); #else - extern const uint32_t __freertos_irq_stack_top[]; - const StackType_t xISRStackTop = ( StackType_t ) __freertos_irq_stack_top; + extern const uint32_t __freertos_irq_stack_top[]; + const StackType_t xISRStackTop = ( StackType_t ) __freertos_irq_stack_top; #endif /* @@ -84,50 +84,50 @@ stack checking. A problem in the ISR stack will trigger an assert, not call the stack overflow hook function (because the stack overflow hook is specific to a task stack, not the ISR stack). */ #if( configCHECK_FOR_STACK_OVERFLOW > 2 ) - #warning This path not tested, or even compiled yet. - /* Don't use 0xa5 as the stack fill bytes as that is used by the kernerl for - the task stacks, and so will legitimately appear in many positions within - the ISR stack. */ - #define portISR_STACK_FILL_BYTE 0xee + #warning This path not tested, or even compiled yet. + /* Don't use 0xa5 as the stack fill bytes as that is used by the kernerl for + the task stacks, and so will legitimately appear in many positions within + the ISR stack. */ + #define portISR_STACK_FILL_BYTE 0xee - static const uint8_t ucExpectedStackBytes[] = { - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ - portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE }; \ + static const uint8_t ucExpectedStackBytes[] = { + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE }; \ - #define portCHECK_ISR_STACK() configASSERT( ( memcmp( ( void * ) xISRStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) == 0 ) ) + #define portCHECK_ISR_STACK() configASSERT( ( memcmp( ( void * ) xISRStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) == 0 ) ) #else - /* Define the function away. */ - #define portCHECK_ISR_STACK() + /* Define the function away. */ + #define portCHECK_ISR_STACK() #endif /* configCHECK_FOR_STACK_OVERFLOW > 2 */ /*-----------------------------------------------------------*/ #if( configCLINT_BASE_ADDRESS != 0 ) - void vPortSetupTimerInterrupt( void ) - { - uint32_t ulCurrentTimeHigh, ulCurrentTimeLow; - volatile uint32_t * const pulTimeHigh = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFFC ); - volatile uint32_t * const pulTimeLow = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFF8 ); + void vPortSetupTimerInterrupt( void ) + { + uint32_t ulCurrentTimeHigh, ulCurrentTimeLow; + volatile uint32_t * const pulTimeHigh = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFFC ); + volatile uint32_t * const pulTimeLow = ( volatile uint32_t * const ) ( configCLINT_BASE_ADDRESS + 0xBFF8 ); - do - { - ulCurrentTimeHigh = *pulTimeHigh; - ulCurrentTimeLow = *pulTimeLow; - } while( ulCurrentTimeHigh != *pulTimeHigh ); + do + { + ulCurrentTimeHigh = *pulTimeHigh; + ulCurrentTimeLow = *pulTimeLow; + } while( ulCurrentTimeHigh != *pulTimeHigh ); - ullNextTime = ( uint64_t ) ulCurrentTimeHigh; - ullNextTime <<= 32ULL; - ullNextTime |= ( uint64_t ) ulCurrentTimeLow; - ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; - *pullMachineTimerCompareRegister = ullNextTime; + ullNextTime = ( uint64_t ) ulCurrentTimeHigh; + ullNextTime <<= 32ULL; + ullNextTime |= ( uint64_t ) ulCurrentTimeLow; + ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; + *pullMachineTimerCompareRegister = ullNextTime; - /* Prepare the time to use after the next tick interrupt. */ - ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; - } + /* Prepare the time to use after the next tick interrupt. */ + ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; + } #endif /* ( configCLINT_BASE_ADDRESS != 0 ) */ /*-----------------------------------------------------------*/ @@ -136,40 +136,40 @@ BaseType_t xPortStartScheduler( void ) { extern void xPortStartFirstTask( void ); - #if( configASSERT_DEFINED == 1 ) - { - volatile uint32_t mtvec = 0; + #if( configASSERT_DEFINED == 1 ) + { + volatile uint32_t mtvec = 0; - /* Check the least significant two bits of mtvec are 00 - indicating - single vector mode. */ - __asm volatile( "csrr %0, mtvec" : "=r"( mtvec ) ); + /* Check the least significant two bits of mtvec are 00 - indicating + single vector mode. */ + __asm volatile( "csrr %0, mtvec" : "=r"( mtvec ) ); - /* Check alignment of the interrupt stack - which is the same as the - stack that was being used by main() prior to the scheduler being - started. */ - configASSERT( ( xISRStackTop & portBYTE_ALIGNMENT_MASK ) == 0 ); - } - #endif /* configASSERT_DEFINED */ + /* Check alignment of the interrupt stack - which is the same as the + stack that was being used by main() prior to the scheduler being + started. */ + configASSERT( ( xISRStackTop & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + #endif /* configASSERT_DEFINED */ #if 1 - /* If there is a CLINT then it is ok to use the default implementation - in this file, otherwise vPortSetupTimerInterrupt() must be implemented to - configure whichever clock is to be used to generate the tick interrupt. */ - vPortSetupTimerInterrupt(); + /* If there is a CLINT then it is ok to use the default implementation + in this file, otherwise vPortSetupTimerInterrupt() must be implemented to + configure whichever clock is to be used to generate the tick interrupt. */ + vPortSetupTimerInterrupt(); - #if( configCLINT_BASE_ADDRESS != 0 ) - { - /* Enable mtime and external interrupts. 1<<7 for timer interrupt, 1<<11 - for external interrupt. _RB_ What happens here when mtime is not present as - with pulpino? */ - __asm volatile( "csrs mie, %0" :: "r"(0x880) ); - } - #else - { - /* Enable external interrupts. */ - __asm volatile( "csrs mie, %0" :: "r"(0x800) ); - } - #endif /* configCLINT_BASE_ADDRESS */ + #if( configCLINT_BASE_ADDRESS != 0 ) + { + /* Enable mtime and external interrupts. 1<<7 for timer interrupt, 1<<11 + for external interrupt. _RB_ What happens here when mtime is not present as + with pulpino? */ + __asm volatile( "csrs mie, %0" :: "r"(0x880) ); + } + #else + { + /* Enable external interrupts. */ + __asm volatile( "csrs mie, %0" :: "r"(0x800) ); + } + #endif /* configCLINT_BASE_ADDRESS */ #else int bl_timer_tick_enable(void); bl_timer_tick_enable(); @@ -181,18 +181,18 @@ int bl_timer_tick_enable(void); /*Enable mtimer interrrupt*/ *(volatile uint8_t*)configCLIC_TIMER_ENABLE_ADDRESS = 1; - xPortStartFirstTask(); + xPortStartFirstTask(); - /* Should not get here as after calling xPortStartFirstTask() only tasks - should be executing. */ - return pdFAIL; + /* Should not get here as after calling xPortStartFirstTask() only tasks + should be executing. */ + return pdFAIL; } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { - /* Not implemented. */ - for( ;; ); + /* Not implemented. */ + for( ;; ); } diff --git a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/portmacro.h b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/portmacro.h index 2fe491fd..f3a8b4d6 100644 --- a/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/portmacro.h +++ b/components/bl602/freertos_riscv_ram/portable/GCC/RISC-V/portmacro.h @@ -45,17 +45,17 @@ extern "C" { /* Type definitions. */ #if __riscv_xlen == 64 - #define portSTACK_TYPE uint64_t - #define portBASE_TYPE int64_t - #define portUBASE_TYPE uint64_t - #define portMAX_DELAY ( TickType_t ) 0xffffffffffffffffUL + #define portSTACK_TYPE uint64_t + #define portBASE_TYPE int64_t + #define portUBASE_TYPE uint64_t + #define portMAX_DELAY ( TickType_t ) 0xffffffffffffffffUL #elif __riscv_xlen == 32 - #define portSTACK_TYPE uint32_t - #define portBASE_TYPE int32_t - #define portUBASE_TYPE uint32_t - #define portMAX_DELAY ( TickType_t ) 0xffffffffUL + #define portSTACK_TYPE uint32_t + #define portBASE_TYPE int32_t + #define portUBASE_TYPE uint32_t + #define portMAX_DELAY ( TickType_t ) 0xffffffffUL #else - #error Assembler did not define __riscv_xlen + #error Assembler did not define __riscv_xlen #endif @@ -70,13 +70,13 @@ not need to be guarded with a critical section. */ /*-----------------------------------------------------------*/ /* Architecture specifics. */ -#define portSTACK_GROWTH ( -1 ) -#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) +#define portSTACK_GROWTH ( -1 ) +#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) #ifdef __riscv64 - #error This is the RV32 port that has not yet been adapted for 64. - #define portBYTE_ALIGNMENT 16 + #error This is the RV32 port that has not yet been adapted for 64. + #define portBYTE_ALIGNMENT 16 #else - #define portBYTE_ALIGNMENT 8 + #define portBYTE_ALIGNMENT 8 #endif /*-----------------------------------------------------------*/ @@ -90,38 +90,38 @@ extern void vTaskSwitchContext( void ); /* Critical section management. */ -#define portCRITICAL_NESTING_IN_TCB 1 +#define portCRITICAL_NESTING_IN_TCB 1 extern void vTaskEnterCritical( void ); extern void vTaskExitCritical( void ); #define portSET_INTERRUPT_MASK_FROM_ISR() 0 #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue -#define portDISABLE_INTERRUPTS() __asm volatile( "csrc mstatus, 8" ) -#define portENABLE_INTERRUPTS() __asm volatile( "csrs mstatus, 8" ) -#define portENTER_CRITICAL() vTaskEnterCritical() -#define portEXIT_CRITICAL() vTaskExitCritical() +#define portDISABLE_INTERRUPTS() __asm volatile( "csrc mstatus, 8" ) +#define portENABLE_INTERRUPTS() __asm volatile( "csrs mstatus, 8" ) +#define portENTER_CRITICAL() vTaskEnterCritical() +#define portEXIT_CRITICAL() vTaskExitCritical() /*-----------------------------------------------------------*/ /* Architecture specific optimisations. */ #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION - #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #endif #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 ) - /* Check the configuration. */ - #if( configMAX_PRIORITIES > 32 ) - #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. - #endif + /* Check the configuration. */ + #if( configMAX_PRIORITIES > 32 ) + #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. + #endif - /* Store/clear the ready priorities in a bit map. */ - #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) - #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) + /* Store/clear the ready priorities in a bit map. */ + #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) + #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - __builtin_clz( uxReadyPriorities ) ) + #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - __builtin_clz( uxReadyPriorities ) ) #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ @@ -136,12 +136,12 @@ not necessary for to use this port. They are defined so the common demo files /*-----------------------------------------------------------*/ -#define portNOP() __asm volatile ( " nop " ) +#define portNOP() __asm volatile ( " nop " ) -#define portINLINE __inline +#define portINLINE __inline #ifndef portFORCE_INLINE - #define portFORCE_INLINE inline __attribute__(( always_inline)) + #define portFORCE_INLINE inline __attribute__(( always_inline)) #endif #define portMEMORY_BARRIER() __asm volatile( "" ::: "memory" ) diff --git a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_1.c b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_1.c index 542317dc..a28bac89 100644 --- a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_1.c +++ b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_1.c @@ -46,19 +46,19 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* A few bytes might be lost to byte aligning the heap start address. */ -#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) +#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) /* Allocate the memory for the heap. */ #if( configAPPLICATION_ALLOCATED_HEAP == 1 ) - /* The application writer has already defined the array used for the RTOS - heap - probably so it can be placed in a special segment or address. */ - extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + /* The application writer has already defined the array used for the RTOS + heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #else - static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #endif /* configAPPLICATION_ALLOCATED_HEAP */ /* Index into the ucHeap array. */ @@ -71,75 +71,75 @@ void *pvPortMalloc( size_t xWantedSize ) void *pvReturn = NULL; static uint8_t *pucAlignedHeap = NULL; - /* Ensure that blocks are always aligned to the required number of bytes. */ - #if( portBYTE_ALIGNMENT != 1 ) - { - if( xWantedSize & portBYTE_ALIGNMENT_MASK ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - } - } - #endif + /* Ensure that blocks are always aligned to the required number of bytes. */ + #if( portBYTE_ALIGNMENT != 1 ) + { + if( xWantedSize & portBYTE_ALIGNMENT_MASK ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + } + #endif - vTaskSuspendAll(); - { - if( pucAlignedHeap == NULL ) - { - /* Ensure the heap starts on a correctly aligned boundary. */ - pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); - } + vTaskSuspendAll(); + { + if( pucAlignedHeap == NULL ) + { + /* Ensure the heap starts on a correctly aligned boundary. */ + pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + } - /* Check there is enough room left for the allocation. */ - if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) && - ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) )/* Check for overflow. */ - { - /* Return the next free byte then increment the index past this - block. */ - pvReturn = pucAlignedHeap + xNextFreeByte; - xNextFreeByte += xWantedSize; - } + /* Check there is enough room left for the allocation. */ + if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) && + ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) )/* Check for overflow. */ + { + /* Return the next free byte then increment the index past this + block. */ + pvReturn = pucAlignedHeap + xNextFreeByte; + xNextFreeByte += xWantedSize; + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ void vPortFree( void *pv ) { - /* Memory cannot be freed using this scheme. See heap_2.c, heap_3.c and - heap_4.c for alternative implementations, and the memory management pages of - http://www.FreeRTOS.org for more information. */ - ( void ) pv; + /* Memory cannot be freed using this scheme. See heap_2.c, heap_3.c and + heap_4.c for alternative implementations, and the memory management pages of + http://www.FreeRTOS.org for more information. */ + ( void ) pv; - /* Force an assert as it is invalid to call this function. */ - configASSERT( pv == NULL ); + /* Force an assert as it is invalid to call this function. */ + configASSERT( pv == NULL ); } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { - /* Only required when static memory is not cleared. */ - xNextFreeByte = ( size_t ) 0; + /* Only required when static memory is not cleared. */ + xNextFreeByte = ( size_t ) 0; } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return ( configADJUSTED_HEAP_SIZE - xNextFreeByte ); + return ( configADJUSTED_HEAP_SIZE - xNextFreeByte ); } diff --git a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_2.c b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_2.c index 7d069212..4d912dce 100644 --- a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_2.c +++ b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_2.c @@ -47,11 +47,11 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* A few bytes might be lost to byte aligning the heap start address. */ -#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) +#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) /* * Initialises the heap structures before their first use. @@ -60,11 +60,11 @@ static void prvHeapInit( void ); /* Allocate the memory for the heap. */ #if( configAPPLICATION_ALLOCATED_HEAP == 1 ) - /* The application writer has already defined the array used for the RTOS - heap - probably so it can be placed in a special segment or address. */ - extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + /* The application writer has already defined the array used for the RTOS + heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #else - static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #endif /* configAPPLICATION_ALLOCATED_HEAP */ @@ -72,13 +72,13 @@ static void prvHeapInit( void ); of their size. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; -static const uint16_t heapSTRUCT_SIZE = ( ( sizeof ( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK ); -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) ) +static const uint16_t heapSTRUCT_SIZE = ( ( sizeof ( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK ); +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) ) /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, xEnd; @@ -94,24 +94,24 @@ static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE; * the block. Small blocks at the start of the list and large blocks at the end * of the list. */ -#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \ -{ \ -BlockLink_t *pxIterator; \ -size_t xBlockSize; \ - \ - xBlockSize = pxBlockToInsert->xBlockSize; \ - \ - /* Iterate through the list until a block is found that has a larger size */ \ - /* than the block we are inserting. */ \ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \ - { \ - /* There is nothing to do here - just iterate to the correct position. */ \ - } \ - \ - /* Update the list to include the block being inserted in the correct */ \ - /* position. */ \ - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \ - pxIterator->pxNextFreeBlock = pxBlockToInsert; \ +#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \ +{ \ +BlockLink_t *pxIterator; \ +size_t xBlockSize; \ + \ + xBlockSize = pxBlockToInsert->xBlockSize; \ + \ + /* Iterate through the list until a block is found that has a larger size */ \ + /* than the block we are inserting. */ \ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \ + { \ + /* There is nothing to do here - just iterate to the correct position. */ \ + } \ + \ + /* Update the list to include the block being inserted in the correct */ \ + /* position. */ \ + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \ + pxIterator->pxNextFreeBlock = pxBlockToInsert; \ } /*-----------------------------------------------------------*/ @@ -121,89 +121,89 @@ BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; static BaseType_t xHeapHasBeenInitialised = pdFALSE; void *pvReturn = NULL; - vTaskSuspendAll(); - { - /* If this is the first call to malloc then the heap will require - initialisation to setup the list of free blocks. */ - if( xHeapHasBeenInitialised == pdFALSE ) - { - prvHeapInit(); - xHeapHasBeenInitialised = pdTRUE; - } + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + initialisation to setup the list of free blocks. */ + if( xHeapHasBeenInitialised == pdFALSE ) + { + prvHeapInit(); + xHeapHasBeenInitialised = pdTRUE; + } - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += heapSTRUCT_SIZE; + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += heapSTRUCT_SIZE; - /* Ensure that blocks are always aligned to the required number of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - } - } + /* Ensure that blocks are always aligned to the required number of bytes. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + } - if( ( xWantedSize > 0 ) && ( xWantedSize < configADJUSTED_HEAP_SIZE ) ) - { - /* Blocks are stored in byte order - traverse the list from the start - (smallest) block until one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } + if( ( xWantedSize > 0 ) && ( xWantedSize < configADJUSTED_HEAP_SIZE ) ) + { + /* Blocks are stored in byte order - traverse the list from the start + (smallest) block until one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } - /* If we found the end marker then a block of adequate size was not found. */ - if( pxBlock != &xEnd ) - { - /* Return the memory space - jumping over the BlockLink_t structure - at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE ); + /* If we found the end marker then a block of adequate size was not found. */ + if( pxBlock != &xEnd ) + { + /* Return the memory space - jumping over the BlockLink_t structure + at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE ); - /* This block is being returned for use so must be taken out of the - list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + /* This block is being returned for use so must be taken out of the + list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - /* If the block is larger than required it can be split into two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new block - following the number of bytes requested. The void cast is - used to prevent byte alignment warnings from the compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + /* If the block is larger than required it can be split into two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new block + following the number of bytes requested. The void cast is + used to prevent byte alignment warnings from the compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - /* Calculate the sizes of two blocks split from the single - block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; + /* Calculate the sizes of two blocks split from the single + block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); - } + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + } - xFreeBytesRemaining -= pxBlock->xBlockSize; - } - } + xFreeBytesRemaining -= pxBlock->xBlockSize; + } + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ @@ -212,37 +212,37 @@ void vPortFree( void *pv ) uint8_t *puc = ( uint8_t * ) pv; BlockLink_t *pxLink; - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= heapSTRUCT_SIZE; + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= heapSTRUCT_SIZE; - /* This unexpected casting is to keep some compilers from issuing - byte alignment warnings. */ - pxLink = ( void * ) puc; + /* This unexpected casting is to keep some compilers from issuing + byte alignment warnings. */ + pxLink = ( void * ) puc; - vTaskSuspendAll(); - { - /* Add this block to the list of free blocks. */ - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - } - ( void ) xTaskResumeAll(); - } + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + } + ( void ) xTaskResumeAll(); + } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return xFreeBytesRemaining; + return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { - /* This just exists to keep the linker quiet. */ + /* This just exists to keep the linker quiet. */ } /*-----------------------------------------------------------*/ @@ -251,22 +251,22 @@ static void prvHeapInit( void ) BlockLink_t *pxFirstFreeBlock; uint8_t *pucAlignedHeap; - /* Ensure the heap starts on a correctly aligned boundary. */ - pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + /* Ensure the heap starts on a correctly aligned boundary. */ + pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); - /* xStart is used to hold a pointer to the first item in the list of free - blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; + /* xStart is used to hold a pointer to the first item in the list of free + blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; - /* xEnd is used to mark the end of the list of free blocks. */ - xEnd.xBlockSize = configADJUSTED_HEAP_SIZE; - xEnd.pxNextFreeBlock = NULL; + /* xEnd is used to mark the end of the list of free blocks. */ + xEnd.xBlockSize = configADJUSTED_HEAP_SIZE; + xEnd.pxNextFreeBlock = NULL; - /* To start with there is a single free block that is sized to take up the - entire heap space. */ - pxFirstFreeBlock = ( void * ) pucAlignedHeap; - pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE; - pxFirstFreeBlock->pxNextFreeBlock = &xEnd; + /* To start with there is a single free block that is sized to take up the + entire heap space. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE; + pxFirstFreeBlock->pxNextFreeBlock = &xEnd; } /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_3.c b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_3.c index e6a29908..5f575cf9 100644 --- a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_3.c +++ b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_3.c @@ -50,7 +50,7 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /*-----------------------------------------------------------*/ @@ -59,38 +59,38 @@ void *pvPortMalloc( size_t xWantedSize ) { void *pvReturn; - vTaskSuspendAll(); - { - pvReturn = malloc( xWantedSize ); - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + vTaskSuspendAll(); + { + pvReturn = malloc( xWantedSize ); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ void vPortFree( void *pv ) { - if( pv ) - { - vTaskSuspendAll(); - { - free( pv ); - traceFREE( pv, 0 ); - } - ( void ) xTaskResumeAll(); - } + if( pv ) + { + vTaskSuspendAll(); + { + free( pv ); + traceFREE( pv, 0 ); + } + ( void ) xTaskResumeAll(); + } } diff --git a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_4.c b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_4.c index d7cd8a5b..aa2a885a 100644 --- a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_4.c +++ b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_4.c @@ -46,30 +46,30 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* Block sizes must not get too small. */ -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) /* Assumes 8bit bytes! */ -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) /* Allocate the memory for the heap. */ #if( configAPPLICATION_ALLOCATED_HEAP == 1 ) - /* The application writer has already defined the array used for the RTOS - heap - probably so it can be placed in a special segment or address. */ - extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + /* The application writer has already defined the array used for the RTOS + heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #else - static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; + static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #endif /* configAPPLICATION_ALLOCATED_HEAP */ /* Define the linked list structure. This is used to link free blocks in order of their memory address. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; /*-----------------------------------------------------------*/ @@ -92,7 +92,7 @@ static void prvHeapInit( void ); /* The size of the structure placed at the beginning of each allocated memory block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); +static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; @@ -115,148 +115,148 @@ void *pvPortMalloc( size_t xWantedSize ) BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; void *pvReturn = NULL; - vTaskSuspendAll(); - { - /* If this is the first call to malloc then the heap will require - initialisation to setup the list of free blocks. */ - if( pxEnd == NULL ) - { - prvHeapInit(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + initialisation to setup the list of free blocks. */ + if( pxEnd == NULL ) + { + prvHeapInit(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Check the requested block size is not so large that the top bit is - set. The top bit of the block size member of the BlockLink_t structure - is used to determine who owns the block - the application or the - kernel, so it must be free. */ - if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) - { - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += xHeapStructSize; + /* Check the requested block size is not so large that the top bit is + set. The top bit of the block size member of the BlockLink_t structure + is used to determine who owns the block - the application or the + kernel, so it must be free. */ + if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) + { + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += xHeapStructSize; - /* Ensure that blocks are always aligned to the required number - of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Ensure that blocks are always aligned to the required number + of bytes. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) - { - /* Traverse the list from the start (lowest address) block until - one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } - /* If the end marker was reached then a block of adequate size - was not found. */ - if( pxBlock != pxEnd ) - { - /* Return the memory space pointed to - jumping over the - BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + /* If the end marker was reached then a block of adequate size + was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); - /* This block is being returned for use so must be taken out - of the list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + /* This block is being returned for use so must be taken out + of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - /* If the block is larger than required it can be split into - two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new - block following the number of bytes requested. The void - cast is used to prevent byte alignment warnings from the - compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); + /* If the block is larger than required it can be split into + two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + block following the number of bytes requested. The void + cast is used to prevent byte alignment warnings from the + compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); - /* Calculate the sizes of two blocks split from the - single block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; + /* Calculate the sizes of two blocks split from the + single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( pxNewBlockLink ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( pxNewBlockLink ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xFreeBytesRemaining -= pxBlock->xBlockSize; + xFreeBytesRemaining -= pxBlock->xBlockSize; - if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) - { - xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The block is being returned - it is allocated and owned - by the application and has no "next" block. */ - pxBlock->xBlockSize |= xBlockAllocatedBit; - pxBlock->pxNextFreeBlock = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* The block is being returned - it is allocated and owned + by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif - configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); - return pvReturn; + configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); + return pvReturn; } /*-----------------------------------------------------------*/ @@ -265,64 +265,64 @@ void vPortFree( void *pv ) uint8_t *puc = ( uint8_t * ) pv; BlockLink_t *pxLink; - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= xHeapStructSize; + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= xHeapStructSize; - /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; - /* Check the block is actually allocated. */ - configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - configASSERT( pxLink->pxNextFreeBlock == NULL ); + /* Check the block is actually allocated. */ + configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + configASSERT( pxLink->pxNextFreeBlock == NULL ); - if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) - { - if( pxLink->pxNextFreeBlock == NULL ) - { - /* The block is being returned to the heap - it is no longer - allocated. */ - pxLink->xBlockSize &= ~xBlockAllocatedBit; + if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) + { + if( pxLink->pxNextFreeBlock == NULL ) + { + /* The block is being returned to the heap - it is no longer + allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; - vTaskSuspendAll(); - { - /* Add this block to the list of free blocks. */ - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return xFreeBytesRemaining; + return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ size_t xPortGetMinimumEverFreeHeapSize( void ) { - return xMinimumEverFreeBytesRemaining; + return xMinimumEverFreeBytesRemaining; } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { - /* This just exists to keep the linker quiet. */ + /* This just exists to keep the linker quiet. */ } /*-----------------------------------------------------------*/ @@ -333,44 +333,44 @@ uint8_t *pucAlignedHeap; size_t uxAddress; size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; - /* Ensure the heap starts on a correctly aligned boundary. */ - uxAddress = ( size_t ) ucHeap; + /* Ensure the heap starts on a correctly aligned boundary. */ + uxAddress = ( size_t ) ucHeap; - if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - uxAddress += ( portBYTE_ALIGNMENT - 1 ); - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; - } + if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + uxAddress += ( portBYTE_ALIGNMENT - 1 ); + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; + } - pucAlignedHeap = ( uint8_t * ) uxAddress; + pucAlignedHeap = ( uint8_t * ) uxAddress; - /* xStart is used to hold a pointer to the first item in the list of free - blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; + /* xStart is used to hold a pointer to the first item in the list of free + blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; - /* pxEnd is used to mark the end of the list of free blocks and is inserted - at the end of the heap space. */ - uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; - uxAddress -= xHeapStructSize; - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - pxEnd = ( void * ) uxAddress; - pxEnd->xBlockSize = 0; - pxEnd->pxNextFreeBlock = NULL; + /* pxEnd is used to mark the end of the list of free blocks and is inserted + at the end of the heap space. */ + uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; + uxAddress -= xHeapStructSize; + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + pxEnd = ( void * ) uxAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; - /* To start with there is a single free block that is sized to take up the - entire heap space, minus the space taken by pxEnd. */ - pxFirstFreeBlock = ( void * ) pucAlignedHeap; - pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; - pxFirstFreeBlock->pxNextFreeBlock = pxEnd; + /* To start with there is a single free block that is sized to take up the + entire heap space, minus the space taken by pxEnd. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; + pxFirstFreeBlock->pxNextFreeBlock = pxEnd; - /* Only one block exists - and it covers the entire usable heap space. */ - xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + /* Only one block exists - and it covers the entire usable heap space. */ + xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); } /*-----------------------------------------------------------*/ @@ -379,58 +379,58 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) BlockLink_t *pxIterator; uint8_t *puc; - /* Iterate through the list until a block is found that has a higher address - than the block being inserted. */ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) - { - /* Nothing to do here, just iterate to the right position. */ - } + /* Iterate through the list until a block is found that has a higher address + than the block being inserted. */ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) + { + /* Nothing to do here, just iterate to the right position. */ + } - /* Do the block being inserted, and the block it is being inserted after - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; - if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) - { - pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; - pxBlockToInsert = pxIterator; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Do the block being inserted, and the block it is being inserted after + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxIterator; + if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) + { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Do the block being inserted, and the block it is being inserted before - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; - if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) - { - if( pxIterator->pxNextFreeBlock != pxEnd ) - { - /* Form one big block from the two blocks. */ - pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxEnd; - } - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; - } + /* Do the block being inserted, and the block it is being inserted before + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxBlockToInsert; + if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) + { + if( pxIterator->pxNextFreeBlock != pxEnd ) + { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } - /* If the block being inserted plugged a gab, so was merged with the block - before and the block after, then it's pxNextFreeBlock pointer will have - already been set, and should not be set here as that would make it point - to itself. */ - if( pxIterator != pxBlockToInsert ) - { - pxIterator->pxNextFreeBlock = pxBlockToInsert; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the block being inserted plugged a gab, so was merged with the block + before and the block after, then it's pxNextFreeBlock pointer will have + already been set, and should not be set here as that would make it point + to itself. */ + if( pxIterator != pxBlockToInsert ) + { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } diff --git a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_5.c b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_5.c index c2916924..7080771d 100644 --- a/components/bl602/freertos_riscv_ram/portable/MemMang/heap_5.c +++ b/components/bl602/freertos_riscv_ram/portable/MemMang/heap_5.c @@ -46,8 +46,8 @@ * * typedef struct HeapRegion * { - * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap. - * size_t xSizeInBytes; << Size of the block of memory. + * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap. + * size_t xSizeInBytes; << Size of the block of memory. * } HeapRegion_t; * * The array is terminated using a NULL zero sized region definition, and the @@ -57,9 +57,9 @@ * * HeapRegion_t xHeapRegions[] = * { - * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000 - * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000 - * { NULL, 0 } << Terminates the array. + * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000 + * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000 + * { NULL, 0 } << Terminates the array. * }; * * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions(). @@ -81,21 +81,21 @@ task.h is included from an application file. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) - #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* Block sizes must not get too small. */ -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) /* Assumes 8bit bytes! */ -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) /* Define the linked list structure. This is used to link free blocks in order of their memory address. */ typedef struct A_BLOCK_LINK { - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; /*-----------------------------------------------------------*/ @@ -112,7 +112,7 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); /* The size of the structure placed at the beginning of each allocated memory block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); +static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; @@ -135,138 +135,138 @@ void *pvPortMalloc( size_t xWantedSize ) BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; void *pvReturn = NULL; - /* The heap must be initialised before the first call to - prvPortMalloc(). */ - configASSERT( pxEnd ); + /* The heap must be initialised before the first call to + prvPortMalloc(). */ + configASSERT( pxEnd ); - vTaskSuspendAll(); - { - /* Check the requested block size is not so large that the top bit is - set. The top bit of the block size member of the BlockLink_t structure - is used to determine who owns the block - the application or the - kernel, so it must be free. */ - if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) - { - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += xHeapStructSize; + vTaskSuspendAll(); + { + /* Check the requested block size is not so large that the top bit is + set. The top bit of the block size member of the BlockLink_t structure + is used to determine who owns the block - the application or the + kernel, so it must be free. */ + if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) + { + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += xHeapStructSize; - /* Ensure that blocks are always aligned to the required number - of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Ensure that blocks are always aligned to the required number + of bytes. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) - { - /* Traverse the list from the start (lowest address) block until - one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } - /* If the end marker was reached then a block of adequate size - was not found. */ - if( pxBlock != pxEnd ) - { - /* Return the memory space pointed to - jumping over the - BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + /* If the end marker was reached then a block of adequate size + was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); - /* This block is being returned for use so must be taken out - of the list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + /* This block is being returned for use so must be taken out + of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - /* If the block is larger than required it can be split into - two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new - block following the number of bytes requested. The void - cast is used to prevent byte alignment warnings from the - compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + /* If the block is larger than required it can be split into + two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + block following the number of bytes requested. The void + cast is used to prevent byte alignment warnings from the + compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - /* Calculate the sizes of two blocks split from the - single block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; + /* Calculate the sizes of two blocks split from the + single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xFreeBytesRemaining -= pxBlock->xBlockSize; + xFreeBytesRemaining -= pxBlock->xBlockSize; - if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) - { - xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The block is being returned - it is allocated and owned - by the application and has no "next" block. */ - pxBlock->xBlockSize |= xBlockAllocatedBit; - pxBlock->pxNextFreeBlock = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* The block is being returned - it is allocated and owned + by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceMALLOC( pvReturn, xWantedSize ); - } - ( void ) xTaskResumeAll(); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); - #if( configUSE_MALLOC_FAILED_HOOK == 1 ) - { - if( pvReturn == NULL ) - { - extern void vApplicationMallocFailedHook( void ); - vApplicationMallocFailedHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ @@ -286,58 +286,58 @@ void vPortFree( void *pv ) uint8_t *puc = ( uint8_t * ) pv; BlockLink_t *pxLink; - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= xHeapStructSize; + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= xHeapStructSize; - /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; - /* Check the block is actually allocated. */ - configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - configASSERT( pxLink->pxNextFreeBlock == NULL ); + /* Check the block is actually allocated. */ + configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + configASSERT( pxLink->pxNextFreeBlock == NULL ); - if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) - { - if( pxLink->pxNextFreeBlock == NULL ) - { - /* The block is being returned to the heap - it is no longer - allocated. */ - pxLink->xBlockSize &= ~xBlockAllocatedBit; + if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) + { + if( pxLink->pxNextFreeBlock == NULL ) + { + /* The block is being returned to the heap - it is no longer + allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; - vTaskSuspendAll(); - { - /* Add this block to the list of free blocks. */ - xFreeBytesRemaining += pxLink->xBlockSize; - traceFREE( pv, pxLink->xBlockSize ); - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { - return xFreeBytesRemaining; + return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ size_t xPortGetMinimumEverFreeHeapSize( void ) { - return xMinimumEverFreeBytesRemaining; + return xMinimumEverFreeBytesRemaining; } /*-----------------------------------------------------------*/ @@ -346,59 +346,59 @@ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) BlockLink_t *pxIterator; uint8_t *puc; - /* Iterate through the list until a block is found that has a higher address - than the block being inserted. */ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) - { - /* Nothing to do here, just iterate to the right position. */ - } + /* Iterate through the list until a block is found that has a higher address + than the block being inserted. */ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) + { + /* Nothing to do here, just iterate to the right position. */ + } - /* Do the block being inserted, and the block it is being inserted after - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; - if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) - { - pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; - pxBlockToInsert = pxIterator; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Do the block being inserted, and the block it is being inserted after + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxIterator; + if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) + { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Do the block being inserted, and the block it is being inserted before - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; - if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) - { - if( pxIterator->pxNextFreeBlock != pxEnd ) - { - /* Form one big block from the two blocks. */ - pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxEnd; - } - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; - } + /* Do the block being inserted, and the block it is being inserted before + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxBlockToInsert; + if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) + { + if( pxIterator->pxNextFreeBlock != pxEnd ) + { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } - /* If the block being inserted plugged a gab, so was merged with the block - before and the block after, then it's pxNextFreeBlock pointer will have - already been set, and should not be set here as that would make it point - to itself. */ - if( pxIterator != pxBlockToInsert ) - { - pxIterator->pxNextFreeBlock = pxBlockToInsert; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the block being inserted plugged a gab, so was merged with the block + before and the block after, then it's pxNextFreeBlock pointer will have + already been set, and should not be set here as that would make it point + to itself. */ + if( pxIterator != pxBlockToInsert ) + { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } /*-----------------------------------------------------------*/ @@ -411,87 +411,87 @@ BaseType_t xDefinedRegions = 0; size_t xAddress; const HeapRegion_t *pxHeapRegion; - /* Can only call once! */ - configASSERT( pxEnd == NULL ); + /* Can only call once! */ + configASSERT( pxEnd == NULL ); - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); - while( pxHeapRegion->xSizeInBytes > 0 ) - { - xTotalRegionSize = pxHeapRegion->xSizeInBytes; + while( pxHeapRegion->xSizeInBytes > 0 ) + { + xTotalRegionSize = pxHeapRegion->xSizeInBytes; - /* Ensure the heap region starts on a correctly aligned boundary. */ - xAddress = ( size_t ) pxHeapRegion->pucStartAddress; - if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - xAddress += ( portBYTE_ALIGNMENT - 1 ); - xAddress &= ~portBYTE_ALIGNMENT_MASK; + /* Ensure the heap region starts on a correctly aligned boundary. */ + xAddress = ( size_t ) pxHeapRegion->pucStartAddress; + if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + xAddress += ( portBYTE_ALIGNMENT - 1 ); + xAddress &= ~portBYTE_ALIGNMENT_MASK; - /* Adjust the size for the bytes lost to alignment. */ - xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress; - } + /* Adjust the size for the bytes lost to alignment. */ + xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress; + } - xAlignedHeap = xAddress; + xAlignedHeap = xAddress; - /* Set xStart if it has not already been set. */ - if( xDefinedRegions == 0 ) - { - /* xStart is used to hold a pointer to the first item in the list of - free blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; - } - else - { - /* Should only get here if one region has already been added to the - heap. */ - configASSERT( pxEnd != NULL ); + /* Set xStart if it has not already been set. */ + if( xDefinedRegions == 0 ) + { + /* xStart is used to hold a pointer to the first item in the list of + free blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; + } + else + { + /* Should only get here if one region has already been added to the + heap. */ + configASSERT( pxEnd != NULL ); - /* Check blocks are passed in with increasing start addresses. */ - configASSERT( xAddress > ( size_t ) pxEnd ); - } + /* Check blocks are passed in with increasing start addresses. */ + configASSERT( xAddress > ( size_t ) pxEnd ); + } - /* Remember the location of the end marker in the previous region, if - any. */ - pxPreviousFreeBlock = pxEnd; + /* Remember the location of the end marker in the previous region, if + any. */ + pxPreviousFreeBlock = pxEnd; - /* pxEnd is used to mark the end of the list of free blocks and is - inserted at the end of the region space. */ - xAddress = xAlignedHeap + xTotalRegionSize; - xAddress -= xHeapStructSize; - xAddress &= ~portBYTE_ALIGNMENT_MASK; - pxEnd = ( BlockLink_t * ) xAddress; - pxEnd->xBlockSize = 0; - pxEnd->pxNextFreeBlock = NULL; + /* pxEnd is used to mark the end of the list of free blocks and is + inserted at the end of the region space. */ + xAddress = xAlignedHeap + xTotalRegionSize; + xAddress -= xHeapStructSize; + xAddress &= ~portBYTE_ALIGNMENT_MASK; + pxEnd = ( BlockLink_t * ) xAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; - /* To start with there is a single free block in this region that is - sized to take up the entire heap region minus the space taken by the - free block structure. */ - pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap; - pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion; - pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd; + /* To start with there is a single free block in this region that is + sized to take up the entire heap region minus the space taken by the + free block structure. */ + pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap; + pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion; + pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd; - /* If this is not the first region that makes up the entire heap space - then link the previous region to this region. */ - if( pxPreviousFreeBlock != NULL ) - { - pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion; - } + /* If this is not the first region that makes up the entire heap space + then link the previous region to this region. */ + if( pxPreviousFreeBlock != NULL ) + { + pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion; + } - xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize; + xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize; - /* Move onto the next HeapRegion_t structure. */ - xDefinedRegions++; - pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); - } + /* Move onto the next HeapRegion_t structure. */ + xDefinedRegions++; + pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + } - xMinimumEverFreeBytesRemaining = xTotalHeapSize; - xFreeBytesRemaining = xTotalHeapSize; + xMinimumEverFreeBytesRemaining = xTotalHeapSize; + xFreeBytesRemaining = xTotalHeapSize; - /* Check something was actually defined before it is accessed. */ - configASSERT( xTotalHeapSize ); + /* Check something was actually defined before it is accessed. */ + configASSERT( xTotalHeapSize ); - /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); } diff --git a/components/bl602/freertos_riscv_ram/queue.c b/components/bl602/freertos_riscv_ram/queue.c index d882bf67..78e2d5ac 100644 --- a/components/bl602/freertos_riscv_ram/queue.c +++ b/components/bl602/freertos_riscv_ram/queue.c @@ -38,7 +38,7 @@ task.h is included from an application file. */ #include "queue.h" #if ( configUSE_CO_ROUTINES == 1 ) - #include "croutine.h" + #include "croutine.h" #endif /* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified @@ -49,8 +49,8 @@ correct privileged Vs unprivileged linkage and placement. */ /* Constants used with the cRxLock and cTxLock structure members. */ -#define queueUNLOCKED ( ( int8_t ) -1 ) -#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) +#define queueUNLOCKED ( ( int8_t ) -1 ) +#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) /* When the Queue_t structure is used to represent a base queue its pcHead and pcTail members are used as pointers into the queue storage area. When the @@ -61,32 +61,32 @@ names to the pcHead and structure member to ensure the readability of the code is maintained. The QueuePointers_t and SemaphoreData_t types are used to form a union as their usage is mutually exclusive dependent on what the queue is being used for. */ -#define uxQueueType pcHead -#define queueQUEUE_IS_MUTEX NULL +#define uxQueueType pcHead +#define queueQUEUE_IS_MUTEX NULL typedef struct QueuePointers { - int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ - int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ + int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ + int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ } QueuePointers_t; typedef struct SemaphoreData { - TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ - UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ + TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ + UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ } SemaphoreData_t; /* Semaphores do not actually store or copy data, so have an item size of zero. */ #define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) -#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) +#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) #if( configUSE_PREEMPTION == 0 ) - /* If the cooperative scheduler is being used then a yield should not be - performed just because a higher priority task has been woken. */ - #define queueYIELD_IF_USING_PREEMPTION() + /* If the cooperative scheduler is being used then a yield should not be + performed just because a higher priority task has been woken. */ + #define queueYIELD_IF_USING_PREEMPTION() #else - #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() + #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() #endif /* @@ -94,39 +94,39 @@ zero. */ * Items are queued by copy, not reference. See the following link for the * rationale: https://www.freertos.org/Embedded-RTOS-Queues.html */ -typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ { - int8_t *pcHead; /*< Points to the beginning of the queue storage area. */ - int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */ + int8_t *pcHead; /*< Points to the beginning of the queue storage area. */ + int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */ - union - { - QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ - SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ - } u; + union + { + QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ + SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ + } u; - List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ - List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ + List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ + List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ - volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */ - UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ - UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ + volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */ + UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ + UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ - volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ - #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ - #endif + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ + #endif - #if ( configUSE_QUEUE_SETS == 1 ) - struct QueueDefinition *pxQueueSetContainer; - #endif + #if ( configUSE_QUEUE_SETS == 1 ) + struct QueueDefinition *pxQueueSetContainer; + #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxQueueNumber; - uint8_t ucQueueType; - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxQueueNumber; + uint8_t ucQueueType; + #endif } xQUEUE; @@ -142,24 +142,24 @@ typedef xQUEUE Queue_t; */ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - /* The type stored within the queue registry array. This allows a name - to be assigned to each queue making kernel aware debugging a little - more user friendly. */ - typedef struct QUEUE_REGISTRY_ITEM - { - const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - QueueHandle_t xHandle; - } xQueueRegistryItem; + /* The type stored within the queue registry array. This allows a name + to be assigned to each queue making kernel aware debugging a little + more user friendly. */ + typedef struct QUEUE_REGISTRY_ITEM + { + const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + QueueHandle_t xHandle; + } xQueueRegistryItem; - /* The old xQueueRegistryItem name is maintained above then typedefed to the - new xQueueRegistryItem name below to enable the use of older kernel aware - debuggers. */ - typedef xQueueRegistryItem QueueRegistryItem_t; + /* The old xQueueRegistryItem name is maintained above then typedefed to the + new xQueueRegistryItem name below to enable the use of older kernel aware + debuggers. */ + typedef xQueueRegistryItem QueueRegistryItem_t; - /* The queue registry is simply an array of QueueRegistryItem_t structures. - The pcQueueName member of a structure being NULL is indicative of the - array position being vacant. */ - PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; + /* The queue registry is simply an array of QueueRegistryItem_t structures. + The pcQueueName member of a structure being NULL is indicative of the + array position being vacant. */ + PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; #endif /* configQUEUE_REGISTRY_SIZE */ @@ -199,11 +199,11 @@ static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvIte static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION; #if ( configUSE_QUEUE_SETS == 1 ) - /* - * Checks to see if a queue is a member of a queue set, and if so, notifies - * the queue set that the queue contains data. - */ - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; + /* + * Checks to see if a queue is a member of a queue set, and if so, notifies + * the queue set that the queue contains data. + */ + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; #endif /* @@ -218,18 +218,18 @@ static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseT * as a mutex. */ #if( configUSE_MUTEXES == 1 ) - static void prvInitialiseMutex( Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; + static void prvInitialiseMutex( Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; #endif #if( configUSE_MUTEXES == 1 ) - /* - * If a task waiting for a mutex causes the mutex holder to inherit a - * priority, but the waiting task times out, then the holder should - * disinherit the priority - but only down to the highest priority of any - * other tasks that are waiting for the same mutex. This function returns - * that priority. - */ - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; + /* + * If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. This function returns + * that priority. + */ + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; #endif /*-----------------------------------------------------------*/ @@ -237,509 +237,509 @@ static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseT * Macro to mark a queue as locked. Locking a queue prevents an ISR from * accessing the queue event lists. */ -#define prvLockQueue( pxQueue ) \ - taskENTER_CRITICAL(); \ - { \ - if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ - } \ - if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ - { \ - ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ - } \ - } \ - taskEXIT_CRITICAL() +#define prvLockQueue( pxQueue ) \ + taskENTER_CRITICAL(); \ + { \ + if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ + } \ + if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ + } \ + } \ + taskEXIT_CRITICAL() /*-----------------------------------------------------------*/ BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) { Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); + configASSERT( pxQueue ); - taskENTER_CRITICAL(); - { - pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; - pxQueue->pcWriteTo = pxQueue->pcHead; - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - pxQueue->cRxLock = queueUNLOCKED; - pxQueue->cTxLock = queueUNLOCKED; + taskENTER_CRITICAL(); + { + pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; + pxQueue->pcWriteTo = pxQueue->pcHead; + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->cRxLock = queueUNLOCKED; + pxQueue->cTxLock = queueUNLOCKED; - if( xNewQueue == pdFALSE ) - { - /* If there are tasks blocked waiting to read from the queue, then - the tasks will remain blocked as after this function exits the queue - will still be empty. If there are tasks blocked waiting to write to - the queue, then one should be unblocked as after this function exits - it will be possible to write to it. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Ensure the event queues start in the correct state. */ - vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); - vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); - } - } - taskEXIT_CRITICAL(); + if( xNewQueue == pdFALSE ) + { + /* If there are tasks blocked waiting to read from the queue, then + the tasks will remain blocked as after this function exits the queue + will still be empty. If there are tasks blocked waiting to write to + the queue, then one should be unblocked as after this function exits + it will be possible to write to it. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Ensure the event queues start in the correct state. */ + vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); + vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); + } + } + taskEXIT_CRITICAL(); - /* A value is returned for calling semantic consistency with previous - versions. */ - return pdPASS; + /* A value is returned for calling semantic consistency with previous + versions. */ + return pdPASS; } /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) - { - Queue_t *pxNewQueue; + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) + { + Queue_t *pxNewQueue; - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); + configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - /* The StaticQueue_t structure and the queue storage area must be - supplied. */ - configASSERT( pxStaticQueue != NULL ); + /* The StaticQueue_t structure and the queue storage area must be + supplied. */ + configASSERT( pxStaticQueue != NULL ); - /* A queue storage area should be provided if the item size is not 0, and - should not be provided if the item size is 0. */ - configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); - configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); + /* A queue storage area should be provided if the item size is not 0, and + should not be provided if the item size is 0. */ + configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); + configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticQueue_t or StaticSemaphore_t equals the size of - the real queue and semaphore structures. */ - volatile size_t xSize = sizeof( StaticQueue_t ); - configASSERT( xSize == sizeof( Queue_t ) ); - ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ - } - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticQueue_t or StaticSemaphore_t equals the size of + the real queue and semaphore structures. */ + volatile size_t xSize = sizeof( StaticQueue_t ); + configASSERT( xSize == sizeof( Queue_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ - /* The address of a statically allocated queue was passed in, use it. - The address of a statically allocated storage area was also passed in - but is already set. */ - pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + /* The address of a statically allocated queue was passed in, use it. + The address of a statically allocated storage area was also passed in + but is already set. */ + pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - if( pxNewQueue != NULL ) - { - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Queues can be allocated wither statically or dynamically, so - note this queue was allocated statically in case the queue is - later deleted. */ - pxNewQueue->ucStaticallyAllocated = pdTRUE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + if( pxNewQueue != NULL ) + { + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Queues can be allocated wither statically or dynamically, so + note this queue was allocated statically in case the queue is + later deleted. */ + pxNewQueue->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - mtCOVERAGE_TEST_MARKER(); - } + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } - return pxNewQueue; - } + return pxNewQueue; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) - { - Queue_t *pxNewQueue; - size_t xQueueSizeInBytes; - uint8_t *pucQueueStorage; + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) + { + Queue_t *pxNewQueue; + size_t xQueueSizeInBytes; + uint8_t *pucQueueStorage; - configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); + configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); - if( uxItemSize == ( UBaseType_t ) 0 ) - { - /* There is not going to be a queue storage area. */ - xQueueSizeInBytes = ( size_t ) 0; - } - else - { - /* Allocate enough space to hold the maximum number of items that - can be in the queue at any time. */ - xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } + if( uxItemSize == ( UBaseType_t ) 0 ) + { + /* There is not going to be a queue storage area. */ + xQueueSizeInBytes = ( size_t ) 0; + } + else + { + /* Allocate enough space to hold the maximum number of items that + can be in the queue at any time. */ + xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } - /* Allocate the queue and storage area. Justification for MISRA - deviation as follows: pvPortMalloc() always ensures returned memory - blocks are aligned per the requirements of the MCU stack. In this case - pvPortMalloc() must return a pointer that is guaranteed to meet the - alignment requirements of the Queue_t structure - which in this case - is an int8_t *. Therefore, whenever the stack alignment requirements - are greater than or equal to the pointer to char requirements the cast - is safe. In other cases alignment requirements are not strict (one or - two bytes). */ - pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */ + /* Allocate the queue and storage area. Justification for MISRA + deviation as follows: pvPortMalloc() always ensures returned memory + blocks are aligned per the requirements of the MCU stack. In this case + pvPortMalloc() must return a pointer that is guaranteed to meet the + alignment requirements of the Queue_t structure - which in this case + is an int8_t *. Therefore, whenever the stack alignment requirements + are greater than or equal to the pointer to char requirements the cast + is safe. In other cases alignment requirements are not strict (one or + two bytes). */ + pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */ - if( pxNewQueue != NULL ) - { - /* Jump past the queue structure to find the location of the queue - storage area. */ - pucQueueStorage = ( uint8_t * ) pxNewQueue; - pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + if( pxNewQueue != NULL ) + { + /* Jump past the queue structure to find the location of the queue + storage area. */ + pucQueueStorage = ( uint8_t * ) pxNewQueue; + pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* Queues can be created either statically or dynamically, so - note this task was created dynamically in case it is later - deleted. */ - pxNewQueue->ucStaticallyAllocated = pdFALSE; - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Queues can be created either statically or dynamically, so + note this task was created dynamically in case it is later + deleted. */ + pxNewQueue->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ - prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); - } - else - { - traceQUEUE_CREATE_FAILED( ucQueueType ); - mtCOVERAGE_TEST_MARKER(); - } + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } - return pxNewQueue; - } + return pxNewQueue; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) { - /* Remove compiler warnings about unused parameters should - configUSE_TRACE_FACILITY not be set to 1. */ - ( void ) ucQueueType; + /* Remove compiler warnings about unused parameters should + configUSE_TRACE_FACILITY not be set to 1. */ + ( void ) ucQueueType; - if( uxItemSize == ( UBaseType_t ) 0 ) - { - /* No RAM was allocated for the queue storage area, but PC head cannot - be set to NULL because NULL is used as a key to say the queue is used as - a mutex. Therefore just set pcHead to point to the queue as a benign - value that is known to be within the memory map. */ - pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; - } - else - { - /* Set the head to the start of the queue storage area. */ - pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; - } + if( uxItemSize == ( UBaseType_t ) 0 ) + { + /* No RAM was allocated for the queue storage area, but PC head cannot + be set to NULL because NULL is used as a key to say the queue is used as + a mutex. Therefore just set pcHead to point to the queue as a benign + value that is known to be within the memory map. */ + pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; + } + else + { + /* Set the head to the start of the queue storage area. */ + pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; + } - /* Initialise the queue members as described where the queue type is - defined. */ - pxNewQueue->uxLength = uxQueueLength; - pxNewQueue->uxItemSize = uxItemSize; - ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); + /* Initialise the queue members as described where the queue type is + defined. */ + pxNewQueue->uxLength = uxQueueLength; + pxNewQueue->uxItemSize = uxItemSize; + ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); - #if ( configUSE_TRACE_FACILITY == 1 ) - { - pxNewQueue->ucQueueType = ucQueueType; - } - #endif /* configUSE_TRACE_FACILITY */ + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxNewQueue->ucQueueType = ucQueueType; + } + #endif /* configUSE_TRACE_FACILITY */ - #if( configUSE_QUEUE_SETS == 1 ) - { - pxNewQueue->pxQueueSetContainer = NULL; - } - #endif /* configUSE_QUEUE_SETS */ + #if( configUSE_QUEUE_SETS == 1 ) + { + pxNewQueue->pxQueueSetContainer = NULL; + } + #endif /* configUSE_QUEUE_SETS */ - traceQUEUE_CREATE( pxNewQueue ); + traceQUEUE_CREATE( pxNewQueue ); } /*-----------------------------------------------------------*/ #if( configUSE_MUTEXES == 1 ) - static void prvInitialiseMutex( Queue_t *pxNewQueue ) - { - if( pxNewQueue != NULL ) - { - /* The queue create function will set all the queue structure members - correctly for a generic queue, but this function is creating a - mutex. Overwrite those members that need to be set differently - - in particular the information required for priority inheritance. */ - pxNewQueue->u.xSemaphore.xMutexHolder = NULL; - pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; + static void prvInitialiseMutex( Queue_t *pxNewQueue ) + { + if( pxNewQueue != NULL ) + { + /* The queue create function will set all the queue structure members + correctly for a generic queue, but this function is creating a + mutex. Overwrite those members that need to be set differently - + in particular the information required for priority inheritance. */ + pxNewQueue->u.xSemaphore.xMutexHolder = NULL; + pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; - /* In case this is a recursive mutex. */ - pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; + /* In case this is a recursive mutex. */ + pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; - traceCREATE_MUTEX( pxNewQueue ); + traceCREATE_MUTEX( pxNewQueue ); - /* Start with the semaphore in the expected state. */ - ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); - } - else - { - traceCREATE_MUTEX_FAILED(); - } - } + /* Start with the semaphore in the expected state. */ + ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); + } + else + { + traceCREATE_MUTEX_FAILED(); + } + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) - { - QueueHandle_t xNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); - prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); - return xNewQueue; - } + return xNewQueue; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) - { - QueueHandle_t xNewQueue; - const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; - /* Prevent compiler warnings about unused parameters if - configUSE_TRACE_FACILITY does not equal 1. */ - ( void ) ucQueueType; + /* Prevent compiler warnings about unused parameters if + configUSE_TRACE_FACILITY does not equal 1. */ + ( void ) ucQueueType; - xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); - prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); - return xNewQueue; - } + return xNewQueue; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) - { - TaskHandle_t pxReturn; - Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; + TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; - /* This function is called by xSemaphoreGetMutexHolder(), and should not - be called directly. Note: This is a good way of determining if the - calling task is the mutex holder, but not a good way of determining the - identity of the mutex holder, as the holder may change between the - following critical section exiting and the function returning. */ - taskENTER_CRITICAL(); - { - if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; - } - else - { - pxReturn = NULL; - } - } - taskEXIT_CRITICAL(); + /* This function is called by xSemaphoreGetMutexHolder(), and should not + be called directly. Note: This is a good way of determining if the + calling task is the mutex holder, but not a good way of determining the + identity of the mutex holder, as the holder may change between the + following critical section exiting and the function returning. */ + taskENTER_CRITICAL(); + { + if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + } + taskEXIT_CRITICAL(); - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ #endif /*-----------------------------------------------------------*/ #if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) - TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) - { - TaskHandle_t pxReturn; + TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; - configASSERT( xSemaphore ); + configASSERT( xSemaphore ); - /* Mutexes cannot be used in interrupt service routines, so the mutex - holder should not change in an ISR, and therefore a critical section is - not required here. */ - if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) - { - pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; - } - else - { - pxReturn = NULL; - } + /* Mutexes cannot be used in interrupt service routines, so the mutex + holder should not change in an ISR, and therefore a critical section is + not required here. */ + if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } - return pxReturn; - } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ #endif /*-----------------------------------------------------------*/ #if ( configUSE_RECURSIVE_MUTEXES == 1 ) - BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; + BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; - configASSERT( pxMutex ); + configASSERT( pxMutex ); - /* If this is the task that holds the mutex then xMutexHolder will not - change outside of this task. If this task does not hold the mutex then - pxMutexHolder can never coincidentally equal the tasks handle, and as - this is the only condition we are interested in it does not matter if - pxMutexHolder is accessed simultaneously by another task. Therefore no - mutual exclusion is required to test the pxMutexHolder variable. */ - if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) - { - traceGIVE_MUTEX_RECURSIVE( pxMutex ); + /* If this is the task that holds the mutex then xMutexHolder will not + change outside of this task. If this task does not hold the mutex then + pxMutexHolder can never coincidentally equal the tasks handle, and as + this is the only condition we are interested in it does not matter if + pxMutexHolder is accessed simultaneously by another task. Therefore no + mutual exclusion is required to test the pxMutexHolder variable. */ + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + traceGIVE_MUTEX_RECURSIVE( pxMutex ); - /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to - the task handle, therefore no underflow check is required. Also, - uxRecursiveCallCount is only modified by the mutex holder, and as - there can only be one, no mutual exclusion is required to modify the - uxRecursiveCallCount member. */ - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; + /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to + the task handle, therefore no underflow check is required. Also, + uxRecursiveCallCount is only modified by the mutex holder, and as + there can only be one, no mutual exclusion is required to modify the + uxRecursiveCallCount member. */ + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; - /* Has the recursive call count unwound to 0? */ - if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) - { - /* Return the mutex. This will automatically unblock any other - task that might be waiting to access the mutex. */ - ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Has the recursive call count unwound to 0? */ + if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) + { + /* Return the mutex. This will automatically unblock any other + task that might be waiting to access the mutex. */ + ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xReturn = pdPASS; - } - else - { - /* The mutex cannot be given because the calling task is not the - holder. */ - xReturn = pdFAIL; + xReturn = pdPASS; + } + else + { + /* The mutex cannot be given because the calling task is not the + holder. */ + xReturn = pdFAIL; - traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } + traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_RECURSIVE_MUTEXES == 1 ) - BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxMutex = ( Queue_t * ) xMutex; + BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; - configASSERT( pxMutex ); + configASSERT( pxMutex ); - /* Comments regarding mutual exclusion as per those within - xQueueGiveMutexRecursive(). */ + /* Comments regarding mutual exclusion as per those within + xQueueGiveMutexRecursive(). */ - traceTAKE_MUTEX_RECURSIVE( pxMutex ); + traceTAKE_MUTEX_RECURSIVE( pxMutex ); - if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) - { - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; - xReturn = pdPASS; - } - else - { - xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + xReturn = pdPASS; + } + else + { + xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); - /* pdPASS will only be returned if the mutex was successfully - obtained. The calling task may have entered the Blocked state - before reaching here. */ - if( xReturn != pdFAIL ) - { - ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; - } - else - { - traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); - } - } + /* pdPASS will only be returned if the mutex was successfully + obtained. The calling task may have entered the Blocked state + before reaching here. */ + if( xReturn != pdFAIL ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + } + else + { + traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) - { - QueueHandle_t xHandle; + QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) + { + QueueHandle_t xHandle; - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); + configASSERT( uxMaxCount != 0 ); + configASSERT( uxInitialCount <= uxMaxCount ); - xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } - return xHandle; - } + return xHandle; + } #endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ #if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) - { - QueueHandle_t xHandle; + QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) + { + QueueHandle_t xHandle; - configASSERT( uxMaxCount != 0 ); - configASSERT( uxInitialCount <= uxMaxCount ); + configASSERT( uxMaxCount != 0 ); + configASSERT( uxInitialCount <= uxMaxCount ); - xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); - if( xHandle != NULL ) - { - ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; - traceCREATE_COUNTING_SEMAPHORE(); - } - else - { - traceCREATE_COUNTING_SEMAPHORE_FAILED(); - } + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } - return xHandle; - } + return xHandle; + } #endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ @@ -750,207 +750,207 @@ BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired; TimeOut_t xTimeOut; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to - allow return statements within the function itself. This is done in the - interest of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - /* Is there room on the queue now? The running task must be the - highest priority task wanting to access the queue. If the head item - in the queue is to be overwritten then it does not matter if the - queue is full. */ - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - traceQUEUE_SEND( pxQueue ); + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + /* Is there room on the queue now? The running task must be the + highest priority task wanting to access the queue. If the head item + in the queue is to be overwritten then it does not matter if the + queue is full. */ + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + traceQUEUE_SEND( pxQueue ); - #if ( configUSE_QUEUE_SETS == 1 ) - { - UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + #if ( configUSE_QUEUE_SETS == 1 ) + { + UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; - xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) - { - /* Do not notify the queue set as an existing item - was overwritten in the queue so the number of items - in the queue has not changed. */ - mtCOVERAGE_TEST_MARKER(); - } - else if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - to the queue set caused a higher priority task to - unblock. A context switch is required. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If there was a task waiting for data to arrive on the - queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - our own so yield immediately. Yes it is ok to - do this from within the critical section - the - kernel takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - executed if the task was holding multiple mutexes - and the mutexes were given back in an order that is - different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + was overwritten in the queue so the number of items + in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + to the queue set caused a higher priority task to + unblock. A context switch is required. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If there was a task waiting for data to arrive on the + queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + our own so yield immediately. Yes it is ok to + do this from within the critical section - the + kernel takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + executed if the task was holding multiple mutexes + and the mutexes were given back in an order that is + different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - /* If there was a task waiting for data to arrive on the - queue then unblock it now. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The unblocked task has a priority higher than - our own so yield immediately. Yes it is ok to do - this from within the critical section - the kernel - takes care of that. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else if( xYieldRequired != pdFALSE ) - { - /* This path is a special case that will only get - executed if the task was holding multiple mutexes and - the mutexes were given back in an order that is - different to that in which they were taken. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ + /* If there was a task waiting for data to arrive on the + queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + our own so yield immediately. Yes it is ok to do + this from within the critical section - the kernel + takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + executed if the task was holding multiple mutexes and + the mutexes were given back in an order that is + different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was full and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was full and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); - /* Return to the original privilege level before exiting - the function. */ - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was full and a block time was specified so - configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + /* Return to the original privilege level before exiting + the function. */ + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was full and a block time was specified so + configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_SEND( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_SEND( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); - /* Unlocking the queue means queue events can effect the - event list. It is possible that interrupts occurring now - remove this task from the event list again - but as the - scheduler is suspended the task will go onto the pending - ready last instead of the actual ready list. */ - prvUnlockQueue( pxQueue ); + /* Unlocking the queue means queue events can effect the + event list. It is possible that interrupts occurring now + remove this task from the event list again - but as the + scheduler is suspended the task will go onto the pending + ready last instead of the actual ready list. */ + prvUnlockQueue( pxQueue ); - /* Resuming the scheduler will move tasks from the pending - ready list into the ready list - so it is feasible that this - task is already in a ready list before it yields - in which - case the yield will not cause a context switch unless there - is also a higher priority task in the pending ready list. */ - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - } - else - { - /* Try again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + /* Resuming the scheduler will move tasks from the pending + ready list into the ready list - so it is feasible that this + task is already in a ready list before it yields - in which + case the yield will not cause a context switch unless there + is also a higher priority task in the pending ready list. */ + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + } + else + { + /* Try again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - traceQUEUE_SEND_FAILED( pxQueue ); - return errQUEUE_FULL; - } - } /*lint -restore */ + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -960,148 +960,148 @@ BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - /* Similar to xQueueGenericSend, except without blocking if there is no room - in the queue. Also don't directly wake a task that was blocked on a queue - read, instead return a flag to say whether a context switch is required or - not (i.e. has a task with a higher priority than us been woken by this - post). */ - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) - { - const int8_t cTxLock = pxQueue->cTxLock; + /* Similar to xQueueGenericSend, except without blocking if there is no room + in the queue. Also don't directly wake a task that was blocked on a queue + read, instead return a flag to say whether a context switch is required or + not (i.e. has a task with a higher priority than us been woken by this + post). */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + const int8_t cTxLock = pxQueue->cTxLock; - traceQUEUE_SEND_FROM_ISR( pxQueue ); + traceQUEUE_SEND_FROM_ISR( pxQueue ); - /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a - semaphore or mutex. That means prvCopyDataToQueue() cannot result - in a task disinheriting a priority and prvCopyDataToQueue() can be - called here even though the disinherit function does not check if - the scheduler is suspended before accessing the ready lists. */ - ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a + semaphore or mutex. That means prvCopyDataToQueue() cannot result + in a task disinheriting a priority and prvCopyDataToQueue() can be + called here even though the disinherit function does not check if + the scheduler is suspended before accessing the ready lists. */ + ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); - /* The event list is not altered if the queue is locked. This will - be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting - to the queue set caused a higher priority task to - unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was posted while it was locked. */ - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } + /* The event list is not altered if the queue is locked. This will + be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + to the queue set caused a higher priority task to + unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was posted while it was locked. */ + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1111,162 +1111,162 @@ BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; Queue_t * const pxQueue = xQueue; - /* Similar to xQueueGenericSendFromISR() but used with semaphores where the - item size is 0. Don't directly wake a task that was blocked on a queue - read, instead return a flag to say whether a context switch is required or - not (i.e. has a task with a higher priority than us been woken by this - post). */ + /* Similar to xQueueGenericSendFromISR() but used with semaphores where the + item size is 0. Don't directly wake a task that was blocked on a queue + read, instead return a flag to say whether a context switch is required or + not (i.e. has a task with a higher priority than us been woken by this + post). */ - configASSERT( pxQueue ); + configASSERT( pxQueue ); - /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() - if the item size is not 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); + /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() + if the item size is not 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); - /* Normally a mutex would not be given from an interrupt, especially if - there is a mutex holder, as priority inheritance makes no sense for an - interrupts, only tasks. */ - configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); + /* Normally a mutex would not be given from an interrupt, especially if + there is a mutex holder, as priority inheritance makes no sense for an + interrupts, only tasks. */ + configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* When the queue is used to implement a semaphore no data is ever - moved through the queue but it is still valid to see if the queue 'has - space'. */ - if( uxMessagesWaiting < pxQueue->uxLength ) - { - const int8_t cTxLock = pxQueue->cTxLock; + /* When the queue is used to implement a semaphore no data is ever + moved through the queue but it is still valid to see if the queue 'has + space'. */ + if( uxMessagesWaiting < pxQueue->uxLength ) + { + const int8_t cTxLock = pxQueue->cTxLock; - traceQUEUE_SEND_FROM_ISR( pxQueue ); + traceQUEUE_SEND_FROM_ISR( pxQueue ); - /* A task can only have an inherited priority if it is a mutex - holder - and if there is a mutex holder then the mutex cannot be - given from an ISR. As this is the ISR version of the function it - can be assumed there is no mutex holder and no need to determine if - priority disinheritance is needed. Simply increase the count of - messages (semaphores) available. */ - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + /* A task can only have an inherited priority if it is a mutex + holder - and if there is a mutex holder then the mutex cannot be + given from an ISR. As this is the ISR version of the function it + can be assumed there is no mutex holder and no need to determine if + priority disinheritance is needed. Simply increase the count of + messages (semaphores) available. */ + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - /* The event list is not altered if the queue is locked. This will - be done when the queue is unlocked later. */ - if( cTxLock == queueUNLOCKED ) - { - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) - { - /* The semaphore is a member of a queue set, and - posting to the queue set caused a higher priority - task to unblock. A context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so - record that a context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_QUEUE_SETS */ - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was posted while it was locked. */ - pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } + /* The event list is not altered if the queue is locked. This will + be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) + { + /* The semaphore is a member of a queue set, and + posting to the queue set caused a higher priority + task to unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was posted while it was locked. */ + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } - xReturn = pdPASS; - } - else - { - traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); - xReturn = errQUEUE_FULL; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1276,138 +1276,138 @@ BaseType_t xEntryTimeSet = pdFALSE; TimeOut_t xTimeOut; Queue_t * const pxQueue = xQueue; - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); - /* The buffer into which data is received can only be NULL if the data size - is zero (so no data is copied into the buffer. */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + /* The buffer into which data is received can only be NULL if the data size + is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to - allow return statements within the function itself. This is done in the - interest of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data available, remove one item. */ - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_RECEIVE( pxQueue ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data available, remove one item. */ + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_RECEIVE( pxQueue ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - /* There is now space in the queue, were any tasks waiting to - post to the queue? If so, unblock the highest priority waiting - task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* There is now space in the queue, were any tasks waiting to + post to the queue? If so, unblock the highest priority waiting + task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - configure the timeout structure. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* The timeout has not expired. If the queue is still empty place - the task on the list of tasks waiting to receive from the queue. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The queue contains data again. Loop back to try and read the - data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. If there is no data in the queue exit, otherwise loop - back and attempt to read the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* The timeout has not expired. If the queue is still empty place + the task on the list of tasks waiting to receive from the queue. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The queue contains data again. Loop back to try and read the + data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. If there is no data in the queue exit, otherwise loop + back and attempt to read the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -1418,214 +1418,214 @@ TimeOut_t xTimeOut; Queue_t * const pxQueue = xQueue; #if( configUSE_MUTEXES == 1 ) - BaseType_t xInheritanceOccurred = pdFALSE; + BaseType_t xInheritanceOccurred = pdFALSE; #endif - /* Check the queue pointer is not NULL. */ - configASSERT( ( pxQueue ) ); + /* Check the queue pointer is not NULL. */ + configASSERT( ( pxQueue ) ); - /* Check this really is a semaphore, in which case the item size will be - 0. */ - configASSERT( pxQueue->uxItemSize == 0 ); + /* Check this really is a semaphore, in which case the item size will be + 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to allow return - statements within the function itself. This is done in the interest - of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - /* Semaphores are queues with an item size of 0, and where the - number of messages in the queue is the semaphore's count value. */ - const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; + /*lint -save -e904 This function relaxes the coding standard somewhat to allow return + statements within the function itself. This is done in the interest + of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + /* Semaphores are queues with an item size of 0, and where the + number of messages in the queue is the semaphore's count value. */ + const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxSemaphoreCount > ( UBaseType_t ) 0 ) - { - traceQUEUE_RECEIVE( pxQueue ); + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxSemaphoreCount > ( UBaseType_t ) 0 ) + { + traceQUEUE_RECEIVE( pxQueue ); - /* Semaphores are queues with a data size of zero and where the - messages waiting is the semaphore's count. Reduce the count. */ - pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; + /* Semaphores are queues with a data size of zero and where the + messages waiting is the semaphore's count. Reduce the count. */ + pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* Record the information required to implement - priority inheritance should it become necessary. */ - pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* Record the information required to implement + priority inheritance should it become necessary. */ + pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ - /* Check to see if other tasks are blocked waiting to give the - semaphore, and if so, unblock the highest priority such task. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Check to see if other tasks are blocked waiting to give the + semaphore, and if so, unblock the highest priority such task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* For inheritance to have occurred there must have been an - initial timeout, and an adjusted timeout cannot become 0, as - if it were 0 the function would have exited. */ - #if( configUSE_MUTEXES == 1 ) - { - configASSERT( xInheritanceOccurred == pdFALSE ); - } - #endif /* configUSE_MUTEXES */ + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* For inheritance to have occurred there must have been an + initial timeout, and an adjusted timeout cannot become 0, as + if it were 0 the function would have exited. */ + #if( configUSE_MUTEXES == 1 ) + { + configASSERT( xInheritanceOccurred == pdFALSE ); + } + #endif /* configUSE_MUTEXES */ - /* The semaphore count was 0 and no block time is specified - (or the block time has expired) so exit now. */ - taskEXIT_CRITICAL(); - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The semaphore count was 0 and a block time was specified - so configure the timeout structure ready to block. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + /* The semaphore count was 0 and no block time is specified + (or the block time has expired) so exit now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The semaphore count was 0 and a block time was specified + so configure the timeout structure ready to block. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can give to and take from the semaphore - now the critical section has been exited. */ + /* Interrupts and other tasks can give to and take from the semaphore + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* A block time is specified and not expired. If the semaphore - count is 0 then enter the Blocked state to wait for a semaphore to - become available. As semaphores are implemented with queues the - queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* A block time is specified and not expired. If the semaphore + count is 0 then enter the Blocked state to wait for a semaphore to + become available. As semaphores are implemented with queues the + queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - taskENTER_CRITICAL(); - { - xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + taskENTER_CRITICAL(); + { + xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There was no timeout and the semaphore count was not 0, so - attempt to take the semaphore again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* Timed out. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There was no timeout and the semaphore count was not 0, so + attempt to take the semaphore again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - /* If the semaphore count is 0 exit now as the timeout has - expired. Otherwise return to attempt to take the semaphore that is - known to be available. As semaphores are implemented by queues the - queue being empty is equivalent to the semaphore count being 0. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - #if ( configUSE_MUTEXES == 1 ) - { - /* xInheritanceOccurred could only have be set if - pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to - test the mutex type again to check it is actually a mutex. */ - if( xInheritanceOccurred != pdFALSE ) - { - taskENTER_CRITICAL(); - { - UBaseType_t uxHighestWaitingPriority; + /* If the semaphore count is 0 exit now as the timeout has + expired. Otherwise return to attempt to take the semaphore that is + known to be available. As semaphores are implemented by queues the + queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + #if ( configUSE_MUTEXES == 1 ) + { + /* xInheritanceOccurred could only have be set if + pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to + test the mutex type again to check it is actually a mutex. */ + if( xInheritanceOccurred != pdFALSE ) + { + taskENTER_CRITICAL(); + { + UBaseType_t uxHighestWaitingPriority; - /* This task blocking on the mutex caused another - task to inherit this task's priority. Now this task - has timed out the priority should be disinherited - again, but only as low as the next highest priority - task that is waiting for the same mutex. */ - uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); - vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); - } - taskEXIT_CRITICAL(); - } - } - #endif /* configUSE_MUTEXES */ + /* This task blocking on the mutex caused another + task to inherit this task's priority. Now this task + has timed out the priority should be disinherited + again, but only as low as the next highest priority + task that is waiting for the same mutex. */ + uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); + vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); + } + taskEXIT_CRITICAL(); + } + } + #endif /* configUSE_MUTEXES */ - traceQUEUE_RECEIVE_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -1636,145 +1636,145 @@ TimeOut_t xTimeOut; int8_t *pcOriginalReadPosition; Queue_t * const pxQueue = xQueue; - /* Check the pointer is not NULL. */ - configASSERT( ( pxQueue ) ); + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); - /* The buffer into which data is received can only be NULL if the data size - is zero (so no data is copied into the buffer. */ - configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + /* The buffer into which data is received can only be NULL if the data size + is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); - /* Cannot block if the scheduler is suspended. */ - #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - { - configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); - } - #endif + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif - /*lint -save -e904 This function relaxes the coding standard somewhat to - allow return statements within the function itself. This is done in the - interest of execution time efficiency. */ - for( ;; ) - { - taskENTER_CRITICAL(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* Is there data in the queue now? To be running the calling task - must be the highest priority task wanting to access the queue. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Remember the read position so it can be reset after the data - is read from the queue as this function is only peeking the - data, not removing it. */ - pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Remember the read position so it can be reset after the data + is read from the queue as this function is only peeking the + data, not removing it. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; - prvCopyDataFromQueue( pxQueue, pvBuffer ); - traceQUEUE_PEEK( pxQueue ); + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_PEEK( pxQueue ); - /* The data is not being removed, so reset the read pointer. */ - pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + /* The data is not being removed, so reset the read pointer. */ + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; - /* The data is being left in the queue, so see if there are - any other tasks waiting for the data. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than this task. */ - queueYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* The data is being left in the queue, so see if there are + any other tasks waiting for the data. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than this task. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskEXIT_CRITICAL(); - return pdPASS; - } - else - { - if( xTicksToWait == ( TickType_t ) 0 ) - { - /* The queue was empty and no block time is specified (or - the block time has expired) so leave now. */ - taskEXIT_CRITICAL(); - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else if( xEntryTimeSet == pdFALSE ) - { - /* The queue was empty and a block time was specified so - configure the timeout structure ready to enter the blocked - state. */ - vTaskInternalSetTimeOutState( &xTimeOut ); - xEntryTimeSet = pdTRUE; - } - else - { - /* Entry time was already set. */ - mtCOVERAGE_TEST_MARKER(); - } - } - } - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + configure the timeout structure ready to enter the blocked + state. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); - /* Interrupts and other tasks can send to and receive from the queue - now the critical section has been exited. */ + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ - vTaskSuspendAll(); - prvLockQueue( pxQueue ); + vTaskSuspendAll(); + prvLockQueue( pxQueue ); - /* Update the timeout state to see if it has expired yet. */ - if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) - { - /* Timeout has not expired yet, check to see if there is data in the - queue now, and if not enter the Blocked state to wait for data. */ - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); - vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); - prvUnlockQueue( pxQueue ); - if( xTaskResumeAll() == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* There is data in the queue now, so don't enter the blocked - state, instead return to try and obtain the data. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); - } - } - else - { - /* The timeout has expired. If there is still no data in the queue - exit, otherwise go back and try to read the data again. */ - prvUnlockQueue( pxQueue ); - ( void ) xTaskResumeAll(); + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* Timeout has not expired yet, check to see if there is data in the + queue now, and if not enter the Blocked state to wait for data. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There is data in the queue now, so don't enter the blocked + state, instead return to try and obtain the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. If there is still no data in the queue + exit, otherwise go back and try to read the data again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); - if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) - { - traceQUEUE_PEEK_FAILED( pxQueue ); - return errQUEUE_EMPTY; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } /*lint -restore */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ } /*-----------------------------------------------------------*/ @@ -1784,88 +1784,88 @@ BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; - /* Cannot block in an ISR, so check there is data available. */ - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - const int8_t cRxLock = pxQueue->cRxLock; + /* Cannot block in an ISR, so check there is data available. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + const int8_t cRxLock = pxQueue->cRxLock; - traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); + traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; - /* If the queue is locked the event list will not be modified. - Instead update the lock count so the task that unlocks the queue - will know that an ISR has removed data while the queue was - locked. */ - if( cRxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - /* The task waiting has a higher priority than us so - force a context switch. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Increment the lock count so the task that unlocks the queue - knows that data was removed while it was locked. */ - pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); - } + /* If the queue is locked the event list will not be modified. + Instead update the lock count so the task that unlocks the queue + will know that an ISR has removed data while the queue was + locked. */ + if( cRxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than us so + force a context switch. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was removed while it was locked. */ + pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); + } - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1876,50 +1876,50 @@ UBaseType_t uxSavedInterruptStatus; int8_t *pcOriginalReadPosition; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); - configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* Cannot block in an ISR, so check there is data available. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - traceQUEUE_PEEK_FROM_ISR( pxQueue ); + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* Cannot block in an ISR, so check there is data available. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + traceQUEUE_PEEK_FROM_ISR( pxQueue ); - /* Remember the read position so it can be reset as nothing is - actually being removed from the queue. */ - pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; - prvCopyDataFromQueue( pxQueue, pvBuffer ); - pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + /* Remember the read position so it can be reset as nothing is + actually being removed from the queue. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1927,15 +1927,15 @@ UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) { UBaseType_t uxReturn; - configASSERT( xQueue ); + configASSERT( xQueue ); - taskENTER_CRITICAL(); - { - uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); - return uxReturn; + return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ @@ -1944,15 +1944,15 @@ UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) UBaseType_t uxReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); + configASSERT( pxQueue ); - taskENTER_CRITICAL(); - { - uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); - return uxReturn; + return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ @@ -1961,10 +1961,10 @@ UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) UBaseType_t uxReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - uxReturn = pxQueue->uxMessagesWaiting; + configASSERT( pxQueue ); + uxReturn = pxQueue->uxMessagesWaiting; - return uxReturn; + return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ @@ -1972,97 +1972,97 @@ void vQueueDelete( QueueHandle_t xQueue ) { Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - traceQUEUE_DELETE( pxQueue ); + configASSERT( pxQueue ); + traceQUEUE_DELETE( pxQueue ); - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - vQueueUnregisterQueue( pxQueue ); - } - #endif + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + vQueueUnregisterQueue( pxQueue ); + } + #endif - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) - { - /* The queue can only have been allocated dynamically - free it - again. */ - vPortFree( pxQueue ); - } - #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - { - /* The queue could have been allocated statically or dynamically, so - check before attempting to free the memory. */ - if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) - { - vPortFree( pxQueue ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #else - { - /* The queue must have been statically allocated, so is not going to be - deleted. Avoid compiler warnings about the unused parameter. */ - ( void ) pxQueue; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The queue can only have been allocated dynamically - free it + again. */ + vPortFree( pxQueue ); + } + #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The queue could have been allocated statically or dynamically, so + check before attempting to free the memory. */ + if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxQueue ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else + { + /* The queue must have been statically allocated, so is not going to be + deleted. Avoid compiler warnings about the unused parameter. */ + ( void ) pxQueue; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->uxQueueNumber; - } + UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->uxQueueNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) - { - ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; - } + void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) + { + ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) - { - return ( ( Queue_t * ) xQueue )->ucQueueType; - } + uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->ucQueueType; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if( configUSE_MUTEXES == 1 ) - static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) - { - UBaseType_t uxHighestPriorityOfWaitingTasks; + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) + { + UBaseType_t uxHighestPriorityOfWaitingTasks; - /* If a task waiting for a mutex causes the mutex holder to inherit a - priority, but the waiting task times out, then the holder should - disinherit the priority - but only down to the highest priority of any - other tasks that are waiting for the same mutex. For this purpose, - return the priority of the highest priority task that is waiting for the - mutex. */ - if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) - { - uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); - } - else - { - uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; - } + /* If a task waiting for a mutex causes the mutex holder to inherit a + priority, but the waiting task times out, then the holder should + disinherit the priority - but only down to the highest priority of any + other tasks that are waiting for the same mutex. For this purpose, + return the priority of the highest priority task that is waiting for the + mutex. */ + if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) + { + uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); + } + else + { + uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; + } - return uxHighestPriorityOfWaitingTasks; - } + return uxHighestPriorityOfWaitingTasks; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ @@ -2072,215 +2072,215 @@ static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvIte BaseType_t xReturn = pdFALSE; UBaseType_t uxMessagesWaiting; - /* This function is called from a critical section. */ + /* This function is called from a critical section. */ - uxMessagesWaiting = pxQueue->uxMessagesWaiting; + uxMessagesWaiting = pxQueue->uxMessagesWaiting; - if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) - { - #if ( configUSE_MUTEXES == 1 ) - { - if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) - { - /* The mutex is no longer being held. */ - xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); - pxQueue->u.xSemaphore.xMutexHolder = NULL; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_MUTEXES */ - } - else if( xPosition == queueSEND_TO_BACK ) - { - ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ - pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ - if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->pcWriteTo = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ - pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; - if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ - { - pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) + { + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* The mutex is no longer being held. */ + xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); + pxQueue->u.xSemaphore.xMutexHolder = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + } + else if( xPosition == queueSEND_TO_BACK ) + { + ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->pcWriteTo = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ + pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xPosition == queueOVERWRITE ) - { - if( uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* An item is not being added but overwritten, so subtract - one from the recorded number of items in the queue so when - one is added again below the number of recorded items remains - correct. */ - --uxMessagesWaiting; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( xPosition == queueOVERWRITE ) + { + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* An item is not being added but overwritten, so subtract + one from the recorded number of items in the queue so when + one is added again below the number of recorded items remains + correct. */ + --uxMessagesWaiting; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) { - if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) - { - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ - } + if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) + { + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + } } /*-----------------------------------------------------------*/ static void prvUnlockQueue( Queue_t * const pxQueue ) { - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ - /* The lock counts contains the number of extra data items placed or - removed from the queue while the queue was locked. When a queue is - locked items can be added or removed, but the event lists cannot be - updated. */ - taskENTER_CRITICAL(); - { - int8_t cTxLock = pxQueue->cTxLock; + /* The lock counts contains the number of extra data items placed or + removed from the queue while the queue was locked. When a queue is + locked items can be added or removed, but the event lists cannot be + updated. */ + taskENTER_CRITICAL(); + { + int8_t cTxLock = pxQueue->cTxLock; - /* See if data was added to the queue while it was locked. */ - while( cTxLock > queueLOCKED_UNMODIFIED ) - { - /* Data was posted while the queue was locked. Are any tasks - blocked waiting for data to become available? */ - #if ( configUSE_QUEUE_SETS == 1 ) - { - if( pxQueue->pxQueueSetContainer != NULL ) - { - if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) - { - /* The queue is a member of a queue set, and posting to - the queue set caused a higher priority task to unblock. - A context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* Tasks that are removed from the event list will get - added to the pending ready list as the scheduler is still - suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that a - context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - } - #else /* configUSE_QUEUE_SETS */ - { - /* Tasks that are removed from the event list will get added to - the pending ready list as the scheduler is still suspended. */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority so record that - a context switch is required. */ - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - break; - } - } - #endif /* configUSE_QUEUE_SETS */ + /* See if data was added to the queue while it was locked. */ + while( cTxLock > queueLOCKED_UNMODIFIED ) + { + /* Data was posted while the queue was locked. Are any tasks + blocked waiting for data to become available? */ + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting to + the queue set caused a higher priority task to unblock. + A context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Tasks that are removed from the event list will get + added to the pending ready list as the scheduler is still + suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + /* Tasks that are removed from the event list will get added to + the pending ready list as the scheduler is still suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that + a context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + #endif /* configUSE_QUEUE_SETS */ - --cTxLock; - } + --cTxLock; + } - pxQueue->cTxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); + pxQueue->cTxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); - /* Do the same for the Rx lock. */ - taskENTER_CRITICAL(); - { - int8_t cRxLock = pxQueue->cRxLock; + /* Do the same for the Rx lock. */ + taskENTER_CRITICAL(); + { + int8_t cRxLock = pxQueue->cRxLock; - while( cRxLock > queueLOCKED_UNMODIFIED ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - vTaskMissedYield(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + while( cRxLock > queueLOCKED_UNMODIFIED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - --cRxLock; - } - else - { - break; - } - } + --cRxLock; + } + else + { + break; + } + } - pxQueue->cRxLock = queueUNLOCKED; - } - taskEXIT_CRITICAL(); + pxQueue->cRxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ @@ -2288,20 +2288,20 @@ static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) { BaseType_t xReturn; - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -2310,17 +2310,17 @@ BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) BaseType_t xReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + configASSERT( pxQueue ); + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ /*-----------------------------------------------------------*/ @@ -2328,20 +2328,20 @@ static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) { BaseType_t xReturn; - taskENTER_CRITICAL(); - { - if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -2350,581 +2350,581 @@ BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) BaseType_t xReturn; Queue_t * const pxQueue = xQueue; - configASSERT( pxQueue ); - if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + configASSERT( pxQueue ); + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; - /* If the queue is already full we may have to block. A critical section - is required to prevent an interrupt removing something from the queue - between the check to see if the queue is full and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( prvIsQueueFull( pxQueue ) != pdFALSE ) - { - /* The queue is full - do we want to block or just leave without - posting? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is called from a coroutine we cannot block directly, but - return indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - } - portENABLE_INTERRUPTS(); + /* If the queue is already full we may have to block. A critical section + is required to prevent an interrupt removing something from the queue + between the check to see if the queue is full and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + /* The queue is full - do we want to block or just leave without + posting? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is called from a coroutine we cannot block directly, but + return indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + } + portENABLE_INTERRUPTS(); - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - /* There is room in the queue, copy the data into the queue. */ - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - xReturn = pdPASS; + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + /* There is room in the queue, copy the data into the queue. */ + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + xReturn = pdPASS; - /* Were any co-routines waiting for data to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - into the ready list as we are within a critical section. - Instead the same pending ready list mechanism is used as if - the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The co-routine waiting has a higher priority so record - that a yield might be appropriate. */ - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = errQUEUE_FULL; - } - } - portENABLE_INTERRUPTS(); + /* Were any co-routines waiting for data to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + into the ready list as we are within a critical section. + Instead the same pending ready list mechanism is used as if + the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The co-routine waiting has a higher priority so record + that a yield might be appropriate. */ + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = errQUEUE_FULL; + } + } + portENABLE_INTERRUPTS(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; - /* If the queue is already empty we may have to block. A critical section - is required to prevent an interrupt adding something to the queue - between the check to see if the queue is empty and blocking on the queue. */ - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) - { - /* There are no messages in the queue, do we want to block or just - leave with nothing? */ - if( xTicksToWait > ( TickType_t ) 0 ) - { - /* As this is a co-routine we cannot block directly, but return - indicating that we need to block. */ - vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); - portENABLE_INTERRUPTS(); - return errQUEUE_BLOCKED; - } - else - { - portENABLE_INTERRUPTS(); - return errQUEUE_FULL; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portENABLE_INTERRUPTS(); + /* If the queue is already empty we may have to block. A critical section + is required to prevent an interrupt adding something to the queue + between the check to see if the queue is empty and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + /* There are no messages in the queue, do we want to block or just + leave with nothing? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is a co-routine we cannot block directly, but return + indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portENABLE_INTERRUPTS(); - portDISABLE_INTERRUPTS(); - { - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Data is available from the queue. */ - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --( pxQueue->uxMessagesWaiting ); - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data is available from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - xReturn = pdPASS; + xReturn = pdPASS; - /* Were any co-routines waiting for space to become available? */ - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - /* In this instance the co-routine could be placed directly - into the ready list as we are within a critical section. - Instead the same pending ready list mechanism is used as if - the event were caused from within an interrupt. */ - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - xReturn = errQUEUE_YIELD; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xReturn = pdFAIL; - } - } - portENABLE_INTERRUPTS(); + /* Were any co-routines waiting for space to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + into the ready list as we are within a critical section. + Instead the same pending ready list mechanism is used as if + the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = pdFAIL; + } + } + portENABLE_INTERRUPTS(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ) - { - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ) + { + Queue_t * const pxQueue = xQueue; - /* Cannot block within an ISR so if there is no space on the queue then - exit without doing anything. */ - if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) - { - prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + /* Cannot block within an ISR so if there is no space on the queue then + exit without doing anything. */ + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); - /* We only want to wake one co-routine per ISR, so check that a - co-routine has not already been woken. */ - if( xCoRoutinePreviouslyWoken == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) - { - return pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* We only want to wake one co-routine per ISR, so check that a + co-routine has not already been woken. */ + if( xCoRoutinePreviouslyWoken == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + return pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xCoRoutinePreviouslyWoken; - } + return xCoRoutinePreviouslyWoken; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) - BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken ) - { - BaseType_t xReturn; - Queue_t * const pxQueue = xQueue; + BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; - /* We cannot block from an ISR, so check there is data available. If - not then just leave without doing anything. */ - if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) - { - /* Copy the data from the queue. */ - pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; - if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) - { - pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --( pxQueue->uxMessagesWaiting ); - ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + /* We cannot block from an ISR, so check there is data available. If + not then just leave without doing anything. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Copy the data from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); - if( ( *pxCoRoutineWoken ) == pdFALSE ) - { - if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) - { - if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) - { - *pxCoRoutineWoken = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( ( *pxCoRoutineWoken ) == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + *pxCoRoutineWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; + void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; - /* See if there is an empty space in the registry. A NULL name denotes - a free slot. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].pcQueueName == NULL ) - { - /* Store the information on this queue. */ - xQueueRegistry[ ux ].pcQueueName = pcQueueName; - xQueueRegistry[ ux ].xHandle = xQueue; + /* See if there is an empty space in the registry. A NULL name denotes + a free slot. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].pcQueueName == NULL ) + { + /* Store the information on this queue. */ + xQueueRegistry[ ux ].pcQueueName = pcQueueName; + xQueueRegistry[ ux ].xHandle = xQueue; - traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } + traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - const char *pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t ux; - const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const char *pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; + const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - /* Note there is nothing here to protect against another task adding or - removing entries from the registry while it is being searched. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - pcReturn = xQueueRegistry[ ux ].pcQueueName; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Note there is nothing here to protect against another task adding or + removing entries from the registry while it is being searched. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + pcReturn = xQueueRegistry[ ux ].pcQueueName; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - return pcReturn; - } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ + return pcReturn; + } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) - void vQueueUnregisterQueue( QueueHandle_t xQueue ) - { - UBaseType_t ux; + void vQueueUnregisterQueue( QueueHandle_t xQueue ) + { + UBaseType_t ux; - /* See if the handle of the queue being unregistered in actually in the - registry. */ - for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) - { - if( xQueueRegistry[ ux ].xHandle == xQueue ) - { - /* Set the name to NULL to show that this slot if free again. */ - xQueueRegistry[ ux ].pcQueueName = NULL; + /* See if the handle of the queue being unregistered in actually in the + registry. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + /* Set the name to NULL to show that this slot if free again. */ + xQueueRegistry[ ux ].pcQueueName = NULL; - /* Set the handle to NULL to ensure the same queue handle cannot - appear in the registry twice if it is added, removed, then - added again. */ - xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Set the handle to NULL to ensure the same queue handle cannot + appear in the registry twice if it is added, removed, then + added again. */ + xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ + } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configUSE_TIMERS == 1 ) - void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) - { - Queue_t * const pxQueue = xQueue; + void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) + { + Queue_t * const pxQueue = xQueue; - /* This function should not be called by application code hence the - 'Restricted' in its name. It is not part of the public API. It is - designed for use by kernel code, and has special calling requirements. - It can result in vListInsert() being called on a list that can only - possibly ever have one item in it, so the list will be fast, but even - so it should be called with the scheduler locked and not from a critical - section. */ + /* This function should not be called by application code hence the + 'Restricted' in its name. It is not part of the public API. It is + designed for use by kernel code, and has special calling requirements. + It can result in vListInsert() being called on a list that can only + possibly ever have one item in it, so the list will be fast, but even + so it should be called with the scheduler locked and not from a critical + section. */ - /* Only do anything if there are no messages in the queue. This function - will not actually cause the task to block, just place it on a blocked - list. It will not block until the scheduler is unlocked - at which - time a yield will be performed. If an item is added to the queue while - the queue is locked, and the calling task blocks on the queue, then the - calling task will be immediately unblocked when the queue is unlocked. */ - prvLockQueue( pxQueue ); - if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) - { - /* There is nothing in the queue, block for the specified period. */ - vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - prvUnlockQueue( pxQueue ); - } + /* Only do anything if there are no messages in the queue. This function + will not actually cause the task to block, just place it on a blocked + list. It will not block until the scheduler is unlocked - at which + time a yield will be performed. If an item is added to the queue while + the queue is locked, and the calling task blocks on the queue, then the + calling task will be immediately unblocked when the queue is unlocked. */ + prvLockQueue( pxQueue ); + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) + { + /* There is nothing in the queue, block for the specified period. */ + vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + prvUnlockQueue( pxQueue ); + } #endif /* configUSE_TIMERS */ /*-----------------------------------------------------------*/ #if( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) - { - QueueSetHandle_t pxQueue; + QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) + { + QueueSetHandle_t pxQueue; - pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); + pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); - return pxQueue; - } + return pxQueue; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; + BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; - taskENTER_CRITICAL(); - { - if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) - { - /* Cannot add a queue/semaphore to more than one queue set. */ - xReturn = pdFAIL; - } - else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* Cannot add a queue/semaphore to a queue set if there are already - items in the queue/semaphore. */ - xReturn = pdFAIL; - } - else - { - ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; - xReturn = pdPASS; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) + { + /* Cannot add a queue/semaphore to more than one queue set. */ + xReturn = pdFAIL; + } + else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* Cannot add a queue/semaphore to a queue set if there are already + items in the queue/semaphore. */ + xReturn = pdFAIL; + } + else + { + ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; + xReturn = pdPASS; + } + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) - { - BaseType_t xReturn; - Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; + BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; - if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) - { - /* The queue was not a member of the set. */ - xReturn = pdFAIL; - } - else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) - { - /* It is dangerous to remove a queue from a set when the queue is - not empty because the queue set will still hold pending events for - the queue. */ - xReturn = pdFAIL; - } - else - { - taskENTER_CRITICAL(); - { - /* The queue is no longer contained in the set. */ - pxQueueOrSemaphore->pxQueueSetContainer = NULL; - } - taskEXIT_CRITICAL(); - xReturn = pdPASS; - } + if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) + { + /* The queue was not a member of the set. */ + xReturn = pdFAIL; + } + else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* It is dangerous to remove a queue from a set when the queue is + not empty because the queue set will still hold pending events for + the queue. */ + xReturn = pdFAIL; + } + else + { + taskENTER_CRITICAL(); + { + /* The queue is no longer contained in the set. */ + pxQueueOrSemaphore->pxQueueSetContainer = NULL; + } + taskEXIT_CRITICAL(); + xReturn = pdPASS; + } - return xReturn; - } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ + return xReturn; + } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait ) - { - QueueSetMemberHandle_t xReturn = NULL; + QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait ) + { + QueueSetMemberHandle_t xReturn = NULL; - ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } + ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) - { - QueueSetMemberHandle_t xReturn = NULL; + QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) + { + QueueSetMemberHandle_t xReturn = NULL; - ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ - return xReturn; - } + ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) - static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) - { - Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer; - BaseType_t xReturn = pdFALSE; + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) + { + Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer; + BaseType_t xReturn = pdFALSE; - /* This function must be called form a critical section. */ + /* This function must be called form a critical section. */ - configASSERT( pxQueueSetContainer ); - configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); + configASSERT( pxQueueSetContainer ); + configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); - if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) - { - const int8_t cTxLock = pxQueueSetContainer->cTxLock; + if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) + { + const int8_t cTxLock = pxQueueSetContainer->cTxLock; - traceQUEUE_SEND( pxQueueSetContainer ); + traceQUEUE_SEND( pxQueueSetContainer ); - /* The data copied is the handle of the queue that contains data. */ - xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition ); + /* The data copied is the handle of the queue that contains data. */ + xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition ); - if( cTxLock == queueUNLOCKED ) - { - if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) - { - if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) - { - /* The task waiting has a higher priority. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( cTxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_QUEUE_SETS */ diff --git a/components/bl602/freertos_riscv_ram/stream_buffer.c b/components/bl602/freertos_riscv_ram/stream_buffer.c index 85519707..5a370c5a 100644 --- a/components/bl602/freertos_riscv_ram/stream_buffer.c +++ b/components/bl602/freertos_riscv_ram/stream_buffer.c @@ -40,7 +40,7 @@ task.h is included from an application file. */ #include "stream_buffer.h" #if( configUSE_TASK_NOTIFICATIONS != 1 ) - #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c + #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c #endif /* Lint e961, e9021 and e750 are suppressed as a MISRA exception justified @@ -54,77 +54,77 @@ or #defined the notification macros away, them provide default implementations that uses task notifications. */ /*lint -save -e9026 Function like macros allowed and needed here so they can be overidden. */ #ifndef sbRECEIVE_COMPLETED - #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); + #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); #endif /* sbRECEIVE_COMPLETED */ #ifndef sbRECEIVE_COMPLETED_FROM_ISR - #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ - pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } + #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ + pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } #endif /* sbRECEIVE_COMPLETED_FROM_ISR */ /* If the user has not provided an application specific Tx notification macro, or #defined the notification macro away, them provide a default implementation that uses task notifications. */ #ifndef sbSEND_COMPLETED - #define sbSEND_COMPLETED( pxStreamBuffer ) \ - vTaskSuspendAll(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - ( void ) xTaskResumeAll(); + #define sbSEND_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); #endif /* sbSEND_COMPLETED */ #ifndef sbSEND_COMPLETE_FROM_ISR - #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ - { \ - UBaseType_t uxSavedInterruptStatus; \ - \ - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ - { \ - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ - { \ - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ - ( uint32_t ) 0, \ - eNoAction, \ - pxHigherPriorityTaskWoken ); \ - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ - } \ - } \ - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ - } + #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } #endif /* sbSEND_COMPLETE_FROM_ISR */ /*lint -restore (9026) */ @@ -132,7 +132,7 @@ that uses task notifications. */ #define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) /* Bits stored in the ucFlags field of the stream buffer. */ -#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ +#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ #define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ /*-----------------------------------------------------------*/ @@ -140,18 +140,18 @@ that uses task notifications. */ /* Structure that hold state information on the buffer. */ typedef struct StreamBufferDef_t /*lint !e9058 Style convention uses tag. */ { - volatile size_t xTail; /* Index to the next item to read within the buffer. */ - volatile size_t xHead; /* Index to the next item to write within the buffer. */ - size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ - size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ - volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ - volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ - uint8_t *pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ - uint8_t ucFlags; + volatile size_t xTail; /* Index to the next item to read within the buffer. */ + volatile size_t xHead; /* Index to the next item to write within the buffer. */ + size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ + size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ + volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ + volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ + uint8_t *pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ + uint8_t ucFlags; - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ + #endif } StreamBuffer_t; /* @@ -175,10 +175,10 @@ static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, cons * buffer's data storage area. */ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) PRIVILEGED_FUNCTION; + void *pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable, + size_t xBytesToStoreMessageLength ) PRIVILEGED_FUNCTION; /* * If the stream buffer is being used as a message buffer, then writes an entire @@ -188,170 +188,170 @@ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, * data storage area. */ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) PRIVILEGED_FUNCTION; + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) PRIVILEGED_FUNCTION; /* * Read xMaxCount bytes from the pxStreamBuffer message buffer and write them * to pucData. */ static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, - uint8_t *pucData, - size_t xMaxCount, - size_t xBytesAvailable ) PRIVILEGED_FUNCTION; + uint8_t *pucData, + size_t xMaxCount, + size_t xBytesAvailable ) PRIVILEGED_FUNCTION; /* * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to * initialise the members of the newly created stream buffer structure. */ static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - uint8_t ucFlags ) PRIVILEGED_FUNCTION; + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) PRIVILEGED_FUNCTION; /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) - { - uint8_t *pucAllocatedMemory; - uint8_t ucFlags; + StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) + { + uint8_t *pucAllocatedMemory; + uint8_t ucFlags; - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - if( xIsMessageBuffer == pdTRUE ) - { - /* Is a message buffer but not statically allocated. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* Not a message buffer and not statically allocated. */ - ucFlags = 0; - configASSERT( xBufferSizeBytes > 0 ); - } - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + /* In case the stream buffer is going to be used as a message buffer + (that is, it will hold discrete messages with a little meta data that + says how big the next message is) check the buffer will be large enough + to hold at least one message. */ + if( xIsMessageBuffer == pdTRUE ) + { + /* Is a message buffer but not statically allocated. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else + { + /* Not a message buffer and not statically allocated. */ + ucFlags = 0; + configASSERT( xBufferSizeBytes > 0 ); + } + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } + /* A trigger level of 0 would cause a waiting task to unblock even when + the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } - /* A stream buffer requires a StreamBuffer_t structure and a buffer. - Both are allocated in a single call to pvPortMalloc(). The - StreamBuffer_t structure is placed at the start of the allocated memory - and the buffer follows immediately after. The requested size is - incremented so the free space is returned as the user would expect - - this is a quirk of the implementation that means otherwise the free - space would be reported as one byte smaller than would be logically - expected. */ - xBufferSizeBytes++; - pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ + /* A stream buffer requires a StreamBuffer_t structure and a buffer. + Both are allocated in a single call to pvPortMalloc(). The + StreamBuffer_t structure is placed at the start of the allocated memory + and the buffer follows immediately after. The requested size is + incremented so the free space is returned as the user would expect - + this is a quirk of the implementation that means otherwise the free + space would be reported as one byte smaller than would be logically + expected. */ + xBufferSizeBytes++; + pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ - if( pucAllocatedMemory != NULL ) - { - prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ - pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); + if( pucAllocatedMemory != NULL ) + { + prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ + pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); - traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); - } - else - { - traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); - } + traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); + } + else + { + traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); + } - return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ - } + return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) - { - StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ - StreamBufferHandle_t xReturn; - uint8_t ucFlags; + StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) + { + StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ + StreamBufferHandle_t xReturn; + uint8_t ucFlags; - configASSERT( pucStreamBufferStorageArea ); - configASSERT( pxStaticStreamBuffer ); - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + configASSERT( pucStreamBufferStorageArea ); + configASSERT( pxStaticStreamBuffer ); + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } + /* A trigger level of 0 would cause a waiting task to unblock even when + the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } - if( xIsMessageBuffer != pdFALSE ) - { - /* Statically allocated message buffer. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; - } - else - { - /* Statically allocated stream buffer. */ - ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; - } + if( xIsMessageBuffer != pdFALSE ) + { + /* Statically allocated message buffer. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; + } + else + { + /* Statically allocated stream buffer. */ + ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; + } - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + /* In case the stream buffer is going to be used as a message buffer + (that is, it will hold discrete messages with a little meta data that + says how big the next message is) check the buffer will be large enough + to hold at least one message. */ + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticStreamBuffer_t equals the size of the real - message buffer structure. */ - volatile size_t xSize = sizeof( StaticStreamBuffer_t ); - configASSERT( xSize == sizeof( StreamBuffer_t ) ); - } /*lint !e529 xSize is referenced is configASSERT() is defined. */ - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticStreamBuffer_t equals the size of the real + message buffer structure. */ + volatile size_t xSize = sizeof( StaticStreamBuffer_t ); + configASSERT( xSize == sizeof( StreamBuffer_t ) ); + } /*lint !e529 xSize is referenced is configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ - if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pucStreamBufferStorageArea, - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); + if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pucStreamBufferStorageArea, + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); - /* Remember this was statically allocated in case it is ever deleted - again. */ - pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; + /* Remember this was statically allocated in case it is ever deleted + again. */ + pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; - traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); + traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); - xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ - } - else - { - xReturn = NULL; - traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); - } + xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ + } + else + { + xReturn = NULL; + traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); + } - return xReturn; - } + return xReturn; + } #endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ /*-----------------------------------------------------------*/ @@ -360,32 +360,32 @@ void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) { StreamBuffer_t * pxStreamBuffer = xStreamBuffer; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - traceSTREAM_BUFFER_DELETE( xStreamBuffer ); + traceSTREAM_BUFFER_DELETE( xStreamBuffer ); - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) - { - #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* Both the structure and the buffer were allocated using a single call - to pvPortMalloc(), hence only one call to vPortFree() is required. */ - vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ - } - #else - { - /* Should not be possible to get here, ucFlags must be corrupt. - Force an assert. */ - configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); - } - #endif - } - else - { - /* The structure and buffer were not allocated dynamically and cannot be - freed - just scrub the structure so future use will assert. */ - ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); - } + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) + { + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both the structure and the buffer were allocated using a single call + to pvPortMalloc(), hence only one call to vPortFree() is required. */ + vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ + } + #else + { + /* Should not be possible to get here, ucFlags must be corrupt. + Force an assert. */ + configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); + } + #endif + } + else + { + /* The structure and buffer were not allocated dynamically and cannot be + freed - just scrub the structure so future use will assert. */ + ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); + } } /*-----------------------------------------------------------*/ @@ -395,46 +395,46 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn = pdFAIL; #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferNumber; + UBaseType_t uxStreamBufferNumber; #endif - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - #if( configUSE_TRACE_FACILITY == 1 ) - { - /* Store the stream buffer number so it can be restored after the - reset. */ - uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; - } - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + { + /* Store the stream buffer number so it can be restored after the + reset. */ + uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; + } + #endif - /* Can only reset a message buffer if there are no tasks blocked on it. */ - taskENTER_CRITICAL(); - { - if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) - { - if( pxStreamBuffer->xTaskWaitingToSend == NULL ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pxStreamBuffer->pucBuffer, - pxStreamBuffer->xLength, - pxStreamBuffer->xTriggerLevelBytes, - pxStreamBuffer->ucFlags ); - xReturn = pdPASS; + /* Can only reset a message buffer if there are no tasks blocked on it. */ + taskENTER_CRITICAL(); + { + if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) + { + if( pxStreamBuffer->xTaskWaitingToSend == NULL ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pxStreamBuffer->pucBuffer, + pxStreamBuffer->xLength, + pxStreamBuffer->xTriggerLevelBytes, + pxStreamBuffer->ucFlags ); + xReturn = pdPASS; - #if( configUSE_TRACE_FACILITY == 1 ) - { - pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; - } - #endif + #if( configUSE_TRACE_FACILITY == 1 ) + { + pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + #endif - traceSTREAM_BUFFER_RESET( xStreamBuffer ); - } - } - } - taskEXIT_CRITICAL(); + traceSTREAM_BUFFER_RESET( xStreamBuffer ); + } + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -443,27 +443,27 @@ BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, siz StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* It is not valid for the trigger level to be 0. */ - if( xTriggerLevel == ( size_t ) 0 ) - { - xTriggerLevel = ( size_t ) 1; - } + /* It is not valid for the trigger level to be 0. */ + if( xTriggerLevel == ( size_t ) 0 ) + { + xTriggerLevel = ( size_t ) 1; + } - /* The trigger level is the number of bytes that must be in the stream - buffer before a task that is waiting for data is unblocked. */ - if( xTriggerLevel <= pxStreamBuffer->xLength ) - { - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; - xReturn = pdPASS; - } - else - { - xReturn = pdFALSE; - } + /* The trigger level is the number of bytes that must be in the stream + buffer before a task that is waiting for data is unblocked. */ + if( xTriggerLevel <= pxStreamBuffer->xLength ) + { + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; + xReturn = pdPASS; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -472,22 +472,22 @@ size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xSpace; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; - xSpace -= pxStreamBuffer->xHead; - xSpace -= ( size_t ) 1; + xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; + xSpace -= pxStreamBuffer->xHead; + xSpace -= ( size_t ) 1; - if( xSpace >= pxStreamBuffer->xLength ) - { - xSpace -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSpace >= pxStreamBuffer->xLength ) + { + xSpace -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xSpace; + return xSpace; } /*-----------------------------------------------------------*/ @@ -496,321 +496,321 @@ size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - xReturn = prvBytesInBuffer( pxStreamBuffer ); - return xReturn; + xReturn = prvBytesInBuffer( pxStreamBuffer ); + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - TickType_t xTicksToWait ) + const void *pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn, xSpace = 0; size_t xRequiredSpace = xDataLengthBytes; TimeOut_t xTimeOut; - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); - /* This send function is used to write to both message buffers and stream - buffers. If this is a message buffer then the space needed must be - increased by the amount of bytes needed to store the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + /* This send function is used to write to both message buffers and stream + buffers. If this is a message buffer then the space needed must be + increased by the amount of bytes needed to store the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - /* Overflow? */ - configASSERT( xRequiredSpace > xDataLengthBytes ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Overflow? */ + configASSERT( xRequiredSpace > xDataLengthBytes ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xTicksToWait != ( TickType_t ) 0 ) - { - vTaskSetTimeOutState( &xTimeOut ); + if( xTicksToWait != ( TickType_t ) 0 ) + { + vTaskSetTimeOutState( &xTimeOut ); - do - { - /* Wait until the required number of bytes are free in the message - buffer. */ - taskENTER_CRITICAL(); - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + do + { + /* Wait until the required number of bytes are free in the message + buffer. */ + taskENTER_CRITICAL(); + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - if( xSpace < xRequiredSpace ) - { - /* Clear notification state as going to wait for space. */ - ( void ) xTaskNotifyStateClear( NULL ); + if( xSpace < xRequiredSpace ) + { + /* Clear notification state as going to wait for space. */ + ( void ) xTaskNotifyStateClear( NULL ); - /* Should only be one writer. */ - configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); - pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); - } - else - { - taskEXIT_CRITICAL(); - break; - } - } - taskEXIT_CRITICAL(); + /* Should only be one writer. */ + configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); + pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); + } + else + { + taskEXIT_CRITICAL(); + break; + } + } + taskEXIT_CRITICAL(); - traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToSend = NULL; + traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToSend = NULL; - } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xSpace == ( size_t ) 0 ) - { - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSpace == ( size_t ) 0 ) + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - if( xReturn > ( size_t ) 0 ) - { - traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); + if( xReturn > ( size_t ) 0 ) + { + traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); - } + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, - const void *pvTxData, - size_t xDataLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) + const void *pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn, xSpace; size_t xRequiredSpace = xDataLengthBytes; - configASSERT( pvTxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); - /* This send function is used to write to both message buffers and stream - buffers. If this is a message buffer then the space needed must be - increased by the amount of bytes needed to store the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* This send function is used to write to both message buffers and stream + buffers. If this is a message buffer then the space needed must be + increased by the amount of bytes needed to store the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); - xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); - if( xReturn > ( size_t ) 0 ) - { - /* Was a task waiting for the data? */ - if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) - { - sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xReturn > ( size_t ) 0 ) + { + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); + traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, - const void * pvTxData, - size_t xDataLengthBytes, - size_t xSpace, - size_t xRequiredSpace ) + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) { - BaseType_t xShouldWrite; - size_t xReturn; + BaseType_t xShouldWrite; + size_t xReturn; - if( xSpace == ( size_t ) 0 ) - { - /* Doesn't matter if this is a stream buffer or a message buffer, there - is no space to write. */ - xShouldWrite = pdFALSE; - } - else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) - { - /* This is a stream buffer, as opposed to a message buffer, so writing a - stream of bytes rather than discrete messages. Write as many bytes as - possible. */ - xShouldWrite = pdTRUE; - xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); - } - else if( xSpace >= xRequiredSpace ) - { - /* This is a message buffer, as opposed to a stream buffer, and there - is enough space to write both the message length and the message itself - into the buffer. Start by writing the length of the data, the data - itself will be written later in this function. */ - xShouldWrite = pdTRUE; - ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* There is space available, but not enough space. */ - xShouldWrite = pdFALSE; - } + if( xSpace == ( size_t ) 0 ) + { + /* Doesn't matter if this is a stream buffer or a message buffer, there + is no space to write. */ + xShouldWrite = pdFALSE; + } + else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) + { + /* This is a stream buffer, as opposed to a message buffer, so writing a + stream of bytes rather than discrete messages. Write as many bytes as + possible. */ + xShouldWrite = pdTRUE; + xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); + } + else if( xSpace >= xRequiredSpace ) + { + /* This is a message buffer, as opposed to a stream buffer, and there + is enough space to write both the message length and the message itself + into the buffer. Start by writing the length of the data, the data + itself will be written later in this function. */ + xShouldWrite = pdTRUE; + ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else + { + /* There is space available, but not enough space. */ + xShouldWrite = pdFALSE; + } - if( xShouldWrite != pdFALSE ) - { - /* Writes the data itself. */ - xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */ - } - else - { - xReturn = 0; - } + if( xShouldWrite != pdFALSE ) + { + /* Writes the data itself. */ + xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */ + } + else + { + xReturn = 0; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - TickType_t xTicksToWait ) + void *pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); - /* This receive function is used by both message buffers, which store - discrete messages, and stream buffers, which store a continuous stream of - bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } + /* This receive function is used by both message buffers, which store + discrete messages, and stream buffers, which store a continuous stream of + bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } - if( xTicksToWait != ( TickType_t ) 0 ) - { - /* Checking if there is data and clearing the notification state must be - performed atomically. */ - taskENTER_CRITICAL(); - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + if( xTicksToWait != ( TickType_t ) 0 ) + { + /* Checking if there is data and clearing the notification state must be + performed atomically. */ + taskENTER_CRITICAL(); + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - /* If this function was invoked by a message buffer read then - xBytesToStoreMessageLength holds the number of bytes used to hold - the length of the next discrete message. If this function was - invoked by a stream buffer read then xBytesToStoreMessageLength will - be 0. */ - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Clear notification state as going to wait for data. */ - ( void ) xTaskNotifyStateClear( NULL ); + /* If this function was invoked by a message buffer read then + xBytesToStoreMessageLength holds the number of bytes used to hold + the length of the next discrete message. If this function was + invoked by a stream buffer read then xBytesToStoreMessageLength will + be 0. */ + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Clear notification state as going to wait for data. */ + ( void ) xTaskNotifyStateClear( NULL ); - /* Should only be one reader. */ - configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); - pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* Should only be one reader. */ + configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); + pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - if( xBytesAvailable <= xBytesToStoreMessageLength ) - { - /* Wait for data to be available. */ - traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); - ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); - pxStreamBuffer->xTaskWaitingToReceive = NULL; + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Wait for data to be available. */ + traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToReceive = NULL; - /* Recheck the data available after blocking. */ - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - } + /* Recheck the data available after blocking. */ + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - holds the number of bytes used to store the message length) or a stream of - bytes (where xBytesToStoreMessageLength is zero), the number of bytes - available must be greater than xBytesToStoreMessageLength to be able to - read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + holds the number of bytes used to store the message length) or a stream of + bytes (where xBytesToStoreMessageLength is zero), the number of bytes + available must be greater than xBytesToStoreMessageLength to be able to + read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); - sbRECEIVE_COMPLETED( pxStreamBuffer ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); - mtCOVERAGE_TEST_MARKER(); - } + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); + sbRECEIVE_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); + mtCOVERAGE_TEST_MARKER(); + } - return xReceivedLength; + return xReceivedLength; } /*-----------------------------------------------------------*/ @@ -820,150 +820,150 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReturn, xBytesAvailable, xOriginalTail; configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* Ensure the stream buffer is being used as a message buffer. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) - { - /* The number of bytes available is greater than the number of bytes - required to hold the length of the next message, so another message - is available. Return its length without removing the length bytes - from the buffer. A copy of the tail is stored so the buffer can be - returned to its prior state as the message is not actually being - removed from the buffer. */ - xOriginalTail = pxStreamBuffer->xTail; - ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, xBytesAvailable ); - xReturn = ( size_t ) xTempReturn; - pxStreamBuffer->xTail = xOriginalTail; - } - else - { - /* The minimum amount of bytes in a message buffer is - ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is - less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid - value is 0. */ - configASSERT( xBytesAvailable == 0 ); - xReturn = 0; - } - } - else - { - xReturn = 0; - } + /* Ensure the stream buffer is being used as a message buffer. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) + { + /* The number of bytes available is greater than the number of bytes + required to hold the length of the next message, so another message + is available. Return its length without removing the length bytes + from the buffer. A copy of the tail is stored so the buffer can be + returned to its prior state as the message is not actually being + removed from the buffer. */ + xOriginalTail = pxStreamBuffer->xTail; + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, xBytesAvailable ); + xReturn = ( size_t ) xTempReturn; + pxStreamBuffer->xTail = xOriginalTail; + } + else + { + /* The minimum amount of bytes in a message buffer is + ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is + less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid + value is 0. */ + configASSERT( xBytesAvailable == 0 ); + xReturn = 0; + } + } + else + { + xReturn = 0; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - BaseType_t * const pxHigherPriorityTaskWoken ) + void *pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; - configASSERT( pvRxData ); - configASSERT( pxStreamBuffer ); + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); - /* This receive function is used by both message buffers, which store - discrete messages, and stream buffers, which store a continuous stream of - bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the - message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } + /* This receive function is used by both message buffers, which store + discrete messages, and stream buffers, which store a continuous stream of + bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } - xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); - /* Whether receiving a discrete message (where xBytesToStoreMessageLength - holds the number of bytes used to store the message length) or a stream of - bytes (where xBytesToStoreMessageLength is zero), the number of bytes - available must be greater than xBytesToStoreMessageLength to be able to - read bytes from the buffer. */ - if( xBytesAvailable > xBytesToStoreMessageLength ) - { - xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + holds the number of bytes used to store the message length) or a stream of + bytes (where xBytesToStoreMessageLength is zero), the number of bytes + available must be greater than xBytesToStoreMessageLength to be able to + read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); - /* Was a task waiting for space in the buffer? */ - if( xReceivedLength != ( size_t ) 0 ) - { - sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); + traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); - return xReceivedLength; + return xReceivedLength; } /*-----------------------------------------------------------*/ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, - void *pvRxData, - size_t xBufferLengthBytes, - size_t xBytesAvailable, - size_t xBytesToStoreMessageLength ) + void *pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable, + size_t xBytesToStoreMessageLength ) { size_t xOriginalTail, xReceivedLength, xNextMessageLength; configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength; - if( xBytesToStoreMessageLength != ( size_t ) 0 ) - { - /* A discrete message is being received. First receive the length - of the message. A copy of the tail is stored so the buffer can be - returned to its prior state if the length of the message is too - large for the provided buffer. */ - xOriginalTail = pxStreamBuffer->xTail; - ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); - xNextMessageLength = ( size_t ) xTempNextMessageLength; + if( xBytesToStoreMessageLength != ( size_t ) 0 ) + { + /* A discrete message is being received. First receive the length + of the message. A copy of the tail is stored so the buffer can be + returned to its prior state if the length of the message is too + large for the provided buffer. */ + xOriginalTail = pxStreamBuffer->xTail; + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); + xNextMessageLength = ( size_t ) xTempNextMessageLength; - /* Reduce the number of bytes available by the number of bytes just - read out. */ - xBytesAvailable -= xBytesToStoreMessageLength; + /* Reduce the number of bytes available by the number of bytes just + read out. */ + xBytesAvailable -= xBytesToStoreMessageLength; - /* Check there is enough space in the buffer provided by the - user. */ - if( xNextMessageLength > xBufferLengthBytes ) - { - /* The user has provided insufficient space to read the message - so return the buffer to its previous state (so the length of - the message is in the buffer again). */ - pxStreamBuffer->xTail = xOriginalTail; - xNextMessageLength = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* A stream of bytes is being received (as opposed to a discrete - message), so read as many bytes as possible. */ - xNextMessageLength = xBufferLengthBytes; - } + /* Check there is enough space in the buffer provided by the + user. */ + if( xNextMessageLength > xBufferLengthBytes ) + { + /* The user has provided insufficient space to read the message + so return the buffer to its previous state (so the length of + the message is in the buffer again). */ + pxStreamBuffer->xTail = xOriginalTail; + xNextMessageLength = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* A stream of bytes is being received (as opposed to a discrete + message), so read as many bytes as possible. */ + xNextMessageLength = xBufferLengthBytes; + } - /* Read the actual data. */ - xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ + /* Read the actual data. */ + xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ - return xReceivedLength; + return xReceivedLength; } /*-----------------------------------------------------------*/ @@ -973,20 +973,20 @@ const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; size_t xTail; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* True if no bytes are available. */ - xTail = pxStreamBuffer->xTail; - if( pxStreamBuffer->xHead == xTail ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + /* True if no bytes are available. */ + xTail = pxStreamBuffer->xTail; + if( pxStreamBuffer->xHead == xTail ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -996,32 +996,32 @@ BaseType_t xReturn; size_t xBytesToStoreMessageLength; const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - /* This generic version of the receive function is used by both message - buffers, which store discrete messages, and stream buffers, which store a - continuous stream of bytes. Discrete messages include an additional - sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ - if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) - { - xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; - } - else - { - xBytesToStoreMessageLength = 0; - } + /* This generic version of the receive function is used by both message + buffers, which store discrete messages, and stream buffers, which store a + continuous stream of bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } - /* True if the available space equals zero. */ - if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) - { - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + /* True if the available space equals zero. */ + if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1031,27 +1031,27 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1061,27 +1061,27 @@ StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; BaseType_t xReturn; UBaseType_t uxSavedInterruptStatus; - configASSERT( pxStreamBuffer ); + configASSERT( pxStreamBuffer ); - uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) - { - ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, - ( uint32_t ) 0, - eNoAction, - pxHigherPriorityTaskWoken ); - ( pxStreamBuffer )->xTaskWaitingToSend = NULL; - xReturn = pdTRUE; - } - else - { - xReturn = pdFALSE; - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -1089,45 +1089,45 @@ static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, cons { size_t xNextHead, xFirstLength; - configASSERT( xCount > ( size_t ) 0 ); + configASSERT( xCount > ( size_t ) 0 ); - xNextHead = pxStreamBuffer->xHead; + xNextHead = pxStreamBuffer->xHead; - /* Calculate the number of bytes that can be added in the first write - - which may be less than the total number of bytes that need to be added if - the buffer will wrap back to the beginning. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); + /* Calculate the number of bytes that can be added in the first write - + which may be less than the total number of bytes that need to be added if + the buffer will wrap back to the beginning. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); - /* Write as many bytes as can be written in the first write. */ - configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) memcpy( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + /* Write as many bytes as can be written in the first write. */ + configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - /* If the number of bytes written was less than the number that could be - written in the first write... */ - if( xCount > xFirstLength ) - { - /* ...then write the remaining bytes to the start of the buffer. */ - configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the number of bytes written was less than the number that could be + written in the first write... */ + if( xCount > xFirstLength ) + { + /* ...then write the remaining bytes to the start of the buffer. */ + configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xNextHead += xCount; - if( xNextHead >= pxStreamBuffer->xLength ) - { - xNextHead -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + xNextHead += xCount; + if( xNextHead >= pxStreamBuffer->xLength ) + { + xNextHead -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxStreamBuffer->xHead = xNextHead; + pxStreamBuffer->xHead = xNextHead; - return xCount; + return xCount; } /*-----------------------------------------------------------*/ @@ -1135,54 +1135,54 @@ static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, uint8_t *p { size_t xCount, xFirstLength, xNextTail; - /* Use the minimum of the wanted bytes and the available bytes. */ - xCount = configMIN( xBytesAvailable, xMaxCount ); + /* Use the minimum of the wanted bytes and the available bytes. */ + xCount = configMIN( xBytesAvailable, xMaxCount ); - if( xCount > ( size_t ) 0 ) - { - xNextTail = pxStreamBuffer->xTail; + if( xCount > ( size_t ) 0 ) + { + xNextTail = pxStreamBuffer->xTail; - /* Calculate the number of bytes that can be read - which may be - less than the number wanted if the data wraps around to the start of - the buffer. */ - xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); + /* Calculate the number of bytes that can be read - which may be + less than the number wanted if the data wraps around to the start of + the buffer. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); - /* Obtain the number of bytes it is possible to obtain in the first - read. Asserts check bounds of read and write. */ - configASSERT( xFirstLength <= xMaxCount ); - configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); - ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + /* Obtain the number of bytes it is possible to obtain in the first + read. Asserts check bounds of read and write. */ + configASSERT( xFirstLength <= xMaxCount ); + configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - /* If the total number of wanted bytes is greater than the number - that could be read in the first read... */ - if( xCount > xFirstLength ) - { - /*...then read the remaining bytes from the start of the buffer. */ - configASSERT( xCount <= xMaxCount ); - ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the total number of wanted bytes is greater than the number + that could be read in the first read... */ + if( xCount > xFirstLength ) + { + /*...then read the remaining bytes from the start of the buffer. */ + configASSERT( xCount <= xMaxCount ); + ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Move the tail pointer to effectively remove the data read from - the buffer. */ - xNextTail += xCount; + /* Move the tail pointer to effectively remove the data read from + the buffer. */ + xNextTail += xCount; - if( xNextTail >= pxStreamBuffer->xLength ) - { - xNextTail -= pxStreamBuffer->xLength; - } + if( xNextTail >= pxStreamBuffer->xLength ) + { + xNextTail -= pxStreamBuffer->xLength; + } - pxStreamBuffer->xTail = xNextTail; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + pxStreamBuffer->xTail = xNextTail; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xCount; + return xCount; } /*-----------------------------------------------------------*/ @@ -1191,73 +1191,73 @@ static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) /* Returns the distance between xTail and xHead. */ size_t xCount; - xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; - xCount -= pxStreamBuffer->xTail; - if ( xCount >= pxStreamBuffer->xLength ) - { - xCount -= pxStreamBuffer->xLength; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; + xCount -= pxStreamBuffer->xTail; + if ( xCount >= pxStreamBuffer->xLength ) + { + xCount -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xCount; + return xCount; } /*-----------------------------------------------------------*/ static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, - uint8_t * const pucBuffer, - size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - uint8_t ucFlags ) + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) { - /* Assert here is deliberately writing to the entire buffer to ensure it can - be written to without generating exceptions, and is setting the buffer to a - known value to assist in development/debugging. */ - #if( configASSERT_DEFINED == 1 ) - { - /* The value written just has to be identifiable when looking at the - memory. Don't use 0xA5 as that is the stack fill value and could - result in confusion as to what is actually being observed. */ - const BaseType_t xWriteValue = 0x55; - configASSERT( memset( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); - } /*lint !e529 !e438 xWriteValue is only used if configASSERT() is defined. */ - #endif + /* Assert here is deliberately writing to the entire buffer to ensure it can + be written to without generating exceptions, and is setting the buffer to a + known value to assist in development/debugging. */ + #if( configASSERT_DEFINED == 1 ) + { + /* The value written just has to be identifiable when looking at the + memory. Don't use 0xA5 as that is the stack fill value and could + result in confusion as to what is actually being observed. */ + const BaseType_t xWriteValue = 0x55; + configASSERT( memset( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); + } /*lint !e529 !e438 xWriteValue is only used if configASSERT() is defined. */ + #endif - ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ - pxStreamBuffer->pucBuffer = pucBuffer; - pxStreamBuffer->xLength = xBufferSizeBytes; - pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; - pxStreamBuffer->ucFlags = ucFlags; + ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ + pxStreamBuffer->pucBuffer = pucBuffer; + pxStreamBuffer->xLength = xBufferSizeBytes; + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; + pxStreamBuffer->ucFlags = ucFlags; } #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) - { - return xStreamBuffer->uxStreamBufferNumber; - } + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) + { + return xStreamBuffer->uxStreamBufferNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) - { - xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; - } + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) + { + xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) - { - return ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ); - } + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) + { + return ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ); + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ diff --git a/components/bl602/freertos_riscv_ram/tasks.c b/components/bl602/freertos_riscv_ram/tasks.c index c13e1c71..7337a911 100644 --- a/components/bl602/freertos_riscv_ram/tasks.c +++ b/components/bl602/freertos_riscv_ram/tasks.c @@ -49,145 +49,145 @@ correct privileged Vs unprivileged linkage and placement. */ /* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting functions but without including stdio.h here. */ #if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) - /* At the bottom of this file are two optional functions that can be used - to generate human readable text from the raw data generated by the - uxTaskGetSystemState() function. Note the formatting functions are provided - for convenience only, and are NOT considered part of the kernel. */ - #include + /* At the bottom of this file are two optional functions that can be used + to generate human readable text from the raw data generated by the + uxTaskGetSystemState() function. Note the formatting functions are provided + for convenience only, and are NOT considered part of the kernel. */ + #include #endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ #if( configUSE_PREEMPTION == 0 ) - /* If the cooperative scheduler is being used then a yield should not be - performed just because a higher priority task has been woken. */ - #define taskYIELD_IF_USING_PREEMPTION() + /* If the cooperative scheduler is being used then a yield should not be + performed just because a higher priority task has been woken. */ + #define taskYIELD_IF_USING_PREEMPTION() #else - #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() + #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() #endif /* Values that can be assigned to the ucNotifyState member of the TCB. */ -#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) -#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) -#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) +#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) +#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) +#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) /* * The value used to fill the stack of a task when the task is created. This * is used purely for checking the high water mark for tasks. */ -#define tskSTACK_FILL_BYTE ( 0xa5U ) +#define tskSTACK_FILL_BYTE ( 0xa5U ) /* Bits used to recored how a task's stack and TCB were allocated. */ -#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) -#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) -#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) +#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) +#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) +#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) /* If any of the following are set then task stacks are filled with a known value so the high water mark can be determined. If none of the following are set then don't fill the stack so there is no unnecessary dependency on memset. */ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 #else - #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 #endif /* * Macros used by vListTask to indicate which state a task is in. */ -#define tskRUNNING_CHAR ( 'X' ) -#define tskBLOCKED_CHAR ( 'B' ) -#define tskREADY_CHAR ( 'R' ) -#define tskDELETED_CHAR ( 'D' ) -#define tskSUSPENDED_CHAR ( 'S' ) +#define tskRUNNING_CHAR ( 'X' ) +#define tskBLOCKED_CHAR ( 'B' ) +#define tskREADY_CHAR ( 'R' ) +#define tskDELETED_CHAR ( 'D' ) +#define tskSUSPENDED_CHAR ( 'S' ) /* * Some kernel aware debuggers require the data the debugger needs access to be * global, rather than file scope. */ #ifdef portREMOVE_STATIC_QUALIFIER - #define static + #define static #endif /* The name allocated to the Idle task. This can be overridden by defining configIDLE_TASK_NAME in FreeRTOSConfig.h. */ #ifndef configIDLE_TASK_NAME - #define configIDLE_TASK_NAME "IDLE" + #define configIDLE_TASK_NAME "IDLE" #endif #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is - performed in a generic way that is not optimised to any particular - microcontroller architecture. */ + /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is + performed in a generic way that is not optimised to any particular + microcontroller architecture. */ - /* uxTopReadyPriority holds the priority of the highest priority ready - state task. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) \ - { \ - if( ( uxPriority ) > uxTopReadyPriority ) \ - { \ - uxTopReadyPriority = ( uxPriority ); \ - } \ - } /* taskRECORD_READY_PRIORITY */ + /* uxTopReadyPriority holds the priority of the highest priority ready + state task. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) \ + { \ + if( ( uxPriority ) > uxTopReadyPriority ) \ + { \ + uxTopReadyPriority = ( uxPriority ); \ + } \ + } /* taskRECORD_READY_PRIORITY */ - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority = uxTopReadyPriority; \ - \ - /* Find the highest priority queue that contains ready tasks. */ \ - while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ - { \ - configASSERT( uxTopPriority ); \ - --uxTopPriority; \ - } \ - \ - /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ - the same priority get an equal share of the processor time. */ \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - uxTopReadyPriority = uxTopPriority; \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK */ + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority = uxTopReadyPriority; \ + \ + /* Find the highest priority queue that contains ready tasks. */ \ + while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ + { \ + configASSERT( uxTopPriority ); \ + --uxTopPriority; \ + } \ + \ + /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ + the same priority get an equal share of the processor time. */ \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + uxTopReadyPriority = uxTopPriority; \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK */ - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as - they are only required when a port optimised method of task selection is - being used. */ - #define taskRESET_READY_PRIORITY( uxPriority ) - #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as + they are only required when a port optimised method of task selection is + being used. */ + #define taskRESET_READY_PRIORITY( uxPriority ) + #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) #else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ - /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is - performed in a way that is tailored to the particular microcontroller - architecture being used. */ + /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is + performed in a way that is tailored to the particular microcontroller + architecture being used. */ - /* A port optimised version is provided. Call the port defined macros. */ - #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + /* A port optimised version is provided. Call the port defined macros. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - #define taskSELECT_HIGHEST_PRIORITY_TASK() \ - { \ - UBaseType_t uxTopPriority; \ - \ - /* Find the highest priority list that contains ready tasks. */ \ - portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ - configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ - listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ - } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority; \ + \ + /* Find the highest priority list that contains ready tasks. */ \ + portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ + configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ - /*-----------------------------------------------------------*/ + /*-----------------------------------------------------------*/ - /* A port optimised version is provided, call it only if the TCB being reset - is being referenced from a ready list. If it is referenced from a delayed - or suspended list then it won't be in a ready list. */ - #define taskRESET_READY_PRIORITY( uxPriority ) \ - { \ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ - { \ - portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ - } \ - } + /* A port optimised version is provided, call it only if the TCB being reset + is being referenced from a ready list. If it is referenced from a delayed + or suspended list then it won't be in a ready list. */ + #define taskRESET_READY_PRIORITY( uxPriority ) \ + { \ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ + { \ + portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ + } \ + } #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ @@ -195,18 +195,18 @@ configIDLE_TASK_NAME in FreeRTOSConfig.h. */ /* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick count overflows. */ -#define taskSWITCH_DELAYED_LISTS() \ -{ \ - List_t *pxTemp; \ - \ - /* The delayed tasks list should be empty when the lists are switched. */ \ - configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ - \ - pxTemp = pxDelayedTaskList; \ - pxDelayedTaskList = pxOverflowDelayedTaskList; \ - pxOverflowDelayedTaskList = pxTemp; \ - xNumOfOverflows++; \ - prvResetNextTaskUnblockTime(); \ +#define taskSWITCH_DELAYED_LISTS() \ +{ \ + List_t *pxTemp; \ + \ + /* The delayed tasks list should be empty when the lists are switched. */ \ + configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ + \ + pxTemp = pxDelayedTaskList; \ + pxDelayedTaskList = pxOverflowDelayedTaskList; \ + pxOverflowDelayedTaskList = pxTemp; \ + xNumOfOverflows++; \ + prvResetNextTaskUnblockTime(); \ } /*-----------------------------------------------------------*/ @@ -215,11 +215,11 @@ count overflows. */ * Place the task represented by pxTCB into the appropriate ready list for * the task. It is inserted at the end of the list. */ -#define prvAddTaskToReadyList( pxTCB ) \ - traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ - taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ - vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ - tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +#define prvAddTaskToReadyList( pxTCB ) \ + traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ + taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ + vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ + tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) /*-----------------------------------------------------------*/ /* @@ -239,9 +239,9 @@ the scheduler that the value should not be changed - in which case it is the responsibility of whichever module is using the value to ensure it gets set back to its original value when it is released. */ #if( configUSE_16_BIT_TICKS == 1 ) - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U #else - #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL #endif /* @@ -249,79 +249,79 @@ to its original value when it is released. */ * and stores task state information, including a pointer to the task's context * (the task's run time environment, including register values) */ -typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ { - volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ + volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ - #if ( portUSING_MPU_WRAPPERS == 1 ) - xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ - #endif + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ + #endif - ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ - ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ - UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ - StackType_t *pxStack; /*< Points to the start of the stack. */ - char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ + ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ + UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ + StackType_t *pxStack; /*< Points to the start of the stack. */ + char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) - StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */ - #endif + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */ + #endif - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ - #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ + #endif - #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ - UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ - #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ + UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ + #endif - #if ( configUSE_MUTEXES == 1 ) - UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ - UBaseType_t uxMutexesHeld; - #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ + UBaseType_t uxMutexesHeld; + #endif - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t pxTaskTag; - #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + TaskHookFunction_t pxTaskTag; + #endif - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) - void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; - #endif + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif - #if( configGENERATE_RUN_TIME_STATS == 1 ) - uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ - #endif + #if( configGENERATE_RUN_TIME_STATS == 1 ) + uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ + #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - /* Allocate a Newlib reent structure that is specific to this task. - Note Newlib support has been included by popular demand, but is not - used by the FreeRTOS maintainers themselves. FreeRTOS is not - responsible for resulting newlib operation. User must be familiar with - newlib and must provide system-wide implementations of the necessary - stubs. Be warned that (at the time of writing) the current newlib design - implements a system-wide malloc() that must be provided with locks. */ - struct _reent xNewLib_reent; - #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + /* Allocate a Newlib reent structure that is specific to this task. + Note Newlib support has been included by popular demand, but is not + used by the FreeRTOS maintainers themselves. FreeRTOS is not + responsible for resulting newlib operation. User must be familiar with + newlib and must provide system-wide implementations of the necessary + stubs. Be warned that (at the time of writing) the current newlib design + implements a system-wide malloc() that must be provided with locks. */ + struct _reent xNewLib_reent; + #endif - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - volatile uint32_t ulNotifiedValue; - volatile uint8_t ucNotifyState; - #endif + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + volatile uint32_t ulNotifiedValue; + volatile uint8_t ucNotifyState; + #endif - /* See the comments in FreeRTOS.h with the definition of - tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ - #endif + /* See the comments in FreeRTOS.h with the definition of + tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ + #endif - #if( INCLUDE_xTaskAbortDelay == 1 ) - uint8_t ucDelayAborted; - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDelayAborted; + #endif - #if( configUSE_POSIX_ERRNO == 1 ) - int iTaskErrno; - #endif + #if( configUSE_POSIX_ERRNO == 1 ) + int iTaskErrno; + #endif } tskTCB; @@ -338,42 +338,42 @@ xDelayedTaskList1 and xDelayedTaskList2 could be move to function scople but doing so breaks some kernel aware debuggers and debuggers that rely on removing the static qualifier. */ PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ -PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ -PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ -PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ +PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ +PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ #if( INCLUDE_vTaskDelete == 1 ) - PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ - PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; + PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ + PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; #endif #if ( INCLUDE_vTaskSuspend == 1 ) - PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ + PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ #endif /* Global POSIX errno. Its value is changed upon context switching to match the errno of the currently running task. */ #if ( configUSE_POSIX_ERRNO == 1 ) - int FreeRTOS_errno = 0; + int FreeRTOS_errno = 0; #endif /* Other file private variables. --------------------------------*/ -PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; -PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; -PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; -PRIVILEGED_DATA static volatile UBaseType_t uxPendedTicks = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; -PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; -PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; -PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ -PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ +PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; +PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; +PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; +PRIVILEGED_DATA static volatile UBaseType_t uxPendedTicks = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; +PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; +PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ +PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ /* Context switches are held pending while the scheduler is suspended. Also, interrupts must not manipulate the xStateListItem of a TCB, or any of the @@ -383,14 +383,14 @@ moves the task's event list item into the xPendingReadyList, ready for the kernel to move the task from the pending ready list into the real ready list when the scheduler is unsuspended. The pending ready list itself can only be accessed from a critical section. */ -PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; +PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; #if ( configGENERATE_RUN_TIME_STATS == 1 ) - /* Do not move these variables to function scope as doing so prevents the - code working with debuggers that need to remove the static qualifier. */ - PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ - PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ + /* Do not move these variables to function scope as doing so prevents the + code working with debuggers that need to remove the static qualifier. */ + PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ + PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ #endif @@ -401,19 +401,19 @@ PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t /* Callback function prototypes. --------------------------*/ #if( configCHECK_FOR_STACK_OVERFLOW > 0 ) - extern void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ); + extern void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ); #endif #if( configUSE_TICK_HOOK > 0 ) - extern void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ + extern void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ #endif #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - extern void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ + extern void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ #endif @@ -426,7 +426,7 @@ PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t */ #if ( INCLUDE_vTaskSuspend == 1 ) - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; #endif /* INCLUDE_vTaskSuspend */ @@ -458,7 +458,7 @@ static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ); */ #if ( INCLUDE_vTaskDelete == 1 ) - static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION; + static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION; #endif @@ -485,7 +485,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( configUSE_TRACE_FACILITY == 1 ) - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION; + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION; #endif @@ -495,7 +495,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( INCLUDE_xTaskGetHandle == 1 ) - static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; + static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; #endif @@ -506,7 +506,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; #endif @@ -521,7 +521,7 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT */ #if ( configUSE_TICKLESS_IDLE != 0 ) - static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; + static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; #endif @@ -533,11 +533,11 @@ static void prvResetNextTaskUnblockTime( void ); #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - /* - * Helper function used to pad task names with spaces when printing out - * human readable tables of task information. - */ - static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) PRIVILEGED_FUNCTION; + /* + * Helper function used to pad task names with spaces when printing out + * human readable tables of task information. + */ + static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) PRIVILEGED_FUNCTION; #endif @@ -545,14 +545,14 @@ static void prvResetNextTaskUnblockTime( void ); * Called after a Task_t structure has been allocated either statically or * dynamically to fill in the structure's members. */ -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t *pxNewTCB, - const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t *pxNewTCB, + const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; /* * Called after a new task has been created and initialised to place the task @@ -567,7 +567,7 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION; */ #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; + static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; #endif @@ -575,1318 +575,1318 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION; #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - StackType_t * const puxStackBuffer, - StaticTask_t * const pxTaskBuffer ) - { - TCB_t *pxNewTCB; - TaskHandle_t xReturn; + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) + { + TCB_t *pxNewTCB; + TaskHandle_t xReturn; - configASSERT( puxStackBuffer != NULL ); - configASSERT( pxTaskBuffer != NULL ); + configASSERT( puxStackBuffer != NULL ); + configASSERT( pxTaskBuffer != NULL ); - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticTask_t equals the size of the real task - structure. */ - volatile size_t xSize = sizeof( StaticTask_t ); - configASSERT( xSize == sizeof( TCB_t ) ); - ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ - } - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticTask_t equals the size of the real task + structure. */ + volatile size_t xSize = sizeof( StaticTask_t ); + configASSERT( xSize == sizeof( TCB_t ) ); + ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ + } + #endif /* configASSERT_DEFINED */ - if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) - { - /* The memory used for the task's TCB and stack are passed into this - function - use them. */ - pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ - pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; + if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) + { + /* The memory used for the task's TCB and stack are passed into this + function - use them. */ + pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - } - else - { - xReturn = NULL; - } + prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + } + else + { + xReturn = NULL; + } - return xReturn; - } + return xReturn; + } #endif /* SUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) - BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); - configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); + configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); + configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); - if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) - { - /* Allocate space for the TCB. Where the memory comes from depends - on the implementation of the port malloc function and whether or - not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; + if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) + { + /* Allocate space for the TCB. Where the memory comes from depends + on the implementation of the port malloc function and whether or + not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - { - /* Tasks can be created statically or dynamically, so note this - task was created statically in case the task is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } - return xReturn; - } + return xReturn; + } #endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ /*-----------------------------------------------------------*/ #if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - configASSERT( pxTaskDefinition->puxStackBuffer ); + configASSERT( pxTaskDefinition->puxStackBuffer ); - if( pxTaskDefinition->puxStackBuffer != NULL ) - { - /* Allocate space for the TCB. Where the memory comes from depends - on the implementation of the port malloc function and whether or - not static allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + if( pxTaskDefinition->puxStackBuffer != NULL ) + { + /* Allocate space for the TCB. Where the memory comes from depends + on the implementation of the port malloc function and whether or + not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) - { - /* Tasks can be created statically or dynamically, so note - this task had a statically allocated stack in case it is - later deleted. The TCB was allocated dynamically. */ - pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note + this task had a statically allocated stack in case it is + later deleted. The TCB was allocated dynamically. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, - pxTaskDefinition->pcName, - ( uint32_t ) pxTaskDefinition->usStackDepth, - pxTaskDefinition->pvParameters, - pxTaskDefinition->uxPriority, - pxCreatedTask, pxNewTCB, - pxTaskDefinition->xRegions ); + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - } + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + } - return xReturn; - } + return xReturn; + } #endif /* portUSING_MPU_WRAPPERS */ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const configSTACK_DEPTH_TYPE usStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask ) - { - TCB_t *pxNewTCB; - BaseType_t xReturn; + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn; - /* If the stack grows down then allocate the stack then the TCB so the stack - does not grow into the TCB. Likewise if the stack grows up then allocate - the TCB then the stack. */ - #if( portSTACK_GROWTH > 0 ) - { - /* Allocate space for the TCB. Where the memory comes from depends on - the implementation of the port malloc function and whether or not static - allocation is being used. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + /* If the stack grows down then allocate the stack then the TCB so the stack + does not grow into the TCB. Likewise if the stack grows up then allocate + the TCB then the stack. */ + #if( portSTACK_GROWTH > 0 ) + { + /* Allocate space for the TCB. Where the memory comes from depends on + the implementation of the port malloc function and whether or not static + allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); - if( pxNewTCB != NULL ) - { - /* Allocate space for the stack used by the task being created. - The base of the stack memory stored in the TCB so the task can - be deleted later if required. */ - pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + if( pxNewTCB != NULL ) + { + /* Allocate space for the stack used by the task being created. + The base of the stack memory stored in the TCB so the task can + be deleted later if required. */ + pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - if( pxNewTCB->pxStack == NULL ) - { - /* Could not allocate the stack. Delete the allocated TCB. */ - vPortFree( pxNewTCB ); - pxNewTCB = NULL; - } - } - } - #else /* portSTACK_GROWTH */ - { - StackType_t *pxStack; + if( pxNewTCB->pxStack == NULL ) + { + /* Could not allocate the stack. Delete the allocated TCB. */ + vPortFree( pxNewTCB ); + pxNewTCB = NULL; + } + } + } + #else /* portSTACK_GROWTH */ + { + StackType_t *pxStack; - /* Allocate space for the stack used by the task being created. */ - pxStack = pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */ + /* Allocate space for the stack used by the task being created. */ + pxStack = pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */ - if( pxStack != NULL ) - { - /* Allocate space for the TCB. */ - pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */ + if( pxStack != NULL ) + { + /* Allocate space for the TCB. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */ - if( pxNewTCB != NULL ) - { - /* Store the stack location in the TCB. */ - pxNewTCB->pxStack = pxStack; - } - else - { - /* The stack cannot be used as the TCB was not created. Free - it again. */ - vPortFree( pxStack ); - } - } - else - { - pxNewTCB = NULL; - } - } - #endif /* portSTACK_GROWTH */ + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxStack; + } + else + { + /* The stack cannot be used as the TCB was not created. Free + it again. */ + vPortFree( pxStack ); + } + } + else + { + pxNewTCB = NULL; + } + } + #endif /* portSTACK_GROWTH */ - if( pxNewTCB != NULL ) - { - #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */ - { - /* Tasks can be created statically or dynamically, so note this - task was created dynamically in case it is later deleted. */ - pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; - } - #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + if( pxNewTCB != NULL ) + { + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + task was created dynamically in case it is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ - prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); - prvAddNewTaskToReadyList( pxNewTCB ); - xReturn = pdPASS; - } - else - { - xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - } + prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } - return xReturn; - } + return xReturn; + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ -static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, - const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const uint32_t ulStackDepth, - void * const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t * const pxCreatedTask, - TCB_t *pxNewTCB, - const MemoryRegion_t * const xRegions ) +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t *pxNewTCB, + const MemoryRegion_t * const xRegions ) { StackType_t *pxTopOfStack; UBaseType_t x; - #if( portUSING_MPU_WRAPPERS == 1 ) - /* Should the task be created in privileged mode? */ - BaseType_t xRunPrivileged; - if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) - { - xRunPrivileged = pdTRUE; - } - else - { - xRunPrivileged = pdFALSE; - } - uxPriority &= ~portPRIVILEGE_BIT; - #endif /* portUSING_MPU_WRAPPERS == 1 */ + #if( portUSING_MPU_WRAPPERS == 1 ) + /* Should the task be created in privileged mode? */ + BaseType_t xRunPrivileged; + if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) + { + xRunPrivileged = pdTRUE; + } + else + { + xRunPrivileged = pdFALSE; + } + uxPriority &= ~portPRIVILEGE_BIT; + #endif /* portUSING_MPU_WRAPPERS == 1 */ - /* Avoid dependency on memset() if it is not required. */ - #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) - { - /* Fill the stack with a known value to assist debugging. */ - ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); - } - #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ + /* Avoid dependency on memset() if it is not required. */ + #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) + { + /* Fill the stack with a known value to assist debugging. */ + ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); + } + #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ - /* Calculate the top of stack address. This depends on whether the stack - grows from high memory to low (as per the 80x86) or vice versa. - portSTACK_GROWTH is used to make the result positive or negative as required - by the port. */ - #if( portSTACK_GROWTH < 0 ) - { - pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] ); - pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */ + /* Calculate the top of stack address. This depends on whether the stack + grows from high memory to low (as per the 80x86) or vice versa. + portSTACK_GROWTH is used to make the result positive or negative as required + by the port. */ + #if( portSTACK_GROWTH < 0 ) + { + pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] ); + pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */ - /* Check the alignment of the calculated top of stack is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + /* Check the alignment of the calculated top of stack is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - #if( configRECORD_STACK_HIGH_ADDRESS == 1 ) - { - /* Also record the stack's high address, which may assist - debugging. */ - pxNewTCB->pxEndOfStack = pxTopOfStack; - } - #endif /* configRECORD_STACK_HIGH_ADDRESS */ - } - #else /* portSTACK_GROWTH */ - { - pxTopOfStack = pxNewTCB->pxStack; + #if( configRECORD_STACK_HIGH_ADDRESS == 1 ) + { + /* Also record the stack's high address, which may assist + debugging. */ + pxNewTCB->pxEndOfStack = pxTopOfStack; + } + #endif /* configRECORD_STACK_HIGH_ADDRESS */ + } + #else /* portSTACK_GROWTH */ + { + pxTopOfStack = pxNewTCB->pxStack; - /* Check the alignment of the stack buffer is correct. */ - configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + /* Check the alignment of the stack buffer is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); - /* The other extreme of the stack space is required if stack checking is - performed. */ - pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); - } - #endif /* portSTACK_GROWTH */ + /* The other extreme of the stack space is required if stack checking is + performed. */ + pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); + } + #endif /* portSTACK_GROWTH */ - /* Store the task name in the TCB. */ - if( pcName != NULL ) - { - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - pxNewTCB->pcTaskName[ x ] = pcName[ x ]; + /* Store the task name in the TCB. */ + if( pcName != NULL ) + { + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + pxNewTCB->pcTaskName[ x ] = pcName[ x ]; - /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than - configMAX_TASK_NAME_LEN characters just in case the memory after the - string is not accessible (extremely unlikely). */ - if( pcName[ x ] == ( char ) 0x00 ) - { - break; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than + configMAX_TASK_NAME_LEN characters just in case the memory after the + string is not accessible (extremely unlikely). */ + if( pcName[ x ] == ( char ) 0x00 ) + { + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - /* Ensure the name string is terminated in the case that the string length - was greater or equal to configMAX_TASK_NAME_LEN. */ - pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; - } - else - { - /* The task has not been given a name, so just ensure there is a NULL - terminator when it is read out. */ - pxNewTCB->pcTaskName[ 0 ] = 0x00; - } + /* Ensure the name string is terminated in the case that the string length + was greater or equal to configMAX_TASK_NAME_LEN. */ + pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; + } + else + { + /* The task has not been given a name, so just ensure there is a NULL + terminator when it is read out. */ + pxNewTCB->pcTaskName[ 0 ] = 0x00; + } - /* This is used as an array index so must ensure it's not too large. First - remove the privilege bit if one is present. */ - if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* This is used as an array index so must ensure it's not too large. First + remove the privilege bit if one is present. */ + if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxNewTCB->uxPriority = uxPriority; - #if ( configUSE_MUTEXES == 1 ) - { - pxNewTCB->uxBasePriority = uxPriority; - pxNewTCB->uxMutexesHeld = 0; - } - #endif /* configUSE_MUTEXES */ + pxNewTCB->uxPriority = uxPriority; + #if ( configUSE_MUTEXES == 1 ) + { + pxNewTCB->uxBasePriority = uxPriority; + pxNewTCB->uxMutexesHeld = 0; + } + #endif /* configUSE_MUTEXES */ - vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); - vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); + vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); + vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); - /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get - back to the containing TCB from a generic item in a list. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); + /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get + back to the containing TCB from a generic item in a list. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); - /* Event lists are always in priority order. */ - listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); - #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - { - pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; - } - #endif /* portCRITICAL_NESTING_IN_TCB */ + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + { + pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; + } + #endif /* portCRITICAL_NESTING_IN_TCB */ - #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - { - pxNewTCB->pxTaskTag = NULL; - } - #endif /* configUSE_APPLICATION_TASK_TAG */ + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + { + pxNewTCB->pxTaskTag = NULL; + } + #endif /* configUSE_APPLICATION_TASK_TAG */ - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxNewTCB->ulRunTimeCounter = 0UL; - } - #endif /* configGENERATE_RUN_TIME_STATS */ + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxNewTCB->ulRunTimeCounter = 0UL; + } + #endif /* configGENERATE_RUN_TIME_STATS */ - #if ( portUSING_MPU_WRAPPERS == 1 ) - { - vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); - } - #else - { - /* Avoid compiler warning about unreferenced parameter. */ - ( void ) xRegions; - } - #endif + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); + } + #else + { + /* Avoid compiler warning about unreferenced parameter. */ + ( void ) xRegions; + } + #endif - #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - { - for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ ) - { - pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL; - } - } - #endif + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + { + for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ ) + { + pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL; + } + } + #endif - #if ( configUSE_TASK_NOTIFICATIONS == 1 ) - { - pxNewTCB->ulNotifiedValue = 0; - pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + pxNewTCB->ulNotifiedValue = 0; + pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Initialise this task's Newlib reent structure. */ - _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); - } - #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Initialise this task's Newlib reent structure. */ + _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); + } + #endif - #if( INCLUDE_xTaskAbortDelay == 1 ) - { - pxNewTCB->ucDelayAborted = pdFALSE; - } - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + { + pxNewTCB->ucDelayAborted = pdFALSE; + } + #endif - /* Initialize the TCB stack to look as if the task was already running, - but had been interrupted by the scheduler. The return address is set - to the start of the task function. Once the stack has been initialised - the top of stack variable is updated. */ - #if( portUSING_MPU_WRAPPERS == 1 ) - { - /* If the port has capability to detect stack overflow, - pass the stack end address to the stack initialization - function as well. */ - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - { - #if( portSTACK_GROWTH < 0 ) - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #else /* portSTACK_GROWTH */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #endif /* portSTACK_GROWTH */ - } - #else /* portHAS_STACK_OVERFLOW_CHECKING */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); - } - #endif /* portHAS_STACK_OVERFLOW_CHECKING */ - } - #else /* portUSING_MPU_WRAPPERS */ - { - /* If the port has capability to detect stack overflow, - pass the stack end address to the stack initialization - function as well. */ - #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) - { - #if( portSTACK_GROWTH < 0 ) - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); - } - #else /* portSTACK_GROWTH */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); - } - #endif /* portSTACK_GROWTH */ - } - #else /* portHAS_STACK_OVERFLOW_CHECKING */ - { - pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); - } - #endif /* portHAS_STACK_OVERFLOW_CHECKING */ - } - #endif /* portUSING_MPU_WRAPPERS */ + /* Initialize the TCB stack to look as if the task was already running, + but had been interrupted by the scheduler. The return address is set + to the start of the task function. Once the stack has been initialised + the top of stack variable is updated. */ + #if( portUSING_MPU_WRAPPERS == 1 ) + { + /* If the port has capability to detect stack overflow, + pass the stack end address to the stack initialization + function as well. */ + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #else /* portUSING_MPU_WRAPPERS */ + { + /* If the port has capability to detect stack overflow, + pass the stack end address to the stack initialization + function as well. */ + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #endif /* portUSING_MPU_WRAPPERS */ - if( pxCreatedTask != NULL ) - { - /* Pass the handle out in an anonymous way. The handle can be used to - change the created task's priority, delete the created task, etc.*/ - *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( pxCreatedTask != NULL ) + { + /* Pass the handle out in an anonymous way. The handle can be used to + change the created task's priority, delete the created task, etc.*/ + *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } /*-----------------------------------------------------------*/ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) { - /* Ensure interrupts don't access the task lists while the lists are being - updated. */ - taskENTER_CRITICAL(); - { - uxCurrentNumberOfTasks++; - if( pxCurrentTCB == NULL ) - { - /* There are no other tasks, or all the other tasks are in - the suspended state - make this the current task. */ - pxCurrentTCB = pxNewTCB; + /* Ensure interrupts don't access the task lists while the lists are being + updated. */ + taskENTER_CRITICAL(); + { + uxCurrentNumberOfTasks++; + if( pxCurrentTCB == NULL ) + { + /* There are no other tasks, or all the other tasks are in + the suspended state - make this the current task. */ + pxCurrentTCB = pxNewTCB; - if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) - { - /* This is the first task to be created so do the preliminary - initialisation required. We will not recover if this call - fails, but we will report the failure. */ - prvInitialiseTaskLists(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* If the scheduler is not already running, make this task the - current task if it is the highest priority task to be created - so far. */ - if( xSchedulerRunning == pdFALSE ) - { - if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) - { - pxCurrentTCB = pxNewTCB; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) + { + /* This is the first task to be created so do the preliminary + initialisation required. We will not recover if this call + fails, but we will report the failure. */ + prvInitialiseTaskLists(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If the scheduler is not already running, make this task the + current task if it is the highest priority task to be created + so far. */ + if( xSchedulerRunning == pdFALSE ) + { + if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) + { + pxCurrentTCB = pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - uxTaskNumber++; + uxTaskNumber++; - #if ( configUSE_TRACE_FACILITY == 1 ) - { - /* Add a counter into the TCB for tracing only. */ - pxNewTCB->uxTCBNumber = uxTaskNumber; - } - #endif /* configUSE_TRACE_FACILITY */ - traceTASK_CREATE( pxNewTCB ); + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Add a counter into the TCB for tracing only. */ + pxNewTCB->uxTCBNumber = uxTaskNumber; + } + #endif /* configUSE_TRACE_FACILITY */ + traceTASK_CREATE( pxNewTCB ); - prvAddTaskToReadyList( pxNewTCB ); + prvAddTaskToReadyList( pxNewTCB ); - portSETUP_TCB( pxNewTCB ); - } - taskEXIT_CRITICAL(); + portSETUP_TCB( pxNewTCB ); + } + taskEXIT_CRITICAL(); - if( xSchedulerRunning != pdFALSE ) - { - /* If the created task is of a higher priority than the current task - then it should run now. */ - if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSchedulerRunning != pdFALSE ) + { + /* If the created task is of a higher priority than the current task + then it should run now. */ + if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } } /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelete == 1 ) - void vTaskDelete( TaskHandle_t xTaskToDelete ) - { - TCB_t *pxTCB; + void vTaskDelete( TaskHandle_t xTaskToDelete ) + { + TCB_t *pxTCB; - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the calling task that is - being deleted. */ - pxTCB = prvGetTCBFromHandle( xTaskToDelete ); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the calling task that is + being deleted. */ + pxTCB = prvGetTCBFromHandle( xTaskToDelete ); - /* Remove task from the ready list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Remove task from the ready list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Increment the uxTaskNumber also so kernel aware debuggers can - detect that the task lists need re-generating. This is done before - portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will - not return. */ - uxTaskNumber++; + /* Increment the uxTaskNumber also so kernel aware debuggers can + detect that the task lists need re-generating. This is done before + portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will + not return. */ + uxTaskNumber++; - if( pxTCB == pxCurrentTCB ) - { - /* A task is deleting itself. This cannot complete within the - task itself, as a context switch to another task is required. - Place the task in the termination list. The idle task will - check the termination list and free up any memory allocated by - the scheduler for the TCB and stack of the deleted task. */ - vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); + if( pxTCB == pxCurrentTCB ) + { + /* A task is deleting itself. This cannot complete within the + task itself, as a context switch to another task is required. + Place the task in the termination list. The idle task will + check the termination list and free up any memory allocated by + the scheduler for the TCB and stack of the deleted task. */ + vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); - /* Increment the ucTasksDeleted variable so the idle task knows - there is a task that has been deleted and that it should therefore - check the xTasksWaitingTermination list. */ - ++uxDeletedTasksWaitingCleanUp; + /* Increment the ucTasksDeleted variable so the idle task knows + there is a task that has been deleted and that it should therefore + check the xTasksWaitingTermination list. */ + ++uxDeletedTasksWaitingCleanUp; - /* The pre-delete hook is primarily for the Windows simulator, - in which Windows specific clean up operations are performed, - after which it is not possible to yield away from this task - - hence xYieldPending is used to latch that a context switch is - required. */ - portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); - } - else - { - --uxCurrentNumberOfTasks; - prvDeleteTCB( pxTCB ); + /* The pre-delete hook is primarily for the Windows simulator, + in which Windows specific clean up operations are performed, + after which it is not possible to yield away from this task - + hence xYieldPending is used to latch that a context switch is + required. */ + portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); + } + else + { + --uxCurrentNumberOfTasks; + prvDeleteTCB( pxTCB ); - /* Reset the next expected unblock time in case it referred to - the task that has just been deleted. */ - prvResetNextTaskUnblockTime(); - } + /* Reset the next expected unblock time in case it referred to + the task that has just been deleted. */ + prvResetNextTaskUnblockTime(); + } - traceTASK_DELETE( pxTCB ); - } - taskEXIT_CRITICAL(); + traceTASK_DELETE( pxTCB ); + } + taskEXIT_CRITICAL(); - /* Force a reschedule if it is the currently running task that has just - been deleted. */ - if( xSchedulerRunning != pdFALSE ) - { - if( pxTCB == pxCurrentTCB ) - { - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } + /* Force a reschedule if it is the currently running task that has just + been deleted. */ + if( xSchedulerRunning != pdFALSE ) + { + if( pxTCB == pxCurrentTCB ) + { + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } #endif /* INCLUDE_vTaskDelete */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelayUntil == 1 ) - void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) - { - TickType_t xTimeToWake; - BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; + void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) + { + TickType_t xTimeToWake; + BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; - configASSERT( pxPreviousWakeTime ); - configASSERT( ( xTimeIncrement > 0U ) ); - configASSERT( uxSchedulerSuspended == 0 ); + configASSERT( pxPreviousWakeTime ); + configASSERT( ( xTimeIncrement > 0U ) ); + configASSERT( uxSchedulerSuspended == 0 ); - vTaskSuspendAll(); - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount; + vTaskSuspendAll(); + { + /* Minor optimisation. The tick count cannot change in this + block. */ + const TickType_t xConstTickCount = xTickCount; - /* Generate the tick time at which the task wants to wake. */ - xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; + /* Generate the tick time at which the task wants to wake. */ + xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; - if( xConstTickCount < *pxPreviousWakeTime ) - { - /* The tick count has overflowed since this function was - lasted called. In this case the only time we should ever - actually delay is if the wake time has also overflowed, - and the wake time is greater than the tick time. When this - is the case it is as if neither time had overflowed. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The tick time has not overflowed. In this case we will - delay if either the wake time has overflowed, and/or the - tick time is less than the wake time. */ - if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) - { - xShouldDelay = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( xConstTickCount < *pxPreviousWakeTime ) + { + /* The tick count has overflowed since this function was + lasted called. In this case the only time we should ever + actually delay is if the wake time has also overflowed, + and the wake time is greater than the tick time. When this + is the case it is as if neither time had overflowed. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The tick time has not overflowed. In this case we will + delay if either the wake time has overflowed, and/or the + tick time is less than the wake time. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - /* Update the wake time ready for the next call. */ - *pxPreviousWakeTime = xTimeToWake; + /* Update the wake time ready for the next call. */ + *pxPreviousWakeTime = xTimeToWake; - if( xShouldDelay != pdFALSE ) - { - traceTASK_DELAY_UNTIL( xTimeToWake ); + if( xShouldDelay != pdFALSE ) + { + traceTASK_DELAY_UNTIL( xTimeToWake ); - /* prvAddCurrentTaskToDelayedList() needs the block time, not - the time to wake, so subtract the current tick count. */ - prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - xAlreadyYielded = xTaskResumeAll(); + /* prvAddCurrentTaskToDelayedList() needs the block time, not + the time to wake, so subtract the current tick count. */ + prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); - /* Force a reschedule if xTaskResumeAll has not already done so, we may - have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Force a reschedule if xTaskResumeAll has not already done so, we may + have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskDelayUntil */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelay == 1 ) - void vTaskDelay( const TickType_t xTicksToDelay ) - { - BaseType_t xAlreadyYielded = pdFALSE; + void vTaskDelay( const TickType_t xTicksToDelay ) + { + BaseType_t xAlreadyYielded = pdFALSE; - /* A delay time of zero just forces a reschedule. */ - if( xTicksToDelay > ( TickType_t ) 0U ) - { - configASSERT( uxSchedulerSuspended == 0 ); - vTaskSuspendAll(); - { - traceTASK_DELAY(); + /* A delay time of zero just forces a reschedule. */ + if( xTicksToDelay > ( TickType_t ) 0U ) + { + configASSERT( uxSchedulerSuspended == 0 ); + vTaskSuspendAll(); + { + traceTASK_DELAY(); - /* A task that is removed from the event list while the - scheduler is suspended will not get placed in the ready - list or removed from the blocked list until the scheduler - is resumed. + /* A task that is removed from the event list while the + scheduler is suspended will not get placed in the ready + list or removed from the blocked list until the scheduler + is resumed. - This task cannot be in an event list as it is the currently - executing task. */ - prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); - } - xAlreadyYielded = xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + This task cannot be in an event list as it is the currently + executing task. */ + prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); + } + xAlreadyYielded = xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Force a reschedule if xTaskResumeAll has not already done so, we may - have put ourselves to sleep. */ - if( xAlreadyYielded == pdFALSE ) - { - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Force a reschedule if xTaskResumeAll has not already done so, we may + have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskDelay */ /*-----------------------------------------------------------*/ #if( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) - eTaskState eTaskGetState( TaskHandle_t xTask ) - { - eTaskState eReturn; - List_t const * pxStateList, *pxDelayedList, *pxOverflowedDelayedList; - const TCB_t * const pxTCB = xTask; + eTaskState eTaskGetState( TaskHandle_t xTask ) + { + eTaskState eReturn; + List_t const * pxStateList, *pxDelayedList, *pxOverflowedDelayedList; + const TCB_t * const pxTCB = xTask; - configASSERT( pxTCB ); + configASSERT( pxTCB ); - if( pxTCB == pxCurrentTCB ) - { - /* The task calling this function is querying its own state. */ - eReturn = eRunning; - } - else - { - taskENTER_CRITICAL(); - { - pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); - pxDelayedList = pxDelayedTaskList; - pxOverflowedDelayedList = pxOverflowDelayedTaskList; - } - taskEXIT_CRITICAL(); + if( pxTCB == pxCurrentTCB ) + { + /* The task calling this function is querying its own state. */ + eReturn = eRunning; + } + else + { + taskENTER_CRITICAL(); + { + pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); + pxDelayedList = pxDelayedTaskList; + pxOverflowedDelayedList = pxOverflowDelayedTaskList; + } + taskEXIT_CRITICAL(); - if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) - { - /* The task being queried is referenced from one of the Blocked - lists. */ - eReturn = eBlocked; - } + if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) + { + /* The task being queried is referenced from one of the Blocked + lists. */ + eReturn = eBlocked; + } - #if ( INCLUDE_vTaskSuspend == 1 ) - else if( pxStateList == &xSuspendedTaskList ) - { - /* The task being queried is referenced from the suspended - list. Is it genuinely suspended or is it blocked - indefinitely? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) - { - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - { - /* The task does not appear on the event list item of - and of the RTOS objects, but could still be in the - blocked state if it is waiting on its notification - rather than waiting on an object. */ - if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) - { - eReturn = eBlocked; - } - else - { - eReturn = eSuspended; - } - } - #else - { - eReturn = eSuspended; - } - #endif - } - else - { - eReturn = eBlocked; - } - } - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + else if( pxStateList == &xSuspendedTaskList ) + { + /* The task being queried is referenced from the suspended + list. Is it genuinely suspended or is it blocked + indefinitely? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) + { + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + { + /* The task does not appear on the event list item of + and of the RTOS objects, but could still be in the + blocked state if it is waiting on its notification + rather than waiting on an object. */ + if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) + { + eReturn = eBlocked; + } + else + { + eReturn = eSuspended; + } + } + #else + { + eReturn = eSuspended; + } + #endif + } + else + { + eReturn = eBlocked; + } + } + #endif - #if ( INCLUDE_vTaskDelete == 1 ) - else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) - { - /* The task being queried is referenced from the deleted - tasks list, or it is not referenced from any lists at - all. */ - eReturn = eDeleted; - } - #endif + #if ( INCLUDE_vTaskDelete == 1 ) + else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) + { + /* The task being queried is referenced from the deleted + tasks list, or it is not referenced from any lists at + all. */ + eReturn = eDeleted; + } + #endif - else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ - { - /* If the task is not in any other state, it must be in the - Ready (including pending ready) state. */ - eReturn = eReady; - } - } + else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ + { + /* If the task is not in any other state, it must be in the + Ready (including pending ready) state. */ + eReturn = eReady; + } + } - return eReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + return eReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ #endif /* INCLUDE_eTaskGetState */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskPriorityGet == 1 ) - UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) - { - TCB_t const *pxTCB; - UBaseType_t uxReturn; + UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) + { + TCB_t const *pxTCB; + UBaseType_t uxReturn; - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the task - that called uxTaskPriorityGet() that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the task + that called uxTaskPriorityGet() that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + taskEXIT_CRITICAL(); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskPriorityGet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskPriorityGet == 1 ) - UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) - { - TCB_t const *pxTCB; - UBaseType_t uxReturn, uxSavedInterruptState; + UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) + { + TCB_t const *pxTCB; + UBaseType_t uxReturn, uxSavedInterruptState; - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - https://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); - { - /* If null is passed in here then it is the priority of the calling - task that is being queried. */ - pxTCB = prvGetTCBFromHandle( xTask ); - uxReturn = pxTCB->uxPriority; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); + uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* If null is passed in here then it is the priority of the calling + task that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskPriorityGet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskPrioritySet == 1 ) - void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) - { - TCB_t *pxTCB; - UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; - BaseType_t xYieldRequired = pdFALSE; + void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) + { + TCB_t *pxTCB; + UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; + BaseType_t xYieldRequired = pdFALSE; - configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); + configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); - /* Ensure the new priority is valid. */ - if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) - { - uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Ensure the new priority is valid. */ + if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the priority of the calling - task that is being changed. */ - pxTCB = prvGetTCBFromHandle( xTask ); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the calling + task that is being changed. */ + pxTCB = prvGetTCBFromHandle( xTask ); - traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); + traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); - #if ( configUSE_MUTEXES == 1 ) - { - uxCurrentBasePriority = pxTCB->uxBasePriority; - } - #else - { - uxCurrentBasePriority = pxTCB->uxPriority; - } - #endif + #if ( configUSE_MUTEXES == 1 ) + { + uxCurrentBasePriority = pxTCB->uxBasePriority; + } + #else + { + uxCurrentBasePriority = pxTCB->uxPriority; + } + #endif - if( uxCurrentBasePriority != uxNewPriority ) - { - /* The priority change may have readied a task of higher - priority than the calling task. */ - if( uxNewPriority > uxCurrentBasePriority ) - { - if( pxTCB != pxCurrentTCB ) - { - /* The priority of a task other than the currently - running task is being raised. Is the priority being - raised above that of the running task? */ - if( uxNewPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - /* The priority of the running task is being raised, - but the running task must already be the highest - priority task able to run so no yield is required. */ - } - } - else if( pxTCB == pxCurrentTCB ) - { - /* Setting the priority of the running task down means - there may now be another task of higher priority that - is ready to execute. */ - xYieldRequired = pdTRUE; - } - else - { - /* Setting the priority of any other task down does not - require a yield as the running task must be above the - new priority of the task being modified. */ - } + if( uxCurrentBasePriority != uxNewPriority ) + { + /* The priority change may have readied a task of higher + priority than the calling task. */ + if( uxNewPriority > uxCurrentBasePriority ) + { + if( pxTCB != pxCurrentTCB ) + { + /* The priority of a task other than the currently + running task is being raised. Is the priority being + raised above that of the running task? */ + if( uxNewPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The priority of the running task is being raised, + but the running task must already be the highest + priority task able to run so no yield is required. */ + } + } + else if( pxTCB == pxCurrentTCB ) + { + /* Setting the priority of the running task down means + there may now be another task of higher priority that + is ready to execute. */ + xYieldRequired = pdTRUE; + } + else + { + /* Setting the priority of any other task down does not + require a yield as the running task must be above the + new priority of the task being modified. */ + } - /* Remember the ready list the task might be referenced from - before its uxPriority member is changed so the - taskRESET_READY_PRIORITY() macro can function correctly. */ - uxPriorityUsedOnEntry = pxTCB->uxPriority; + /* Remember the ready list the task might be referenced from + before its uxPriority member is changed so the + taskRESET_READY_PRIORITY() macro can function correctly. */ + uxPriorityUsedOnEntry = pxTCB->uxPriority; - #if ( configUSE_MUTEXES == 1 ) - { - /* Only change the priority being used if the task is not - currently using an inherited priority. */ - if( pxTCB->uxBasePriority == pxTCB->uxPriority ) - { - pxTCB->uxPriority = uxNewPriority; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + #if ( configUSE_MUTEXES == 1 ) + { + /* Only change the priority being used if the task is not + currently using an inherited priority. */ + if( pxTCB->uxBasePriority == pxTCB->uxPriority ) + { + pxTCB->uxPriority = uxNewPriority; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* The base priority gets set whatever. */ - pxTCB->uxBasePriority = uxNewPriority; - } - #else - { - pxTCB->uxPriority = uxNewPriority; - } - #endif + /* The base priority gets set whatever. */ + pxTCB->uxBasePriority = uxNewPriority; + } + #else + { + pxTCB->uxPriority = uxNewPriority; + } + #endif - /* Only reset the event list item value if the value is not - being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Only reset the event list item value if the value is not + being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* If the task is in the blocked or suspended list we need do - nothing more than change its priority variable. However, if - the task is in a ready list it needs to be removed and placed - in the list appropriate to its new priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* The task is currently in its ready list - remove before - adding it to it's new ready list. As we are in a critical - section we can do this even if the scheduler is suspended. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* It is known that the task is in its ready list so - there is no need to check again and the port level - reset macro can be called directly. */ - portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the task is in the blocked or suspended list we need do + nothing more than change its priority variable. However, if + the task is in a ready list it needs to be removed and placed + in the list appropriate to its new priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* The task is currently in its ready list - remove before + adding it to it's new ready list. As we are in a critical + section we can do this even if the scheduler is suspended. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + there is no need to check again and the port level + reset macro can be called directly. */ + portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xYieldRequired != pdFALSE ) - { - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xYieldRequired != pdFALSE ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Remove compiler warning about unused variables when the port - optimised task selection is not being used. */ - ( void ) uxPriorityUsedOnEntry; - } - } - taskEXIT_CRITICAL(); - } + /* Remove compiler warning about unused variables when the port + optimised task selection is not being used. */ + ( void ) uxPriorityUsedOnEntry; + } + } + taskEXIT_CRITICAL(); + } #endif /* INCLUDE_vTaskPrioritySet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) - void vTaskSuspend( TaskHandle_t xTaskToSuspend ) - { - TCB_t *pxTCB; + void vTaskSuspend( TaskHandle_t xTaskToSuspend ) + { + TCB_t *pxTCB; - taskENTER_CRITICAL(); - { - /* If null is passed in here then it is the running task that is - being suspended. */ - pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the running task that is + being suspended. */ + pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); - traceTASK_SUSPEND( pxTCB ); + traceTASK_SUSPEND( pxTCB ); - /* Remove task from the ready/delayed list and place in the - suspended list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Remove task from the ready/delayed list and place in the + suspended list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Is the task waiting on an event also? */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); + vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); - #if( configUSE_TASK_NOTIFICATIONS == 1 ) - { - if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task was blocked to wait for a notification, but is - now suspended, so no notification was received. */ - pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - } - #endif - } - taskEXIT_CRITICAL(); + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + { + if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task was blocked to wait for a notification, but is + now suspended, so no notification was received. */ + pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + } + #endif + } + taskEXIT_CRITICAL(); - if( xSchedulerRunning != pdFALSE ) - { - /* Reset the next expected unblock time in case it referred to the - task that is now in the Suspended state. */ - taskENTER_CRITICAL(); - { - prvResetNextTaskUnblockTime(); - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xSchedulerRunning != pdFALSE ) + { + /* Reset the next expected unblock time in case it referred to the + task that is now in the Suspended state. */ + taskENTER_CRITICAL(); + { + prvResetNextTaskUnblockTime(); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( pxTCB == pxCurrentTCB ) - { - if( xSchedulerRunning != pdFALSE ) - { - /* The current task has just been suspended. */ - configASSERT( uxSchedulerSuspended == 0 ); - portYIELD_WITHIN_API(); - } - else - { - /* The scheduler is not running, but the task that was pointed - to by pxCurrentTCB has just been suspended and pxCurrentTCB - must be adjusted to point to a different task. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ - { - /* No other tasks are ready, so set pxCurrentTCB back to - NULL so when the next task is created pxCurrentTCB will - be set to point to it no matter what its relative priority - is. */ - pxCurrentTCB = NULL; - } - else - { - vTaskSwitchContext(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( pxTCB == pxCurrentTCB ) + { + if( xSchedulerRunning != pdFALSE ) + { + /* The current task has just been suspended. */ + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + /* The scheduler is not running, but the task that was pointed + to by pxCurrentTCB has just been suspended and pxCurrentTCB + must be adjusted to point to a different task. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ + { + /* No other tasks are ready, so set pxCurrentTCB back to + NULL so when the next task is created pxCurrentTCB will + be set to point to it no matter what its relative priority + is. */ + pxCurrentTCB = NULL; + } + else + { + vTaskSwitchContext(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskSuspend */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) - static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) - { - BaseType_t xReturn = pdFALSE; - const TCB_t * const pxTCB = xTask; + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) + { + BaseType_t xReturn = pdFALSE; + const TCB_t * const pxTCB = xTask; - /* Accesses xPendingReadyList so must be called from a critical - section. */ + /* Accesses xPendingReadyList so must be called from a critical + section. */ - /* It does not make sense to check if the calling task is suspended. */ - configASSERT( xTask ); + /* It does not make sense to check if the calling task is suspended. */ + configASSERT( xTask ); - /* Is the task being resumed actually in the suspended list? */ - if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - /* Has the task already been resumed from within an ISR? */ - if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) - { - /* Is it in the suspended list because it is in the Suspended - state, or because is is blocked with no timeout? */ - if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ - { - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task being resumed actually in the suspended list? */ + if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* Has the task already been resumed from within an ISR? */ + if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) + { + /* Is it in the suspended list because it is in the Suspended + state, or because is is blocked with no timeout? */ + if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ + { + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + return xReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ #endif /* INCLUDE_vTaskSuspend */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) - void vTaskResume( TaskHandle_t xTaskToResume ) - { - TCB_t * const pxTCB = xTaskToResume; + void vTaskResume( TaskHandle_t xTaskToResume ) + { + TCB_t * const pxTCB = xTaskToResume; - /* It does not make sense to resume the calling task. */ - configASSERT( xTaskToResume ); + /* It does not make sense to resume the calling task. */ + configASSERT( xTaskToResume ); - /* The parameter cannot be NULL as it is impossible to resume the - currently executing task. */ - if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) - { - taskENTER_CRITICAL(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME( pxTCB ); + /* The parameter cannot be NULL as it is impossible to resume the + currently executing task. */ + if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) + { + taskENTER_CRITICAL(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME( pxTCB ); - /* The ready list can be accessed even if the scheduler is - suspended because this is inside a critical section. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); + /* The ready list can be accessed even if the scheduler is + suspended because this is inside a critical section. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); - /* A higher priority task may have just been resumed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - /* This yield may not cause the task just resumed to run, - but will leave the lists in the correct state for the - next yield. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* A higher priority task may have just been resumed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + /* This yield may not cause the task just resumed to run, + but will leave the lists in the correct state for the + next yield. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* INCLUDE_vTaskSuspend */ @@ -1894,72 +1894,72 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) #if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) - BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) - { - BaseType_t xYieldRequired = pdFALSE; - TCB_t * const pxTCB = xTaskToResume; - UBaseType_t uxSavedInterruptStatus; + BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) + { + BaseType_t xYieldRequired = pdFALSE; + TCB_t * const pxTCB = xTaskToResume; + UBaseType_t uxSavedInterruptStatus; - configASSERT( xTaskToResume ); + configASSERT( xTaskToResume ); - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - https://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) - { - traceTASK_RESUME_FROM_ISR( pxTCB ); + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME_FROM_ISR( pxTCB ); - /* Check the ready lists can be accessed. */ - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Ready lists can be accessed so move the task from the - suspended list to the ready list directly. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Check the ready lists can be accessed. */ + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Ready lists can be accessed so move the task from the + suspended list to the ready list directly. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed or ready lists cannot be accessed so the task - is held in the pending ready list until the scheduler is - unsuspended. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed or ready lists cannot be accessed so the task + is held in the pending ready list until the scheduler is + unsuspended. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xYieldRequired; - } + return xYieldRequired; + } #endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ /*-----------------------------------------------------------*/ @@ -1968,205 +1968,205 @@ void vTaskStartScheduler( void ) { BaseType_t xReturn; - /* Add the idle task at the lowest priority. */ - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t *pxIdleTaskTCBBuffer = NULL; - StackType_t *pxIdleTaskStackBuffer = NULL; - uint32_t ulIdleTaskStackSize; + /* Add the idle task at the lowest priority. */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t *pxIdleTaskTCBBuffer = NULL; + StackType_t *pxIdleTaskStackBuffer = NULL; + uint32_t ulIdleTaskStackSize; - /* The Idle task is created using user provided RAM - obtain the - address of the RAM then create the idle task. */ - vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); - xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, - configIDLE_TASK_NAME, - ulIdleTaskStackSize, - ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ - portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ - pxIdleTaskStackBuffer, - pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + /* The Idle task is created using user provided RAM - obtain the + address of the RAM then create the idle task. */ + vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); + xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, + configIDLE_TASK_NAME, + ulIdleTaskStackSize, + ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + pxIdleTaskStackBuffer, + pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - if( xIdleTaskHandle != NULL ) - { - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - #else - { - /* The Idle task is being created using dynamically allocated RAM. */ - xReturn = xTaskCreate( prvIdleTask, - configIDLE_TASK_NAME, - configMINIMAL_STACK_SIZE, - ( void * ) NULL, - portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ - &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ + if( xIdleTaskHandle != NULL ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + #else + { + /* The Idle task is being created using dynamically allocated RAM. */ + xReturn = xTaskCreate( prvIdleTask, + configIDLE_TASK_NAME, + configMINIMAL_STACK_SIZE, + ( void * ) NULL, + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ - #if ( configUSE_TIMERS == 1 ) - { - if( xReturn == pdPASS ) - { - xReturn = xTimerCreateTimerTask(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TIMERS */ + #if ( configUSE_TIMERS == 1 ) + { + if( xReturn == pdPASS ) + { + xReturn = xTimerCreateTimerTask(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TIMERS */ - if( xReturn == pdPASS ) - { - /* freertos_tasks_c_additions_init() should only be called if the user - definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is - the only macro called by the function. */ - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - { - freertos_tasks_c_additions_init(); - } - #endif + if( xReturn == pdPASS ) + { + /* freertos_tasks_c_additions_init() should only be called if the user + definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is + the only macro called by the function. */ + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + { + freertos_tasks_c_additions_init(); + } + #endif - /* Interrupts are turned off here, to ensure a tick does not occur - before or during the call to xPortStartScheduler(). The stacks of - the created tasks contain a status word with interrupts switched on - so interrupts will automatically get re-enabled when the first task - starts to run. */ - portDISABLE_INTERRUPTS(); + /* Interrupts are turned off here, to ensure a tick does not occur + before or during the call to xPortStartScheduler(). The stacks of + the created tasks contain a status word with interrupts switched on + so interrupts will automatically get re-enabled when the first task + starts to run. */ + portDISABLE_INTERRUPTS(); - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - structure specific to the task that will run first. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + structure specific to the task that will run first. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ - xNextTaskUnblockTime = portMAX_DELAY; - xSchedulerRunning = pdTRUE; - xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; + xNextTaskUnblockTime = portMAX_DELAY; + xSchedulerRunning = pdTRUE; + xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; - /* If configGENERATE_RUN_TIME_STATS is defined then the following - macro must be defined to configure the timer/counter used to generate - the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS - is set to 0 and the following line fails to build then ensure you do not - have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your - FreeRTOSConfig.h file. */ - portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); + /* If configGENERATE_RUN_TIME_STATS is defined then the following + macro must be defined to configure the timer/counter used to generate + the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS + is set to 0 and the following line fails to build then ensure you do not + have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your + FreeRTOSConfig.h file. */ + portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); - traceTASK_SWITCHED_IN(); + traceTASK_SWITCHED_IN(); - /* Setting up the timer tick is hardware specific and thus in the - portable interface. */ - if( xPortStartScheduler() != pdFALSE ) - { - /* Should not reach here as if the scheduler is running the - function will not return. */ - } - else - { - /* Should only reach here if a task calls xTaskEndScheduler(). */ - } - } - else - { - /* This line will only be reached if the kernel could not be started, - because there was not enough FreeRTOS heap to create the idle task - or the timer task. */ - configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); - } + /* Setting up the timer tick is hardware specific and thus in the + portable interface. */ + if( xPortStartScheduler() != pdFALSE ) + { + /* Should not reach here as if the scheduler is running the + function will not return. */ + } + else + { + /* Should only reach here if a task calls xTaskEndScheduler(). */ + } + } + else + { + /* This line will only be reached if the kernel could not be started, + because there was not enough FreeRTOS heap to create the idle task + or the timer task. */ + configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); + } - /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, - meaning xIdleTaskHandle is not used anywhere else. */ - ( void ) xIdleTaskHandle; + /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, + meaning xIdleTaskHandle is not used anywhere else. */ + ( void ) xIdleTaskHandle; } /*-----------------------------------------------------------*/ void vTaskEndScheduler( void ) { - /* Stop the scheduler interrupts and call the portable scheduler end - routine so the original ISRs can be restored if necessary. The port - layer must ensure interrupts enable bit is left in the correct state. */ - portDISABLE_INTERRUPTS(); - xSchedulerRunning = pdFALSE; - vPortEndScheduler(); + /* Stop the scheduler interrupts and call the portable scheduler end + routine so the original ISRs can be restored if necessary. The port + layer must ensure interrupts enable bit is left in the correct state. */ + portDISABLE_INTERRUPTS(); + xSchedulerRunning = pdFALSE; + vPortEndScheduler(); } /*----------------------------------------------------------*/ void vTaskSuspendAll( void ) { - /* A critical section is not required as the variable is of type - BaseType_t. Please read Richard Barry's reply in the following link to a - post in the FreeRTOS support forum before reporting this as a bug! - - http://goo.gl/wu4acr */ - ++uxSchedulerSuspended; - portMEMORY_BARRIER(); + /* A critical section is not required as the variable is of type + BaseType_t. Please read Richard Barry's reply in the following link to a + post in the FreeRTOS support forum before reporting this as a bug! - + http://goo.gl/wu4acr */ + ++uxSchedulerSuspended; + portMEMORY_BARRIER(); } /*----------------------------------------------------------*/ #if ( configUSE_TICKLESS_IDLE != 0 ) - static TickType_t prvGetExpectedIdleTime( void ) - { - TickType_t xReturn; - UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; + static TickType_t prvGetExpectedIdleTime( void ) + { + TickType_t xReturn; + UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; - /* uxHigherPriorityReadyTasks takes care of the case where - configUSE_PREEMPTION is 0, so there may be tasks above the idle priority - task that are in the Ready state, even though the idle task is - running. */ - #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) - { - if( uxTopReadyPriority > tskIDLE_PRIORITY ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #else - { - const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; + /* uxHigherPriorityReadyTasks takes care of the case where + configUSE_PREEMPTION is 0, so there may be tasks above the idle priority + task that are in the Ready state, even though the idle task is + running. */ + #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + { + if( uxTopReadyPriority > tskIDLE_PRIORITY ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #else + { + const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; - /* When port optimised task selection is used the uxTopReadyPriority - variable is used as a bit map. If bits other than the least - significant bit are set then there are tasks that have a priority - above the idle priority that are in the Ready state. This takes - care of the case where the co-operative scheduler is in use. */ - if( uxTopReadyPriority > uxLeastSignificantBit ) - { - uxHigherPriorityReadyTasks = pdTRUE; - } - } - #endif + /* When port optimised task selection is used the uxTopReadyPriority + variable is used as a bit map. If bits other than the least + significant bit are set then there are tasks that have a priority + above the idle priority that are in the Ready state. This takes + care of the case where the co-operative scheduler is in use. */ + if( uxTopReadyPriority > uxLeastSignificantBit ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #endif - if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) - { - xReturn = 0; - } - else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) - { - /* There are other idle priority tasks in the ready state. If - time slicing is used then the very next tick interrupt must be - processed. */ - xReturn = 0; - } - else if( uxHigherPriorityReadyTasks != pdFALSE ) - { - /* There are tasks in the Ready state that have a priority above the - idle priority. This path can only be reached if - configUSE_PREEMPTION is 0. */ - xReturn = 0; - } - else - { - xReturn = xNextTaskUnblockTime - xTickCount; - } + if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) + { + xReturn = 0; + } + else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) + { + /* There are other idle priority tasks in the ready state. If + time slicing is used then the very next tick interrupt must be + processed. */ + xReturn = 0; + } + else if( uxHigherPriorityReadyTasks != pdFALSE ) + { + /* There are tasks in the Ready state that have a priority above the + idle priority. This path can only be reached if + configUSE_PREEMPTION is 0. */ + xReturn = 0; + } + else + { + xReturn = xNextTaskUnblockTime - xTickCount; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_TICKLESS_IDLE */ /*----------------------------------------------------------*/ @@ -2176,108 +2176,108 @@ BaseType_t xTaskResumeAll( void ) TCB_t *pxTCB = NULL; BaseType_t xAlreadyYielded = pdFALSE; - /* If uxSchedulerSuspended is zero then this function does not match a - previous call to vTaskSuspendAll(). */ - configASSERT( uxSchedulerSuspended ); + /* If uxSchedulerSuspended is zero then this function does not match a + previous call to vTaskSuspendAll(). */ + configASSERT( uxSchedulerSuspended ); - /* It is possible that an ISR caused a task to be removed from an event - list while the scheduler was suspended. If this was the case then the - removed task will have been added to the xPendingReadyList. Once the - scheduler has been resumed it is safe to move all the pending ready - tasks from this list into their appropriate ready list. */ - taskENTER_CRITICAL(); - { - --uxSchedulerSuspended; + /* It is possible that an ISR caused a task to be removed from an event + list while the scheduler was suspended. If this was the case then the + removed task will have been added to the xPendingReadyList. Once the + scheduler has been resumed it is safe to move all the pending ready + tasks from this list into their appropriate ready list. */ + taskENTER_CRITICAL(); + { + --uxSchedulerSuspended; - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) - { - /* Move any readied tasks from the pending list into the - appropriate ready list. */ - while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) - { - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) + { + /* Move any readied tasks from the pending list into the + appropriate ready list. */ + while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); - /* If the moved task has a priority higher than the current - task then a yield must be performed. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* If the moved task has a priority higher than the current + task then a yield must be performed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - if( pxTCB != NULL ) - { - /* A task was unblocked while the scheduler was suspended, - which may have prevented the next unblock time from being - re-calculated, in which case re-calculate it now. Mainly - important for low power tickless implementations, where - this can prevent an unnecessary exit from low power - state. */ - prvResetNextTaskUnblockTime(); - } + if( pxTCB != NULL ) + { + /* A task was unblocked while the scheduler was suspended, + which may have prevented the next unblock time from being + re-calculated, in which case re-calculate it now. Mainly + important for low power tickless implementations, where + this can prevent an unnecessary exit from low power + state. */ + prvResetNextTaskUnblockTime(); + } - /* If any ticks occurred while the scheduler was suspended then - they should be processed now. This ensures the tick count does - not slip, and that any delayed tasks are resumed at the correct - time. */ - { - UBaseType_t uxPendedCounts = uxPendedTicks; /* Non-volatile copy. */ + /* If any ticks occurred while the scheduler was suspended then + they should be processed now. This ensures the tick count does + not slip, and that any delayed tasks are resumed at the correct + time. */ + { + UBaseType_t uxPendedCounts = uxPendedTicks; /* Non-volatile copy. */ - if( uxPendedCounts > ( UBaseType_t ) 0U ) - { - do - { - if( xTaskIncrementTick() != pdFALSE ) - { - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - --uxPendedCounts; - } while( uxPendedCounts > ( UBaseType_t ) 0U ); + if( uxPendedCounts > ( UBaseType_t ) 0U ) + { + do + { + if( xTaskIncrementTick() != pdFALSE ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --uxPendedCounts; + } while( uxPendedCounts > ( UBaseType_t ) 0U ); - uxPendedTicks = 0; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + uxPendedTicks = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - if( xYieldPending != pdFALSE ) - { - #if( configUSE_PREEMPTION != 0 ) - { - xAlreadyYielded = pdTRUE; - } - #endif - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + if( xYieldPending != pdFALSE ) + { + #if( configUSE_PREEMPTION != 0 ) + { + xAlreadyYielded = pdTRUE; + } + #endif + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - return xAlreadyYielded; + return xAlreadyYielded; } /*-----------------------------------------------------------*/ @@ -2285,27 +2285,27 @@ TickType_t xTaskGetTickCount( void ) { TickType_t xTicks; - /* Critical section required if running on a 16 bit processor. */ - portTICK_TYPE_ENTER_CRITICAL(); - { - xTicks = xTickCount; - } - portTICK_TYPE_EXIT_CRITICAL(); + /* Critical section required if running on a 16 bit processor. */ + portTICK_TYPE_ENTER_CRITICAL(); + { + xTicks = xTickCount; + } + portTICK_TYPE_EXIT_CRITICAL(); - return xTicks; + return xTicks; } BaseType_t xTaskGetTickCount2( TickType_t *ticks, BaseType_t *overflow ) { //FIXME TODO potential BUG for TICK count - portTICK_TYPE_ENTER_CRITICAL(); - { - *ticks = xTickCount; + portTICK_TYPE_ENTER_CRITICAL(); + { + *ticks = xTickCount; *overflow = xNumOfOverflows; - } - portTICK_TYPE_EXIT_CRITICAL(); + } + portTICK_TYPE_EXIT_CRITICAL(); - return pdTRUE; + return pdTRUE; } /*-----------------------------------------------------------*/ @@ -2314,37 +2314,37 @@ TickType_t xTaskGetTickCountFromISR( void ) TickType_t xReturn; UBaseType_t uxSavedInterruptStatus; - /* RTOS ports that support interrupt nesting have the concept of a maximum - system call (or maximum API call) interrupt priority. Interrupts that are - above the maximum system call priority are kept permanently enabled, even - when the RTOS kernel is in a critical section, but cannot make any calls to - FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h - then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has been - assigned a priority above the configured maximum system call priority. - Only FreeRTOS functions that end in FromISR can be called from interrupts - that have been assigned a priority at or (logically) below the maximum - system call interrupt priority. FreeRTOS maintains a separate interrupt - safe API to ensure interrupt entry is as fast and as simple as possible. - More information (albeit Cortex-M specific) is provided on the following - link: https://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); - { - xReturn = xTickCount; - } - portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = xTickCount; + } + portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ UBaseType_t uxTaskGetNumberOfTasks( void ) { - /* A critical section is not required because the variables are of type - BaseType_t. */ - return uxCurrentNumberOfTasks; + /* A critical section is not required because the variables are of type + BaseType_t. */ + return uxCurrentNumberOfTasks; } /*-----------------------------------------------------------*/ @@ -2352,230 +2352,230 @@ char *pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char t { TCB_t *pxTCB; - /* If null is passed in here then the name of the calling task is being - queried. */ - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - configASSERT( pxTCB ); - return &( pxTCB->pcTaskName[ 0 ] ); + /* If null is passed in here then the name of the calling task is being + queried. */ + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + configASSERT( pxTCB ); + return &( pxTCB->pcTaskName[ 0 ] ); } /*-----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetHandle == 1 ) - static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) - { - TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL; - UBaseType_t x; - char cNextChar; - BaseType_t xBreakLoop; + static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) + { + TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL; + UBaseType_t x; + char cNextChar; + BaseType_t xBreakLoop; - /* This function is called with the scheduler suspended. */ + /* This function is called with the scheduler suspended. */ - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - /* Check each character in the name looking for a match or - mismatch. */ - xBreakLoop = pdFALSE; - for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) - { - cNextChar = pxNextTCB->pcTaskName[ x ]; + /* Check each character in the name looking for a match or + mismatch. */ + xBreakLoop = pdFALSE; + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + cNextChar = pxNextTCB->pcTaskName[ x ]; - if( cNextChar != pcNameToQuery[ x ] ) - { - /* Characters didn't match. */ - xBreakLoop = pdTRUE; - } - else if( cNextChar == ( char ) 0x00 ) - { - /* Both strings terminated, a match must have been - found. */ - pxReturn = pxNextTCB; - xBreakLoop = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( cNextChar != pcNameToQuery[ x ] ) + { + /* Characters didn't match. */ + xBreakLoop = pdTRUE; + } + else if( cNextChar == ( char ) 0x00 ) + { + /* Both strings terminated, a match must have been + found. */ + pxReturn = pxNextTCB; + xBreakLoop = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - if( xBreakLoop != pdFALSE ) - { - break; - } - } + if( xBreakLoop != pdFALSE ) + { + break; + } + } - if( pxReturn != NULL ) - { - /* The handle has been found. */ - break; - } + if( pxReturn != NULL ) + { + /* The handle has been found. */ + break; + } - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return pxReturn; - } + return pxReturn; + } #endif /* INCLUDE_xTaskGetHandle */ /*-----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetHandle == 1 ) - TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - { - UBaseType_t uxQueue = configMAX_PRIORITIES; - TCB_t* pxTCB; + TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t uxQueue = configMAX_PRIORITIES; + TCB_t* pxTCB; - /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ - configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); + /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ + configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); - vTaskSuspendAll(); - { - /* Search the ready lists. */ - do - { - uxQueue--; - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); + vTaskSuspendAll(); + { + /* Search the ready lists. */ + do + { + uxQueue--; + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); - if( pxTCB != NULL ) - { - /* Found the handle. */ - break; - } + if( pxTCB != NULL ) + { + /* Found the handle. */ + break; + } - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - /* Search the delayed lists. */ - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); - } + /* Search the delayed lists. */ + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); + } - if( pxTCB == NULL ) - { - pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); - } + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); + } - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the suspended list. */ - pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); - } - } - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the suspended list. */ + pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); + } + } + #endif - #if( INCLUDE_vTaskDelete == 1 ) - { - if( pxTCB == NULL ) - { - /* Search the deleted list. */ - pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); - } - } - #endif - } - ( void ) xTaskResumeAll(); + #if( INCLUDE_vTaskDelete == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the deleted list. */ + pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); + } + } + #endif + } + ( void ) xTaskResumeAll(); - return pxTCB; - } + return pxTCB; + } #endif /* INCLUDE_xTaskGetHandle */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) - { - UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; + UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) + { + UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; - vTaskSuspendAll(); - { - /* Is there a space in the array for each task in the system? */ - if( uxArraySize >= uxCurrentNumberOfTasks ) - { - /* Fill in an TaskStatus_t structure with information on each - task in the Ready state. */ - do - { - uxQueue--; - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); + vTaskSuspendAll(); + { + /* Is there a space in the array for each task in the system? */ + if( uxArraySize >= uxCurrentNumberOfTasks ) + { + /* Fill in an TaskStatus_t structure with information on each + task in the Ready state. */ + do + { + uxQueue--; + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); - } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - /* Fill in an TaskStatus_t structure with information on each - task in the Blocked state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); + /* Fill in an TaskStatus_t structure with information on each + task in the Blocked state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); - #if( INCLUDE_vTaskDelete == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - each task that has been deleted but not yet cleaned up. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); - } - #endif + #if( INCLUDE_vTaskDelete == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + each task that has been deleted but not yet cleaned up. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); + } + #endif - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* Fill in an TaskStatus_t structure with information on - each task in the Suspended state. */ - uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); - } - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + each task in the Suspended state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); + } + #endif - #if ( configGENERATE_RUN_TIME_STATS == 1) - { - if( pulTotalRunTime != NULL ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); - #else - *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif - } - } - #else - { - if( pulTotalRunTime != NULL ) - { - *pulTotalRunTime = 0; - } - } - #endif - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); + #if ( configGENERATE_RUN_TIME_STATS == 1) + { + if( pulTotalRunTime != NULL ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); + #else + *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + } + } + #else + { + if( pulTotalRunTime != NULL ) + { + *pulTotalRunTime = 0; + } + } + #endif + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); - return uxTask; - } + return uxTask; + } #endif /* configUSE_TRACE_FACILITY */ /*----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) - TaskHandle_t xTaskGetIdleTaskHandle( void ) - { - /* If xTaskGetIdleTaskHandle() is called before the scheduler has been - started, then xIdleTaskHandle will be NULL. */ - configASSERT( ( xIdleTaskHandle != NULL ) ); - return xIdleTaskHandle; - } + TaskHandle_t xTaskGetIdleTaskHandle( void ) + { + /* If xTaskGetIdleTaskHandle() is called before the scheduler has been + started, then xIdleTaskHandle will be NULL. */ + configASSERT( ( xIdleTaskHandle != NULL ) ); + return xIdleTaskHandle; + } #endif /* INCLUDE_xTaskGetIdleTaskHandle */ /*----------------------------------------------------------*/ @@ -2586,145 +2586,145 @@ implementations require configUSE_TICKLESS_IDLE to be set to a value other than 1. */ #if ( configUSE_TICKLESS_IDLE != 0 ) - void vTaskStepTick( const TickType_t xTicksToJump ) - { - /* Correct the tick count value after a period during which the tick - was suppressed. Note this does *not* call the tick hook function for - each stepped tick. */ - configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); - xTickCount += xTicksToJump; - traceINCREASE_TICK_COUNT( xTicksToJump ); - } + void vTaskStepTick( const TickType_t xTicksToJump ) + { + /* Correct the tick count value after a period during which the tick + was suppressed. Note this does *not* call the tick hook function for + each stepped tick. */ + configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); + xTickCount += xTicksToJump; + traceINCREASE_TICK_COUNT( xTicksToJump ); + } #endif /* configUSE_TICKLESS_IDLE */ /*----------------------------------------------------------*/ void vTaskStepTickSafe( const TickType_t xTicksToJump ) { - TCB_t * pxTCB; - TickType_t xTickDelta = ( TickType_t ) 0 - xTickCount; + TCB_t * pxTCB; + TickType_t xTickDelta = ( TickType_t ) 0 - xTickCount; - if( xTicksToJump >= xTickDelta ) - { - for( ;; ) - { - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The delayed list is empty. */ - break; - } - else - { - /* The delayed list is not empty, get the value of the - item at the head of the delayed list. This is the time - at which the task at the head of the delayed list must - be removed from the Blocked state. */ - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + if( xTicksToJump >= xTickDelta ) + { + for( ;; ) + { + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The delayed list is empty. */ + break; + } + else + { + /* The delayed list is not empty, get the value of the + item at the head of the delayed list. This is the time + at which the task at the head of the delayed list must + be removed from the Blocked state. */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - /* It is time to remove the item from the Blocked state. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + /* It is time to remove the item from the Blocked state. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - /* Is the task waiting on an event also? If so remove - it from the event list. */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task waiting on an event also? If so remove + it from the event list. */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Place the unblocked task into the appropriate ready - list. */ - prvAddTaskToReadyList( pxTCB ); - } - } + /* Place the unblocked task into the appropriate ready + list. */ + prvAddTaskToReadyList( pxTCB ); + } + } - taskSWITCH_DELAYED_LISTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + taskSWITCH_DELAYED_LISTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - xTickCount += xTicksToJump; - traceINCREASE_TICK_COUNT( xTicksToJump ); + xTickCount += xTicksToJump; + traceINCREASE_TICK_COUNT( xTicksToJump ); } /*-----------------------------------------------------------*/ #if ( INCLUDE_xTaskAbortDelay == 1 ) - BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) - { - TCB_t *pxTCB = xTask; - BaseType_t xReturn; + BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) + { + TCB_t *pxTCB = xTask; + BaseType_t xReturn; - configASSERT( pxTCB ); + configASSERT( pxTCB ); - vTaskSuspendAll(); - { - /* A task can only be prematurely removed from the Blocked state if - it is actually in the Blocked state. */ - if( eTaskGetState( xTask ) == eBlocked ) - { - xReturn = pdPASS; + vTaskSuspendAll(); + { + /* A task can only be prematurely removed from the Blocked state if + it is actually in the Blocked state. */ + if( eTaskGetState( xTask ) == eBlocked ) + { + xReturn = pdPASS; - /* Remove the reference to the task from the blocked list. An - interrupt won't touch the xStateListItem because the - scheduler is suspended. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + /* Remove the reference to the task from the blocked list. An + interrupt won't touch the xStateListItem because the + scheduler is suspended. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - /* Is the task waiting on an event also? If so remove it from - the event list too. Interrupts can touch the event list item, - even though the scheduler is suspended, so a critical section - is used. */ - taskENTER_CRITICAL(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - pxTCB->ucDelayAborted = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* Is the task waiting on an event also? If so remove it from + the event list too. Interrupts can touch the event list item, + even though the scheduler is suspended, so a critical section + is used. */ + taskENTER_CRITICAL(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + pxTCB->ucDelayAborted = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - /* Place the unblocked task into the appropriate ready list. */ - prvAddTaskToReadyList( pxTCB ); + /* Place the unblocked task into the appropriate ready list. */ + prvAddTaskToReadyList( pxTCB ); - /* A task being unblocked cannot cause an immediate context - switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should only be - performed if the unblocked task has a priority that is - equal to or higher than the currently executing task. */ - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Pend the yield to be performed when the scheduler - is unsuspended. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - else - { - xReturn = pdFAIL; - } - } - ( void ) xTaskResumeAll(); + /* A task being unblocked cannot cause an immediate context + switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should only be + performed if the unblocked task has a priority that is + equal to or higher than the currently executing task. */ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Pend the yield to be performed when the scheduler + is unsuspended. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + else + { + xReturn = pdFAIL; + } + } + ( void ) xTaskResumeAll(); - return xReturn; - } + return xReturn; + } #endif /* INCLUDE_xTaskAbortDelay */ /*----------------------------------------------------------*/ @@ -2736,435 +2736,435 @@ TickType_t xItemValue; BaseType_t xSwitchRequired = pdFALSE; #if 1 - uint32_t tmp; + uint32_t tmp; - /* Do not increment tick if FreeRTOS clock is faster than RTC clock */ - extern int bl_sys_time_sync_state(uint32_t *xTicksToJump); - if( bl_sys_time_sync_state(&tmp) == 0 ) - { - return pdFALSE; - } + /* Do not increment tick if FreeRTOS clock is faster than RTC clock */ + extern int bl_sys_time_sync_state(uint32_t *xTicksToJump); + if( bl_sys_time_sync_state(&tmp) == 0 ) + { + return pdFALSE; + } #endif - /* Called by the portable layer each time a tick interrupt occurs. - Increments the tick then checks to see if the new tick value will cause any - tasks to be unblocked. */ - traceTASK_INCREMENT_TICK( xTickCount ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - /* Minor optimisation. The tick count cannot change in this - block. */ - const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; + /* Called by the portable layer each time a tick interrupt occurs. + Increments the tick then checks to see if the new tick value will cause any + tasks to be unblocked. */ + traceTASK_INCREMENT_TICK( xTickCount ); + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Minor optimisation. The tick count cannot change in this + block. */ + const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; - /* Increment the RTOS tick, switching the delayed and overflowed - delayed lists if it wraps to 0. */ - xTickCount = xConstTickCount; + /* Increment the RTOS tick, switching the delayed and overflowed + delayed lists if it wraps to 0. */ + xTickCount = xConstTickCount; - if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ - { - taskSWITCH_DELAYED_LISTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ + { + taskSWITCH_DELAYED_LISTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* See if this tick has made a timeout expire. Tasks are stored in - the queue in the order of their wake time - meaning once one task - has been found whose block time has not expired there is no need to - look any further down the list. */ - if( xConstTickCount >= xNextTaskUnblockTime ) - { - for( ;; ) - { - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The delayed list is empty. Set xNextTaskUnblockTime - to the maximum possible value so it is extremely - unlikely that the - if( xTickCount >= xNextTaskUnblockTime ) test will pass - next time through. */ - xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - break; - } - else - { - /* The delayed list is not empty, get the value of the - item at the head of the delayed list. This is the time - at which the task at the head of the delayed list must - be removed from the Blocked state. */ - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); + /* See if this tick has made a timeout expire. Tasks are stored in + the queue in the order of their wake time - meaning once one task + has been found whose block time has not expired there is no need to + look any further down the list. */ + if( xConstTickCount >= xNextTaskUnblockTime ) + { + for( ;; ) + { + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The delayed list is empty. Set xNextTaskUnblockTime + to the maximum possible value so it is extremely + unlikely that the + if( xTickCount >= xNextTaskUnblockTime ) test will pass + next time through. */ + xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + break; + } + else + { + /* The delayed list is not empty, get the value of the + item at the head of the delayed list. This is the time + at which the task at the head of the delayed list must + be removed from the Blocked state. */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); - if( xConstTickCount < xItemValue ) - { - /* It is not time to unblock this item yet, but the - item value is the time at which the task at the head - of the blocked list must be removed from the Blocked - state - so record the item value in - xNextTaskUnblockTime. */ - xNextTaskUnblockTime = xItemValue; - break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xConstTickCount < xItemValue ) + { + /* It is not time to unblock this item yet, but the + item value is the time at which the task at the head + of the blocked list must be removed from the Blocked + state - so record the item value in + xNextTaskUnblockTime. */ + xNextTaskUnblockTime = xItemValue; + break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* It is time to remove the item from the Blocked state. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + /* It is time to remove the item from the Blocked state. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - /* Is the task waiting on an event also? If so remove - it from the event list. */ - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Is the task waiting on an event also? If so remove + it from the event list. */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Place the unblocked task into the appropriate ready - list. */ - prvAddTaskToReadyList( pxTCB ); + /* Place the unblocked task into the appropriate ready + list. */ + prvAddTaskToReadyList( pxTCB ); - /* A task being unblocked cannot cause an immediate - context switch if preemption is turned off. */ - #if ( configUSE_PREEMPTION == 1 ) - { - /* Preemption is on, but a context switch should - only be performed if the unblocked task has a - priority that is equal to or higher than the - currently executing task. */ - if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ - } - } - } + /* A task being unblocked cannot cause an immediate + context switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should + only be performed if the unblocked task has a + priority that is equal to or higher than the + currently executing task. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + } + } - /* Tasks of equal priority to the currently running task will share - processing time (time slice) if preemption is on, and the application - writer has not explicitly turned time slicing off. */ - #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) - { - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ + /* Tasks of equal priority to the currently running task will share + processing time (time slice) if preemption is on, and the application + writer has not explicitly turned time slicing off. */ + #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) + { + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ - #if ( configUSE_TICK_HOOK == 1 ) - { - /* Guard against the tick hook being called when the pended tick - count is being unwound (when the scheduler is being unlocked). */ - if( uxPendedTicks == ( UBaseType_t ) 0U ) - { - vApplicationTickHook(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICK_HOOK */ - } - else - { - ++uxPendedTicks; + #if ( configUSE_TICK_HOOK == 1 ) + { + /* Guard against the tick hook being called when the pended tick + count is being unwound (when the scheduler is being unlocked). */ + if( uxPendedTicks == ( UBaseType_t ) 0U ) + { + vApplicationTickHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICK_HOOK */ + } + else + { + ++uxPendedTicks; - /* The tick hook gets called at regular intervals, even if the - scheduler is locked. */ - #if ( configUSE_TICK_HOOK == 1 ) - { - vApplicationTickHook(); - } - #endif - } + /* The tick hook gets called at regular intervals, even if the + scheduler is locked. */ + #if ( configUSE_TICK_HOOK == 1 ) + { + vApplicationTickHook(); + } + #endif + } - #if ( configUSE_PREEMPTION == 1 ) - { - if( xYieldPending != pdFALSE ) - { - xSwitchRequired = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_PREEMPTION */ + #if ( configUSE_PREEMPTION == 1 ) + { + if( xYieldPending != pdFALSE ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ - return xSwitchRequired; + return xSwitchRequired; } /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) - { - TCB_t *xTCB; + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) + { + TCB_t *xTCB; - /* If xTask is NULL then it is the task hook of the calling task that is - getting set. */ - if( xTask == NULL ) - { - xTCB = ( TCB_t * ) pxCurrentTCB; - } - else - { - xTCB = xTask; - } + /* If xTask is NULL then it is the task hook of the calling task that is + getting set. */ + if( xTask == NULL ) + { + xTCB = ( TCB_t * ) pxCurrentTCB; + } + else + { + xTCB = xTask; + } - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - { - xTCB->pxTaskTag = pxHookFunction; - } - taskEXIT_CRITICAL(); - } + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xTCB->pxTaskTag = pxHookFunction; + } + taskEXIT_CRITICAL(); + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - TaskHookFunction_t xReturn; + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + TaskHookFunction_t xReturn; - /* If xTask is NULL then set the calling task's hook. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - taskENTER_CRITICAL(); - { - xReturn = pxTCB->pxTaskTag; - } - taskEXIT_CRITICAL(); + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xReturn = pxTCB->pxTaskTag; + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - TaskHookFunction_t xReturn; - UBaseType_t uxSavedInterruptStatus; + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + TaskHookFunction_t xReturn; + UBaseType_t uxSavedInterruptStatus; - /* If xTask is NULL then set the calling task's hook. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); - /* Save the hook function in the TCB. A critical section is required as - the value can be accessed from an interrupt. */ - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - xReturn = pxTCB->pxTaskTag; - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = pxTCB->pxTaskTag; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; - } + return xReturn; + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) - BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) - { - TCB_t *xTCB; - BaseType_t xReturn; + BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) + { + TCB_t *xTCB; + BaseType_t xReturn; - /* If xTask is NULL then we are calling our own task hook. */ - if( xTask == NULL ) - { - xTCB = pxCurrentTCB; - } - else - { - xTCB = xTask; - } + /* If xTask is NULL then we are calling our own task hook. */ + if( xTask == NULL ) + { + xTCB = pxCurrentTCB; + } + else + { + xTCB = xTask; + } - if( xTCB->pxTaskTag != NULL ) - { - xReturn = xTCB->pxTaskTag( pvParameter ); - } - else - { - xReturn = pdFAIL; - } + if( xTCB->pxTaskTag != NULL ) + { + xReturn = xTCB->pxTaskTag( pvParameter ); + } + else + { + xReturn = pdFAIL; + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ void vTaskSwitchContext( void ) { - if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) - { - /* The scheduler is currently suspended - do not allow a context - switch. */ - xYieldPending = pdTRUE; - } - else - { - xYieldPending = pdFALSE; - traceTASK_SWITCHED_OUT(); + if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) + { + /* The scheduler is currently suspended - do not allow a context + switch. */ + xYieldPending = pdTRUE; + } + else + { + xYieldPending = pdFALSE; + traceTASK_SWITCHED_OUT(); - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE - portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); - #else - ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); - #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); + #else + ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif - /* Add the amount of time the task has been running to the - accumulated time so far. The time the task started running was - stored in ulTaskSwitchedInTime. Note that there is no overflow - protection here so count values are only valid until the timer - overflows. The guard against negative values is to protect - against suspect run time stat counter implementations - which - are provided by the application, not the kernel. */ - if( ulTotalRunTime > ulTaskSwitchedInTime ) - { - pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - ulTaskSwitchedInTime = ulTotalRunTime; - } - #endif /* configGENERATE_RUN_TIME_STATS */ + /* Add the amount of time the task has been running to the + accumulated time so far. The time the task started running was + stored in ulTaskSwitchedInTime. Note that there is no overflow + protection here so count values are only valid until the timer + overflows. The guard against negative values is to protect + against suspect run time stat counter implementations - which + are provided by the application, not the kernel. */ + if( ulTotalRunTime > ulTaskSwitchedInTime ) + { + pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + ulTaskSwitchedInTime = ulTotalRunTime; + } + #endif /* configGENERATE_RUN_TIME_STATS */ - /* Check for stack overflow, if configured. */ - taskCHECK_FOR_STACK_OVERFLOW(); + /* Check for stack overflow, if configured. */ + taskCHECK_FOR_STACK_OVERFLOW(); - /* Before the currently running task is switched out, save its errno. */ - #if( configUSE_POSIX_ERRNO == 1 ) - { - pxCurrentTCB->iTaskErrno = FreeRTOS_errno; - } - #endif + /* Before the currently running task is switched out, save its errno. */ + #if( configUSE_POSIX_ERRNO == 1 ) + { + pxCurrentTCB->iTaskErrno = FreeRTOS_errno; + } + #endif - /* Select a new task to run using either the generic C or port - optimised asm code. */ - taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - traceTASK_SWITCHED_IN(); + /* Select a new task to run using either the generic C or port + optimised asm code. */ + taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + traceTASK_SWITCHED_IN(); - /* After the new task is switched in, update the global errno. */ - #if( configUSE_POSIX_ERRNO == 1 ) - { - FreeRTOS_errno = pxCurrentTCB->iTaskErrno; - } - #endif + /* After the new task is switched in, update the global errno. */ + #if( configUSE_POSIX_ERRNO == 1 ) + { + FreeRTOS_errno = pxCurrentTCB->iTaskErrno; + } + #endif - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - /* Switch Newlib's _impure_ptr variable to point to the _reent - structure specific to this task. */ - _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ - } + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + structure specific to this task. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + } } /*-----------------------------------------------------------*/ void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) { - configASSERT( pxEventList ); + configASSERT( pxEventList ); - /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE - SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ + /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE + SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ - /* Place the event list item of the TCB in the appropriate event list. - This is placed in the list in priority order so the highest priority task - is the first to be woken by the event. The queue that contains the event - list is locked, preventing simultaneous access from interrupts. */ - vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + /* Place the event list item of the TCB in the appropriate event list. + This is placed in the list in priority order so the highest priority task + is the first to be woken by the event. The queue that contains the event + list is locked, preventing simultaneous access from interrupts. */ + vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); } /*-----------------------------------------------------------*/ void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) { - configASSERT( pxEventList ); + configASSERT( pxEventList ); - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event groups implementation. */ - configASSERT( uxSchedulerSuspended != 0 ); + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + the event groups implementation. */ + configASSERT( uxSchedulerSuspended != 0 ); - /* Store the item value in the event list item. It is safe to access the - event list item here as interrupts won't access the event list item of a - task that is not in the Blocked state. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + /* Store the item value in the event list item. It is safe to access the + event list item here as interrupts won't access the event list item of a + task that is not in the Blocked state. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - /* Place the event list item of the TCB at the end of the appropriate event - list. It is safe to access the event list here because it is part of an - event group implementation - and interrupts don't access event groups - directly (instead they access them indirectly by pending function calls to - the task level). */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + /* Place the event list item of the TCB at the end of the appropriate event + list. It is safe to access the event list here because it is part of an + event group implementation - and interrupts don't access event groups + directly (instead they access them indirectly by pending function calls to + the task level). */ + vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); } /*-----------------------------------------------------------*/ #if( configUSE_TIMERS == 1 ) - void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) - { - configASSERT( pxEventList ); + void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) + { + configASSERT( pxEventList ); - /* This function should not be called by application code hence the - 'Restricted' in its name. It is not part of the public API. It is - designed for use by kernel code, and has special calling requirements - - it should be called with the scheduler suspended. */ + /* This function should not be called by application code hence the + 'Restricted' in its name. It is not part of the public API. It is + designed for use by kernel code, and has special calling requirements - + it should be called with the scheduler suspended. */ - /* Place the event list item of the TCB in the appropriate event list. - In this case it is assume that this is the only task that is going to - be waiting on this event list, so the faster vListInsertEnd() function - can be used in place of vListInsert. */ - vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + /* Place the event list item of the TCB in the appropriate event list. + In this case it is assume that this is the only task that is going to + be waiting on this event list, so the faster vListInsertEnd() function + can be used in place of vListInsert. */ + vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); - /* If the task should block indefinitely then set the block time to a - value that will be recognised as an indefinite delay inside the - prvAddCurrentTaskToDelayedList() function. */ - if( xWaitIndefinitely != pdFALSE ) - { - xTicksToWait = portMAX_DELAY; - } + /* If the task should block indefinitely then set the block time to a + value that will be recognised as an indefinite delay inside the + prvAddCurrentTaskToDelayedList() function. */ + if( xWaitIndefinitely != pdFALSE ) + { + xTicksToWait = portMAX_DELAY; + } - traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); - prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); - } + traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); + prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); + } #endif /* configUSE_TIMERS */ /*-----------------------------------------------------------*/ @@ -3174,66 +3174,66 @@ BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) TCB_t *pxUnblockedTCB; BaseType_t xReturn; - /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be - called from a critical section within an ISR. */ + /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be + called from a critical section within an ISR. */ - /* The event list is sorted in priority order, so the first in the list can - be removed as it is known to be the highest priority. Remove the TCB from - the delayed list, and add it to the ready list. + /* The event list is sorted in priority order, so the first in the list can + be removed as it is known to be the highest priority. Remove the TCB from + the delayed list, and add it to the ready list. - If an event is for a queue that is locked then this function will never - get called - the lock count on the queue will get modified instead. This - means exclusive access to the event list is guaranteed here. + If an event is for a queue that is locked then this function will never + get called - the lock count on the queue will get modified instead. This + means exclusive access to the event list is guaranteed here. - This function assumes that a check has already been made to ensure that - pxEventList is not empty. */ - pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); + This function assumes that a check has already been made to ensure that + pxEventList is not empty. */ + pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); - #if( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked on a kernel object then xNextTaskUnblockTime - might be set to the blocked task's time out time. If the task is - unblocked for a reason other than a timeout xNextTaskUnblockTime is - normally left unchanged, because it is automatically reset to a new - value when the tick count equals xNextTaskUnblockTime. However if - tickless idling is used it might be more important to enter sleep mode - at the earliest possible time - so reset xNextTaskUnblockTime here to - ensure it is updated at the earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif - } - else - { - /* The delayed and ready lists cannot be accessed, so hold this task - pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); - } + #if( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + might be set to the blocked task's time out time. If the task is + unblocked for a reason other than a timeout xNextTaskUnblockTime is + normally left unchanged, because it is automatically reset to a new + value when the tick count equals xNextTaskUnblockTime. However if + tickless idling is used it might be more important to enter sleep mode + at the earliest possible time - so reset xNextTaskUnblockTime here to + ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + } + else + { + /* The delayed and ready lists cannot be accessed, so hold this task + pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); + } - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* Return true if the task removed from the event list has a higher - priority than the calling task. This allows the calling task to know if - it should force a context switch now. */ - xReturn = pdTRUE; + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Return true if the task removed from the event list has a higher + priority than the calling task. This allows the calling task to know if + it should force a context switch now. */ + xReturn = pdTRUE; - /* Mark that a yield is pending in case the user is not using the - "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - xReturn = pdFALSE; - } + /* Mark that a yield is pending in case the user is not using the + "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + xReturn = pdFALSE; + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ @@ -3241,53 +3241,53 @@ void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const Tick { TCB_t *pxUnblockedTCB; - /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by - the event flags implementation. */ - configASSERT( uxSchedulerSuspended != pdFALSE ); + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + the event flags implementation. */ + configASSERT( uxSchedulerSuspended != pdFALSE ); - /* Store the new item value in the event list. */ - listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + /* Store the new item value in the event list. */ + listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); - /* Remove the event list form the event flag. Interrupts do not access - event flags. */ - pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - configASSERT( pxUnblockedTCB ); - ( void ) uxListRemove( pxEventListItem ); + /* Remove the event list form the event flag. Interrupts do not access + event flags. */ + pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + ( void ) uxListRemove( pxEventListItem ); - /* Remove the task from the delayed list and add it to the ready list. The - scheduler is suspended so interrupts will not be accessing the ready - lists. */ - ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxUnblockedTCB ); + /* Remove the task from the delayed list and add it to the ready list. The + scheduler is suspended so interrupts will not be accessing the ready + lists. */ + ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); - if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The unblocked task has a priority above that of the calling task, so - a context switch is required. This function is called with the - scheduler suspended so xYieldPending is set so the context switch - occurs immediately that the scheduler is resumed (unsuspended). */ - xYieldPending = pdTRUE; - } + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The unblocked task has a priority above that of the calling task, so + a context switch is required. This function is called with the + scheduler suspended so xYieldPending is set so the context switch + occurs immediately that the scheduler is resumed (unsuspended). */ + xYieldPending = pdTRUE; + } } /*-----------------------------------------------------------*/ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) { - configASSERT( pxTimeOut ); - taskENTER_CRITICAL(); - { - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; - } - taskEXIT_CRITICAL(); + configASSERT( pxTimeOut ); + taskENTER_CRITICAL(); + { + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) { - /* For internal use only as it does not use a critical section. */ - pxTimeOut->xOverflowCount = xNumOfOverflows; - pxTimeOut->xTimeOnEntering = xTickCount; + /* For internal use only as it does not use a critical section. */ + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; } /*-----------------------------------------------------------*/ @@ -3295,106 +3295,106 @@ BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const { BaseType_t xReturn; - configASSERT( pxTimeOut ); - configASSERT( pxTicksToWait ); + configASSERT( pxTimeOut ); + configASSERT( pxTicksToWait ); - taskENTER_CRITICAL(); - { - /* Minor optimisation. The tick count cannot change in this block. */ - const TickType_t xConstTickCount = xTickCount; - const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; + taskENTER_CRITICAL(); + { + /* Minor optimisation. The tick count cannot change in this block. */ + const TickType_t xConstTickCount = xTickCount; + const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; - #if( INCLUDE_xTaskAbortDelay == 1 ) - if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) - { - /* The delay was aborted, which is not the same as a time out, - but has the same result. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - xReturn = pdTRUE; - } - else - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) + { + /* The delay was aborted, which is not the same as a time out, + but has the same result. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + xReturn = pdTRUE; + } + else + #endif - #if ( INCLUDE_vTaskSuspend == 1 ) - if( *pxTicksToWait == portMAX_DELAY ) - { - /* If INCLUDE_vTaskSuspend is set to 1 and the block time - specified is the maximum block time then the task should block - indefinitely, and therefore never time out. */ - xReturn = pdFALSE; - } - else - #endif + #if ( INCLUDE_vTaskSuspend == 1 ) + if( *pxTicksToWait == portMAX_DELAY ) + { + /* If INCLUDE_vTaskSuspend is set to 1 and the block time + specified is the maximum block time then the task should block + indefinitely, and therefore never time out. */ + xReturn = pdFALSE; + } + else + #endif - if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ - { - /* The tick count is greater than the time at which - vTaskSetTimeout() was called, but has also overflowed since - vTaskSetTimeOut() was called. It must have wrapped all the way - around and gone past again. This passed since vTaskSetTimeout() - was called. */ - xReturn = pdTRUE; - } - else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ - { - /* Not a genuine timeout. Adjust parameters for time remaining. */ - *pxTicksToWait -= xElapsedTime; - vTaskInternalSetTimeOutState( pxTimeOut ); - xReturn = pdFALSE; - } - else - { - *pxTicksToWait = 0; - xReturn = pdTRUE; - } - } - taskEXIT_CRITICAL(); + if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ + { + /* The tick count is greater than the time at which + vTaskSetTimeout() was called, but has also overflowed since + vTaskSetTimeOut() was called. It must have wrapped all the way + around and gone past again. This passed since vTaskSetTimeout() + was called. */ + xReturn = pdTRUE; + } + else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ + { + /* Not a genuine timeout. Adjust parameters for time remaining. */ + *pxTicksToWait -= xElapsedTime; + vTaskInternalSetTimeOutState( pxTimeOut ); + xReturn = pdFALSE; + } + else + { + *pxTicksToWait = 0; + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ void vTaskMissedYield( void ) { - xYieldPending = pdTRUE; + xYieldPending = pdTRUE; } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) - { - UBaseType_t uxReturn; - TCB_t const *pxTCB; + UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) + { + UBaseType_t uxReturn; + TCB_t const *pxTCB; - if( xTask != NULL ) - { - pxTCB = xTask; - uxReturn = pxTCB->uxTaskNumber; - } - else - { - uxReturn = 0U; - } + if( xTask != NULL ) + { + pxTCB = xTask; + uxReturn = pxTCB->uxTaskNumber; + } + else + { + uxReturn = 0U; + } - return uxReturn; - } + return uxReturn; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) - { - TCB_t * pxTCB; + void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) + { + TCB_t * pxTCB; - if( xTask != NULL ) - { - pxTCB = xTask; - pxTCB->uxTaskNumber = uxHandle; - } - } + if( xTask != NULL ) + { + pxTCB = xTask; + pxTCB->uxTaskNumber = uxHandle; + } + } #endif /* configUSE_TRACE_FACILITY */ @@ -3411,212 +3411,212 @@ void vTaskMissedYield( void ) */ static portTASK_FUNCTION( prvIdleTask, pvParameters ) { - /* Stop warnings. */ - ( void ) pvParameters; + /* Stop warnings. */ + ( void ) pvParameters; - /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE - SCHEDULER IS STARTED. **/ + /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE + SCHEDULER IS STARTED. **/ - /* In case a task that has a secure context deletes itself, in which case - the idle task is responsible for deleting the task's secure context, if - any. */ - portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); + /* In case a task that has a secure context deletes itself, in which case + the idle task is responsible for deleting the task's secure context, if + any. */ + portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); - for( ;; ) - { - /* See if any tasks have deleted themselves - if so then the idle task - is responsible for freeing the deleted task's TCB and stack. */ - prvCheckTasksWaitingTermination(); + for( ;; ) + { + /* See if any tasks have deleted themselves - if so then the idle task + is responsible for freeing the deleted task's TCB and stack. */ + prvCheckTasksWaitingTermination(); - #if ( configUSE_PREEMPTION == 0 ) - { - /* If we are not using preemption we keep forcing a task switch to - see if any other task has become available. If we are using - preemption we don't need to do this as any task becoming available - will automatically get the processor anyway. */ - taskYIELD(); - } - #endif /* configUSE_PREEMPTION */ + #if ( configUSE_PREEMPTION == 0 ) + { + /* If we are not using preemption we keep forcing a task switch to + see if any other task has become available. If we are using + preemption we don't need to do this as any task becoming available + will automatically get the processor anyway. */ + taskYIELD(); + } + #endif /* configUSE_PREEMPTION */ - #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) - { - /* When using preemption tasks of equal priority will be - timesliced. If a task that is sharing the idle priority is ready - to run then the idle task should yield before the end of the - timeslice. + #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) + { + /* When using preemption tasks of equal priority will be + timesliced. If a task that is sharing the idle priority is ready + to run then the idle task should yield before the end of the + timeslice. - A critical region is not required here as we are just reading from - the list, and an occasional incorrect value will not matter. If - the ready list at the idle priority contains more than one task - then a task other than the idle task is ready to execute. */ - if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) - { - taskYIELD(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ + A critical region is not required here as we are just reading from + the list, and an occasional incorrect value will not matter. If + the ready list at the idle priority contains more than one task + then a task other than the idle task is ready to execute. */ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) + { + taskYIELD(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ - #if ( configUSE_IDLE_HOOK == 1 ) - { - extern void vApplicationIdleHook( void ); + #if ( configUSE_IDLE_HOOK == 1 ) + { + extern void vApplicationIdleHook( void ); - /* Call the user defined function from within the idle task. This - allows the application designer to add background functionality - without the overhead of a separate task. - NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, - CALL A FUNCTION THAT MIGHT BLOCK. */ - vApplicationIdleHook(); - } - #endif /* configUSE_IDLE_HOOK */ + /* Call the user defined function from within the idle task. This + allows the application designer to add background functionality + without the overhead of a separate task. + NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, + CALL A FUNCTION THAT MIGHT BLOCK. */ + vApplicationIdleHook(); + } + #endif /* configUSE_IDLE_HOOK */ - /* This conditional compilation should use inequality to 0, not equality - to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when - user defined low power mode implementations require - configUSE_TICKLESS_IDLE to be set to a value other than 1. */ - #if ( configUSE_TICKLESS_IDLE != 0 ) - { - TickType_t xExpectedIdleTime; + /* This conditional compilation should use inequality to 0, not equality + to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when + user defined low power mode implementations require + configUSE_TICKLESS_IDLE to be set to a value other than 1. */ + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + TickType_t xExpectedIdleTime; - /* It is not desirable to suspend then resume the scheduler on - each iteration of the idle task. Therefore, a preliminary - test of the expected idle time is performed without the - scheduler suspended. The result here is not necessarily - valid. */ - xExpectedIdleTime = prvGetExpectedIdleTime(); + /* It is not desirable to suspend then resume the scheduler on + each iteration of the idle task. Therefore, a preliminary + test of the expected idle time is performed without the + scheduler suspended. The result here is not necessarily + valid. */ + xExpectedIdleTime = prvGetExpectedIdleTime(); - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - vTaskSuspendAll(); - { - /* Now the scheduler is suspended, the expected idle - time can be sampled again, and this time its value can - be used. */ - configASSERT( xNextTaskUnblockTime >= xTickCount ); - xExpectedIdleTime = prvGetExpectedIdleTime(); + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + vTaskSuspendAll(); + { + /* Now the scheduler is suspended, the expected idle + time can be sampled again, and this time its value can + be used. */ + configASSERT( xNextTaskUnblockTime >= xTickCount ); + xExpectedIdleTime = prvGetExpectedIdleTime(); - /* Define the following macro to set xExpectedIdleTime to 0 - if the application does not want - portSUPPRESS_TICKS_AND_SLEEP() to be called. */ - configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); + /* Define the following macro to set xExpectedIdleTime to 0 + if the application does not want + portSUPPRESS_TICKS_AND_SLEEP() to be called. */ + configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); - if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) - { - traceLOW_POWER_IDLE_BEGIN(); - portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); - traceLOW_POWER_IDLE_END(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - ( void ) xTaskResumeAll(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configUSE_TICKLESS_IDLE */ - } + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + traceLOW_POWER_IDLE_BEGIN(); + portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); + traceLOW_POWER_IDLE_END(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICKLESS_IDLE */ + } } /*-----------------------------------------------------------*/ #if( configUSE_TICKLESS_IDLE != 0 ) - eSleepModeStatus eTaskConfirmSleepModeStatus( void ) - { - /* The idle task exists in addition to the application tasks. */ - const UBaseType_t uxNonApplicationTasks = 1; - eSleepModeStatus eReturn = eStandardSleep; + eSleepModeStatus eTaskConfirmSleepModeStatus( void ) + { + /* The idle task exists in addition to the application tasks. */ + const UBaseType_t uxNonApplicationTasks = 1; + eSleepModeStatus eReturn = eStandardSleep; - if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) - { - /* A task was made ready while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else if( xYieldPending != pdFALSE ) - { - /* A yield was pended while the scheduler was suspended. */ - eReturn = eAbortSleep; - } - else - { - /* If all the tasks are in the suspended list (which might mean they - have an infinite block time rather than actually being suspended) - then it is safe to turn all clocks off and just wait for external - interrupts. */ - if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) - { - eReturn = eNoTasksWaitingTimeout; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) + { + /* A task was made ready while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xYieldPending != pdFALSE ) + { + /* A yield was pended while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else + { + /* If all the tasks are in the suspended list (which might mean they + have an infinite block time rather than actually being suspended) + then it is safe to turn all clocks off and just wait for external + interrupts. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) + { + eReturn = eNoTasksWaitingTimeout; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - return eReturn; - } + return eReturn; + } #endif /* configUSE_TICKLESS_IDLE */ /*-----------------------------------------------------------*/ #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) - { - TCB_t *pxTCB; + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) + { + TCB_t *pxTCB; - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToSet ); - pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; - } - } + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToSet ); + pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; + } + } #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ /*-----------------------------------------------------------*/ #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) - void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) - { - void *pvReturn = NULL; - TCB_t *pxTCB; + void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) + { + void *pvReturn = NULL; + TCB_t *pxTCB; - if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) - { - pxTCB = prvGetTCBFromHandle( xTaskToQuery ); - pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; - } - else - { - pvReturn = NULL; - } + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; + } + else + { + pvReturn = NULL; + } - return pvReturn; - } + return pvReturn; + } #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ /*-----------------------------------------------------------*/ #if ( portUSING_MPU_WRAPPERS == 1 ) - void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions ) - { - TCB_t *pxTCB; + void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions ) + { + TCB_t *pxTCB; - /* If null is passed in here then we are modifying the MPU settings of - the calling task. */ - pxTCB = prvGetTCBFromHandle( xTaskToModify ); + /* If null is passed in here then we are modifying the MPU settings of + the calling task. */ + pxTCB = prvGetTCBFromHandle( xTaskToModify ); - vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); - } + vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); + } #endif /* portUSING_MPU_WRAPPERS */ /*-----------------------------------------------------------*/ @@ -3625,332 +3625,332 @@ static void prvInitialiseTaskLists( void ) { UBaseType_t uxPriority; - for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) - { - vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); - } + for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) + { + vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); + } - vListInitialise( &xDelayedTaskList1 ); - vListInitialise( &xDelayedTaskList2 ); - vListInitialise( &xPendingReadyList ); + vListInitialise( &xDelayedTaskList1 ); + vListInitialise( &xDelayedTaskList2 ); + vListInitialise( &xPendingReadyList ); - #if ( INCLUDE_vTaskDelete == 1 ) - { - vListInitialise( &xTasksWaitingTermination ); - } - #endif /* INCLUDE_vTaskDelete */ + #if ( INCLUDE_vTaskDelete == 1 ) + { + vListInitialise( &xTasksWaitingTermination ); + } + #endif /* INCLUDE_vTaskDelete */ - #if ( INCLUDE_vTaskSuspend == 1 ) - { - vListInitialise( &xSuspendedTaskList ); - } - #endif /* INCLUDE_vTaskSuspend */ + #if ( INCLUDE_vTaskSuspend == 1 ) + { + vListInitialise( &xSuspendedTaskList ); + } + #endif /* INCLUDE_vTaskSuspend */ - /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList - using list2. */ - pxDelayedTaskList = &xDelayedTaskList1; - pxOverflowDelayedTaskList = &xDelayedTaskList2; + /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList + using list2. */ + pxDelayedTaskList = &xDelayedTaskList1; + pxOverflowDelayedTaskList = &xDelayedTaskList2; } /*-----------------------------------------------------------*/ static void prvCheckTasksWaitingTermination( void ) { - /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ + /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ - #if ( INCLUDE_vTaskDelete == 1 ) - { - TCB_t *pxTCB; + #if ( INCLUDE_vTaskDelete == 1 ) + { + TCB_t *pxTCB; - /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() - being called too often in the idle task. */ - while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) - { - taskENTER_CRITICAL(); - { - pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - --uxCurrentNumberOfTasks; - --uxDeletedTasksWaitingCleanUp; - } - taskEXIT_CRITICAL(); + /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() + being called too often in the idle task. */ + while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) + { + taskENTER_CRITICAL(); + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + --uxCurrentNumberOfTasks; + --uxDeletedTasksWaitingCleanUp; + } + taskEXIT_CRITICAL(); - prvDeleteTCB( pxTCB ); - } - } - #endif /* INCLUDE_vTaskDelete */ + prvDeleteTCB( pxTCB ); + } + } + #endif /* INCLUDE_vTaskDelete */ } /*-----------------------------------------------------------*/ #if( configUSE_TRACE_FACILITY == 1 ) - void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) - { - TCB_t *pxTCB; + void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) + { + TCB_t *pxTCB; - /* xTask is NULL then get the state of the calling task. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* xTask is NULL then get the state of the calling task. */ + pxTCB = prvGetTCBFromHandle( xTask ); - pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; - pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] ); - pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; - pxTaskStatus->pxStackBase = pxTCB->pxStack; - pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; + pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; + pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] ); + pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; + pxTaskStatus->pxStackBase = pxTCB->pxStack; + pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; - #if ( configUSE_MUTEXES == 1 ) - { - pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; - } - #else - { - pxTaskStatus->uxBasePriority = 0; - } - #endif + #if ( configUSE_MUTEXES == 1 ) + { + pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; + } + #else + { + pxTaskStatus->uxBasePriority = 0; + } + #endif - #if ( configGENERATE_RUN_TIME_STATS == 1 ) - { - pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; - } - #else - { - pxTaskStatus->ulRunTimeCounter = 0; - } - #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; + } + #else + { + pxTaskStatus->ulRunTimeCounter = 0; + } + #endif - /* Obtaining the task state is a little fiddly, so is only done if the - value of eState passed into this function is eInvalid - otherwise the - state is just set to whatever is passed in. */ - if( eState != eInvalid ) - { - if( pxTCB == pxCurrentTCB ) - { - pxTaskStatus->eCurrentState = eRunning; - } - else - { - pxTaskStatus->eCurrentState = eState; + /* Obtaining the task state is a little fiddly, so is only done if the + value of eState passed into this function is eInvalid - otherwise the + state is just set to whatever is passed in. */ + if( eState != eInvalid ) + { + if( pxTCB == pxCurrentTCB ) + { + pxTaskStatus->eCurrentState = eRunning; + } + else + { + pxTaskStatus->eCurrentState = eState; - #if ( INCLUDE_vTaskSuspend == 1 ) - { - /* If the task is in the suspended list then there is a - chance it is actually just blocked indefinitely - so really - it should be reported as being in the Blocked state. */ - if( eState == eSuspended ) - { - vTaskSuspendAll(); - { - if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) - { - pxTaskStatus->eCurrentState = eBlocked; - } - } - ( void ) xTaskResumeAll(); - } - } - #endif /* INCLUDE_vTaskSuspend */ - } - } - else - { - pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); - } + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* If the task is in the suspended list then there is a + chance it is actually just blocked indefinitely - so really + it should be reported as being in the Blocked state. */ + if( eState == eSuspended ) + { + vTaskSuspendAll(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + pxTaskStatus->eCurrentState = eBlocked; + } + } + ( void ) xTaskResumeAll(); + } + } + #endif /* INCLUDE_vTaskSuspend */ + } + } + else + { + pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); + } - /* Obtaining the stack space takes some time, so the xGetFreeStackSpace - parameter is provided to allow it to be skipped. */ - if( xGetFreeStackSpace != pdFALSE ) - { - #if ( portSTACK_GROWTH > 0 ) - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); - } - #else - { - pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); - } - #endif - } - else - { - pxTaskStatus->usStackHighWaterMark = 0; - } - } + /* Obtaining the stack space takes some time, so the xGetFreeStackSpace + parameter is provided to allow it to be skipped. */ + if( xGetFreeStackSpace != pdFALSE ) + { + #if ( portSTACK_GROWTH > 0 ) + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); + } + #else + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); + } + #endif + } + else + { + pxTaskStatus->usStackHighWaterMark = 0; + } + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) - { - configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB; - UBaseType_t uxTask = 0; + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) + { + configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB; + UBaseType_t uxTask = 0; - if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) - { - listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - /* Populate an TaskStatus_t structure within the - pxTaskStatusArray array for each task that is referenced from - pxList. See the definition of TaskStatus_t in task.h for the - meaning of each TaskStatus_t structure member. */ - do - { - listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); - uxTask++; - } while( pxNextTCB != pxFirstTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Populate an TaskStatus_t structure within the + pxTaskStatusArray array for each task that is referenced from + pxList. See the definition of TaskStatus_t in task.h for the + meaning of each TaskStatus_t structure member. */ + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); + uxTask++; + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return uxTask; - } + return uxTask; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) - static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) - { - uint32_t ulCount = 0U; + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) + { + uint32_t ulCount = 0U; - while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) - { - pucStackByte -= portSTACK_GROWTH; - ulCount++; - } + while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) + { + pucStackByte -= portSTACK_GROWTH; + ulCount++; + } - ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ + ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ - return ( configSTACK_DEPTH_TYPE ) ulCount; - } + return ( configSTACK_DEPTH_TYPE ) ulCount; + } #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) - /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the - same except for their return type. Using configSTACK_DEPTH_TYPE allows the - user to determine the return type. It gets around the problem of the value - overflowing on 8-bit types without breaking backward compatibility for - applications that expect an 8-bit return type. */ - configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - uint8_t *pucEndOfStack; - configSTACK_DEPTH_TYPE uxReturn; + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + same except for their return type. Using configSTACK_DEPTH_TYPE allows the + user to determine the return type. It gets around the problem of the value + overflowing on 8-bit types without breaking backward compatibility for + applications that expect an 8-bit return type. */ + configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + uint8_t *pucEndOfStack; + configSTACK_DEPTH_TYPE uxReturn; - /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are - the same except for their return type. Using configSTACK_DEPTH_TYPE - allows the user to determine the return type. It gets around the - problem of the value overflowing on 8-bit types without breaking - backward compatibility for applications that expect an 8-bit return - type. */ + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are + the same except for their return type. Using configSTACK_DEPTH_TYPE + allows the user to determine the return type. It gets around the + problem of the value overflowing on 8-bit types without breaking + backward compatibility for applications that expect an 8-bit return + type. */ - pxTCB = prvGetTCBFromHandle( xTask ); + pxTCB = prvGetTCBFromHandle( xTask ); - #if portSTACK_GROWTH < 0 - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; - } - #else - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; - } - #endif + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif - uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); + uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) - UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - uint8_t *pucEndOfStack; - UBaseType_t uxReturn; + UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + uint8_t *pucEndOfStack; + UBaseType_t uxReturn; - pxTCB = prvGetTCBFromHandle( xTask ); + pxTCB = prvGetTCBFromHandle( xTask ); - #if portSTACK_GROWTH < 0 - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; - } - #else - { - pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; - } - #endif + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif - uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); + uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); - return uxReturn; - } + return uxReturn; + } #endif /* INCLUDE_uxTaskGetStackHighWaterMark */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelete == 1 ) - static void prvDeleteTCB( TCB_t *pxTCB ) - { - /* This call is required specifically for the TriCore port. It must be - above the vPortFree() calls. The call is also used by ports/demos that - want to allocate and clean RAM statically. */ - portCLEAN_UP_TCB( pxTCB ); + static void prvDeleteTCB( TCB_t *pxTCB ) + { + /* This call is required specifically for the TriCore port. It must be + above the vPortFree() calls. The call is also used by ports/demos that + want to allocate and clean RAM statically. */ + portCLEAN_UP_TCB( pxTCB ); - /* Free up the memory allocated by the scheduler for the task. It is up - to the task to free any memory allocated at the application level. */ - #if ( configUSE_NEWLIB_REENTRANT == 1 ) - { - _reclaim_reent( &( pxTCB->xNewLib_reent ) ); - } - #endif /* configUSE_NEWLIB_REENTRANT */ + /* Free up the memory allocated by the scheduler for the task. It is up + to the task to free any memory allocated at the application level. */ + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + _reclaim_reent( &( pxTCB->xNewLib_reent ) ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ - #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) - { - /* The task can only have been allocated dynamically - free both - the stack and TCB. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ - { - /* The task could have been allocated statically or dynamically, so - check what was statically allocated before trying to free the - memory. */ - if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) - { - /* Both the stack and TCB were allocated dynamically, so both - must be freed. */ - vPortFree( pxTCB->pxStack ); - vPortFree( pxTCB ); - } - else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) - { - /* Only the stack was statically allocated, so the TCB is the - only memory that must be freed. */ - vPortFree( pxTCB ); - } - else - { - /* Neither the stack nor the TCB were allocated dynamically, so - nothing needs to be freed. */ - configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - } + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) + { + /* The task can only have been allocated dynamically - free both + the stack and TCB. */ + vPortFree( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* The task could have been allocated statically or dynamically, so + check what was statically allocated before trying to free the + memory. */ + if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) + { + /* Both the stack and TCB were allocated dynamically, so both + must be freed. */ + vPortFree( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) + { + /* Only the stack was statically allocated, so the TCB is the + only memory that must be freed. */ + vPortFree( pxTCB ); + } + else + { + /* Neither the stack nor the TCB were allocated dynamically, so + nothing needs to be freed. */ + configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } #endif /* INCLUDE_vTaskDelete */ /*-----------------------------------------------------------*/ @@ -3959,653 +3959,653 @@ static void prvResetNextTaskUnblockTime( void ) { TCB_t *pxTCB; - if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) - { - /* The new current delayed list is empty. Set xNextTaskUnblockTime to - the maximum possible value so it is extremely unlikely that the - if( xTickCount >= xNextTaskUnblockTime ) test will pass until - there is an item in the delayed list. */ - xNextTaskUnblockTime = portMAX_DELAY; - } - else - { - /* The new current delayed list is not empty, get the value of - the item at the head of the delayed list. This is the time at - which the task at the head of the delayed list should be removed - from the Blocked state. */ - ( pxTCB ) = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); - } + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The new current delayed list is empty. Set xNextTaskUnblockTime to + the maximum possible value so it is extremely unlikely that the + if( xTickCount >= xNextTaskUnblockTime ) test will pass until + there is an item in the delayed list. */ + xNextTaskUnblockTime = portMAX_DELAY; + } + else + { + /* The new current delayed list is not empty, get the value of + the item at the head of the delayed list. This is the time at + which the task at the head of the delayed list should be removed + from the Blocked state. */ + ( pxTCB ) = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); + } } /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) - TaskHandle_t xTaskGetCurrentTaskHandle( void ) - { - TaskHandle_t xReturn; + TaskHandle_t xTaskGetCurrentTaskHandle( void ) + { + TaskHandle_t xReturn; - /* A critical section is not required as this is not called from - an interrupt and the current TCB will always be the same for any - individual execution thread. */ - xReturn = pxCurrentTCB; + /* A critical section is not required as this is not called from + an interrupt and the current TCB will always be the same for any + individual execution thread. */ + xReturn = pxCurrentTCB; - return xReturn; - } + return xReturn; + } #endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) - BaseType_t xTaskGetSchedulerState( void ) - { - BaseType_t xReturn; + BaseType_t xTaskGetSchedulerState( void ) + { + BaseType_t xReturn; - if( xSchedulerRunning == pdFALSE ) - { - xReturn = taskSCHEDULER_NOT_STARTED; - } - else - { - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - xReturn = taskSCHEDULER_RUNNING; - } - else - { - xReturn = taskSCHEDULER_SUSPENDED; - } - } + if( xSchedulerRunning == pdFALSE ) + { + xReturn = taskSCHEDULER_NOT_STARTED; + } + else + { + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + xReturn = taskSCHEDULER_RUNNING; + } + else + { + xReturn = taskSCHEDULER_SUSPENDED; + } + } - return xReturn; - } + return xReturn; + } #endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxMutexHolderTCB = pxMutexHolder; - BaseType_t xReturn = pdFALSE; + BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxMutexHolderTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; - /* If the mutex was given back by an interrupt while the queue was - locked then the mutex holder might now be NULL. _RB_ Is this still - needed as interrupts can no longer use mutexes? */ - if( pxMutexHolder != NULL ) - { - /* If the holder of the mutex has a priority below the priority of - the task attempting to obtain the mutex then it will temporarily - inherit the priority of the task attempting to obtain the mutex. */ - if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) - { - /* Adjust the mutex holder state to account for its new - priority. Only reset the event list item value if the value is - not being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the mutex was given back by an interrupt while the queue was + locked then the mutex holder might now be NULL. _RB_ Is this still + needed as interrupts can no longer use mutexes? */ + if( pxMutexHolder != NULL ) + { + /* If the holder of the mutex has a priority below the priority of + the task attempting to obtain the mutex then it will temporarily + inherit the priority of the task attempting to obtain the mutex. */ + if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) + { + /* Adjust the mutex holder state to account for its new + priority. Only reset the event list item value if the value is + not being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* If the task being modified is in the ready state it will need - to be moved into a new list. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the task being modified is in the ready state it will need + to be moved into a new list. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Inherit the priority before being moved into the new list. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - prvAddTaskToReadyList( pxMutexHolderTCB ); - } - else - { - /* Just inherit the priority. */ - pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; - } + /* Inherit the priority before being moved into the new list. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + prvAddTaskToReadyList( pxMutexHolderTCB ); + } + else + { + /* Just inherit the priority. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + } - traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); + traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); - /* Inheritance occurred. */ - xReturn = pdTRUE; - } - else - { - if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) - { - /* The base priority of the mutex holder is lower than the - priority of the task attempting to take the mutex, but the - current priority of the mutex holder is not lower than the - priority of the task attempting to take the mutex. - Therefore the mutex holder must have already inherited a - priority, but inheritance would have occurred if that had - not been the case. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Inheritance occurred. */ + xReturn = pdTRUE; + } + else + { + if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) + { + /* The base priority of the mutex holder is lower than the + priority of the task attempting to take the mutex, but the + current priority of the mutex holder is not lower than the + priority of the task attempting to take the mutex. + Therefore the mutex holder must have already inherited a + priority, but inheritance would have occurred if that had + not been the case. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) - { - TCB_t * const pxTCB = pxMutexHolder; - BaseType_t xReturn = pdFALSE; + BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; - if( pxMutexHolder != NULL ) - { - /* A task can only have an inherited priority if it holds the mutex. - If the mutex is held by a task then it cannot be given from an - interrupt, and if a mutex is given by the holding task then it must - be the running state task. */ - configASSERT( pxTCB == pxCurrentTCB ); - configASSERT( pxTCB->uxMutexesHeld ); - ( pxTCB->uxMutexesHeld )--; + if( pxMutexHolder != NULL ) + { + /* A task can only have an inherited priority if it holds the mutex. + If the mutex is held by a task then it cannot be given from an + interrupt, and if a mutex is given by the holding task then it must + be the running state task. */ + configASSERT( pxTCB == pxCurrentTCB ); + configASSERT( pxTCB->uxMutexesHeld ); + ( pxTCB->uxMutexesHeld )--; - /* Has the holder of the mutex inherited the priority of another - task? */ - if( pxTCB->uxPriority != pxTCB->uxBasePriority ) - { - /* Only disinherit if no other mutexes are held. */ - if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) - { - /* A task can only have an inherited priority if it holds - the mutex. If the mutex is held by a task then it cannot be - given from an interrupt, and if a mutex is given by the - holding task then it must be the running state task. Remove - the holding task from the ready list. */ - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Has the holder of the mutex inherited the priority of another + task? */ + if( pxTCB->uxPriority != pxTCB->uxBasePriority ) + { + /* Only disinherit if no other mutexes are held. */ + if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) + { + /* A task can only have an inherited priority if it holds + the mutex. If the mutex is held by a task then it cannot be + given from an interrupt, and if a mutex is given by the + holding task then it must be the running state task. Remove + the holding task from the ready list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Disinherit the priority before adding the task into the - new ready list. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); - pxTCB->uxPriority = pxTCB->uxBasePriority; + /* Disinherit the priority before adding the task into the + new ready list. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + pxTCB->uxPriority = pxTCB->uxBasePriority; - /* Reset the event list item value. It cannot be in use for - any other purpose if this task is running, and it must be - running to give back the mutex. */ - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - prvAddTaskToReadyList( pxTCB ); + /* Reset the event list item value. It cannot be in use for + any other purpose if this task is running, and it must be + running to give back the mutex. */ + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + prvAddTaskToReadyList( pxTCB ); - /* Return true to indicate that a context switch is required. - This is only actually required in the corner case whereby - multiple mutexes were held and the mutexes were given back - in an order different to that in which they were taken. - If a context switch did not occur when the first mutex was - returned, even if a task was waiting on it, then a context - switch should occur when the last mutex is returned whether - a task is waiting on it or not. */ - xReturn = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Return true to indicate that a context switch is required. + This is only actually required in the corner case whereby + multiple mutexes were held and the mutexes were given back + in an order different to that in which they were taken. + If a context switch did not occur when the first mutex was + returned, even if a task was waiting on it, then a context + switch should occur when the last mutex is returned whether + a task is waiting on it or not. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; - } + return xReturn; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) - { - TCB_t * const pxTCB = pxMutexHolder; - UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; - const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; + void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) + { + TCB_t * const pxTCB = pxMutexHolder; + UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; + const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; - if( pxMutexHolder != NULL ) - { - /* If pxMutexHolder is not NULL then the holder must hold at least - one mutex. */ - configASSERT( pxTCB->uxMutexesHeld ); + if( pxMutexHolder != NULL ) + { + /* If pxMutexHolder is not NULL then the holder must hold at least + one mutex. */ + configASSERT( pxTCB->uxMutexesHeld ); - /* Determine the priority to which the priority of the task that - holds the mutex should be set. This will be the greater of the - holding task's base priority and the priority of the highest - priority task that is waiting to obtain the mutex. */ - if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) - { - uxPriorityToUse = uxHighestPriorityWaitingTask; - } - else - { - uxPriorityToUse = pxTCB->uxBasePriority; - } + /* Determine the priority to which the priority of the task that + holds the mutex should be set. This will be the greater of the + holding task's base priority and the priority of the highest + priority task that is waiting to obtain the mutex. */ + if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) + { + uxPriorityToUse = uxHighestPriorityWaitingTask; + } + else + { + uxPriorityToUse = pxTCB->uxBasePriority; + } - /* Does the priority need to change? */ - if( pxTCB->uxPriority != uxPriorityToUse ) - { - /* Only disinherit if no other mutexes are held. This is a - simplification in the priority inheritance implementation. If - the task that holds the mutex is also holding other mutexes then - the other mutexes may have caused the priority inheritance. */ - if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) - { - /* If a task has timed out because it already holds the - mutex it was trying to obtain then it cannot of inherited - its own priority. */ - configASSERT( pxTCB != pxCurrentTCB ); + /* Does the priority need to change? */ + if( pxTCB->uxPriority != uxPriorityToUse ) + { + /* Only disinherit if no other mutexes are held. This is a + simplification in the priority inheritance implementation. If + the task that holds the mutex is also holding other mutexes then + the other mutexes may have caused the priority inheritance. */ + if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) + { + /* If a task has timed out because it already holds the + mutex it was trying to obtain then it cannot of inherited + its own priority. */ + configASSERT( pxTCB != pxCurrentTCB ); - /* Disinherit the priority, remembering the previous - priority to facilitate determining the subject task's - state. */ - traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); - uxPriorityUsedOnEntry = pxTCB->uxPriority; - pxTCB->uxPriority = uxPriorityToUse; + /* Disinherit the priority, remembering the previous + priority to facilitate determining the subject task's + state. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + uxPriorityUsedOnEntry = pxTCB->uxPriority; + pxTCB->uxPriority = uxPriorityToUse; - /* Only reset the event list item value if the value is not - being used for anything else. */ - if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) - { - listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Only reset the event list item value if the value is not + being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* If the running task is not the task that holds the mutex - then the task that holds the mutex could be in either the - Ready, Blocked or Suspended states. Only remove the task - from its current state list if it is in the Ready state as - the task's priority is going to change and there is one - Ready list per priority. */ - if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) - { - if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - taskRESET_READY_PRIORITY( pxTCB->uxPriority ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* If the running task is not the task that holds the mutex + then the task that holds the mutex could be in either the + Ready, Blocked or Suspended states. Only remove the task + from its current state list if it is in the Ready state as + the task's priority is going to change and there is one + Ready list per priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - prvAddTaskToReadyList( pxTCB ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - void vTaskEnterCritical( void ) - { - portDISABLE_INTERRUPTS(); + void vTaskEnterCritical( void ) + { + portDISABLE_INTERRUPTS(); - if( xSchedulerRunning != pdFALSE ) - { - ( pxCurrentTCB->uxCriticalNesting )++; + if( xSchedulerRunning != pdFALSE ) + { + ( pxCurrentTCB->uxCriticalNesting )++; - /* This is not the interrupt safe version of the enter critical - function so assert() if it is being called from an interrupt - context. Only API functions that end in "FromISR" can be used in an - interrupt. Only assert if the critical nesting count is 1 to - protect against recursive calls if the assert function also uses a - critical section. */ - if( pxCurrentTCB->uxCriticalNesting == 1 ) - { - portASSERT_IF_IN_ISR(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* This is not the interrupt safe version of the enter critical + function so assert() if it is being called from an interrupt + context. Only API functions that end in "FromISR" can be used in an + interrupt. Only assert if the critical nesting count is 1 to + protect against recursive calls if the assert function also uses a + critical section. */ + if( pxCurrentTCB->uxCriticalNesting == 1 ) + { + portASSERT_IF_IN_ISR(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* portCRITICAL_NESTING_IN_TCB */ /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) - void vTaskExitCritical( void ) - { - if( xSchedulerRunning != pdFALSE ) - { - if( pxCurrentTCB->uxCriticalNesting > 0U ) - { - ( pxCurrentTCB->uxCriticalNesting )--; + void vTaskExitCritical( void ) + { + if( xSchedulerRunning != pdFALSE ) + { + if( pxCurrentTCB->uxCriticalNesting > 0U ) + { + ( pxCurrentTCB->uxCriticalNesting )--; - if( pxCurrentTCB->uxCriticalNesting == 0U ) - { - portENABLE_INTERRUPTS(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( pxCurrentTCB->uxCriticalNesting == 0U ) + { + portENABLE_INTERRUPTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* portCRITICAL_NESTING_IN_TCB */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) - static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) - { - size_t x; + static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) + { + size_t x; - /* Start by copying the entire string. */ - strcpy( pcBuffer, pcTaskName ); + /* Start by copying the entire string. */ + strcpy( pcBuffer, pcTaskName ); - /* Pad the end of the string with spaces to ensure columns line up when - printed out. */ - for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) - { - pcBuffer[ x ] = ' '; - } + /* Pad the end of the string with spaces to ensure columns line up when + printed out. */ + for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) + { + pcBuffer[ x ] = ' '; + } - /* Terminate. */ - pcBuffer[ x ] = ( char ) 0x00; + /* Terminate. */ + pcBuffer[ x ] = ( char ) 0x00; - /* Return the new end of string. */ - return &( pcBuffer[ x ] ); - } + /* Return the new end of string. */ + return &( pcBuffer[ x ] ); + } #endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - void vTaskList( char * pcWriteBuffer ) - { - TaskStatus_t *pxTaskStatusArray; - UBaseType_t uxArraySize, x; - char cStatus; + void vTaskList( char * pcWriteBuffer ) + { + TaskStatus_t *pxTaskStatusArray; + UBaseType_t uxArraySize, x; + char cStatus; - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskList() calls uxTaskGetSystemState(), then formats part of the - * uxTaskGetSystemState() output into a human readable table that - * displays task names, states and stack usage. - * - * vTaskList() has a dependency on the sprintf() C library function that - * might bloat the code size, use a lot of stack, and provide different - * results on different platforms. An alternative, tiny, third party, - * and limited functionality implementation of sprintf() is provided in - * many of the FreeRTOS/Demo sub-directories in a file called - * printf-stdarg.c (note printf-stdarg.c does not provide a full - * snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskList(). - */ + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that + * displays task names, states and stack usage. + * + * vTaskList() has a dependency on the sprintf() C library function that + * might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, + * and limited functionality implementation of sprintf() is provided in + * many of the FreeRTOS/Demo sub-directories in a file called + * printf-stdarg.c (note printf-stdarg.c does not provide a full + * snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskList(). + */ - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = ( char ) 0x00; + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; - /* Take a snapshot of the number of tasks in case it changes while this - function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; + /* Take a snapshot of the number of tasks in case it changes while this + function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; - /* Allocate an array index for each task. NOTE! if - configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + /* Allocate an array index for each task. NOTE! if + configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - switch( pxTaskStatusArray[ x ].eCurrentState ) - { - case eRunning: cStatus = tskRUNNING_CHAR; - break; + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + switch( pxTaskStatusArray[ x ].eCurrentState ) + { + case eRunning: cStatus = tskRUNNING_CHAR; + break; - case eReady: cStatus = tskREADY_CHAR; - break; + case eReady: cStatus = tskREADY_CHAR; + break; - case eBlocked: cStatus = tskBLOCKED_CHAR; - break; + case eBlocked: cStatus = tskBLOCKED_CHAR; + break; - case eSuspended: cStatus = tskSUSPENDED_CHAR; - break; + case eSuspended: cStatus = tskSUSPENDED_CHAR; + break; - case eDeleted: cStatus = tskDELETED_CHAR; - break; + case eDeleted: cStatus = tskDELETED_CHAR; + break; - case eInvalid: /* Fall through. */ - default: /* Should not get here, but it is included - to prevent static checking errors. */ - cStatus = ( char ) 0x00; - break; - } + case eInvalid: /* Fall through. */ + default: /* Should not get here, but it is included + to prevent static checking errors. */ + cStatus = ( char ) 0x00; + break; + } - /* Write the task name to the string, padding with spaces so it - can be printed in tabular form more easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + /* Write the task name to the string, padding with spaces so it + can be printed in tabular form more easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - /* Write the rest of the string. */ - sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\t%p\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber, + /* Write the rest of the string. */ + sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\t%p\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber, pxTaskStatusArray[ x ].pxStackBase ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ - } + pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*----------------------------------------------------------*/ #if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) - void vTaskGetRunTimeStats( char *pcWriteBuffer ) - { - TaskStatus_t *pxTaskStatusArray; - UBaseType_t uxArraySize, x; - uint32_t ulTotalTime, ulStatsAsPercentage; + void vTaskGetRunTimeStats( char *pcWriteBuffer ) + { + TaskStatus_t *pxTaskStatusArray; + UBaseType_t uxArraySize, x; + uint32_t ulTotalTime, ulStatsAsPercentage; - #if( configUSE_TRACE_FACILITY != 1 ) - { - #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). - } - #endif + #if( configUSE_TRACE_FACILITY != 1 ) + { + #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). + } + #endif - /* - * PLEASE NOTE: - * - * This function is provided for convenience only, and is used by many - * of the demo applications. Do not consider it to be part of the - * scheduler. - * - * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part - * of the uxTaskGetSystemState() output into a human readable table that - * displays the amount of time each task has spent in the Running state - * in both absolute and percentage terms. - * - * vTaskGetRunTimeStats() has a dependency on the sprintf() C library - * function that might bloat the code size, use a lot of stack, and - * provide different results on different platforms. An alternative, - * tiny, third party, and limited functionality implementation of - * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in - * a file called printf-stdarg.c (note printf-stdarg.c does not provide - * a full snprintf() implementation!). - * - * It is recommended that production systems call uxTaskGetSystemState() - * directly to get access to raw stats data, rather than indirectly - * through a call to vTaskGetRunTimeStats(). - */ + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part + * of the uxTaskGetSystemState() output into a human readable table that + * displays the amount of time each task has spent in the Running state + * in both absolute and percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the sprintf() C library + * function that might bloat the code size, use a lot of stack, and + * provide different results on different platforms. An alternative, + * tiny, third party, and limited functionality implementation of + * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in + * a file called printf-stdarg.c (note printf-stdarg.c does not provide + * a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskGetRunTimeStats(). + */ - /* Make sure the write buffer does not contain a string. */ - *pcWriteBuffer = ( char ) 0x00; + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; - /* Take a snapshot of the number of tasks in case it changes while this - function is executing. */ - uxArraySize = uxCurrentNumberOfTasks; + /* Take a snapshot of the number of tasks in case it changes while this + function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; - /* Allocate an array index for each task. NOTE! If - configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will - equate to NULL. */ - pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + /* Allocate an array index for each task. NOTE! If + configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ - if( pxTaskStatusArray != NULL ) - { - /* Generate the (binary) data. */ - uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); - /* For percentage calculations. */ - ulTotalTime /= 100UL; + /* For percentage calculations. */ + ulTotalTime /= 100UL; - /* Avoid divide by zero errors. */ - if( ulTotalTime > 0UL ) - { - /* Create a human readable table from the binary data. */ - for( x = 0; x < uxArraySize; x++ ) - { - /* What percentage of the total run time has the task used? - This will always be rounded down to the nearest integer. - ulTotalRunTimeDiv100 has already been divided by 100. */ - ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; + /* Avoid divide by zero errors. */ + if( ulTotalTime > 0UL ) + { + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + /* What percentage of the total run time has the task used? + This will always be rounded down to the nearest integer. + ulTotalRunTimeDiv100 has already been divided by 100. */ + ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; - /* Write the task name to the string, padding with - spaces so it can be printed in tabular form more - easily. */ - pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + /* Write the task name to the string, padding with + spaces so it can be printed in tabular form more + easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); - if( ulStatsAsPercentage > 0UL ) - { - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - } - #endif - } - else - { - /* If the percentage is zero here then the task has - consumed less than 1% of the total run time. */ - #ifdef portLU_PRINTF_SPECIFIER_REQUIRED - { - sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); - } - #else - { - /* sizeof( int ) == sizeof( long ) so a smaller - printf() library can be used. */ - sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ - } - #endif - } + if( ulStatsAsPercentage > 0UL ) + { + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } + else + { + /* If the percentage is zero here then the task has + consumed less than 1% of the total run time. */ + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } - pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION - is 0 then vPortFree() will be #defined to nothing. */ - vPortFree( pxTaskStatusArray ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } #endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ @@ -4614,506 +4614,506 @@ TickType_t uxTaskResetEventItemValue( void ) { TickType_t uxReturn; - uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); + uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); - /* Reset the event list item to its normal value - so it can be used with - queues and semaphores. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + /* Reset the event list item to its normal value - so it can be used with + queues and semaphores. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - return uxReturn; + return uxReturn; } /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) - TaskHandle_t pvTaskIncrementMutexHeldCount( void ) - { - /* If xSemaphoreCreateMutex() is called before any tasks have been created - then pxCurrentTCB will be NULL. */ - if( pxCurrentTCB != NULL ) - { - ( pxCurrentTCB->uxMutexesHeld )++; - } + TaskHandle_t pvTaskIncrementMutexHeldCount( void ) + { + /* If xSemaphoreCreateMutex() is called before any tasks have been created + then pxCurrentTCB will be NULL. */ + if( pxCurrentTCB != NULL ) + { + ( pxCurrentTCB->uxMutexesHeld )++; + } - return pxCurrentTCB; - } + return pxCurrentTCB; + } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) - { - uint32_t ulReturn; + uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) + { + uint32_t ulReturn; - taskENTER_CRITICAL(); - { - /* Only block if the notification count is not already non-zero. */ - if( pxCurrentTCB->ulNotifiedValue == 0UL ) - { - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; + taskENTER_CRITICAL(); + { + /* Only block if the notification count is not already non-zero. */ + if( pxCurrentTCB->ulNotifiedValue == 0UL ) + { + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_TAKE_BLOCK(); + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_TAKE_BLOCK(); - /* All ports are written to allow a yield in a critical - section (some will yield immediately, others wait until the - critical section exits) - but it is not something that - application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* All ports are written to allow a yield in a critical + section (some will yield immediately, others wait until the + critical section exits) - but it is not something that + application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_TAKE(); - ulReturn = pxCurrentTCB->ulNotifiedValue; + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_TAKE(); + ulReturn = pxCurrentTCB->ulNotifiedValue; - if( ulReturn != 0UL ) - { - if( xClearCountOnExit != pdFALSE ) - { - pxCurrentTCB->ulNotifiedValue = 0UL; - } - else - { - pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( ulReturn != 0UL ) + { + if( xClearCountOnExit != pdFALSE ) + { + pxCurrentTCB->ulNotifiedValue = 0UL; + } + else + { + pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); + pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); - return ulReturn; - } + return ulReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) - { - BaseType_t xReturn; + BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) + { + BaseType_t xReturn; - taskENTER_CRITICAL(); - { - /* Only block if a notification is not already pending. */ - if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) - { - /* Clear bits in the task's notification value as bits may get - set by the notifying task or interrupt. This can be used to - clear the value to zero. */ - pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry; + taskENTER_CRITICAL(); + { + /* Only block if a notification is not already pending. */ + if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) + { + /* Clear bits in the task's notification value as bits may get + set by the notifying task or interrupt. This can be used to + clear the value to zero. */ + pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry; - /* Mark this task as waiting for a notification. */ - pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; - if( xTicksToWait > ( TickType_t ) 0 ) - { - prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); - traceTASK_NOTIFY_WAIT_BLOCK(); + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_WAIT_BLOCK(); - /* All ports are written to allow a yield in a critical - section (some will yield immediately, others wait until the - critical section exits) - but it is not something that - application code should ever do. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + /* All ports are written to allow a yield in a critical + section (some will yield immediately, others wait until the + critical section exits) - but it is not something that + application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - taskENTER_CRITICAL(); - { - traceTASK_NOTIFY_WAIT(); + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_WAIT(); - if( pulNotificationValue != NULL ) - { - /* Output the current notification value, which may or may not - have changed. */ - *pulNotificationValue = pxCurrentTCB->ulNotifiedValue; - } + if( pulNotificationValue != NULL ) + { + /* Output the current notification value, which may or may not + have changed. */ + *pulNotificationValue = pxCurrentTCB->ulNotifiedValue; + } - /* If ucNotifyValue is set then either the task never entered the - blocked state (because a notification was already pending) or the - task unblocked because of a notification. Otherwise the task - unblocked because of a timeout. */ - if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) - { - /* A notification was not received. */ - xReturn = pdFALSE; - } - else - { - /* A notification was already pending or a notification was - received while the task was waiting. */ - pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit; - xReturn = pdTRUE; - } + /* If ucNotifyValue is set then either the task never entered the + blocked state (because a notification was already pending) or the + task unblocked because of a notification. Otherwise the task + unblocked because of a timeout. */ + if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) + { + /* A notification was not received. */ + xReturn = pdFALSE; + } + else + { + /* A notification was already pending or a notification was + received while the task was waiting. */ + pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit; + xReturn = pdTRUE; + } - pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - } - taskEXIT_CRITICAL(); + pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) - { - TCB_t * pxTCB; - BaseType_t xReturn = pdPASS; - uint8_t ucOriginalNotifyState; + BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) + { + TCB_t * pxTCB; + BaseType_t xReturn = pdPASS; + uint8_t ucOriginalNotifyState; - configASSERT( xTaskToNotify ); - pxTCB = xTaskToNotify; + configASSERT( xTaskToNotify ); + pxTCB = xTaskToNotify; - taskENTER_CRITICAL(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; - } + taskENTER_CRITICAL(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; + } - ucOriginalNotifyState = pxTCB->ucNotifyState; + ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - switch( eAction ) - { - case eSetBits : - pxTCB->ulNotifiedValue |= ulValue; - break; + switch( eAction ) + { + case eSetBits : + pxTCB->ulNotifiedValue |= ulValue; + break; - case eIncrement : - ( pxTCB->ulNotifiedValue )++; - break; + case eIncrement : + ( pxTCB->ulNotifiedValue )++; + break; - case eSetValueWithOverwrite : - pxTCB->ulNotifiedValue = ulValue; - break; + case eSetValueWithOverwrite : + pxTCB->ulNotifiedValue = ulValue; + break; - case eSetValueWithoutOverwrite : - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - break; + case eSetValueWithoutOverwrite : + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + break; - case eNoAction: - /* The task is being notified without its notify value being - updated. */ - break; + case eNoAction: + /* The task is being notified without its notify value being + updated. */ + break; - default: - /* Should not get here if all enums are handled. - Artificially force an assert by testing a value the - compiler can't assume is const. */ - configASSERT( pxTCB->ulNotifiedValue == ~0UL ); + default: + /* Should not get here if all enums are handled. + Artificially force an assert by testing a value the + compiler can't assume is const. */ + configASSERT( pxTCB->ulNotifiedValue == ~0UL ); - break; - } + break; + } - traceTASK_NOTIFY(); + traceTASK_NOTIFY(); - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - #if( configUSE_TICKLESS_IDLE != 0 ) - { - /* If a task is blocked waiting for a notification then - xNextTaskUnblockTime might be set to the blocked task's time - out time. If the task is unblocked for a reason other than - a timeout xNextTaskUnblockTime is normally left unchanged, - because it will automatically get reset to a new value when - the tick count equals xNextTaskUnblockTime. However if - tickless idling is used it might be more important to enter - sleep mode at the earliest possible time - so reset - xNextTaskUnblockTime here to ensure it is updated at the - earliest possible time. */ - prvResetNextTaskUnblockTime(); - } - #endif + #if( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked waiting for a notification then + xNextTaskUnblockTime might be set to the blocked task's time + out time. If the task is unblocked for a reason other than + a timeout xNextTaskUnblockTime is normally left unchanged, + because it will automatically get reset to a new value when + the tick count equals xNextTaskUnblockTime. However if + tickless idling is used it might be more important to enter + sleep mode at the earliest possible time - so reset + xNextTaskUnblockTime here to ensure it is updated at the + earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - taskYIELD_IF_USING_PREEMPTION(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - BaseType_t xReturn = pdPASS; - UBaseType_t uxSavedInterruptStatus; + BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + BaseType_t xReturn = pdPASS; + UBaseType_t uxSavedInterruptStatus; - configASSERT( xTaskToNotify ); + configASSERT( xTaskToNotify ); - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - pxTCB = xTaskToNotify; + pxTCB = xTaskToNotify; - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - if( pulPreviousNotificationValue != NULL ) - { - *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; - } + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; + } - ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + ucOriginalNotifyState = pxTCB->ucNotifyState; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - switch( eAction ) - { - case eSetBits : - pxTCB->ulNotifiedValue |= ulValue; - break; + switch( eAction ) + { + case eSetBits : + pxTCB->ulNotifiedValue |= ulValue; + break; - case eIncrement : - ( pxTCB->ulNotifiedValue )++; - break; + case eIncrement : + ( pxTCB->ulNotifiedValue )++; + break; - case eSetValueWithOverwrite : - pxTCB->ulNotifiedValue = ulValue; - break; + case eSetValueWithOverwrite : + pxTCB->ulNotifiedValue = ulValue; + break; - case eSetValueWithoutOverwrite : - if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) - { - pxTCB->ulNotifiedValue = ulValue; - } - else - { - /* The value could not be written to the task. */ - xReturn = pdFAIL; - } - break; + case eSetValueWithoutOverwrite : + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + break; - case eNoAction : - /* The task is being notified without its notify value being - updated. */ - break; + case eNoAction : + /* The task is being notified without its notify value being + updated. */ + break; - default: - /* Should not get here if all enums are handled. - Artificially force an assert by testing a value the - compiler can't assume is const. */ - configASSERT( pxTCB->ulNotifiedValue == ~0UL ); - break; - } + default: + /* Should not get here if all enums are handled. + Artificially force an assert by testing a value the + compiler can't assume is const. */ + configASSERT( pxTCB->ulNotifiedValue == ~0UL ); + break; + } - traceTASK_NOTIFY_FROM_ISR(); + traceTASK_NOTIFY_FROM_ISR(); - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + this task pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } - /* Mark that a yield is pending in case the user is not - using the "xHigherPriorityTaskWoken" parameter to an ISR - safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + /* Mark that a yield is pending in case the user is not + using the "xHigherPriorityTaskWoken" parameter to an ISR + safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) - void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) - { - TCB_t * pxTCB; - uint8_t ucOriginalNotifyState; - UBaseType_t uxSavedInterruptStatus; + void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + UBaseType_t uxSavedInterruptStatus; - configASSERT( xTaskToNotify ); + configASSERT( xTaskToNotify ); - /* RTOS ports that support interrupt nesting have the concept of a - maximum system call (or maximum API call) interrupt priority. - Interrupts that are above the maximum system call priority are keep - permanently enabled, even when the RTOS kernel is in a critical section, - but cannot make any calls to FreeRTOS API functions. If configASSERT() - is defined in FreeRTOSConfig.h then - portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion - failure if a FreeRTOS API function is called from an interrupt that has - been assigned a priority above the configured maximum system call - priority. Only FreeRTOS functions that end in FromISR can be called - from interrupts that have been assigned a priority at or (logically) - below the maximum system call interrupt priority. FreeRTOS maintains a - separate interrupt safe API to ensure interrupt entry is as fast and as - simple as possible. More information (albeit Cortex-M specific) is - provided on the following link: - http://www.freertos.org/RTOS-Cortex-M3-M4.html */ - portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); - pxTCB = xTaskToNotify; + pxTCB = xTaskToNotify; - uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); - { - ucOriginalNotifyState = pxTCB->ucNotifyState; - pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + ucOriginalNotifyState = pxTCB->ucNotifyState; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; - /* 'Giving' is equivalent to incrementing a count in a counting - semaphore. */ - ( pxTCB->ulNotifiedValue )++; + /* 'Giving' is equivalent to incrementing a count in a counting + semaphore. */ + ( pxTCB->ulNotifiedValue )++; - traceTASK_NOTIFY_GIVE_FROM_ISR(); + traceTASK_NOTIFY_GIVE_FROM_ISR(); - /* If the task is in the blocked state specifically to wait for a - notification then unblock it now. */ - if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) - { - /* The task should not have been on an event list. */ - configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); - if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) - { - ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); - prvAddTaskToReadyList( pxTCB ); - } - else - { - /* The delayed and ready lists cannot be accessed, so hold - this task pending until the scheduler is resumed. */ - vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); - } + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + this task pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } - if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) - { - /* The notified task has a priority above the currently - executing task so a yield is required. */ - if( pxHigherPriorityTaskWoken != NULL ) - { - *pxHigherPriorityTaskWoken = pdTRUE; - } + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } - /* Mark that a yield is pending in case the user is not - using the "xHigherPriorityTaskWoken" parameter in an ISR - safe FreeRTOS function. */ - xYieldPending = pdTRUE; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); - } + /* Mark that a yield is pending in case the user is not + using the "xHigherPriorityTaskWoken" parameter in an ISR + safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + } #endif /* configUSE_TASK_NOTIFICATIONS */ @@ -5121,40 +5121,40 @@ TickType_t uxReturn; #if( configUSE_TASK_NOTIFICATIONS == 1 ) - BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ) - { - TCB_t *pxTCB; - BaseType_t xReturn; + BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + BaseType_t xReturn; - /* If null is passed in here then it is the calling task that is having - its notification state cleared. */ - pxTCB = prvGetTCBFromHandle( xTask ); + /* If null is passed in here then it is the calling task that is having + its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); - taskENTER_CRITICAL(); - { - if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED ) - { - pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; - xReturn = pdPASS; - } - else - { - xReturn = pdFAIL; - } - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED ) + { + pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + taskEXIT_CRITICAL(); - return xReturn; - } + return xReturn; + } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) - TickType_t xTaskGetIdleRunTimeCounter( void ) - { - return xIdleTaskHandle->ulRunTimeCounter; - } + TickType_t xTaskGetIdleRunTimeCounter( void ) + { + return xIdleTaskHandle->ulRunTimeCounter; + } #endif /*-----------------------------------------------------------*/ @@ -5163,110 +5163,110 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT TickType_t xTimeToWake; const TickType_t xConstTickCount = xTickCount; - #if( INCLUDE_xTaskAbortDelay == 1 ) - { - /* About to enter a delayed list, so ensure the ucDelayAborted flag is - reset to pdFALSE so it can be detected as having been set to pdTRUE - when the task leaves the Blocked state. */ - pxCurrentTCB->ucDelayAborted = pdFALSE; - } - #endif + #if( INCLUDE_xTaskAbortDelay == 1 ) + { + /* About to enter a delayed list, so ensure the ucDelayAborted flag is + reset to pdFALSE so it can be detected as having been set to pdTRUE + when the task leaves the Blocked state. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + } + #endif - /* Remove the task from the ready list before adding it to the blocked list - as the same list item is used for both lists. */ - if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) - { - /* The current task must be in a ready list, so there is no need to - check, and the port reset macro can be called directly. */ - portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + /* Remove the task from the ready list before adding it to the blocked list + as the same list item is used for both lists. */ + if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* The current task must be in a ready list, so there is no need to + check, and the port reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - #if ( INCLUDE_vTaskSuspend == 1 ) - { - if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) - { - /* Add the task to the suspended task list instead of a delayed task - list to ensure it is not woken by a timing event. It will block - indefinitely. */ - vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* Calculate the time at which the task should be woken if the event - does not occur. This may overflow but this doesn't matter, the - kernel will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) + { + /* Add the task to the suspended task list instead of a delayed task + list to ensure it is not woken by a timing event. It will block + indefinitely. */ + vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* Calculate the time at which the task should be woken if the event + does not occur. This may overflow but this doesn't matter, the + kernel will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow - list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list - is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow + list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list + is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - /* If the task entering the blocked state was placed at the - head of the list of blocked tasks then xNextTaskUnblockTime - needs to be updated too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - } - #else /* INCLUDE_vTaskSuspend */ - { - /* Calculate the time at which the task should be woken if the event - does not occur. This may overflow but this doesn't matter, the kernel - will manage it correctly. */ - xTimeToWake = xConstTickCount + xTicksToWait; + /* If the task entering the blocked state was placed at the + head of the list of blocked tasks then xNextTaskUnblockTime + needs to be updated too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + } + #else /* INCLUDE_vTaskSuspend */ + { + /* Calculate the time at which the task should be woken if the event + does not occur. This may overflow but this doesn't matter, the kernel + will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; - /* The list item will be inserted in wake time order. */ - listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); - if( xTimeToWake < xConstTickCount ) - { - /* Wake time has overflowed. Place this item in the overflow list. */ - vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - } - else - { - /* The wake time has not overflowed, so the current block list is used. */ - vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); - /* If the task entering the blocked state was placed at the head of the - list of blocked tasks then xNextTaskUnblockTime needs to be updated - too. */ - if( xTimeToWake < xNextTaskUnblockTime ) - { - xNextTaskUnblockTime = xTimeToWake; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + /* If the task entering the blocked state was placed at the head of the + list of blocked tasks then xNextTaskUnblockTime needs to be updated + too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ - ( void ) xCanBlockIndefinitely; - } - #endif /* INCLUDE_vTaskSuspend */ + /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ + ( void ) xCanBlockIndefinitely; + } + #endif /* INCLUDE_vTaskSuspend */ } /* Code below here allows additional code to be inserted into this source file, @@ -5274,20 +5274,20 @@ especially where access to file scope functions and data is needed (for example when performing module tests). */ #ifdef FREERTOS_MODULE_TEST - #include "tasks_test_access_functions.h" + #include "tasks_test_access_functions.h" #endif #if( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) - #include "freertos_tasks_c_additions.h" + #include "freertos_tasks_c_additions.h" - #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT - static void freertos_tasks_c_additions_init( void ) - { - FREERTOS_TASKS_C_ADDITIONS_INIT(); - } - #endif + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + static void freertos_tasks_c_additions_init( void ) + { + FREERTOS_TASKS_C_ADDITIONS_INIT(); + } + #endif #endif diff --git a/components/bl602/freertos_riscv_ram/timers.c b/components/bl602/freertos_riscv_ram/timers.c index ad18f3e1..3d7bc949 100644 --- a/components/bl602/freertos_riscv_ram/timers.c +++ b/components/bl602/freertos_riscv_ram/timers.c @@ -39,7 +39,7 @@ task.h is included from an application file. */ #include "timers.h" #if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) - #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. + #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. #endif /* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified @@ -56,31 +56,31 @@ configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ #if ( configUSE_TIMERS == 1 ) /* Misc definitions. */ -#define tmrNO_DELAY ( TickType_t ) 0U +#define tmrNO_DELAY ( TickType_t ) 0U /* The name assigned to the timer service task. This can be overridden by defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ #ifndef configTIMER_SERVICE_TASK_NAME - #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" + #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" #endif /* Bit definitions used in the ucStatus member of a timer structure. */ -#define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 ) -#define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 ) -#define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 ) +#define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 ) +#define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 ) +#define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 ) /* The definition of the timers themselves. */ typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */ { - const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ - TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ - void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ - TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ - #if( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ - #endif - uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ + const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ + TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ + void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ + TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ + #endif + uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ } xTIMER; /* The old xTIMER name is maintained above then typedefed to the new Timer_t @@ -94,33 +94,33 @@ two message types are defined in two separate structures, xTimerParametersType and xCallbackParametersType respectively. */ typedef struct tmrTimerParameters { - TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ - Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ + TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ + Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ } TimerParameter_t; typedef struct tmrCallbackParameters { - PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ - void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */ - uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ + PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ + void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */ + uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ } CallbackParameters_t; /* The structure that contains the two message types, along with an identifier that is used to determine which message type is valid. */ typedef struct tmrTimerQueueMessage { - BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ - union - { - TimerParameter_t xTimerParameters; + BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ + union + { + TimerParameter_t xTimerParameters; - /* Don't include xCallbackParameters if it is not going to be used as - it makes the structure (and therefore the timer queue) larger. */ - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - CallbackParameters_t xCallbackParameters; - #endif /* INCLUDE_xTimerPendFunctionCall */ - } u; + /* Don't include xCallbackParameters if it is not going to be used as + it makes the structure (and therefore the timer queue) larger. */ + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + CallbackParameters_t xCallbackParameters; + #endif /* INCLUDE_xTimerPendFunctionCall */ + } u; } DaemonTaskMessage_t; /*lint -save -e956 A manual analysis and inspection has been used to determine @@ -147,11 +147,11 @@ PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL; #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - /* If static allocation is supported then the application must provide the - following callback function - which enables the application to optionally - provide the memory that will be used by the timer task as the task's stack - and TCB. */ - extern void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ); + /* If static allocation is supported then the application must provide the + following callback function - which enables the application to optionally + provide the memory that will be used by the timer task as the task's stack + and TCB. */ + extern void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ); #endif @@ -216,165 +216,165 @@ static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseTy * Called after a Timer_t structure has been allocated either statically or * dynamically to fill in the structure's members. */ -static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION; +static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION; /*-----------------------------------------------------------*/ BaseType_t xTimerCreateTimerTask( void ) { BaseType_t xReturn = pdFAIL; - /* This function is called when the scheduler is started if - configUSE_TIMERS is set to 1. Check that the infrastructure used by the - timer service task has been created/initialised. If timers have already - been created then the initialisation will already have been performed. */ - prvCheckForValidListAndQueue(); + /* This function is called when the scheduler is started if + configUSE_TIMERS is set to 1. Check that the infrastructure used by the + timer service task has been created/initialised. If timers have already + been created then the initialisation will already have been performed. */ + prvCheckForValidListAndQueue(); - if( xTimerQueue != NULL ) - { - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - StaticTask_t *pxTimerTaskTCBBuffer = NULL; - StackType_t *pxTimerTaskStackBuffer = NULL; - uint32_t ulTimerTaskStackSize; + if( xTimerQueue != NULL ) + { + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t *pxTimerTaskTCBBuffer = NULL; + StackType_t *pxTimerTaskStackBuffer = NULL; + uint32_t ulTimerTaskStackSize; - vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); - xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - ulTimerTaskStackSize, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - pxTimerTaskStackBuffer, - pxTimerTaskTCBBuffer ); + vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); + xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + ulTimerTaskStackSize, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + pxTimerTaskStackBuffer, + pxTimerTaskTCBBuffer ); - if( xTimerTaskHandle != NULL ) - { - xReturn = pdPASS; - } - } - #else - { - xReturn = xTaskCreate( prvTimerTask, - configTIMER_SERVICE_TASK_NAME, - configTIMER_TASK_STACK_DEPTH, - NULL, - ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, - &xTimerTaskHandle ); - } - #endif /* configSUPPORT_STATIC_ALLOCATION */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( xTimerTaskHandle != NULL ) + { + xReturn = pdPASS; + } + } + #else + { + xReturn = xTaskCreate( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + configTIMER_TASK_STACK_DEPTH, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + &xTimerTaskHandle ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - configASSERT( xReturn ); - return xReturn; + configASSERT( xReturn ); + return xReturn; } /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction ) - { - Timer_t *pxNewTimer; + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) + { + Timer_t *pxNewTimer; - pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ + pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ - if( pxNewTimer != NULL ) - { - /* Status is thus far zero as the timer is not created statically - and has not been started. The autoreload bit may get set in - prvInitialiseNewTimer. */ - pxNewTimer->ucStatus = 0x00; - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - } + if( pxNewTimer != NULL ) + { + /* Status is thus far zero as the timer is not created statically + and has not been started. The autoreload bit may get set in + prvInitialiseNewTimer. */ + pxNewTimer->ucStatus = 0x00; + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } - return pxNewTimer; - } + return pxNewTimer; + } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - StaticTimer_t *pxTimerBuffer ) - { - Timer_t *pxNewTimer; + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t *pxTimerBuffer ) + { + Timer_t *pxNewTimer; - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticTimer_t equals the size of the real timer - structure. */ - volatile size_t xSize = sizeof( StaticTimer_t ); - configASSERT( xSize == sizeof( Timer_t ) ); - ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ - } - #endif /* configASSERT_DEFINED */ + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticTimer_t equals the size of the real timer + structure. */ + volatile size_t xSize = sizeof( StaticTimer_t ); + configASSERT( xSize == sizeof( Timer_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ - /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ - configASSERT( pxTimerBuffer ); - pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ + /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ + configASSERT( pxTimerBuffer ); + pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ - if( pxNewTimer != NULL ) - { - /* Timers can be created statically or dynamically so note this - timer was created statically in case it is later deleted. The - autoreload bit may get set in prvInitialiseNewTimer(). */ - pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; + if( pxNewTimer != NULL ) + { + /* Timers can be created statically or dynamically so note this + timer was created statically in case it is later deleted. The + autoreload bit may get set in prvInitialiseNewTimer(). */ + pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; - prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); - } + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } - return pxNewTimer; - } + return pxNewTimer; + } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ -static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ - const TickType_t xTimerPeriodInTicks, - const UBaseType_t uxAutoReload, - void * const pvTimerID, - TimerCallbackFunction_t pxCallbackFunction, - Timer_t *pxNewTimer ) +static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t *pxNewTimer ) { - /* 0 is not a valid value for xTimerPeriodInTicks. */ - configASSERT( ( xTimerPeriodInTicks > 0 ) ); + /* 0 is not a valid value for xTimerPeriodInTicks. */ + configASSERT( ( xTimerPeriodInTicks > 0 ) ); - if( pxNewTimer != NULL ) - { - /* Ensure the infrastructure used by the timer service task has been - created/initialised. */ - prvCheckForValidListAndQueue(); + if( pxNewTimer != NULL ) + { + /* Ensure the infrastructure used by the timer service task has been + created/initialised. */ + prvCheckForValidListAndQueue(); - /* Initialise the timer structure members using the function - parameters. */ - pxNewTimer->pcTimerName = pcTimerName; - pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; - pxNewTimer->pvTimerID = pvTimerID; - pxNewTimer->pxCallbackFunction = pxCallbackFunction; - vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); - if( uxAutoReload != pdFALSE ) - { - pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; - } - traceTIMER_CREATE( pxNewTimer ); - } + /* Initialise the timer structure members using the function + parameters. */ + pxNewTimer->pcTimerName = pcTimerName; + pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; + pxNewTimer->pvTimerID = pvTimerID; + pxNewTimer->pxCallbackFunction = pxCallbackFunction; + vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); + if( uxAutoReload != pdFALSE ) + { + pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + traceTIMER_CREATE( pxNewTimer ); + } } /*-----------------------------------------------------------*/ @@ -383,50 +383,50 @@ BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommand BaseType_t xReturn = pdFAIL; DaemonTaskMessage_t xMessage; - configASSERT( xTimer ); + configASSERT( xTimer ); - /* Send a message to the timer service task to perform a particular action - on a particular timer definition. */ - if( xTimerQueue != NULL ) - { - /* Send a command to the timer service task to start the xTimer timer. */ - xMessage.xMessageID = xCommandID; - xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; - xMessage.u.xTimerParameters.pxTimer = xTimer; + /* Send a message to the timer service task to perform a particular action + on a particular timer definition. */ + if( xTimerQueue != NULL ) + { + /* Send a command to the timer service task to start the xTimer timer. */ + xMessage.xMessageID = xCommandID; + xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; + xMessage.u.xTimerParameters.pxTimer = xTimer; - if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) - { - if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - } - else - { - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); - } - } - else - { - xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - } + if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) + { + if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + } + else + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); + } + } + else + { + xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + } - traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - return xReturn; + return xReturn; } /*-----------------------------------------------------------*/ TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) { - /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been - started, then xTimerTaskHandle will be NULL. */ - configASSERT( ( xTimerTaskHandle != NULL ) ); - return xTimerTaskHandle; + /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been + started, then xTimerTaskHandle will be NULL. */ + configASSERT( ( xTimerTaskHandle != NULL ) ); + return xTimerTaskHandle; } /*-----------------------------------------------------------*/ @@ -434,8 +434,8 @@ TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) { Timer_t *pxTimer = xTimer; - configASSERT( xTimer ); - return pxTimer->xTimerPeriodInTicks; + configASSERT( xTimer ); + return pxTimer->xTimerPeriodInTicks; } /*-----------------------------------------------------------*/ @@ -443,19 +443,19 @@ void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ) { Timer_t * pxTimer = xTimer; - configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - if( uxAutoReload != pdFALSE ) - { - pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; - } - } - taskEXIT_CRITICAL(); + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( uxAutoReload != pdFALSE ) + { + pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; + } + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ @@ -464,9 +464,9 @@ TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) Timer_t * pxTimer = xTimer; TickType_t xReturn; - configASSERT( xTimer ); - xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); - return xReturn; + configASSERT( xTimer ); + xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); + return xReturn; } /*-----------------------------------------------------------*/ @@ -474,8 +474,8 @@ const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified cha { Timer_t *pxTimer = xTimer; - configASSERT( xTimer ); - return pxTimer->pcTimerName; + configASSERT( xTimer ); + return pxTimer->pcTimerName; } /*-----------------------------------------------------------*/ @@ -484,39 +484,39 @@ static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const Tick BaseType_t xResult; Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - /* Remove the timer from the list of active timers. A check has already - been performed to ensure the list is not empty. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); + /* Remove the timer from the list of active timers. A check has already + been performed to ensure the list is not empty. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + traceTIMER_EXPIRED( pxTimer ); - /* If the timer is an auto reload timer then calculate the next - expiry time and re-insert the timer in the list of active timers. */ - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - /* The timer is inserted into a list using a time relative to anything - other than the current time. It will therefore be inserted into the - correct list relative to the time this task thinks it is now. */ - if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) - { - /* The timer expired before it was added to the active timer - list. Reload it now. */ - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - mtCOVERAGE_TEST_MARKER(); - } + /* If the timer is an auto reload timer then calculate the next + expiry time and re-insert the timer in the list of active timers. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + /* The timer is inserted into a list using a time relative to anything + other than the current time. It will therefore be inserted into the + correct list relative to the time this task thinks it is now. */ + if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) + { + /* The timer expired before it was added to the active timer + list. Reload it now. */ + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + mtCOVERAGE_TEST_MARKER(); + } - /* Call the timer callback. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + /* Call the timer callback. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); } /*-----------------------------------------------------------*/ @@ -525,34 +525,34 @@ static portTASK_FUNCTION( prvTimerTask, pvParameters ) TickType_t xNextExpireTime; BaseType_t xListWasEmpty; - /* Just to avoid compiler warnings. */ - ( void ) pvParameters; + /* Just to avoid compiler warnings. */ + ( void ) pvParameters; - #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) - { - extern void vApplicationDaemonTaskStartupHook( void ); + #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) + { + extern void vApplicationDaemonTaskStartupHook( void ); - /* Allow the application writer to execute some code in the context of - this task at the point the task starts executing. This is useful if the - application includes initialisation code that would benefit from - executing after the scheduler has been started. */ - vApplicationDaemonTaskStartupHook(); - } - #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ + /* Allow the application writer to execute some code in the context of + this task at the point the task starts executing. This is useful if the + application includes initialisation code that would benefit from + executing after the scheduler has been started. */ + vApplicationDaemonTaskStartupHook(); + } + #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ - for( ;; ) - { - /* Query the timers list to see if it contains any timers, and if so, - obtain the time at which the next timer will expire. */ - xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); + for( ;; ) + { + /* Query the timers list to see if it contains any timers, and if so, + obtain the time at which the next timer will expire. */ + xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); - /* If a timer has expired, process it. Otherwise, block this task - until either a timer does expire, or a command is received. */ - prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); + /* If a timer has expired, process it. Otherwise, block this task + until either a timer does expire, or a command is received. */ + prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); - /* Empty the command queue. */ - prvProcessReceivedCommands(); - } + /* Empty the command queue. */ + prvProcessReceivedCommands(); + } } /*-----------------------------------------------------------*/ @@ -561,58 +561,58 @@ static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseTy TickType_t xTimeNow; BaseType_t xTimerListsWereSwitched; - vTaskSuspendAll(); - { - /* Obtain the time now to make an assessment as to whether the timer - has expired or not. If obtaining the time causes the lists to switch - then don't process this timer as any timers that remained in the list - when the lists were switched will have been processed within the - prvSampleTimeNow() function. */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - if( xTimerListsWereSwitched == pdFALSE ) - { - /* The tick count has not overflowed, has the timer expired? */ - if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) - { - ( void ) xTaskResumeAll(); - prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); - } - else - { - /* The tick count has not overflowed, and the next expire - time has not been reached yet. This task should therefore - block to wait for the next expire time or a command to be - received - whichever comes first. The following line cannot - be reached unless xNextExpireTime > xTimeNow, except in the - case when the current timer list is empty. */ - if( xListWasEmpty != pdFALSE ) - { - /* The current timer list is empty - is the overflow list - also empty? */ - xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); - } + vTaskSuspendAll(); + { + /* Obtain the time now to make an assessment as to whether the timer + has expired or not. If obtaining the time causes the lists to switch + then don't process this timer as any timers that remained in the list + when the lists were switched will have been processed within the + prvSampleTimeNow() function. */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + if( xTimerListsWereSwitched == pdFALSE ) + { + /* The tick count has not overflowed, has the timer expired? */ + if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) + { + ( void ) xTaskResumeAll(); + prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); + } + else + { + /* The tick count has not overflowed, and the next expire + time has not been reached yet. This task should therefore + block to wait for the next expire time or a command to be + received - whichever comes first. The following line cannot + be reached unless xNextExpireTime > xTimeNow, except in the + case when the current timer list is empty. */ + if( xListWasEmpty != pdFALSE ) + { + /* The current timer list is empty - is the overflow list + also empty? */ + xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); + } - vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); + vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); - if( xTaskResumeAll() == pdFALSE ) - { - /* Yield to wait for either a command to arrive, or the - block time to expire. If a command arrived between the - critical section being exited and this yield then the yield - will not cause the task to block. */ - portYIELD_WITHIN_API(); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - } - else - { - ( void ) xTaskResumeAll(); - } - } + if( xTaskResumeAll() == pdFALSE ) + { + /* Yield to wait for either a command to arrive, or the + block time to expire. If a command arrived between the + critical section being exited and this yield then the yield + will not cause the task to block. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + ( void ) xTaskResumeAll(); + } + } } /*-----------------------------------------------------------*/ @@ -620,25 +620,25 @@ static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) { TickType_t xNextExpireTime; - /* Timers are listed in expiry time order, with the head of the list - referencing the task that will expire first. Obtain the time at which - the timer with the nearest expiry time will expire. If there are no - active timers then just set the next expire time to 0. That will cause - this task to unblock when the tick count overflows, at which point the - timer lists will be switched and the next expiry time can be - re-assessed. */ - *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); - if( *pxListWasEmpty == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - } - else - { - /* Ensure the task unblocks when the tick count rolls over. */ - xNextExpireTime = ( TickType_t ) 0U; - } + /* Timers are listed in expiry time order, with the head of the list + referencing the task that will expire first. Obtain the time at which + the timer with the nearest expiry time will expire. If there are no + active timers then just set the next expire time to 0. That will cause + this task to unblock when the tick count overflows, at which point the + timer lists will be switched and the next expiry time can be + re-assessed. */ + *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); + if( *pxListWasEmpty == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + } + else + { + /* Ensure the task unblocks when the tick count rolls over. */ + xNextExpireTime = ( TickType_t ) 0U; + } - return xNextExpireTime; + return xNextExpireTime; } /*-----------------------------------------------------------*/ @@ -647,21 +647,21 @@ static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched TickType_t xTimeNow; PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */ - xTimeNow = xTaskGetTickCount(); + xTimeNow = xTaskGetTickCount(); - if( xTimeNow < xLastTime ) - { - prvSwitchTimerLists(); - *pxTimerListsWereSwitched = pdTRUE; - } - else - { - *pxTimerListsWereSwitched = pdFALSE; - } + if( xTimeNow < xLastTime ) + { + prvSwitchTimerLists(); + *pxTimerListsWereSwitched = pdTRUE; + } + else + { + *pxTimerListsWereSwitched = pdFALSE; + } - xLastTime = xTimeNow; + xLastTime = xTimeNow; - return xTimeNow; + return xTimeNow; } /*-----------------------------------------------------------*/ @@ -669,188 +669,188 @@ static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const Tic { BaseType_t xProcessTimerNow = pdFALSE; - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - if( xNextExpiryTime <= xTimeNow ) - { - /* Has the expiry time elapsed between the command to start/reset a - timer was issued, and the time the command was processed? */ - if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - { - /* The time between a command being issued and the command being - processed actually exceeds the timers period. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); - } - } - else - { - if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) - { - /* If, since the command was issued, the tick count has overflowed - but the expiry time has not, then the timer must have already passed - its expiry time and should be processed immediately. */ - xProcessTimerNow = pdTRUE; - } - else - { - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - } + if( xNextExpiryTime <= xTimeNow ) + { + /* Has the expiry time elapsed between the command to start/reset a + timer was issued, and the time the command was processed? */ + if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + { + /* The time between a command being issued and the command being + processed actually exceeds the timers period. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); + } + } + else + { + if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) + { + /* If, since the command was issued, the tick count has overflowed + but the expiry time has not, then the timer must have already passed + its expiry time and should be processed immediately. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + } - return xProcessTimerNow; + return xProcessTimerNow; } /*-----------------------------------------------------------*/ -static void prvProcessReceivedCommands( void ) +static void prvProcessReceivedCommands( void ) { DaemonTaskMessage_t xMessage; Timer_t *pxTimer; BaseType_t xTimerListsWereSwitched, xResult; TickType_t xTimeNow; - while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ - { - #if ( INCLUDE_xTimerPendFunctionCall == 1 ) - { - /* Negative commands are pended function calls rather than timer - commands. */ - if( xMessage.xMessageID < ( BaseType_t ) 0 ) - { - const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); + while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ + { + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + { + /* Negative commands are pended function calls rather than timer + commands. */ + if( xMessage.xMessageID < ( BaseType_t ) 0 ) + { + const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); - /* The timer uses the xCallbackParameters member to request a - callback be executed. Check the callback is not NULL. */ - configASSERT( pxCallback ); + /* The timer uses the xCallbackParameters member to request a + callback be executed. Check the callback is not NULL. */ + configASSERT( pxCallback ); - /* Call the function. */ - pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* INCLUDE_xTimerPendFunctionCall */ + /* Call the function. */ + pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* INCLUDE_xTimerPendFunctionCall */ - /* Commands that are positive are timer commands rather than pended - function calls. */ - if( xMessage.xMessageID >= ( BaseType_t ) 0 ) - { - /* The messages uses the xTimerParameters member to work on a - software timer. */ - pxTimer = xMessage.u.xTimerParameters.pxTimer; + /* Commands that are positive are timer commands rather than pended + function calls. */ + if( xMessage.xMessageID >= ( BaseType_t ) 0 ) + { + /* The messages uses the xTimerParameters member to work on a + software timer. */ + pxTimer = xMessage.u.xTimerParameters.pxTimer; - if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ - { - /* The timer is in a list, remove it. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } + if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ + { + /* The timer is in a list, remove it. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } - traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); + traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); - /* In this case the xTimerListsWereSwitched parameter is not used, but - it must be present in the function call. prvSampleTimeNow() must be - called after the message is received from xTimerQueue so there is no - possibility of a higher priority task adding a message to the message - queue with a time that is ahead of the timer daemon task (because it - pre-empted the timer daemon task after the xTimeNow value was set). */ - xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + /* In this case the xTimerListsWereSwitched parameter is not used, but + it must be present in the function call. prvSampleTimeNow() must be + called after the message is received from xTimerQueue so there is no + possibility of a higher priority task adding a message to the message + queue with a time that is ahead of the timer daemon task (because it + pre-empted the timer daemon task after the xTimeNow value was set). */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); - switch( xMessage.xMessageID ) - { - case tmrCOMMAND_START : - case tmrCOMMAND_START_FROM_ISR : - case tmrCOMMAND_RESET : - case tmrCOMMAND_RESET_FROM_ISR : - case tmrCOMMAND_START_DONT_TRACE : - /* Start or restart a timer. */ - pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; - if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) - { - /* The timer expired before it was added to the active - timer list. Process it now. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - traceTIMER_EXPIRED( pxTimer ); + switch( xMessage.xMessageID ) + { + case tmrCOMMAND_START : + case tmrCOMMAND_START_FROM_ISR : + case tmrCOMMAND_RESET : + case tmrCOMMAND_RESET_FROM_ISR : + case tmrCOMMAND_START_DONT_TRACE : + /* Start or restart a timer. */ + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) + { + /* The timer expired before it was added to the active + timer list. Process it now. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + traceTIMER_EXPIRED( pxTimer ); - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - break; + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + break; - case tmrCOMMAND_STOP : - case tmrCOMMAND_STOP_FROM_ISR : - /* The timer has already been removed from the active list. */ - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - break; + case tmrCOMMAND_STOP : + case tmrCOMMAND_STOP_FROM_ISR : + /* The timer has already been removed from the active list. */ + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + break; - case tmrCOMMAND_CHANGE_PERIOD : - case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR : - pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; - pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; - configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); + case tmrCOMMAND_CHANGE_PERIOD : + case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR : + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; + configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); - /* The new period does not really have a reference, and can - be longer or shorter than the old one. The command time is - therefore set to the current time, and as the period cannot - be zero the next expiry time can only be in the future, - meaning (unlike for the xTimerStart() case above) there is - no fail case that needs to be handled here. */ - ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); - break; + /* The new period does not really have a reference, and can + be longer or shorter than the old one. The command time is + therefore set to the current time, and as the period cannot + be zero the next expiry time can only be in the future, + meaning (unlike for the xTimerStart() case above) there is + no fail case that needs to be handled here. */ + ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); + break; - case tmrCOMMAND_DELETE : - #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) - { - /* The timer has already been removed from the active list, - just free up the memory if the memory was dynamically - allocated. */ - if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) - { - vPortFree( pxTimer ); - } - else - { - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - } - } - #else - { - /* If dynamic allocation is not enabled, the memory - could not have been dynamically allocated. So there is - no need to free the memory - just mark the timer as - "not active". */ - pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; - } - #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ - break; + case tmrCOMMAND_DELETE : + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* The timer has already been removed from the active list, + just free up the memory if the memory was dynamically + allocated. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) + { + vPortFree( pxTimer ); + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + } + } + #else + { + /* If dynamic allocation is not enabled, the memory + could not have been dynamically allocated. So there is + no need to free the memory - just mark the timer as + "not active". */ + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + break; - default : - /* Don't expect to get here. */ - break; - } - } - } + default : + /* Don't expect to get here. */ + break; + } + } + } } /*-----------------------------------------------------------*/ @@ -861,106 +861,106 @@ List_t *pxTemp; Timer_t *pxTimer; BaseType_t xResult; - /* The tick count has overflowed. The timer lists must be switched. - If there are any timers still referenced from the current timer list - then they must have expired and should be processed before the lists - are switched. */ - while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) - { - xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + /* The tick count has overflowed. The timer lists must be switched. + If there are any timers still referenced from the current timer list + then they must have expired and should be processed before the lists + are switched. */ + while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); - /* Remove the timer from the list. */ - pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ - ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); - traceTIMER_EXPIRED( pxTimer ); + /* Remove the timer from the list. */ + pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + traceTIMER_EXPIRED( pxTimer ); - /* Execute its callback, then send a command to restart the timer if - it is an auto-reload timer. It cannot be restarted here as the lists - have not yet been switched. */ - pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + /* Execute its callback, then send a command to restart the timer if + it is an auto-reload timer. It cannot be restarted here as the lists + have not yet been switched. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); - if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) - { - /* Calculate the reload value, and if the reload value results in - the timer going into the same timer list then it has already expired - and the timer should be re-inserted into the current list so it is - processed again within this loop. Otherwise a command should be sent - to restart the timer to ensure it is only inserted into a list after - the lists have been swapped. */ - xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); - if( xReloadTime > xNextExpireTime ) - { - listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); - listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); - vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); - } - else - { - xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); - configASSERT( xResult ); - ( void ) xResult; - } - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + /* Calculate the reload value, and if the reload value results in + the timer going into the same timer list then it has already expired + and the timer should be re-inserted into the current list so it is + processed again within this loop. Otherwise a command should be sent + to restart the timer to ensure it is only inserted into a list after + the lists have been swapped. */ + xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); + if( xReloadTime > xNextExpireTime ) + { + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + else + { + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } - pxTemp = pxCurrentTimerList; - pxCurrentTimerList = pxOverflowTimerList; - pxOverflowTimerList = pxTemp; + pxTemp = pxCurrentTimerList; + pxCurrentTimerList = pxOverflowTimerList; + pxOverflowTimerList = pxTemp; } /*-----------------------------------------------------------*/ static void prvCheckForValidListAndQueue( void ) { - /* Check that the list from which active timers are referenced, and the - queue used to communicate with the timer service, have been - initialised. */ - taskENTER_CRITICAL(); - { - if( xTimerQueue == NULL ) - { - vListInitialise( &xActiveTimerList1 ); - vListInitialise( &xActiveTimerList2 ); - pxCurrentTimerList = &xActiveTimerList1; - pxOverflowTimerList = &xActiveTimerList2; + /* Check that the list from which active timers are referenced, and the + queue used to communicate with the timer service, have been + initialised. */ + taskENTER_CRITICAL(); + { + if( xTimerQueue == NULL ) + { + vListInitialise( &xActiveTimerList1 ); + vListInitialise( &xActiveTimerList2 ); + pxCurrentTimerList = &xActiveTimerList1; + pxOverflowTimerList = &xActiveTimerList2; - #if( configSUPPORT_STATIC_ALLOCATION == 1 ) - { - /* The timer queue is allocated statically in case - configSUPPORT_DYNAMIC_ALLOCATION is 0. */ - static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* The timer queue is allocated statically in case + configSUPPORT_DYNAMIC_ALLOCATION is 0. */ + static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ - xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); - } - #else - { - xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); - } - #endif + xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); + } + #else + { + xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); + } + #endif - #if ( configQUEUE_REGISTRY_SIZE > 0 ) - { - if( xTimerQueue != NULL ) - { - vQueueAddToRegistry( xTimerQueue, "TmrQ" ); - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - #endif /* configQUEUE_REGISTRY_SIZE */ - } - else - { - mtCOVERAGE_TEST_MARKER(); - } - } - taskEXIT_CRITICAL(); + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + if( xTimerQueue != NULL ) + { + vQueueAddToRegistry( xTimerQueue, "TmrQ" ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configQUEUE_REGISTRY_SIZE */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ @@ -969,23 +969,23 @@ BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) BaseType_t xReturn; Timer_t *pxTimer = xTimer; - configASSERT( xTimer ); + configASSERT( xTimer ); - /* Is the timer in the list of active timers? */ - taskENTER_CRITICAL(); - { - if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) - { - xReturn = pdFALSE; - } - else - { - xReturn = pdTRUE; - } - } - taskEXIT_CRITICAL(); + /* Is the timer in the list of active timers? */ + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); - return xReturn; + return xReturn; } /*lint !e818 Can't be pointer to const due to the typedef. */ /*-----------------------------------------------------------*/ @@ -994,15 +994,15 @@ void *pvTimerGetTimerID( const TimerHandle_t xTimer ) Timer_t * const pxTimer = xTimer; void *pvReturn; - configASSERT( xTimer ); + configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - pvReturn = pxTimer->pvTimerID; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + pvReturn = pxTimer->pvTimerID; + } + taskEXIT_CRITICAL(); - return pvReturn; + return pvReturn; } /*-----------------------------------------------------------*/ @@ -1010,85 +1010,85 @@ void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) { Timer_t * const pxTimer = xTimer; - configASSERT( xTimer ); + configASSERT( xTimer ); - taskENTER_CRITICAL(); - { - pxTimer->pvTimerID = pvNewID; - } - taskEXIT_CRITICAL(); + taskENTER_CRITICAL(); + { + pxTimer->pvTimerID = pvNewID; + } + taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ #if( INCLUDE_xTimerPendFunctionCall == 1 ) - BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; + BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; - /* Complete the message with the function parameters and post it to the - daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + /* Complete the message with the function parameters and post it to the + daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); - tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - return xReturn; - } + return xReturn; + } #endif /* INCLUDE_xTimerPendFunctionCall */ /*-----------------------------------------------------------*/ #if( INCLUDE_xTimerPendFunctionCall == 1 ) - BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) - { - DaemonTaskMessage_t xMessage; - BaseType_t xReturn; + BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; - /* This function can only be called after a timer has been created or - after the scheduler has been started because, until then, the timer - queue does not exist. */ - configASSERT( xTimerQueue ); + /* This function can only be called after a timer has been created or + after the scheduler has been started because, until then, the timer + queue does not exist. */ + configASSERT( xTimerQueue ); - /* Complete the message with the function parameters and post it to the - daemon task. */ - xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; - xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; - xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; - xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + /* Complete the message with the function parameters and post it to the + daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; - xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); - tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); - return xReturn; - } + return xReturn; + } #endif /* INCLUDE_xTimerPendFunctionCall */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) - { - return ( ( Timer_t * ) xTimer )->uxTimerNumber; - } + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) + { + return ( ( Timer_t * ) xTimer )->uxTimerNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) - void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) - { - ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; - } + void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) + { + ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; + } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ diff --git a/components/fs/romfs/genromfs/genromfs.c b/components/fs/romfs/genromfs/genromfs.c index fa46f3eb..edcb56ef 100644 --- a/components/fs/romfs/genromfs/genromfs.c +++ b/components/fs/romfs/genromfs/genromfs.c @@ -59,7 +59,7 @@ * # genromfs -d rescue -f testimg.rom -V "Install disk" * * Other options: - * -a N force all regular file data to be aligned on N bytes boundary + * -a N force all regular file data to be aligned on N bytes boundary * -A N,/name force named file(s) (shell globbing applied against the filenames) * to be aligned on N bytes boundary * In both cases, N must be a power of two. @@ -81,7 +81,7 @@ #include #include -#include /* Consts & structs defined by the internet system */ +#include /* Consts & structs defined by the internet system */ /* good old times without autoconf... */ #if defined(__linux__) || defined(__sun__) || defined(__CYGWIN__) @@ -90,10 +90,10 @@ struct romfh { - int32_t nextfh; - int32_t spec; - int32_t size; - int32_t checksum; + int32_t nextfh; + int32_t spec; + int32_t size; + int32_t checksum; }; #define ROMFS_MAXFN 128 @@ -110,83 +110,83 @@ struct romfh { struct filenode; struct filehdr { - /* leave h, t, tp at front, this is a linked list header */ - struct filenode *head; - struct filenode *tail; - struct filenode *tailpred; - /* end fragile header */ - struct filenode *owner; + /* leave h, t, tp at front, this is a linked list header */ + struct filenode *head; + struct filenode *tail; + struct filenode *tailpred; + /* end fragile header */ + struct filenode *owner; }; struct filenode { - /* leave n, p at front, this is a linked list item */ - struct filenode *next; - struct filenode *prev; - /* end fragile header */ - struct filenode *parent; - struct filehdr dirlist; - struct filenode *orig_link; - char *name; - char *realname; - dev_t ondev; - dev_t devnode; - ino_t onino; - mode_t modes; - unsigned int offset; - unsigned int size; - unsigned int pad; + /* leave n, p at front, this is a linked list item */ + struct filenode *next; + struct filenode *prev; + /* end fragile header */ + struct filenode *parent; + struct filehdr dirlist; + struct filenode *orig_link; + char *name; + char *realname; + dev_t ondev; + dev_t devnode; + ino_t onino; + mode_t modes; + unsigned int offset; + unsigned int size; + unsigned int pad; }; struct aligns { - struct aligns *next; - int align; - char pattern[0]; + struct aligns *next; + int align; + char pattern[0]; }; struct excludes { - struct excludes *next; - char pattern[0]; + struct excludes *next; + char pattern[0]; }; void initlist(struct filehdr *fh, struct filenode *owner) { - fh->head = (struct filenode *)&fh->tail; - fh->tail = NULL; - fh->tailpred = (struct filenode *)&fh->head; - fh->owner = owner; + fh->head = (struct filenode *)&fh->tail; + fh->tail = NULL; + fh->tailpred = (struct filenode *)&fh->head; + fh->owner = owner; } int listisempty(struct filehdr *fh) { - return fh->head == (struct filenode *)&fh->tail; + return fh->head == (struct filenode *)&fh->tail; } void append(struct filehdr *fh, struct filenode *n) { - struct filenode *tail = (struct filenode *)&fh->tail; + struct filenode *tail = (struct filenode *)&fh->tail; - n->next = tail; n->prev = tail->prev; - tail->prev = n; n->prev->next =n; - n->parent = fh->owner; + n->next = tail; n->prev = tail->prev; + tail->prev = n; n->prev->next =n; + n->parent = fh->owner; } void shownode(int level, struct filenode *node, FILE *f) { - struct filenode *p; - fprintf(f, "%-4d %-20s [0x%-8x, 0x%-8x] %07o, sz %5u, at 0x%-6x", - level, node->name, - (int)node->ondev, (int)node->onino, node->modes, node->size, - node->offset); + struct filenode *p; + fprintf(f, "%-4d %-20s [0x%-8x, 0x%-8x] %07o, sz %5u, at 0x%-6x", + level, node->name, + (int)node->ondev, (int)node->onino, node->modes, node->size, + node->offset); - if (node->orig_link) - fprintf(f, " [link to 0x%-6x]", node->orig_link->offset); - fprintf(f, "\n"); + if (node->orig_link) + fprintf(f, " [link to 0x%-6x]", node->orig_link->offset); + fprintf(f, "\n"); - p = node->dirlist.head; - while (p->next) { - shownode(level+1, p, f); - p = p->next; - } + p = node->dirlist.head; + while (p->next) { + shownode(level+1, p, f); + p = p->next; + } } /* Dumping functions */ @@ -203,26 +203,26 @@ int realbase; int nodematch(char *pattern, struct filenode *node) { - char *start = node->name; - /* XXX: ugly realbase is global */ - if (pattern[0] == '/') start = node->realname + realbase; - return fnmatch(pattern,start,FNM_PATHNAME|FNM_PERIOD); + char *start = node->name; + /* XXX: ugly realbase is global */ + if (pattern[0] == '/') start = node->realname + realbase; + return fnmatch(pattern,start,FNM_PATHNAME|FNM_PERIOD); } int findalign(struct filenode *node) { - struct aligns *pa; - int i; - - if (S_ISREG(node->modes)) i = align; - else i = 16; + struct aligns *pa; + int i; - for (pa = alignlist; pa; pa = pa->next) { - if (pa->align > i) { - if (!nodematch(pa->pattern,node)) i = pa->align; - } - } - return i; + if (S_ISREG(node->modes)) i = align; + else i = 16; + + for (pa = alignlist; pa; pa = pa->next) { + if (pa->align > i) { + if (!nodematch(pa->pattern,node)) i = pa->align; + } + } + return i; } int romfs_checksum(void *data, int size) @@ -241,583 +241,583 @@ int romfs_checksum(void *data, int size) void fixsum(struct romfh *ri, int size) { - ri->checksum = 0; - ri->checksum = htonl(-romfs_checksum(ri, size)); + ri->checksum = 0; + ri->checksum = htonl(-romfs_checksum(ri, size)); } void dumpdata(void *addr, int len, FILE *f) { - int tocopy; - struct romfh *ri; + int tocopy; + struct romfh *ri; - if (!len) - return; - if (atoffs >= 512) { - fwrite(addr, len, 1, f); - atoffs+=len; - return; - } + if (!len) + return; + if (atoffs >= 512) { + fwrite(addr, len, 1, f); + atoffs+=len; + return; + } - tocopy = len < 512-atoffs ? len : 512-atoffs; - memcpy(fixbuf+atoffs, addr, tocopy); - atoffs+=tocopy; - addr=(char*)addr+tocopy; - len-=tocopy; + tocopy = len < 512-atoffs ? len : 512-atoffs; + memcpy(fixbuf+atoffs, addr, tocopy); + atoffs+=tocopy; + addr=(char*)addr+tocopy; + len-=tocopy; - if (atoffs==512) { - ri = (struct romfh *)&fixbuf; - fixsum(ri, atoffssize)?atoffs:ntohl(ri->size)); - fwrite(fixbuf, atoffs, 1, f); - } - if (len) { - fwrite(addr, len, 1, f); - atoffs+=len; - } + if (atoffs==512) { + ri = (struct romfh *)&fixbuf; + fixsum(ri, atoffssize)?atoffs:ntohl(ri->size)); + fwrite(fixbuf, atoffs, 1, f); + } + if (len) { + fwrite(addr, len, 1, f); + atoffs+=len; + } } void dumpzero(int len, FILE *f) { - memset(bigbuf, 0, len); - dumpdata(bigbuf, len, f); + memset(bigbuf, 0, len); + dumpdata(bigbuf, len, f); } void dumpdataa(void *addr, int len, FILE *f) { - dumpdata(addr, len, f); - if ((len & 15) != 0) - dumpzero(16-(len&15), f); + dumpdata(addr, len, f); + if ((len & 15) != 0) + dumpzero(16-(len&15), f); } void dumpstring(char *str, FILE *f) { - dumpdataa(str, strlen(str)+1, f); + dumpdataa(str, strlen(str)+1, f); } void dumpri(struct romfh *ri, struct filenode *n, FILE *f) { - int len; + int len; - len = strlen(n->name)+1; - memcpy(bigbuf, ri, sizeof(*ri)); - memcpy(bigbuf+16, n->name, len); - if (len&15) { - memset(bigbuf+16+len, 0, 16-(len&15)); - len += 16-(len&15); - } - len+=16; - ri=(struct romfh *)bigbuf; - if (n->offset) - fixsum(ri, len); - dumpdata(bigbuf, len, f); + len = strlen(n->name)+1; + memcpy(bigbuf, ri, sizeof(*ri)); + memcpy(bigbuf+16, n->name, len); + if (len&15) { + memset(bigbuf+16+len, 0, 16-(len&15)); + len += 16-(len&15); + } + len+=16; + ri=(struct romfh *)bigbuf; + if (n->offset) + fixsum(ri, len); + dumpdata(bigbuf, len, f); #if 0 - fprintf(stderr, "RI: [at %06x] %08lx, %08lx, %08lx, %08lx [%s]\n", - n->offset, - ntohl(ri->nextfh), ntohl(ri->spec), - ntohl(ri->size), ntohl(ri->checksum), - n->name); + fprintf(stderr, "RI: [at %06x] %08lx, %08lx, %08lx, %08lx [%s]\n", + n->offset, + ntohl(ri->nextfh), ntohl(ri->spec), + ntohl(ri->size), ntohl(ri->checksum), + n->name); #endif } void dumpnode(struct filenode *node, FILE *f) { - struct romfh ri; - struct filenode *p; + struct romfh ri; + struct filenode *p; - ri.nextfh = 0; - ri.spec = 0; - ri.size = htonl(node->size); - ri.checksum = htonl(0x55555555); - if (node->pad) - dumpzero(node->pad, f); - if (node->next && node->next->next) - ri.nextfh = htonl(node->next->offset); - if ((node->modes & 0111) && - (S_ISDIR(node->modes) || S_ISREG(node->modes))) - ri.nextfh |= htonl(ROMFH_EXEC); + ri.nextfh = 0; + ri.spec = 0; + ri.size = htonl(node->size); + ri.checksum = htonl(0x55555555); + if (node->pad) + dumpzero(node->pad, f); + if (node->next && node->next->next) + ri.nextfh = htonl(node->next->offset); + if ((node->modes & 0111) && + (S_ISDIR(node->modes) || S_ISREG(node->modes))) + ri.nextfh |= htonl(ROMFH_EXEC); - if (node->orig_link) { - ri.nextfh |= htonl(ROMFH_HRD); - /* Don't allow hardlinks to convey attributes */ - ri.nextfh &= ~htonl(ROMFH_EXEC); - ri.spec = htonl(node->orig_link->offset); - dumpri(&ri, node, f); - } else if (S_ISDIR(node->modes)) { - ri.nextfh |= htonl(ROMFH_DIR); - if (listisempty(&node->dirlist)) { - ri.spec = htonl(node->offset); - } else { - ri.spec = htonl(node->dirlist.head->offset); - } - dumpri(&ri, node, f); - } else if (S_ISLNK(node->modes)) { - ri.nextfh |= htonl(ROMFH_LNK); - dumpri(&ri, node, f); - memset(bigbuf, 0, sizeof(bigbuf)); - readlink(node->realname, bigbuf, node->size); - dumpdataa(bigbuf, node->size, f); - } else if (S_ISREG(node->modes)) { - int offset, len, fd, max, avail; - ri.nextfh |= htonl(ROMFH_REG); - dumpri(&ri, node, f); - offset = 0; - max = node->size; - /* XXX warn about size mismatch */ - fd = open(node->realname, O_RDONLY + if (node->orig_link) { + ri.nextfh |= htonl(ROMFH_HRD); + /* Don't allow hardlinks to convey attributes */ + ri.nextfh &= ~htonl(ROMFH_EXEC); + ri.spec = htonl(node->orig_link->offset); + dumpri(&ri, node, f); + } else if (S_ISDIR(node->modes)) { + ri.nextfh |= htonl(ROMFH_DIR); + if (listisempty(&node->dirlist)) { + ri.spec = htonl(node->offset); + } else { + ri.spec = htonl(node->dirlist.head->offset); + } + dumpri(&ri, node, f); + } else if (S_ISLNK(node->modes)) { + ri.nextfh |= htonl(ROMFH_LNK); + dumpri(&ri, node, f); + memset(bigbuf, 0, sizeof(bigbuf)); + readlink(node->realname, bigbuf, node->size); + dumpdataa(bigbuf, node->size, f); + } else if (S_ISREG(node->modes)) { + int offset, len, fd, max, avail; + ri.nextfh |= htonl(ROMFH_REG); + dumpri(&ri, node, f); + offset = 0; + max = node->size; + /* XXX warn about size mismatch */ + fd = open(node->realname, O_RDONLY #ifdef O_BINARY | O_BINARY #endif ); - if (fd) { - while(offset < max) { - avail = max-offset < sizeof(bigbuf) ? max-offset : sizeof(bigbuf); - len = read(fd, bigbuf, avail); - if (len <= 0) - break; - dumpdata(bigbuf, len, f); - offset+=len; - } - close(fd); - } - max = (max+15)&~15; - while (offset < max) { - avail = max-offset < sizeof(bigbuf) ? max-offset : sizeof(bigbuf); - memset(bigbuf, 0, avail); - dumpdata(bigbuf, avail, f); - offset+=avail; - } - } else if (S_ISCHR(node->modes)) { - ri.nextfh |= htonl(ROMFH_CHR); - ri.spec = htonl(major(node->devnode)<<16|minor(node->devnode)); - dumpri(&ri, node, f); - } else if (S_ISBLK(node->modes)) { - ri.nextfh |= htonl(ROMFH_BLK); - ri.spec = htonl(major(node->devnode)<<16|minor(node->devnode)); - dumpri(&ri, node, f); - } else if (S_ISFIFO(node->modes)) { - ri.nextfh |= htonl(ROMFH_FIF); - dumpri(&ri, node, f); - } else if (S_ISSOCK(node->modes)) { - ri.nextfh |= htonl(ROMFH_SCK); - dumpri(&ri, node, f); - } + if (fd) { + while(offset < max) { + avail = max-offset < sizeof(bigbuf) ? max-offset : sizeof(bigbuf); + len = read(fd, bigbuf, avail); + if (len <= 0) + break; + dumpdata(bigbuf, len, f); + offset+=len; + } + close(fd); + } + max = (max+15)&~15; + while (offset < max) { + avail = max-offset < sizeof(bigbuf) ? max-offset : sizeof(bigbuf); + memset(bigbuf, 0, avail); + dumpdata(bigbuf, avail, f); + offset+=avail; + } + } else if (S_ISCHR(node->modes)) { + ri.nextfh |= htonl(ROMFH_CHR); + ri.spec = htonl(major(node->devnode)<<16|minor(node->devnode)); + dumpri(&ri, node, f); + } else if (S_ISBLK(node->modes)) { + ri.nextfh |= htonl(ROMFH_BLK); + ri.spec = htonl(major(node->devnode)<<16|minor(node->devnode)); + dumpri(&ri, node, f); + } else if (S_ISFIFO(node->modes)) { + ri.nextfh |= htonl(ROMFH_FIF); + dumpri(&ri, node, f); + } else if (S_ISSOCK(node->modes)) { + ri.nextfh |= htonl(ROMFH_SCK); + dumpri(&ri, node, f); + } - p = node->dirlist.head; - while (p->next) { - dumpnode(p, f); - p = p->next; - } + p = node->dirlist.head; + while (p->next) { + dumpnode(p, f); + p = p->next; + } } void dumpall(struct filenode *node, int lastoff, FILE *f) { - struct romfh ri; - struct filenode *p; + struct romfh ri; + struct filenode *p; - ri.nextfh = htonl(0x2d726f6d); - ri.spec = htonl(0x3166732d); - ri.size = htonl(lastoff); - ri.checksum = htonl(0x55555555); - dumpri(&ri, node, f); - p = node->dirlist.head; - while (p->next) { - dumpnode(p, f); - p = p->next; - } - /* Align the whole bunch to ROMBSIZE boundary */ - if (lastoff&1023) - dumpzero(1024-(lastoff&1023), f); + ri.nextfh = htonl(0x2d726f6d); + ri.spec = htonl(0x3166732d); + ri.size = htonl(lastoff); + ri.checksum = htonl(0x55555555); + dumpri(&ri, node, f); + p = node->dirlist.head; + while (p->next) { + dumpnode(p, f); + p = p->next; + } + /* Align the whole bunch to ROMBSIZE boundary */ + if (lastoff&1023) + dumpzero(1024-(lastoff&1023), f); } /* Node manipulating functions */ void freenode(struct filenode *n) { - /* Rare, not yet */ + /* Rare, not yet */ } void setnode(struct filenode *n, dev_t dev, ino_t ino, mode_t um) { - n->ondev = dev; - n->onino = ino; - n->modes = um; + n->ondev = dev; + n->onino = ino; + n->modes = um; } struct filenode *newnode(const char *base, const char *name, int curroffset) { - struct filenode *node; - int len; - char *str; + struct filenode *node; + int len; + char *str; - node = malloc(sizeof (*node)); - if (!node) { - fprintf(stderr,"out of memory\n"); - exit(1); - } + node = malloc(sizeof (*node)); + if (!node) { + fprintf(stderr,"out of memory\n"); + exit(1); + } - len = strlen(name); - str = malloc(len+1); - if (!str) { - fprintf(stderr,"out of memory\n"); - exit(1); - } - strcpy(str, name); - node->name = str; + len = strlen(name); + str = malloc(len+1); + if (!str) { + fprintf(stderr,"out of memory\n"); + exit(1); + } + strcpy(str, name); + node->name = str; - if (!curroffset) { - len = 1; - name = "."; - } - if (strlen(base)) - len++; - str = malloc(strlen(base)+len+1); - if (!str) { - fprintf(stderr,"out of memory\n"); - exit(1); - } - if (strlen(base)) { - sprintf(str, "%s/%s", base, name); - } else { - strcpy(str, name); - } + if (!curroffset) { + len = 1; + name = "."; + } + if (strlen(base)) + len++; + str = malloc(strlen(base)+len+1); + if (!str) { + fprintf(stderr,"out of memory\n"); + exit(1); + } + if (strlen(base)) { + sprintf(str, "%s/%s", base, name); + } else { + strcpy(str, name); + } - node->realname = str; - node->next = node->prev = NULL; - node->parent = NULL; - initlist(&node->dirlist, node); + node->realname = str; + node->next = node->prev = NULL; + node->parent = NULL; + initlist(&node->dirlist, node); - node->ondev = -1; - node->onino = -1; - node->modes = -1; - node->size = 0; - node->devnode = 0; - node->orig_link = NULL; - node->offset = curroffset; - node->pad = 0; + node->ondev = -1; + node->onino = -1; + node->modes = -1; + node->size = 0; + node->devnode = 0; + node->orig_link = NULL; + node->offset = curroffset; + node->pad = 0; - return node; + return node; } struct filenode *findnode(struct filenode *node, dev_t dev, ino_t ino) { - struct filenode *found, *p; + struct filenode *found, *p; - /* scan the whole tree */ - if (node->ondev == dev && node->onino == ino) - return node; - p = node->dirlist.head; - while (p->next) { - found = findnode(p, dev, ino); - if (found) - return found; - p = p->next; - } - return NULL; + /* scan the whole tree */ + if (node->ondev == dev && node->onino == ino) + return node; + p = node->dirlist.head; + while (p->next) { + found = findnode(p, dev, ino); + if (found) + return found; + p = p->next; + } + return NULL; } #define ALIGNUP16(x) (((x)+15)&~15) int spaceneeded(struct filenode *node) { - return 16 + ALIGNUP16(strlen(node->name)+1) + ALIGNUP16(node->size); + return 16 + ALIGNUP16(strlen(node->name)+1) + ALIGNUP16(node->size); } int alignnode(struct filenode *node, int curroffset, int extraspace) { - int align = findalign(node), d; - - d = ((curroffset + extraspace) & (align - 1)); - if (d) { - align -= d; - curroffset += align; - node->offset += align; - node->pad = align; - } - return curroffset; + int align = findalign(node), d; + + d = ((curroffset + extraspace) & (align - 1)); + if (d) { + align -= d; + curroffset += align; + node->offset += align; + node->pad = align; + } + return curroffset; } int processdir(int level, const char *base, const char *dirname, struct stat *sb, - struct filenode *dir, struct filenode *root, int curroffset) + struct filenode *dir, struct filenode *root, int curroffset) { - DIR *dirfd; - struct dirent *dp; - struct filenode *n, *link; - struct excludes *pe; + DIR *dirfd; + struct dirent *dp; + struct filenode *n, *link; + struct excludes *pe; - if (level <= 1) { - /* Ok, to make sure . and .. are handled correctly - * we add them first. Note also that we alloc them - * first to get to know the real name - */ - link = newnode(base, ".", curroffset); - if (!lstat(link->realname, sb)) { - setnode(link, sb->st_dev, sb->st_ino, sb->st_mode); - append(&dir->dirlist, link); + if (level <= 1) { + /* Ok, to make sure . and .. are handled correctly + * we add them first. Note also that we alloc them + * first to get to know the real name + */ + link = newnode(base, ".", curroffset); + if (!lstat(link->realname, sb)) { + setnode(link, sb->st_dev, sb->st_ino, sb->st_mode); + append(&dir->dirlist, link); - /* special case for root node - '..'s in subdirs should link to - * '.' of root node, not root node itself. - */ - dir->dirlist.owner = link; + /* special case for root node - '..'s in subdirs should link to + * '.' of root node, not root node itself. + */ + dir->dirlist.owner = link; - curroffset = alignnode(link, curroffset, 0) + spaceneeded(link); - n = newnode(base, "..", curroffset); + curroffset = alignnode(link, curroffset, 0) + spaceneeded(link); + n = newnode(base, "..", curroffset); - if (!lstat(n->realname, sb)) { - setnode(n, sb->st_dev, sb->st_ino, sb->st_mode); - append(&dir->dirlist, n); - n->orig_link = link; - curroffset = alignnode(n, curroffset, 0) + spaceneeded(n); - } - } - } + if (!lstat(n->realname, sb)) { + setnode(n, sb->st_dev, sb->st_ino, sb->st_mode); + append(&dir->dirlist, n); + n->orig_link = link; + curroffset = alignnode(n, curroffset, 0) + spaceneeded(n); + } + } + } - dirfd = opendir(dir->realname); - if (dirfd == NULL) { - perror(dir->realname); - } - while(dirfd && (dp = readdir(dirfd))) { - /* don't process main . and .. twice */ - if (level <= 1 && - (strcmp(dp->d_name, ".") == 0 - || strcmp(dp->d_name, "..") == 0)) - continue; - n = newnode(base, dp->d_name, curroffset); + dirfd = opendir(dir->realname); + if (dirfd == NULL) { + perror(dir->realname); + } + while(dirfd && (dp = readdir(dirfd))) { + /* don't process main . and .. twice */ + if (level <= 1 && + (strcmp(dp->d_name, ".") == 0 + || strcmp(dp->d_name, "..") == 0)) + continue; + n = newnode(base, dp->d_name, curroffset); - /* Process exclude list. */ - for (pe = excludelist; pe; pe = pe->next) { - if (!nodematch(pe->pattern, n)) { freenode(n); break; } - } - if (pe) continue; + /* Process exclude list. */ + for (pe = excludelist; pe; pe = pe->next) { + if (!nodematch(pe->pattern, n)) { freenode(n); break; } + } + if (pe) continue; - if (lstat(n->realname, sb)) { - fprintf(stderr, "ignoring '%s' (lstat failed)\n", n->realname); - freenode(n); continue; - } + if (lstat(n->realname, sb)) { + fprintf(stderr, "ignoring '%s' (lstat failed)\n", n->realname); + freenode(n); continue; + } - /* Handle special names */ - if ( n->name[0] == '@' ) { - if (S_ISLNK(sb->st_mode)) { - /* this is a link to follow at build time */ - n->name = n->name + 1; /* strip off the leading @ */ - memset(bigbuf, 0, sizeof(bigbuf)); - readlink(n->realname, bigbuf, sizeof(bigbuf)); - n->realname = strdup(bigbuf); + /* Handle special names */ + if ( n->name[0] == '@' ) { + if (S_ISLNK(sb->st_mode)) { + /* this is a link to follow at build time */ + n->name = n->name + 1; /* strip off the leading @ */ + memset(bigbuf, 0, sizeof(bigbuf)); + readlink(n->realname, bigbuf, sizeof(bigbuf)); + n->realname = strdup(bigbuf); - if (lstat(n->realname, sb)) { - fprintf(stderr, "ignoring '%s' (lstat failed)\n", - n->realname); - freenode(n); continue; - } - } else if (S_ISREG(sb->st_mode) && sb->st_size == 0) { - /* - * special file @name,[bcp..],major,minor - */ - char devname[32]; - char type; - int major; - int minor; - - if (sscanf(n->name, "@%[a-zA-Z0-9_+-],%c,%d,%d", - devname, &type, &major, &minor) == 4 ) { - strcpy(n->name, devname); - sb->st_rdev = makedev(major, minor); - sb->st_mode &= ~S_IFMT; - switch (type) { - case 'c': - case 'u': - sb->st_mode |= S_IFCHR; - break; - case 'b': - sb->st_mode |= S_IFBLK; - break; - case 'p': - sb->st_mode |= S_IFIFO; - break; - default: - fprintf(stderr, "Invalid special device type '%c' " - "for file %s\n", type, n->realname); - freenode(n); - continue; - } - } - } - } + if (lstat(n->realname, sb)) { + fprintf(stderr, "ignoring '%s' (lstat failed)\n", + n->realname); + freenode(n); continue; + } + } else if (S_ISREG(sb->st_mode) && sb->st_size == 0) { + /* + * special file @name,[bcp..],major,minor + */ + char devname[32]; + char type; + int major; + int minor; - setnode(n, sb->st_dev, sb->st_ino, sb->st_mode); - /* Skip unreadable files/dirs */ - if (!S_ISLNK(n->modes) && access(n->realname, R_OK)) { - fprintf(stderr, "ignoring '%s' (access failed)\n", n->realname); - freenode(n); continue; - } + if (sscanf(n->name, "@%[a-zA-Z0-9_+-],%c,%d,%d", + devname, &type, &major, &minor) == 4 ) { + strcpy(n->name, devname); + sb->st_rdev = makedev(major, minor); + sb->st_mode &= ~S_IFMT; + switch (type) { + case 'c': + case 'u': + sb->st_mode |= S_IFCHR; + break; + case 'b': + sb->st_mode |= S_IFBLK; + break; + case 'p': + sb->st_mode |= S_IFIFO; + break; + default: + fprintf(stderr, "Invalid special device type '%c' " + "for file %s\n", type, n->realname); + freenode(n); + continue; + } + } + } + } - /* Look up old links */ - if ( strcmp(n->name, ".") == 0 ) { - append(&dir->dirlist, n); - link = n->parent; - } else if (strcmp(n->name, "..") == 0) { - append(&dir->dirlist, n); - link = n->parent->parent; - } else { - link = findnode(root, n->ondev, n->onino); - append(&dir->dirlist, n); - } + setnode(n, sb->st_dev, sb->st_ino, sb->st_mode); + /* Skip unreadable files/dirs */ + if (!S_ISLNK(n->modes) && access(n->realname, R_OK)) { + fprintf(stderr, "ignoring '%s' (access failed)\n", n->realname); + freenode(n); continue; + } - if (link) { - n->orig_link = link; - curroffset = alignnode(n, curroffset, 0) + spaceneeded(n); - continue; - } - if (S_ISREG(sb->st_mode)) { - curroffset = alignnode(n, curroffset, spaceneeded(n)); - n->size = sb->st_size; - } else - curroffset = alignnode(n, curroffset, 0); - if (S_ISLNK(sb->st_mode)) { - n->size = sb->st_size; - } - curroffset += spaceneeded(n); - if (S_ISCHR(sb->st_mode) || S_ISBLK(sb->st_mode)) { - n->devnode = sb->st_rdev; - } + /* Look up old links */ + if ( strcmp(n->name, ".") == 0 ) { + append(&dir->dirlist, n); + link = n->parent; + } else if (strcmp(n->name, "..") == 0) { + append(&dir->dirlist, n); + link = n->parent->parent; + } else { + link = findnode(root, n->ondev, n->onino); + append(&dir->dirlist, n); + } - if (S_ISDIR(sb->st_mode)) { - if (!strcmp(n->name, "..")) { - curroffset = processdir(level+1, dir->realname, dp->d_name, - sb, dir, root, curroffset); - } else { - curroffset = processdir(level+1, n->realname, dp->d_name, - sb, n, root, curroffset); - } - } - } - if (dirfd) closedir(dirfd); - return curroffset; + if (link) { + n->orig_link = link; + curroffset = alignnode(n, curroffset, 0) + spaceneeded(n); + continue; + } + if (S_ISREG(sb->st_mode)) { + curroffset = alignnode(n, curroffset, spaceneeded(n)); + n->size = sb->st_size; + } else + curroffset = alignnode(n, curroffset, 0); + if (S_ISLNK(sb->st_mode)) { + n->size = sb->st_size; + } + curroffset += spaceneeded(n); + if (S_ISCHR(sb->st_mode) || S_ISBLK(sb->st_mode)) { + n->devnode = sb->st_rdev; + } + + if (S_ISDIR(sb->st_mode)) { + if (!strcmp(n->name, "..")) { + curroffset = processdir(level+1, dir->realname, dp->d_name, + sb, dir, root, curroffset); + } else { + curroffset = processdir(level+1, n->realname, dp->d_name, + sb, n, root, curroffset); + } + } + } + if (dirfd) closedir(dirfd); + return curroffset; } void showhelp(const char *argv0) { - printf("genromfs %s\n",VERSION); - printf("Usage: %s [OPTIONS] -f IMAGE\n",argv0); - printf("Create a romfs filesystem image from a directory\n"); - printf("\n"); - printf(" -f IMAGE Output the image into this file\n"); - printf(" -d DIRECTORY Use this directory as source\n"); - printf(" -v (Too) verbose operation\n"); - printf(" -V VOLUME Use the specified volume name\n"); - printf(" -a ALIGN Align regular file data to ALIGN bytes\n"); - printf(" -A ALIGN,PATTERN Align all objects matching pattern to at least ALIGN bytes\n"); - printf(" -x PATTERN Exclude all objects matching pattern\n"); - printf(" -h Show this help\n"); - printf("\n"); - printf("Report bugs to chexum@shadow.banki.hu\n"); + printf("genromfs %s\n",VERSION); + printf("Usage: %s [OPTIONS] -f IMAGE\n",argv0); + printf("Create a romfs filesystem image from a directory\n"); + printf("\n"); + printf(" -f IMAGE Output the image into this file\n"); + printf(" -d DIRECTORY Use this directory as source\n"); + printf(" -v (Too) verbose operation\n"); + printf(" -V VOLUME Use the specified volume name\n"); + printf(" -a ALIGN Align regular file data to ALIGN bytes\n"); + printf(" -A ALIGN,PATTERN Align all objects matching pattern to at least ALIGN bytes\n"); + printf(" -x PATTERN Exclude all objects matching pattern\n"); + printf(" -h Show this help\n"); + printf("\n"); + printf("Report bugs to chexum@shadow.banki.hu\n"); } int main(int argc, char *argv[]) { - int c; - char *dir = "."; - char *outf = NULL; - char *volname = NULL; - int verbose=0; - char buf[256]; - struct filenode *root; - struct stat sb; - int lastoff; - int i; - char *p; - struct aligns *pa, *pa2; - struct excludes *pe, *pe2; - FILE *f; + int c; + char *dir = "."; + char *outf = NULL; + char *volname = NULL; + int verbose=0; + char buf[256]; + struct filenode *root; + struct stat sb; + int lastoff; + int i; + char *p; + struct aligns *pa, *pa2; + struct excludes *pe, *pe2; + FILE *f; - while ((c = getopt(argc, argv, "V:vd:f:ha:A:x:")) != EOF) { - switch(c) { - case 'd': - dir = optarg; - break; - case 'f': - outf = optarg; - break; - case 'V': - volname = optarg; - break; - case 'v': - verbose = 1; - break; - case 'h': - showhelp(argv[0]); - exit(0); - case 'a': - align = strtoul(optarg, NULL, 0); - if (align < 16 || (align & (align - 1))) { - fprintf(stderr, "Align has to be at least 16 bytes and a power of two\n"); - exit(1); - } - break; - case 'A': - i = strtoul(optarg, &p, 0); - if (i < 16 || (i & (i - 1))) { - fprintf(stderr, "Align has to be at least 16 bytes and a power of two\n"); - exit(1); - } - if (*p != ',' || !p[1]) { - fprintf(stderr, "-A takes N,PATTERN format of argument, where N is a number\n"); - exit(1); - } - /* strlen(p+1) + 1 eq strlen(p) */ - pa = (struct aligns *)malloc(sizeof(*pa) + strlen(p)); - pa->align = i; - pa->next = NULL; - strcpy(pa->pattern, p + 1); - if (!alignlist) - alignlist = pa; - else { - for (pa2 = alignlist; pa2->next; pa2 = pa2->next) - ; - pa2->next = pa; - } - break; - case 'x': - pe = (struct excludes *)malloc(sizeof(*pe) + strlen(optarg) + 1); - pe->next = NULL; - strcpy(pe->pattern, optarg); - if (!excludelist) - excludelist = pe; - else { - for (pe2 = excludelist; pe2->next; pe2 = pe2->next) - ; - pe2->next = pe; - } - break; - default: - exit(1); - } - } + while ((c = getopt(argc, argv, "V:vd:f:ha:A:x:")) != EOF) { + switch(c) { + case 'd': + dir = optarg; + break; + case 'f': + outf = optarg; + break; + case 'V': + volname = optarg; + break; + case 'v': + verbose = 1; + break; + case 'h': + showhelp(argv[0]); + exit(0); + case 'a': + align = strtoul(optarg, NULL, 0); + if (align < 16 || (align & (align - 1))) { + fprintf(stderr, "Align has to be at least 16 bytes and a power of two\n"); + exit(1); + } + break; + case 'A': + i = strtoul(optarg, &p, 0); + if (i < 16 || (i & (i - 1))) { + fprintf(stderr, "Align has to be at least 16 bytes and a power of two\n"); + exit(1); + } + if (*p != ',' || !p[1]) { + fprintf(stderr, "-A takes N,PATTERN format of argument, where N is a number\n"); + exit(1); + } + /* strlen(p+1) + 1 eq strlen(p) */ + pa = (struct aligns *)malloc(sizeof(*pa) + strlen(p)); + pa->align = i; + pa->next = NULL; + strcpy(pa->pattern, p + 1); + if (!alignlist) + alignlist = pa; + else { + for (pa2 = alignlist; pa2->next; pa2 = pa2->next) + ; + pa2->next = pa; + } + break; + case 'x': + pe = (struct excludes *)malloc(sizeof(*pe) + strlen(optarg) + 1); + pe->next = NULL; + strcpy(pe->pattern, optarg); + if (!excludelist) + excludelist = pe; + else { + for (pe2 = excludelist; pe2->next; pe2 = pe2->next) + ; + pe2->next = pe; + } + break; + default: + exit(1); + } + } - if (!volname) { - sprintf(buf, "rom %08lx", time(NULL)); - volname = buf; - } - if (!outf) { - fprintf(stderr, "%s: you must specify the destination file\n", argv[0]); - fprintf(stderr, "Try `%s -h' for more information\n",argv[0]); - exit(1); - } - if (strcmp(outf, "-") == 0) { - f = fdopen(1,"wb"); - } else - f = fopen(outf, "wb"); + if (!volname) { + sprintf(buf, "rom %08lx", time(NULL)); + volname = buf; + } + if (!outf) { + fprintf(stderr, "%s: you must specify the destination file\n", argv[0]); + fprintf(stderr, "Try `%s -h' for more information\n",argv[0]); + exit(1); + } + if (strcmp(outf, "-") == 0) { + f = fdopen(1,"wb"); + } else + f = fopen(outf, "wb"); - if (!f) { - perror(outf); - exit(1); - } - - realbase = strlen(dir); - root = newnode(dir, volname, 0); - root->parent = root; - lastoff = processdir (1, dir, dir, &sb, root, root, spaceneeded(root)); - if (verbose) - shownode(0, root, stderr); - dumpall(root, lastoff, f); + if (!f) { + perror(outf); + exit(1); + } - exit(0); + realbase = strlen(dir); + root = newnode(dir, volname, 0); + root->parent = root; + lastoff = processdir (1, dir, dir, &sb, root, root, spaceneeded(root)); + if (verbose) + shownode(0, root, stderr); + dumpall(root, lastoff, f); + + exit(0); } diff --git a/components/fs/romfs/src/bl_romfs.c b/components/fs/romfs/src/bl_romfs.c index 626037b6..98e95766 100644 --- a/components/fs/romfs/src/bl_romfs.c +++ b/components/fs/romfs/src/bl_romfs.c @@ -136,7 +136,7 @@ static int romfs_mount(void) } memset(&info, 0, sizeof(info)); bl_mtd_info(handle_romfs, &info); - + if (0 == info.xip_addr) { log_error("romfs has no XIP-Addr\r\n"); return -1; diff --git a/components/fs/vfs/device/vfs_adc.c b/components/fs/vfs/device/vfs_adc.c index 8b8b79d2..25d9d66a 100644 --- a/components/fs/vfs/device/vfs_adc.c +++ b/components/fs/vfs/device/vfs_adc.c @@ -91,12 +91,12 @@ static ssize_t vfs_adc_read(file_t *fp, void *buf, size_t nbytes) /* check empty pointer. */ if ((fp != NULL) && (fp->node != NULL)) { - /* get the device pointer. */ + /* get the device pointer. */ adc_dev = (adc_dev_t *)(fp->node->i_arg); if (adc_dev != NULL) { - /* get adc sampled value. */ + /* get adc sampled value. */ ret = hal_adc_value_get(adc_dev, &adc_value, HAL_WAIT_FOREVER); /* If the data is got successfully, set the return value to nbytes. */ if (0 == ret) { @@ -174,13 +174,13 @@ static int vfs_adc_ioctl(file_t *fp, int cmd, unsigned long arg) return -EINVAL; } - /* get the device pointer. */ + /* get the device pointer. */ adc_dev = (adc_dev_t *)(fp->node->i_arg); if (adc_dev == NULL) { return -EINVAL; } - + switch(cmd) { case IOCTL_ADC_TRIGGER_DISABLE: /*Disable low level trigger, such as INT*/ diff --git a/components/fs/vfs/device/vfs_i2c.c b/components/fs/vfs/device/vfs_i2c.c index b50c798e..1a0b534e 100644 --- a/components/fs/vfs/device/vfs_i2c.c +++ b/components/fs/vfs/device/vfs_i2c.c @@ -92,8 +92,8 @@ ssize_t vfs_i2c_read(file_t *fp, void *buf, size_t nbytes) /* get data from i2c. */ ret = hal_i2c_master_recv(i2c_dev, dev_addr, (uint8_t *)buf, nbytes, HAL_WAIT_FOREVER); - /* If the data is read correctly, the return - value is set to read bytes. */ + /* If the data is read correctly, the return + value is set to read bytes. */ if (ret == 0) { ret = nbytes; } @@ -102,8 +102,8 @@ ssize_t vfs_i2c_read(file_t *fp, void *buf, size_t nbytes) } } else { ret = -EINVAL; - } - + } + return ret; } @@ -116,7 +116,7 @@ ssize_t vfs_i2c_write(file_t *fp, const void *buf, size_t nbytes) /* check empty pointer. */ if ((fp != NULL) && (fp->node != NULL)) { - /* get the device pointer. */ + /* get the device pointer. */ i2c_dev = (i2c_dev_t *)(fp->node->i_arg); /* get the device address. */ @@ -124,10 +124,10 @@ ssize_t vfs_i2c_write(file_t *fp, const void *buf, size_t nbytes) if (dev_addr != NULL) { - /* send data from i2c. */ + /* send data from i2c. */ ret = hal_i2c_master_send(i2c_dev, dev_addr, (const uint8_t *)buf, nbytes, HAL_WAIT_FOREVER); - /* If the data is sent successfully, set the return + /* If the data is sent successfully, set the return value to nbytes. */ if (ret == 0) { ret = nbytes; diff --git a/components/fs/vfs/device/vfs_pwm.c b/components/fs/vfs/device/vfs_pwm.c index 26804c70..2a99bd4c 100644 --- a/components/fs/vfs/device/vfs_pwm.c +++ b/components/fs/vfs/device/vfs_pwm.c @@ -54,7 +54,7 @@ int vfs_pwm_close(file_t *fp) if (fp->node->refs == 1) { /* get the device pointer. */ - pwm_dev = (pwm_dev_t *)(fp->node->i_arg); + pwm_dev = (pwm_dev_t *)(fp->node->i_arg); if (pwm_dev != NULL) { @@ -86,7 +86,7 @@ int vfs_pwm_ioctl(file_t *fp, int cmd, unsigned long arg) } /* get the device pointer. */ - pwm_dev = (pwm_dev_t *)(fp->node->i_arg); + pwm_dev = (pwm_dev_t *)(fp->node->i_arg); if (pwm_dev == NULL) { return -EINVAL; diff --git a/components/fs/vfs/device/vfs_rtc.c b/components/fs/vfs/device/vfs_rtc.c index ccfc12cc..7a548755 100644 --- a/components/fs/vfs/device/vfs_rtc.c +++ b/components/fs/vfs/device/vfs_rtc.c @@ -53,10 +53,10 @@ int vfs_rtc_close(file_t *fp) if (fp->node->refs == 1) { /* get the device pointer. */ - rtc_dev = (rtc_dev_t *)(fp->node->i_arg); + rtc_dev = (rtc_dev_t *)(fp->node->i_arg); if (rtc_dev != NULL) { - + /* turns off hardware. */ ret = hal_rtc_finalize(rtc_dev); } else { @@ -98,7 +98,7 @@ ssize_t vfs_rtc_read(file_t *fp, void *buf, size_t nbytes) } else { ret = -EINVAL; } - + return ret; } @@ -118,7 +118,7 @@ ssize_t vfs_rtc_write(file_t *fp, const void *buf, size_t nbytes) /* set rtc time. */ ret = hal_rtc_set_time(rtc_dev, (const rtc_time_t *)buf); - /* If the time is set successfully, set the return + /* If the time is set successfully, set the return value to nbytes. */ if (ret == 0) { ret = nbytes; @@ -128,7 +128,7 @@ ssize_t vfs_rtc_write(file_t *fp, const void *buf, size_t nbytes) } } else { ret = -EINVAL; - } + } return ret; } diff --git a/components/fs/vfs/include/device/vfs_gpio.h b/components/fs/vfs/include/device/vfs_gpio.h index 34ddb741..715195ef 100644 --- a/components/fs/vfs/include/device/vfs_gpio.h +++ b/components/fs/vfs/include/device/vfs_gpio.h @@ -39,7 +39,7 @@ int vfs_gpio_close(file_t *fp); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes read on success, + * @return The positive non-zero number of bytes read on success, * 0 on read nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_gpio_write(file_t *fp, const void *buf, size_t nbytes); @@ -51,7 +51,7 @@ ssize_t vfs_gpio_write(file_t *fp, const void *buf, size_t nbytes); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes read on success, + * @return The positive non-zero number of bytes read on success, * 0 on read nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_gpio_read(file_t *fp, void *buf, size_t nbytes); @@ -61,7 +61,7 @@ ssize_t vfs_gpio_read(file_t *fp, void *buf, size_t nbytes); * * @param[in] fp device pointer. * @param[in] cmd command of input and output operating. - * @param[in] arg argument of input and output operating. + * @param[in] arg argument of input and output operating. * * @return 0 on success, negative on failure with errno set appropriately. */ diff --git a/components/fs/vfs/include/device/vfs_i2c.h b/components/fs/vfs/include/device/vfs_i2c.h index 6a1e97e9..de4e47c7 100644 --- a/components/fs/vfs/include/device/vfs_i2c.h +++ b/components/fs/vfs/include/device/vfs_i2c.h @@ -39,7 +39,7 @@ int vfs_i2c_close(file_t *fp); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes read on success, + * @return The positive non-zero number of bytes read on success, * 0 on read nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_i2c_read(file_t *fp, void *buf, size_t nbytes); @@ -51,7 +51,7 @@ ssize_t vfs_i2c_read(file_t *fp, void *buf, size_t nbytes); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes write on success, + * @return The positive non-zero number of bytes write on success, * 0 on write nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_i2c_write(file_t *fp, const void *buf, size_t nbytes); diff --git a/components/fs/vfs/include/device/vfs_pwm.h b/components/fs/vfs/include/device/vfs_pwm.h index 36e271c2..453f72ff 100644 --- a/components/fs/vfs/include/device/vfs_pwm.h +++ b/components/fs/vfs/include/device/vfs_pwm.h @@ -43,7 +43,7 @@ int vfs_pwm_close(file_t *fp); * * @param[in] fp device pointer. * @param[in] cmd command of input and output operating. - * @param[in] arg argument of input and output operating. + * @param[in] arg argument of input and output operating. * * @return 0 on success, negative on failure with errno set appropriately. */ diff --git a/components/fs/vfs/include/device/vfs_rtc.h b/components/fs/vfs/include/device/vfs_rtc.h index ea1764cd..6e0984e6 100644 --- a/components/fs/vfs/include/device/vfs_rtc.h +++ b/components/fs/vfs/include/device/vfs_rtc.h @@ -39,7 +39,7 @@ int vfs_rtc_close(file_t *fp); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes read on success, + * @return The positive non-zero number of bytes read on success, * 0 on read nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_rtc_read(file_t *fp, void *buf, size_t nbytes); @@ -51,7 +51,7 @@ ssize_t vfs_rtc_read(file_t *fp, void *buf, size_t nbytes); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes write on success, + * @return The positive non-zero number of bytes write on success, * 0 on write nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_rtc_write(file_t *fp, const void *buf, size_t nbytes); diff --git a/components/fs/vfs/include/device/vfs_uart.h b/components/fs/vfs/include/device/vfs_uart.h index 7b741d55..1a7edc91 100644 --- a/components/fs/vfs/include/device/vfs_uart.h +++ b/components/fs/vfs/include/device/vfs_uart.h @@ -66,7 +66,7 @@ int vfs_uart_close(file_t *fp); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes read on success, + * @return The positive non-zero number of bytes read on success, * 0 on read nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_uart_read(file_t *fp, void *buf, size_t nbytes); @@ -78,7 +78,7 @@ ssize_t vfs_uart_read(file_t *fp, void *buf, size_t nbytes); * @param[out] buf data buffer for data. * @param[in] nbytes the maximum size of the user-provided buffer. * - * @return The positive non-zero number of bytes write on success, + * @return The positive non-zero number of bytes write on success, * 0 on write nothing, or negative on failure with errno set appropriately. */ ssize_t vfs_uart_write(file_t *fp, const void *buf, size_t nbytes); diff --git a/components/fs/vfs/include/device/vfs_wdg.h b/components/fs/vfs/include/device/vfs_wdg.h index 8c1a9697..9b369ca4 100644 --- a/components/fs/vfs/include/device/vfs_wdg.h +++ b/components/fs/vfs/include/device/vfs_wdg.h @@ -40,7 +40,7 @@ int vfs_wdg_close(file_t *fp); * * @param[in] fp device pointer. * @param[in] cmd command of input and output operating. - * @param[in] arg argument of input and output operating. + * @param[in] arg argument of input and output operating. * * @return 0 on success, negative on failure with errno set appropriately. */ diff --git a/components/fs/vfs/include/hal/soc/gpio.h b/components/fs/vfs/include/hal/soc/gpio.h old mode 100755 new mode 100644 index 260a2402..35f849d7 --- a/components/fs/vfs/include/hal/soc/gpio.h +++ b/components/fs/vfs/include/hal/soc/gpio.h @@ -100,7 +100,7 @@ int32_t hal_gpio_output_toggle(gpio_dev_t *gpio); int32_t hal_gpio_input_get(gpio_dev_t *gpio, uint8_t *value); /** - * Set the GPIO pulltype + * Set the GPIO pulltype * * @param[in] gpio the gpio pin which should be set * @param[in] pulltype the gpio pulltype value diff --git a/components/fs/vfs/include/hal/soc/i2c.h b/components/fs/vfs/include/hal/soc/i2c.h old mode 100755 new mode 100644 diff --git a/components/fs/vfs/include/hal/soc/interpt.h b/components/fs/vfs/include/hal/soc/interpt.h index 5b721311..7000e577 100644 --- a/components/fs/vfs/include/hal/soc/interpt.h +++ b/components/fs/vfs/include/hal/soc/interpt.h @@ -48,7 +48,7 @@ int32_t hal_interpt_umask(int32_t vec); * * @return 0 : on success, -1 : if an error occurred with any step */ -int32_t hal_interpt_install(int32_t vec, hal_interpt_t handler, +int32_t hal_interpt_install(int32_t vec, hal_interpt_t handler, void *para, char *name); #endif diff --git a/components/fs/vfs/include/hal/soc/nand.h b/components/fs/vfs/include/hal/soc/nand.h index 0a2729fb..2038f68e 100644 --- a/components/fs/vfs/include/hal/soc/nand.h +++ b/components/fs/vfs/include/hal/soc/nand.h @@ -22,7 +22,7 @@ typedef struct { typedef struct { uint32_t base_addr; nand_config_t config; - void *priv; + void *priv; } nand_dev_t; /** diff --git a/components/fs/vfs/include/hal/soc/nor.h b/components/fs/vfs/include/hal/soc/nor.h index 8200c5bf..4fe5c01e 100644 --- a/components/fs/vfs/include/hal/soc/nor.h +++ b/components/fs/vfs/include/hal/soc/nor.h @@ -13,7 +13,7 @@ typedef struct { typedef struct { uint32_t base_addr; nor_config_t config; - void *priv; + void *priv; } nor_dev_t; /** @@ -40,7 +40,7 @@ int32_t hal_nor_finalize(nor_dev_t *nor); * @param[in] nor the interface which should be initialised * @param[out] data pointer to the buffer which will store incoming data * @param[in] addr nor memory address - * @param[in] len the number of bytes to read + * @param[in] len the number of bytes to read * * @return 0 : on success, EIO : if an error occurred with any step */ @@ -58,7 +58,7 @@ int32_t hal_nor_read(nor_dev_t *nor, uint32_t *addr, uint8_t *data, uint32_t len * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_nor_write(nor_dev_t *nor, uint32_t *addr, uint8_t *data, uint32_t len); - + /* * Erase the blocks of the NOR memory * diff --git a/components/fs/vfs/include/hal/soc/uart.h b/components/fs/vfs/include/hal/soc/uart.h old mode 100755 new mode 100644 diff --git a/components/fs/vfs/include/hal/soc/usb_hcd.h b/components/fs/vfs/include/hal/soc/usb_hcd.h index 207c4070..cd13f744 100644 --- a/components/fs/vfs/include/hal/soc/usb_hcd.h +++ b/components/fs/vfs/include/hal/soc/usb_hcd.h @@ -11,54 +11,54 @@ /** * @brief Initialize The USB Host Controller - * + * * @param[in] phost pointer to the usb host handler * @param[in] phcd pointer to the usb hcd pointer - * + * * @return 0:success, otherwise is failed */ int hal_usbh_init(void *phost, void **phcd); /** * @brief Finalize The USB Host Controller - * + * * @param[in] hcd pointer to the usb hcd - * + * * @return 0:success, otherwise is failed */ int hal_usbh_finalize(void *hcd); /** * @brief Reset Host Controller's Port - * + * * @param[in] hcd pointer to the usb hcd - * + * * @return 0:success, otherwise is failed */ int hal_usbh_port_reset(void *hcd); /** * @brief Get Device Speed - * + * * @param[in] hcd pointer to the usb hcd - * + * * @return the usb host controller's speed (0, 1, 2) */ int hal_usbh_get_speed(void *hcd); /** * @brief Free The Host Controll's Pipe - * + * * @param[in] hcd pointer to the usb hcd * @param[in] pipe_num the index of the pipe - * + * * @return 0:success, otherwise is failed */ int hal_usbh_pipe_free(void *hcd, uint8_t pipe_num); /** * @brief Configure The Host Controller's Pipe - * + * * @param[in] hcd pointer to the usb hcd * @param[in] index the index of the pipe * @param[in] ep_addr the endpoint address @@ -67,16 +67,16 @@ int hal_usbh_pipe_free(void *hcd, uint8_t pipe_num); * @param[in] token the transmit token * @param[in] ep_type the endpoint type * @param[in] mps the max packet size - * + * * @return 0:success, otherwise is failed */ -int hal_usbh_pipe_configure(void *hcd, uint8_t index, - uint8_t ep_addr, uint8_t dev_addr, +int hal_usbh_pipe_configure(void *hcd, uint8_t index, + uint8_t ep_addr, uint8_t dev_addr, uint8_t speed, uint8_t ep_type, uint16_t mps); /** * @brief Submit The Urb - * + * * @param[in] hcd pointer to the usb hcd * @param[in] pipe_num the index of the pipe * @param[in] direction the transmit direction @@ -84,19 +84,19 @@ int hal_usbh_pipe_configure(void *hcd, uint8_t index, * @param[in] token the transmit token * @param[in/out] buf pointer to the buffer which will be send or recv * @param[in] length the length of buffer - * + * * @return 0:success, otherwise is failed */ -int hal_usbh_submit_urb(void *hcd, uint8_t pipe_num, - uint8_t direction, uint8_t ep_type, +int hal_usbh_submit_urb(void *hcd, uint8_t pipe_num, + uint8_t direction, uint8_t ep_type, uint8_t token, uint8_t *buf, uint16_t length); /** * @brief Get The Urb Transmit State - * + * * @param[in] hcd pointer to the usb hcd * @param[in] pipe_num the index of the pipe - * + * * @return 0:Idle, 1:Done, 2:Not Ready, 3:Nyet, 4:Error, 5:Stall */ int hal_usbh_get_urb_state(void *hcd, uint8_t pipe_num); diff --git a/components/fs/vfs/src/vfs_register.c b/components/fs/vfs/src/vfs_register.c index 8d02ff12..b7c48813 100644 --- a/components/fs/vfs/src/vfs_register.c +++ b/components/fs/vfs/src/vfs_register.c @@ -97,7 +97,7 @@ int aos_register_fs(const char *path, fs_ops_t *ops, void *arg) int aos_unregister_fs(const char *path) { int err, ret; - + if (pdTRUE != xSemaphoreTake(g_vfs_mutex, portMAX_DELAY)) { err = -1; return err; diff --git a/components/hal_drv/bl602_hal/bl_adc.c b/components/hal_drv/bl602_hal/bl_adc.c index 18397880..8856a545 100644 --- a/components/hal_drv/bl602_hal/bl_adc.c +++ b/components/hal_drv/bl602_hal/bl_adc.c @@ -50,7 +50,7 @@ //#define TEMP_OFFSET_X 22791 #define TEMP_OFFSET_X 2318 -#define ADC_CLOCK_FREQ 96000000 +#define ADC_CLOCK_FREQ 96000000 ADC_CFG_Type adcCfg = { .v18Sel=ADC_V18_SEL_1P82V, /*!< ADC 1.8V select */ @@ -99,8 +99,8 @@ void TSEN_Calibration(void) static void ADC_tsen_case(void) { - ADC_Result_Type result; - uint32_t regVal=0; + ADC_Result_Type result; + uint32_t regVal=0; uint8_t i=0; uint32_t v0=0,v1=0; float v_error=0; @@ -117,21 +117,21 @@ static void ADC_tsen_case(void) ADC_FIFO_Cfg(&adcFifoCfg); TSEN_Calibration(); - for(i=0;i<40;i++){ - ADC_Start(); + for(i=0;i<40;i++){ + ADC_Start(); - while(ADC_Get_FIFO_Count() == 0); + while(ADC_Get_FIFO_Count() == 0); - do{ - regVal = ADC_Read_FIFO(); - ADC_Parse_Result(®Val,1,&result); + do{ + regVal = ADC_Read_FIFO(); + ADC_Parse_Result(®Val,1,&result); if(i%2 ==0){ v0 = result.value; }else{ v1 = result.value; - } - }while(ADC_Get_FIFO_Count() != 0); + } + }while(ADC_Get_FIFO_Count() != 0); if(i%2 !=0){ v_error = (float)v0 - (float)v1; @@ -146,8 +146,8 @@ static void ADC_tsen_case(void) else ADC_SET_TSVBE_LOW(); - ARCH_Delay_MS(500); - } + ARCH_Delay_MS(500); + } } @@ -314,7 +314,7 @@ int bl_adc_freq_init(int mode, uint32_t freq) uint32_t div; uint32_t source_freq; uint32_t mode_freq; - + if (mode == 0) { mode_freq = 12; } else { @@ -330,9 +330,9 @@ int bl_adc_freq_init(int mode, uint32_t freq) if (div > 64) { div = 64; } - + GLB_Set_ADC_CLK(ENABLE, GLB_ADC_CLK_96M, div - 1); - + return 0; } @@ -345,7 +345,7 @@ int bl_adc_init(int mode, int gpio_num) ADC_Chan_Type pos_chlist_single[ADC_CHANNEL_MAX]; ADC_Chan_Type neg_chlist_single[ADC_CHANNEL_MAX]; ADC_FIFO_Cfg_Type adc_fifo_cfg; - + adccfg.v18Sel=ADC_V18_SEL_1P82V; adccfg.v11Sel=ADC_V11_SEL_1P1V; adccfg.clkDiv=ADC_CLK_DIV_24; @@ -365,7 +365,7 @@ int bl_adc_init(int mode, int gpio_num) ADC_Reset(); ADC_Init(&adccfg); - + if (mode == 0) { for (i = 0; i < ADC_CHANNEL_MAX; i++) { pos_chlist_single[i] = i; @@ -389,7 +389,7 @@ int bl_adc_init(int mode, int gpio_num) } static void adc_dma_lli_init(DMA_LLI_Ctrl_Type *pstlli, uint32_t *buf, uint32_t data_num) -{ +{ struct DMA_Control_Reg dma_ctrl_reg; dma_ctrl_reg.TransferSize = data_num; @@ -405,15 +405,15 @@ static void adc_dma_lli_init(DMA_LLI_Ctrl_Type *pstlli, uint32_t *buf, uint32_t pstlli[0].srcDmaAddr = 0x40002000+0x4; pstlli[0].destDmaAddr = (uint32_t)&buf[0]; - pstlli[0].nextLLI = (uint32_t)&pstlli[1]; + pstlli[0].nextLLI = (uint32_t)&pstlli[1]; pstlli[0].dmaCtrl= dma_ctrl_reg; pstlli[1].srcDmaAddr = 0x40002000+0x4; pstlli[1].destDmaAddr = (uint32_t)&buf[ADC_CHANNEL_MAX]; pstlli[1].nextLLI = (uint32_t)&pstlli[0]; pstlli[1].dmaCtrl= dma_ctrl_reg; - - return; + + return; } int bl_adc_dma_init(int mode, uint32_t data_num) @@ -435,7 +435,7 @@ int bl_adc_dma_init(int mode, uint32_t data_num) return -1; } - + pstlli = pvPortMalloc(sizeof(DMA_LLI_Ctrl_Type) * 2); if (pstlli == NULL) { blog_error("malloc lli failed. \r\n"); @@ -449,7 +449,7 @@ int bl_adc_dma_init(int mode, uint32_t data_num) return -1; } - + llicfg.dir = DMA_TRNS_P2M; llicfg.srcPeriph = DMA_REQ_GPADC0; llicfg.dstPeriph = DMA_REQ_NONE; @@ -480,14 +480,14 @@ int bl_adc_start(void) ADC_Start(); DMA_Enable(); DMA_Channel_Enable(ADC_DMA_CHANNEL); - + return 0; } int bl_adc_gpio_init(int gpio_num) { uint8_t adc_pin = gpio_num; - + GLB_GPIO_Func_Init(GPIO_FUN_ANALOG, &adc_pin, 1); return 0; @@ -527,10 +527,10 @@ int32_t bl_adc_parse_data(uint32_t *parr, int data_size, int channel, int raw_fl int bl_adc_get_channel_by_gpio(int gpio_num) { int channel; - + if (gpio_num == 4) { channel = 1; - } else if (gpio_num == 5) { + } else if (gpio_num == 5) { channel = 4; } else if (gpio_num == 6) { channel = 5; @@ -551,7 +551,7 @@ int bl_adc_get_channel_by_gpio(int gpio_num) } else { return -1; } - + return channel; } diff --git a/components/hal_drv/bl602_hal/bl_boot2.c b/components/hal_drv/bl602_hal/bl_boot2.c index e2a37f3e..53e47e06 100644 --- a/components/hal_drv/bl602_hal/bl_boot2.c +++ b/components/hal_drv/bl602_hal/bl_boot2.c @@ -49,14 +49,14 @@ PtTable_Error_Type PtTable_Update_Entry(const SPI_Flash_Cfg_Type *pFlashCfg, if(ptEntry==NULL||ptStuff==NULL){ return PT_ERROR_PARAMETER; } - + ptTable=&ptStuff->ptTable; ptEntries=ptStuff->ptEntries; - + if(targetTableID==PT_TABLE_ID_INVALID){ return PT_ERROR_TABLE_NOT_VALID; } - + if(targetTableID==PT_TABLE_ID_0){ writeAddr=BFLB_PT_TABLE0_ADDRESS; }else{ @@ -77,17 +77,17 @@ PtTable_Error_Type PtTable_Update_Entry(const SPI_Flash_Cfg_Type *pFlashCfg, return PT_ERROR_ENTRY_UPDATE_FAIL; } } - + /* Prepare write back to flash */ /* Update age */ ptTable->age++; ptTable->crc32=BFLB_Soft_CRC32((uint8_t*)ptTable,sizeof(PtTable_Config)-4); - + /* Update entries CRC */ entriesLen=ptTable->entryCnt*sizeof(PtTable_Entry_Config); pCrc32=(uint32_t *)((uint32_t)ptEntries+entriesLen); *pCrc32=BFLB_Soft_CRC32((uint8_t *)&ptEntries[0],entriesLen); - + /* Write back to flash */ /* Erase flash first */ ret=bl_flash_erase(writeAddr,sizeof(PtTable_Config)+entriesLen+4); @@ -110,7 +110,7 @@ PtTable_Error_Type PtTable_Get_Active_Entries(PtTable_Stuff_Config *ptStuff, PtTable_Entry_Config *ptEntry) { uint32_t i=0; - + if(ptStuff==NULL||ptEntry==NULL){ return PT_ERROR_PARAMETER; } diff --git a/components/hal_drv/bl602_hal/bl_cks.c b/components/hal_drv/bl602_hal/bl_cks.c index 01fe3b2a..a50c292b 100644 --- a/components/hal_drv/bl602_hal/bl_cks.c +++ b/components/hal_drv/bl602_hal/bl_cks.c @@ -42,14 +42,14 @@ static void _bl_cks_test_case1() { /*case from wiki: https://en.wikipedia.org/wiki/IPv4_header_checksum*/ - static const uint8_t data_src1[] = + static const uint8_t data_src1[] = { 0x45, 0x00, 0x00, 0x73, 0x00, 0x00, 0x40, 0x00, 0x40, 0x11, 0x00, 0x00, 0xc0, 0xa8, 0x00, 0x01, 0xc0, 0xa8, 0x00, 0xc7 }; static const uint8_t data_src1_cks[] = { - 0xB8, 0x61 + 0xB8, 0x61 }; int i; uint16_t cks; diff --git a/components/hal_drv/bl602_hal/bl_dma.c b/components/hal_drv/bl602_hal/bl_dma.c index ad3774e3..ea358025 100644 --- a/components/hal_drv/bl602_hal/bl_dma.c +++ b/components/hal_drv/bl602_hal/bl_dma.c @@ -178,14 +178,14 @@ void *bl_dma_mem_malloc(uint32_t size) addr_start = DTCM_ADDR_START; addr_end = DTCM_ADDR_END; - + ptr_piece_num = xPortGetFreeHeapSize() / MEM_UNIT_SIZE + 1; p_heap_addr = pvPortMalloc(ptr_piece_num * 4); memset(p_heap_addr, 0, ptr_piece_num * 4); if (p_heap_addr == NULL) { return NULL; } - + ptr = NULL; counts = 0; while (1) { @@ -223,19 +223,19 @@ static void bl_dma_int_process(void) int ch; uint32_t intclr; uint32_t tmpval; - uint32_t interr_val; + uint32_t interr_val; struct dma_node *node; struct dma_ctx *pstctx; - void (*handler)(void) = NULL; + void (*handler)(void) = NULL; int tc_flag, interr_flag; - + tmpval = BL_RD_REG(DMA_BASE, DMA_INTTCSTATUS); interr_val = BL_RD_REG(DMA_BASE, DMA_INTERRORSTATUS); - bl_irq_ctx_get(DMA_ALL_IRQn, (void **)&pstctx); + bl_irq_ctx_get(DMA_ALL_IRQn, (void **)&pstctx); for (ch = 0; ch < DMA_CH_MAX; ch++) { tc_flag = BL_GET_REG_BITS_VAL(tmpval, DMA_INTTCSTATUS) & (1 << ch); interr_flag = BL_GET_REG_BITS_VAL(interr_val, DMA_INTERRORSTATUS) & (1 << ch); - + if((tc_flag != 0) || (interr_flag != 0)) { if (tc_flag != 0) { /* tc int, clear interrupt */ @@ -266,11 +266,11 @@ static void bl_dma_int_process(void) handler = (void(*)(void))node->interr_handler; handler(); } - } + } } - } + } } - + return; } @@ -293,7 +293,7 @@ int bl_dma_irq_register(int channel, void *tc_handler, void *interr_handler, voi return -1; } } - pstnode = pvPortMalloc(sizeof(struct dma_node)); + pstnode = pvPortMalloc(sizeof(struct dma_node)); if (pstnode == NULL) { blog_error("malloc dma node failed. \r\n"); } @@ -317,13 +317,13 @@ void *bl_dma_find_node_by_channel(int channel) break; } } - + if (&(node->dlist_item) == pstctx->pstqueue) { blog_error("not find channel register. \r\n"); return NULL; } - + return node; } @@ -362,7 +362,7 @@ int bl_dma_irq_unregister(int channel) blog_error("not find node \r\n"); return -1; } - + return 0; } diff --git a/components/hal_drv/bl602_hal/bl_gpio_cli.c b/components/hal_drv/bl602_hal/bl_gpio_cli.c index 20547e0f..a07f485d 100644 --- a/components/hal_drv/bl602_hal/bl_gpio_cli.c +++ b/components/hal_drv/bl602_hal/bl_gpio_cli.c @@ -36,7 +36,7 @@ #include #define USER_UNUSED(a) ((void)(a)) -static void cmd_gpio_func(char *buf, int len, int argc, char **argv) +static void cmd_gpio_func(char *buf, int len, int argc, char **argv) { int ionum = -1, inputmode = -1, pullup = -1, pulldown = -1; @@ -67,7 +67,7 @@ static void cmd_gpio_func(char *buf, int len, int argc, char **argv) } } -static void cmd_gpio_set(char *buf, int len, int argc, char **argv) +static void cmd_gpio_set(char *buf, int len, int argc, char **argv) { int ionum = -1, val = -1; @@ -90,7 +90,7 @@ static void cmd_gpio_set(char *buf, int len, int argc, char **argv) bl_gpio_output_set(ionum, val ? 1 : 0); } -static void cmd_gpio_get(char *buf, int len, int argc, char **argv) +static void cmd_gpio_get(char *buf, int len, int argc, char **argv) { int ionum = -1, ret; uint8_t val; @@ -119,13 +119,13 @@ const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { {"gpio-func", "gpio-func pinnum 0/1[0:output, 1:input] 0/1[pullup] 0/1[pulldown]", cmd_gpio_func}, {"gpio-set", "gpio-set pinnum 0/1", cmd_gpio_set}, {"gpio-get", "gpio-get pinnum", cmd_gpio_get}, -}; +}; int bl_gpio_cli_init(void) { // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/hal_drv/bl602_hal/bl_hbn.c b/components/hal_drv/bl602_hal/bl_hbn.c index 1509a23a..1651c9b2 100644 --- a/components/hal_drv/bl602_hal/bl_hbn.c +++ b/components/hal_drv/bl602_hal/bl_hbn.c @@ -156,7 +156,7 @@ int bl_hbn_enter(hbn_type_t *hbn, uint32_t *time) log_buf(hbn->buf, hbn->buflen); } - cfg.sleepTime = (*time + 999) / 1000; + cfg.sleepTime = (*time + 999) / 1000; if ((!hbn->buf) || ((hbn->buflen != 1) && (hbn->buflen != 2))) { printf("not support arg.\r\n"); return -1; diff --git a/components/hal_drv/bl602_hal/bl_i2c.c b/components/hal_drv/bl602_hal/bl_i2c.c index 3e74067f..20046d68 100644 --- a/components/hal_drv/bl602_hal/bl_i2c.c +++ b/components/hal_drv/bl602_hal/bl_i2c.c @@ -62,7 +62,7 @@ void i2c_gpio_init(int i2cx) gpiopins[1] = GLB_GPIO_PIN_3; } else { } - + GLB_GPIO_Func_Init(GPIO_FUN_I2C, gpiopins, sizeof(gpiopins) / sizeof(gpiopins[0])); return; } @@ -70,7 +70,7 @@ void i2c_gpio_init(int i2cx) void i2c_clear_status(int i2cx) { uint32_t tmpval; - + if (i2cx == I2C0) { tmpval = BL_RD_REG(I2C_BASE, I2C_INT_STS); tmpval = BL_SET_REG_BIT(tmpval, I2C_CR_I2C_END_CLR); @@ -83,13 +83,13 @@ void i2c_clear_status(int i2cx) return; } -void do_write_data(i2c_msg_t *pstmsg) +void do_write_data(i2c_msg_t *pstmsg) { uint32_t temp = 0; uint32_t val = 0; int i; int count; - + count = pstmsg->len - pstmsg->idex; if (count >= 4) { count = 4; @@ -132,7 +132,7 @@ static void i2c_transfer_enable(i2c_msg_t *pstmsg) if (pstmsg->direct == I2C_M_WRITE) { I2C_IntMask(pstmsg->i2cx, I2C_TX_FIFO_READY_INT, UNMASK); } else if (pstmsg->direct == I2C_M_READ) { - I2C_IntMask(pstmsg->i2cx, I2C_RX_FIFO_READY_INT, UNMASK); + I2C_IntMask(pstmsg->i2cx, I2C_RX_FIFO_READY_INT, UNMASK); } I2C_IntMask(pstmsg->i2cx, I2C_TRANS_END_INT, UNMASK); diff --git a/components/hal_drv/bl602_hal/bl_i2c.h b/components/hal_drv/bl602_hal/bl_i2c.h index 54135b38..80565f23 100644 --- a/components/hal_drv/bl602_hal/bl_i2c.h +++ b/components/hal_drv/bl602_hal/bl_i2c.h @@ -37,12 +37,12 @@ #define I2C_M_NO_BLOCK 1 typedef struct i2c_msg { - uint16_t addr; - uint8_t direct; + uint16_t addr; + uint8_t direct; uint8_t subflag; uint32_t subaddr; uint8_t sublen; - uint32_t len; + uint32_t len; uint8_t *buf; int event; int idex; diff --git a/components/hal_drv/bl602_hal/bl_ir.c b/components/hal_drv/bl602_hal/bl_ir.c index d98fa84f..77cb066a 100644 --- a/components/hal_drv/bl602_hal/bl_ir.c +++ b/components/hal_drv/bl602_hal/bl_ir.c @@ -30,7 +30,7 @@ #include #include #include -#include +#include #include #include #include @@ -64,7 +64,7 @@ static void ir_init(int pin, int ctrltype) } uint32_t bl_receivedata(void) -{ +{ return IR_ReceiveData(IR_WORD_0); } @@ -145,7 +145,7 @@ static void irled_config(HBN_XCLK_CLK_Type clk, uint8_t div, uint8_t unit, uint8 DISABLE, /* Disable signal of output modulation */ ENABLE /* Enable signal of output inverse */ }; - + IR_TxPulseWidthCfg_Type txPWCfg = { code0L, /* Pulse width of logic 0 pulse phase 1 */ code0H, /* Pulse width of logic 0 pulse phase 0 */ @@ -159,17 +159,17 @@ static void irled_config(HBN_XCLK_CLK_Type clk, uint8_t div, uint8_t unit, uint8 1, /* Modulation phase 0 width */ unit /* Pulse width unit */ }; - + HBN_Set_XCLK_CLK_Sel(clk); GLB_Set_IR_CLK(ENABLE,GLB_IR_CLK_SRC_XCLK,div-1); - + /* Disable ir before config */ IR_Disable(IR_TXRX); /* IR tx init */ IR_TxInit(&txCfg); IR_TxPulseWidthConfig(&txPWCfg); - + return; } @@ -177,7 +177,7 @@ static void irled_config(HBN_XCLK_CLK_Type clk, uint8_t div, uint8_t unit, uint8 int bl_irled_gpio_init(void) { GLB_GPIO_Type pin = GLB_GPIO_PIN_11; - + GLB_GPIO_Func_Init(GPIO_FUN_ANALOG,&pin,1); GLB_IR_LED_Driver_Enable(); @@ -185,13 +185,13 @@ int bl_irled_gpio_init(void) } -int bl_irled_init(int chip_type) -{ +int bl_irled_init(int chip_type) +{ if (chip_type == 0) { irled_config(HBN_XCLK_CLK_XTAL, 2, 1, 8, 16, 16, 9); } else { irled_config(HBN_XCLK_CLK_XTAL, 2, 10, 1, 4, 4, 1); - } + } return 0; } diff --git a/components/hal_drv/bl602_hal/bl_ir.h b/components/hal_drv/bl602_hal/bl_ir.h index 07f5a3ba..81e0ad06 100644 --- a/components/hal_drv/bl602_hal/bl_ir.h +++ b/components/hal_drv/bl602_hal/bl_ir.h @@ -36,7 +36,7 @@ void bl_enable_rx_int(void); int bl_ir_init(int pin, int ctrltype); void bl_irmask(int mask); int bl_irled_gpio_init(void); -int bl_irled_init(int chip_type); +int bl_irled_init(int chip_type); int bl_irled_send_one_data(uint32_t data); diff --git a/components/hal_drv/bl602_hal/bl_irq.c b/components/hal_drv/bl602_hal/bl_irq.c index 5a80f378..853be0f8 100644 --- a/components/hal_drv/bl602_hal/bl_irq.c +++ b/components/hal_drv/bl602_hal/bl_irq.c @@ -102,7 +102,7 @@ void bl_irq_default(void) } static void (*handler_list[2][16 + 64])(void) = { - + }; @@ -125,7 +125,7 @@ void bl_irq_register_with_ctx(int irqnum, void *handler, void *ctx) handler_list[0][irqnum] ); } - + if (handler == NULL) { blog_error("handler is NULL pointer! \r\n"); return; @@ -141,7 +141,7 @@ void bl_irq_register_with_ctx(int irqnum, void *handler, void *ctx) } return; - + } void bl_irq_ctx_get(int irqnum, void **ctx) @@ -170,7 +170,7 @@ void bl_irq_unregister(int irqnum, void *handler) handler_list[0][irqnum] = handler; } -void interrupt_entry(uint32_t mcause) +void interrupt_entry(uint32_t mcause) { void *handler = NULL; mcause &= 0x7FFFFFF; @@ -306,9 +306,9 @@ extern void misaligned_store_trap(uintptr_t* regs, uintptr_t mcause, uintptr_t m #ifdef DBG_RECORD_EXCEP_VAL struct{ - uint32_t mcause; - uint32_t mepc; - uint32_t mtval; + uint32_t mcause; + uint32_t mepc; + uint32_t mtval; }rval[4]; int rval_idx; #endif /* DBG_RECORD_EXCEP_VAL */ @@ -316,10 +316,10 @@ int rval_idx; void exception_entry(uint32_t mcause, uint32_t mepc, uint32_t mtval, uintptr_t *regs) { #ifdef DBG_RECORD_EXCEP_VAL - rval[rval_idx&0x3].mcause = mcause; - rval[rval_idx&0x3].mepc = mepc; - rval[rval_idx&0x3].mtval = mtval; - rval_idx++; + rval[rval_idx&0x3].mcause = mcause; + rval[rval_idx&0x3].mepc = mepc; + rval[rval_idx&0x3].mtval = mtval; + rval_idx++; #endif /* DBG_RECORD_EXCEP_VAL */ if ((mcause & 0x3ff) == EXCPT_LOAD_MISALIGNED){ misaligned_load_trap(regs, mcause, mepc); diff --git a/components/hal_drv/bl602_hal/bl_pds.c b/components/hal_drv/bl602_hal/bl_pds.c index bd11bc85..c10a256f 100644 --- a/components/hal_drv/bl602_hal/bl_pds.c +++ b/components/hal_drv/bl602_hal/bl_pds.c @@ -370,17 +370,17 @@ void ATTR_TCM_SECTION bl_pds_init(void) XIP_SFlash_Read_Via_Cache_Need_Lock(BL602_FLASH_XIP_BASE+XTAL_TYPE_OFFSET,&xtalType,1); SFlash_Cache_Flush(); __enable_irq(); - + // Get whether flash continuous read mode configured flashContRead = *(volatile uint32_t *)0x4000B014 & (0x1<<27) ? 0 : 1; - + // Select XTAL32K (XTAL32K is default on) #ifdef CFG_USE_XTAL32K HBN_32K_Sel(HBN_32K_XTAL); #else HBN_32K_Sel(HBN_32K_RC); #endif - + #if 1 // Set clock gating to unused peripherals //GLB_AHB_Slave1_Clock_Gate(1, BL_AHB_SLAVE1_GLB); @@ -419,7 +419,7 @@ void ATTR_TCM_SECTION bl_pds_enter(uint32_t pdsLevel, uint32_t pdsSleepCycles) { PDS_DEFAULT_LV_CFG_Type *pdsCfg; uint32_t pin; - + if(pdsLevel == 0){ pdsCfg = &pdsCfgLevel0; }else if(pdsLevel == 1){ @@ -433,16 +433,16 @@ void ATTR_TCM_SECTION bl_pds_enter(uint32_t pdsLevel, uint32_t pdsSleepCycles) }else{ return; } - + // Disable global interrupt __disable_irq(); - + // Disable GPIO7 pull up/down to reduce PDS current, 0x4000F014[16]=0 HBN_Hw_Pu_Pd_Cfg(DISABLE); - + // Disable GPIO7 IE/SMT, 0x4000F014[8]=0 HBN_Aon_Pad_IeSmt_Cfg(DISABLE); - + // Disable TRNG #if IS_ECO_VERSION == 0 SEC_Eng_Turn_On_Sec_Ring(); @@ -450,17 +450,17 @@ void ATTR_TCM_SECTION bl_pds_enter(uint32_t pdsLevel, uint32_t pdsSleepCycles) SEC_Eng_Turn_Off_Sec_Ring(); #endif Sec_Eng_Trng_Disable(); - + // Power down flash SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); SFlash_Reset_Continue_Read(&flashCfg); SFlash_Powerdown(); - + // Set internal flash pads (GPIO23 - GPIO28) in High-Z mode for(pin=23; pin<=28; pin++){ GLB_GPIO_Set_HZ(pin); } - + #if 1 // Set all external pads (GPIO0 - GPIO22, uart pads excluded) in High-Z mode for(pin=0; pin<=22; pin++){ @@ -470,25 +470,25 @@ void ATTR_TCM_SECTION bl_pds_enter(uint32_t pdsLevel, uint32_t pdsSleepCycles) GLB_GPIO_Set_HZ(pin); } #endif - + // Select RC32M HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_RC32M); PDS_Power_Off_PLL(); - + // Enter PDS PDS_Default_Level_Config(pdsCfg, NULL, pdsSleepCycles); - + // Select PLL PDS_Power_On_PLL((PDS_PLL_XTAL_Type)xtalType); HBN_Set_ROOT_CLK_Sel(HBN_ROOT_CLK_PLL); - + // Initialize internal flash pads SF_Cfg_Init_Flash_Gpio(0, 1); - + // Power on flash SF_Ctrl_Set_Owner(SF_CTRL_OWNER_SAHB); SFlash_Restore_From_Powerdown(&flashCfg, flashContRead); - + // Enable TRNG #if IS_ECO_VERSION == 0 SEC_Eng_Turn_Off_Sec_Ring(); @@ -496,13 +496,13 @@ void ATTR_TCM_SECTION bl_pds_enter(uint32_t pdsLevel, uint32_t pdsSleepCycles) SEC_Eng_Turn_On_Sec_Ring(); #endif Sec_Eng_Trng_Enable(); - + // Enable GPIO7 IE/SMT, 0x4000F014[8]=1 HBN_Aon_Pad_IeSmt_Cfg(ENABLE); - + // Enable GPIO7 pull up/down, 0x4000F014[16]=1 HBN_Hw_Pu_Pd_Cfg(ENABLE); - + // Enable global interrupt __enable_irq(); } diff --git a/components/hal_drv/bl602_hal/bl_pwm.c b/components/hal_drv/bl602_hal/bl_pwm.c index 14a5d754..0003b32c 100644 --- a/components/hal_drv/bl602_hal/bl_pwm.c +++ b/components/hal_drv/bl602_hal/bl_pwm.c @@ -38,12 +38,12 @@ static void gpio_init(uint8_t pin) { - GLB_GPIO_Cfg_Type cfg; + GLB_GPIO_Cfg_Type cfg; - cfg.drive = 0; - cfg.smtCtrl = 1; - cfg.gpioMode = GPIO_MODE_OUTPUT; - cfg.pullType = GPIO_PULL_DOWN; + cfg.drive = 0; + cfg.smtCtrl = 1; + cfg.gpioMode = GPIO_MODE_OUTPUT; + cfg.pullType = GPIO_PULL_DOWN; cfg.gpioPin = pin; cfg.gpioFun = 8; @@ -55,7 +55,7 @@ static int32_t pwm_init(uint8_t id, uint32_t freq) PWM_CH_CFG_Type pwmCfg = { .ch = PWM_CH0, .clk = PWM_CLK_XCLK, //PWM_CLK_BCLK PWM_CLK_XCLK - .stopMode = PWM_STOP_ABRUPT,//PWM_STOP_ABRUPT:default PWM_STOP_GRACEFUL:no change + .stopMode = PWM_STOP_ABRUPT,//PWM_STOP_ABRUPT:default PWM_STOP_GRACEFUL:no change .pol = PWM_POL_NORMAL, //first low .clkDiv = 0, //40/2 = 20M .period = 100, diff --git a/components/hal_drv/bl602_hal/bl_rtc.c b/components/hal_drv/bl602_hal/bl_rtc.c index 6b1c7d02..7304cdcd 100644 --- a/components/hal_drv/bl602_hal/bl_rtc.c +++ b/components/hal_drv/bl602_hal/bl_rtc.c @@ -37,7 +37,7 @@ void bl_rtc_init(void) #else HBN_32K_Sel(HBN_32K_RC); #endif - + HBN_Clear_RTC_Counter(); HBN_Enable_RTC_Counter(); } @@ -45,17 +45,17 @@ void bl_rtc_init(void) uint64_t bl_rtc_get_counter(void) { uint32_t valLow, valHigh; - + HBN_Get_RTC_Timer_Val(&valLow, &valHigh); - + return ((uint64_t)valHigh << 32) | valLow; } uint64_t bl_rtc_get_timestamp_ms(void) { uint64_t cnt; - + cnt = bl_rtc_get_counter(); - + return (cnt >> 5) - (cnt >> 11) - (cnt >> 12); } diff --git a/components/hal_drv/bl602_hal/bl_sec.c b/components/hal_drv/bl602_hal/bl_sec.c index fd924c66..ef4621f7 100644 --- a/components/hal_drv/bl602_hal/bl_sec.c +++ b/components/hal_drv/bl602_hal/bl_sec.c @@ -58,7 +58,7 @@ static inline void _trng_trigger() uint32_t TRNGx = SEC_ENG_BASE + SEC_ENG_TRNG_OFFSET; uint32_t val; - val = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); + val = BL_RD_REG(TRNGx, SEC_ENG_SE_TRNG_CTRL_0); if (BL_IS_REG_BIT_SET(val, SEC_ENG_SE_TRNG_BUSY)) { return; } @@ -260,19 +260,19 @@ static void _pka_test_case2(void) { static const uint8_t n[256] = { 0xd8, 0xa6, 0x4f, 0xea, 0x28, 0xf9, 0xdf, 0x07, 0x04, 0x55, 0xfa, 0xfb, 0x50, 0x5d, 0xbe, 0xb6, - 0x9f, 0x7b, 0x53, 0x96, 0xef, 0x05, 0x5e, 0x0a, 0xf5, 0x2d, 0xe3, 0x67, 0x78, 0x07, 0x6b, 0xf6, - 0xb2, 0x17, 0xac, 0x2e, 0x51, 0x42, 0x84, 0xbb, 0xfe, 0x3e, 0x5f, 0x0c, 0x85, 0xc4, 0x9d, 0xd4, - 0x8b, 0xd5, 0xfa, 0x17, 0x2d, 0xb1, 0x26, 0x81, 0xe7, 0x79, 0x07, 0x45, 0x82, 0x42, 0x22, 0x3d, - 0x0d, 0x97, 0xcf, 0xde, 0xea, 0xb8, 0xba, 0x16, 0x05, 0x8a, 0x5b, 0x0f, 0xec, 0x07, 0x30, 0xa4, - 0xc6, 0xbf, 0xff, 0x20, 0x52, 0x1b, 0x94, 0xad, 0xfa, 0xb7, 0x6e, 0x83, 0x14, 0x48, 0x58, 0x14, - 0x99, 0xe7, 0xa3, 0x9e, 0xc1, 0x08, 0xbd, 0xfe, 0x20, 0x11, 0x56, 0xdb, 0x96, 0x0a, 0xbb, 0x0b, - 0xbc, 0xd4, 0x37, 0x55, 0xf9, 0x9c, 0x6d, 0x5b, 0x87, 0x4e, 0x50, 0x9f, 0x24, 0x0e, 0x3a, 0x1a, - 0x0c, 0x54, 0x67, 0xbd, 0x0f, 0x34, 0x03, 0x5e, 0x45, 0x5b, 0x93, 0x42, 0xbe, 0x71, 0xe6, 0xa7, - 0xf9, 0x49, 0x1a, 0xb3, 0xb2, 0xfb, 0x0e, 0xee, 0x3d, 0xcf, 0x0c, 0x5a, 0xf8, 0xb5, 0x80, 0x42, - 0x7c, 0x0c, 0x75, 0xc5, 0xe1, 0x17, 0x29, 0x39, 0x55, 0x2b, 0xb1, 0xf5, 0x72, 0x06, 0x9e, 0x54, - 0x0b, 0x0e, 0xf2, 0x95, 0xc8, 0x5b, 0x69, 0xaf, 0x5b, 0x81, 0x97, 0xae, 0xb1, 0x6e, 0xc4, 0x6d, - 0x95, 0xd8, 0x22, 0x1e, 0x39, 0xf0, 0x76, 0x54, 0x19, 0x96, 0x03, 0x4c, 0x25, 0x85, 0x2f, 0xe1, - 0x84, 0xd7, 0xc1, 0x62, 0xe1, 0x9e, 0x9f, 0x1f, 0xd4, 0xb8, 0xf0, 0xc2, 0x68, 0x76, 0x7c, 0xcf, + 0x9f, 0x7b, 0x53, 0x96, 0xef, 0x05, 0x5e, 0x0a, 0xf5, 0x2d, 0xe3, 0x67, 0x78, 0x07, 0x6b, 0xf6, + 0xb2, 0x17, 0xac, 0x2e, 0x51, 0x42, 0x84, 0xbb, 0xfe, 0x3e, 0x5f, 0x0c, 0x85, 0xc4, 0x9d, 0xd4, + 0x8b, 0xd5, 0xfa, 0x17, 0x2d, 0xb1, 0x26, 0x81, 0xe7, 0x79, 0x07, 0x45, 0x82, 0x42, 0x22, 0x3d, + 0x0d, 0x97, 0xcf, 0xde, 0xea, 0xb8, 0xba, 0x16, 0x05, 0x8a, 0x5b, 0x0f, 0xec, 0x07, 0x30, 0xa4, + 0xc6, 0xbf, 0xff, 0x20, 0x52, 0x1b, 0x94, 0xad, 0xfa, 0xb7, 0x6e, 0x83, 0x14, 0x48, 0x58, 0x14, + 0x99, 0xe7, 0xa3, 0x9e, 0xc1, 0x08, 0xbd, 0xfe, 0x20, 0x11, 0x56, 0xdb, 0x96, 0x0a, 0xbb, 0x0b, + 0xbc, 0xd4, 0x37, 0x55, 0xf9, 0x9c, 0x6d, 0x5b, 0x87, 0x4e, 0x50, 0x9f, 0x24, 0x0e, 0x3a, 0x1a, + 0x0c, 0x54, 0x67, 0xbd, 0x0f, 0x34, 0x03, 0x5e, 0x45, 0x5b, 0x93, 0x42, 0xbe, 0x71, 0xe6, 0xa7, + 0xf9, 0x49, 0x1a, 0xb3, 0xb2, 0xfb, 0x0e, 0xee, 0x3d, 0xcf, 0x0c, 0x5a, 0xf8, 0xb5, 0x80, 0x42, + 0x7c, 0x0c, 0x75, 0xc5, 0xe1, 0x17, 0x29, 0x39, 0x55, 0x2b, 0xb1, 0xf5, 0x72, 0x06, 0x9e, 0x54, + 0x0b, 0x0e, 0xf2, 0x95, 0xc8, 0x5b, 0x69, 0xaf, 0x5b, 0x81, 0x97, 0xae, 0xb1, 0x6e, 0xc4, 0x6d, + 0x95, 0xd8, 0x22, 0x1e, 0x39, 0xf0, 0x76, 0x54, 0x19, 0x96, 0x03, 0x4c, 0x25, 0x85, 0x2f, 0xe1, + 0x84, 0xd7, 0xc1, 0x62, 0xe1, 0x9e, 0x9f, 0x1f, 0xd4, 0xb8, 0xf0, 0xc2, 0x68, 0x76, 0x7c, 0xcf, 0x43, 0x3e, 0x60, 0x93, 0xd0, 0x89, 0x65, 0xae, 0x72, 0xcd, 0xd6, 0x00, 0x0d, 0x91, 0x42, 0x90, 0x98, 0x02, 0xa9, 0xf6, 0x82, 0x1b, 0xb5, 0x22, 0xfd, 0xb6, 0xc2, 0x5c, 0xad, 0x86, 0x81, 0x1d, }; @@ -292,7 +292,7 @@ static void _pka_test_case2(void) 0x65, 0x32, 0x30, 0x34, 0x63, 0x31, 0x36, 0x31, 0x36, 0x61, 0x31, 0x33, 0x65, 0x33, 0x62, 0x31, 0x34, 0x65, 0x38, 0x65, 0x32, 0x39, 0x63, 0x39, 0x35, 0x33, 0x33, 0x38, 0x36, 0x65, 0x65, 0x64, 0x62, 0x63, 0x30, 0x39, 0x34, 0x30, 0x37, 0x62, 0x39, 0x34, 0x33, 0x34, 0x38, 0x37, 0x37, 0x36, - 0x36, 0x37, 0x63, 0x62, 0x33, 0x30, 0x39, 0x63, 0x36, 0x33, 0x30, 0x34, 0x32, 0x32, 0x36, 0x32, + 0x36, 0x37, 0x63, 0x62, 0x33, 0x30, 0x39, 0x63, 0x36, 0x33, 0x30, 0x34, 0x32, 0x32, 0x36, 0x32, }; static const uint8_t e[4] = { 0x00, 0x01, 0x00, 0x01, @@ -313,7 +313,7 @@ static void _pka_test_case2(void) 0xb3, 0x94, 0x39, 0x32, 0xdd, 0xc4, 0x2b, 0x2f, 0xb0, 0x13, 0xfe, 0xb5, 0x5e, 0xc7, 0x64, 0x93, 0x7a, 0xb5, 0x81, 0x93, 0x1f, 0x9f, 0x96, 0x1e, 0x7a, 0x5c, 0x8d, 0xde, 0x8f, 0xae, 0xd9, 0xc8, 0xdd, 0x35, 0x1e, 0x17, 0x47, 0xb6, 0xab, 0xed, 0xb6, 0x82, 0x22, 0x4c, 0x62, 0xbd, 0x12, 0x4e, - 0x44, 0x5c, 0x48, 0x2b, 0x75, 0x63, 0x1c, 0xde, 0xfa, 0x15, 0x0d, 0xb1, 0x50, 0x31, 0xb6, 0xcb, + 0x44, 0x5c, 0x48, 0x2b, 0x75, 0x63, 0x1c, 0xde, 0xfa, 0x15, 0x0d, 0xb1, 0x50, 0x31, 0xb6, 0xcb, }; static const uint8_t inv_r[256] = { 0x2f, 0xb7, 0xf5, 0x4a, 0xd2, 0x19, 0xde, 0x24, 0x7c, 0xdb, 0xcd, 0x52, 0x6e, 0xbc, 0x2c, 0x5c, @@ -331,7 +331,7 @@ static void _pka_test_case2(void) 0x37, 0xd6, 0xc5, 0xa6, 0x4a, 0x90, 0x6c, 0x44, 0x6a, 0xd9, 0x0f, 0x20, 0xb2, 0xef, 0x22, 0xa0, 0xdf, 0x38, 0x2d, 0x0b, 0xb3, 0x03, 0xb2, 0xc8, 0xe6, 0x8d, 0x74, 0xbf, 0x45, 0x91, 0xe0, 0x22, 0x16, 0xbf, 0xc4, 0xda, 0x54, 0x26, 0xaa, 0x65, 0x85, 0x88, 0xc3, 0xfb, 0x9f, 0xfc, 0x14, 0xc4, - 0xff, 0x8b, 0x88, 0x47, 0x5f, 0xb1, 0x55, 0xdf, 0x47, 0x5c, 0xc0, 0x27, 0x39, 0x7b, 0xe8, 0xad, + 0xff, 0x8b, 0x88, 0x47, 0x5f, 0xb1, 0x55, 0xdf, 0x47, 0x5c, 0xc0, 0x27, 0x39, 0x7b, 0xe8, 0xad, }; uint32_t result[64]; static const uint8_t encrypted[256] = { @@ -487,19 +487,19 @@ static void _pka_test_case_xgcd(void) int count = 0; static const uint8_t n[256] = { 0xd8, 0xa6, 0x4f, 0xea, 0x28, 0xf9, 0xdf, 0x07, 0x04, 0x55, 0xfa, 0xfb, 0x50, 0x5d, 0xbe, 0xb6, - 0x9f, 0x7b, 0x53, 0x96, 0xef, 0x05, 0x5e, 0x0a, 0xf5, 0x2d, 0xe3, 0x67, 0x78, 0x07, 0x6b, 0xf6, - 0xb2, 0x17, 0xac, 0x2e, 0x51, 0x42, 0x84, 0xbb, 0xfe, 0x3e, 0x5f, 0x0c, 0x85, 0xc4, 0x9d, 0xd4, - 0x8b, 0xd5, 0xfa, 0x17, 0x2d, 0xb1, 0x26, 0x81, 0xe7, 0x79, 0x07, 0x45, 0x82, 0x42, 0x22, 0x3d, - 0x0d, 0x97, 0xcf, 0xde, 0xea, 0xb8, 0xba, 0x16, 0x05, 0x8a, 0x5b, 0x0f, 0xec, 0x07, 0x30, 0xa4, - 0xc6, 0xbf, 0xff, 0x20, 0x52, 0x1b, 0x94, 0xad, 0xfa, 0xb7, 0x6e, 0x83, 0x14, 0x48, 0x58, 0x14, - 0x99, 0xe7, 0xa3, 0x9e, 0xc1, 0x08, 0xbd, 0xfe, 0x20, 0x11, 0x56, 0xdb, 0x96, 0x0a, 0xbb, 0x0b, - 0xbc, 0xd4, 0x37, 0x55, 0xf9, 0x9c, 0x6d, 0x5b, 0x87, 0x4e, 0x50, 0x9f, 0x24, 0x0e, 0x3a, 0x1a, - 0x0c, 0x54, 0x67, 0xbd, 0x0f, 0x34, 0x03, 0x5e, 0x45, 0x5b, 0x93, 0x42, 0xbe, 0x71, 0xe6, 0xa7, - 0xf9, 0x49, 0x1a, 0xb3, 0xb2, 0xfb, 0x0e, 0xee, 0x3d, 0xcf, 0x0c, 0x5a, 0xf8, 0xb5, 0x80, 0x42, - 0x7c, 0x0c, 0x75, 0xc5, 0xe1, 0x17, 0x29, 0x39, 0x55, 0x2b, 0xb1, 0xf5, 0x72, 0x06, 0x9e, 0x54, - 0x0b, 0x0e, 0xf2, 0x95, 0xc8, 0x5b, 0x69, 0xaf, 0x5b, 0x81, 0x97, 0xae, 0xb1, 0x6e, 0xc4, 0x6d, - 0x95, 0xd8, 0x22, 0x1e, 0x39, 0xf0, 0x76, 0x54, 0x19, 0x96, 0x03, 0x4c, 0x25, 0x85, 0x2f, 0xe1, - 0x84, 0xd7, 0xc1, 0x62, 0xe1, 0x9e, 0x9f, 0x1f, 0xd4, 0xb8, 0xf0, 0xc2, 0x68, 0x76, 0x7c, 0xcf, + 0x9f, 0x7b, 0x53, 0x96, 0xef, 0x05, 0x5e, 0x0a, 0xf5, 0x2d, 0xe3, 0x67, 0x78, 0x07, 0x6b, 0xf6, + 0xb2, 0x17, 0xac, 0x2e, 0x51, 0x42, 0x84, 0xbb, 0xfe, 0x3e, 0x5f, 0x0c, 0x85, 0xc4, 0x9d, 0xd4, + 0x8b, 0xd5, 0xfa, 0x17, 0x2d, 0xb1, 0x26, 0x81, 0xe7, 0x79, 0x07, 0x45, 0x82, 0x42, 0x22, 0x3d, + 0x0d, 0x97, 0xcf, 0xde, 0xea, 0xb8, 0xba, 0x16, 0x05, 0x8a, 0x5b, 0x0f, 0xec, 0x07, 0x30, 0xa4, + 0xc6, 0xbf, 0xff, 0x20, 0x52, 0x1b, 0x94, 0xad, 0xfa, 0xb7, 0x6e, 0x83, 0x14, 0x48, 0x58, 0x14, + 0x99, 0xe7, 0xa3, 0x9e, 0xc1, 0x08, 0xbd, 0xfe, 0x20, 0x11, 0x56, 0xdb, 0x96, 0x0a, 0xbb, 0x0b, + 0xbc, 0xd4, 0x37, 0x55, 0xf9, 0x9c, 0x6d, 0x5b, 0x87, 0x4e, 0x50, 0x9f, 0x24, 0x0e, 0x3a, 0x1a, + 0x0c, 0x54, 0x67, 0xbd, 0x0f, 0x34, 0x03, 0x5e, 0x45, 0x5b, 0x93, 0x42, 0xbe, 0x71, 0xe6, 0xa7, + 0xf9, 0x49, 0x1a, 0xb3, 0xb2, 0xfb, 0x0e, 0xee, 0x3d, 0xcf, 0x0c, 0x5a, 0xf8, 0xb5, 0x80, 0x42, + 0x7c, 0x0c, 0x75, 0xc5, 0xe1, 0x17, 0x29, 0x39, 0x55, 0x2b, 0xb1, 0xf5, 0x72, 0x06, 0x9e, 0x54, + 0x0b, 0x0e, 0xf2, 0x95, 0xc8, 0x5b, 0x69, 0xaf, 0x5b, 0x81, 0x97, 0xae, 0xb1, 0x6e, 0xc4, 0x6d, + 0x95, 0xd8, 0x22, 0x1e, 0x39, 0xf0, 0x76, 0x54, 0x19, 0x96, 0x03, 0x4c, 0x25, 0x85, 0x2f, 0xe1, + 0x84, 0xd7, 0xc1, 0x62, 0xe1, 0x9e, 0x9f, 0x1f, 0xd4, 0xb8, 0xf0, 0xc2, 0x68, 0x76, 0x7c, 0xcf, 0x43, 0x3e, 0x60, 0x93, 0xd0, 0x89, 0x65, 0xae, 0x72, 0xcd, 0xd6, 0x00, 0x0d, 0x91, 0x42, 0x90, 0x98, 0x02, 0xa9, 0xf6, 0x82, 0x1b, 0xb5, 0x22, 0xfd, 0xb6, 0xc2, 0x5c, 0xad, 0x86, 0x81, 0x1d, }; @@ -520,7 +520,7 @@ static void _pka_test_case_xgcd(void) 0xb3, 0x94, 0x39, 0x32, 0xdd, 0xc4, 0x2b, 0x2f, 0xb0, 0x13, 0xfe, 0xb5, 0x5e, 0xc7, 0x64, 0x93, 0x7a, 0xb5, 0x81, 0x93, 0x1f, 0x9f, 0x96, 0x1e, 0x7a, 0x5c, 0x8d, 0xde, 0x8f, 0xae, 0xd9, 0xc8, 0xdd, 0x35, 0x1e, 0x17, 0x47, 0xb6, 0xab, 0xed, 0xb6, 0x82, 0x22, 0x4c, 0x62, 0xbd, 0x12, 0x4e, - 0x44, 0x5c, 0x48, 0x2b, 0x75, 0x63, 0x1c, 0xde, 0xfa, 0x15, 0x0d, 0xb1, 0x50, 0x31, 0xb6, 0xcb, + 0x44, 0x5c, 0x48, 0x2b, 0x75, 0x63, 0x1c, 0xde, 0xfa, 0x15, 0x0d, 0xb1, 0x50, 0x31, 0xb6, 0xcb, }; static const uint8_t inv_r[256] = { 0x2f, 0xb7, 0xf5, 0x4a, 0xd2, 0x19, 0xde, 0x24, 0x7c, 0xdb, 0xcd, 0x52, 0x6e, 0xbc, 0x2c, 0x5c, @@ -538,7 +538,7 @@ static void _pka_test_case_xgcd(void) 0x37, 0xd6, 0xc5, 0xa6, 0x4a, 0x90, 0x6c, 0x44, 0x6a, 0xd9, 0x0f, 0x20, 0xb2, 0xef, 0x22, 0xa0, 0xdf, 0x38, 0x2d, 0x0b, 0xb3, 0x03, 0xb2, 0xc8, 0xe6, 0x8d, 0x74, 0xbf, 0x45, 0x91, 0xe0, 0x22, 0x16, 0xbf, 0xc4, 0xda, 0x54, 0x26, 0xaa, 0x65, 0x85, 0x88, 0xc3, 0xfb, 0x9f, 0xfc, 0x14, 0xc4, - 0xff, 0x8b, 0x88, 0x47, 0x5f, 0xb1, 0x55, 0xdf, 0x47, 0x5c, 0xc0, 0x27, 0x39, 0x7b, 0xe8, 0xad, + 0xff, 0x8b, 0x88, 0x47, 0x5f, 0xb1, 0x55, 0xdf, 0x47, 0x5c, 0xc0, 0x27, 0x39, 0x7b, 0xe8, 0xad, }; #endif static const uint8_t n_exp[256] = { @@ -557,7 +557,7 @@ static void _pka_test_case_xgcd(void) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; static const uint8_t all_zero[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -575,7 +575,7 @@ static void _pka_test_case_xgcd(void) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; uint32_t result[64]; uint8_t pka_a_eq_0 = 0; diff --git a/components/hal_drv/bl602_hal/bl_sec_aes.c b/components/hal_drv/bl602_hal/bl_sec_aes.c index 2c2e215e..ecb27651 100644 --- a/components/hal_drv/bl602_hal/bl_sec_aes.c +++ b/components/hal_drv/bl602_hal/bl_sec_aes.c @@ -80,7 +80,7 @@ static void _dump_iv_status(SEC_Eng_AES_Link_Config_Type *linkCfg) blog_print("\r\n"); } -static const uint8_t aesSrcBuf_data[] = +static const uint8_t aesSrcBuf_data[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, @@ -99,7 +99,7 @@ void Sec_Eng_AES_Link_Case_CBC_128(SEC_ENG_AES_ID_Type aesId) 0x07, 0x01, 0x34, 0x08, 0x5f, 0x02, 0x75, 0x17, 0x55, 0xef, 0xca, 0x3b, 0x4c, 0xdc, 0x7d, 0x62, }; - + SEC_Eng_AES_Link_Config_Type linkCfg = { .aesMode = SEC_ENG_AES_KEY_128BITS, /* 128-bit key mode select */ .aesDecEn = SEC_ENG_AES_ENCRYPTION, /* Encode */ @@ -126,7 +126,7 @@ void Sec_Eng_AES_Link_Case_CBC_128(SEC_ENG_AES_ID_Type aesId) }; Sec_Eng_AES_Enable_Link(aesId); - + puts("[CBC] AES-128-CBC case...\r\n"); blog_info("[CBC] IV Status Initial, %08lx\r\n", linkCfg.aesSrcAddr); @@ -135,12 +135,12 @@ void Sec_Eng_AES_Link_Case_CBC_128(SEC_ENG_AES_ID_Type aesId) Aes_Compare_Data(aesResult_entrypted_cbc_128, (uint8_t*)linkCfg.aesDstAddr, 32); blog_info("[CBC] IV Status After, %08lx\r\n", linkCfg.aesSrcAddr); _dump_iv_status(&linkCfg); - + Sec_Eng_AES_Link_Work(aesId, (uint32_t)&linkCfg, &(aesSrcBuf_data[0]) + 32, 16, aesDstBuf); Aes_Compare_Data(&(aesResult_entrypted_cbc_128[0]) + 32, (uint8_t*)linkCfg.aesDstAddr, 16); blog_info("[CBC] IV Status After %08lx\r\n", linkCfg.aesSrcAddr); _dump_iv_status(&linkCfg); - + Sec_Eng_AES_Link_Work(aesId, (uint32_t)&linkCfg, &(aesSrcBuf_data[0]) + 48, 16, aesDstBuf); Aes_Compare_Data(&(aesResult_entrypted_cbc_128[0]) + 48, (uint8_t*)linkCfg.aesDstAddr, 16); blog_info("[CBC] IV Status After, %08lx\r\n", linkCfg.aesSrcAddr); @@ -185,7 +185,7 @@ void Sec_Eng_AES_Link_Case_CTR_128(SEC_ENG_AES_ID_Type aesId) }; Sec_Eng_AES_Enable_Link(aesId); - + puts("[CTR] AES-128-CTR case...\r\n"); blog_info("[CTR] IV Status Initial, %08lx\r\n", linkCfg.aesSrcAddr); _dump_iv_status(&linkCfg); @@ -195,12 +195,12 @@ void Sec_Eng_AES_Link_Case_CTR_128(SEC_ENG_AES_ID_Type aesId) blog_info("[CTR] IV Status After %08lx\r\n", linkCfg.aesSrcAddr); _dump_iv_status(&linkCfg); - + Sec_Eng_AES_Link_Work(aesId, (uint32_t)&linkCfg, &(aesSrcBuf_data[0]) + 32, 16, aesDstBuf); Aes_Compare_Data(&(aesResult_entrypted_ctr_128[0]) + 32, (uint8_t*)linkCfg.aesDstAddr, 16); blog_info("[CTR] IV Status After %08lx\r\n", linkCfg.aesSrcAddr); _dump_iv_status(&linkCfg); - + Sec_Eng_AES_Link_Work(aesId, (uint32_t)&linkCfg, &(aesSrcBuf_data[0]) + 48, 16, aesDstBuf); Aes_Compare_Data(&(aesResult_entrypted_ctr_128[0]) + 48, (uint8_t*)linkCfg.aesDstAddr, 16); blog_info("[CTR] IV Status After, %08lx\r\n", linkCfg.aesSrcAddr); @@ -250,10 +250,10 @@ void Sec_Eng_AES_Link_Case_ECB_128(SEC_ENG_AES_ID_Type aesId) Sec_Eng_AES_Link_Work(aesId, (uint32_t)&linkCfg, &(aesSrcBuf_data[0]), 32, aesDstBuf); Aes_Compare_Data(aesResult_entrypted_ecb_128, (uint8_t*)linkCfg.aesDstAddr, 32); - + Sec_Eng_AES_Link_Work(aesId, (uint32_t)&linkCfg, &(aesSrcBuf_data[0]) + 32, 16, aesDstBuf); Aes_Compare_Data(&(aesResult_entrypted_ecb_128[0]) + 32, (uint8_t*)linkCfg.aesDstAddr, 16); - + Sec_Eng_AES_Link_Work(aesId, (uint32_t)&linkCfg, &(aesSrcBuf_data[0]) + 48, 16, aesDstBuf); Aes_Compare_Data(&(aesResult_entrypted_ecb_128[0]) + 48, (uint8_t*)linkCfg.aesDstAddr, 16); diff --git a/components/hal_drv/bl602_hal/bl_sec_sha.c b/components/hal_drv/bl602_hal/bl_sec_sha.c index 90af2824..40e92dec 100644 --- a/components/hal_drv/bl602_hal/bl_sec_sha.c +++ b/components/hal_drv/bl602_hal/bl_sec_sha.c @@ -125,10 +125,10 @@ void sha256_test_case0(void) .linkCfg.shaMsgLen = 1, .linkCfg.shaSrcAddr = 0x50020000, }; - static const uint8_t sha256_test_result[] = + static const uint8_t sha256_test_result[] = { 0x31, 0x38, 0xbb, 0x9b, 0xc7, 0x8d, 0xf2, 0x7c, 0x47, 0x3e, 0xcf, 0xd1, 0x41, 0x0f, 0x7b, 0xd4, - 0x5e, 0xba, 0xc1, 0xf5, 0x9c, 0xf3, 0xff, 0x9c, 0xfe, 0x4d, 0xb7, 0x7a, 0xab, 0x7a, 0xed, 0xd3, + 0x5e, 0xba, 0xc1, 0xf5, 0x9c, 0xf3, 0xff, 0x9c, 0xfe, 0x4d, 0xb7, 0x7a, 0xab, 0x7a, 0xed, 0xd3, }; diff --git a/components/hal_drv/bl602_hal/bl_timer.c b/components/hal_drv/bl602_hal/bl_timer.c index 7b328951..ec9e821e 100644 --- a/components/hal_drv/bl602_hal/bl_timer.c +++ b/components/hal_drv/bl602_hal/bl_timer.c @@ -112,7 +112,7 @@ static void int_timer_cb(void) int bl_timer_tick_enable(void) { - TIMER_CFG_Type timerCh1Cfg = + TIMER_CFG_Type timerCh1Cfg = { TIMER_CH1, /* timer channel 1 */ TIMER_CLKSRC_FCLK, /* timer clock source:bus clock */ diff --git a/components/hal_drv/bl602_hal/bl_wdt_cli.c b/components/hal_drv/bl602_hal/bl_wdt_cli.c index 357f4737..9303ef85 100644 --- a/components/hal_drv/bl602_hal/bl_wdt_cli.c +++ b/components/hal_drv/bl602_hal/bl_wdt_cli.c @@ -34,7 +34,7 @@ #include -static void cmd_wdt_init(char *buf, int len, int argc, char **argv) +static void cmd_wdt_init(char *buf, int len, int argc, char **argv) { int ms = 0; @@ -50,17 +50,17 @@ static void cmd_wdt_init(char *buf, int len, int argc, char **argv) bl_wdt_init(ms); } -static void cmd_wdt_feed(char *buf, int len, int argc, char **argv) +static void cmd_wdt_feed(char *buf, int len, int argc, char **argv) { bl_wdt_feed(); } -static void cmd_wdt_disable(char *buf, int len, int argc, char **argv) +static void cmd_wdt_disable(char *buf, int len, int argc, char **argv) { bl_wdt_disable(); } -static void cmd_timer_start(char *buf, int len, int argc, char **argv) +static void cmd_timer_start(char *buf, int len, int argc, char **argv) { int bl_timer_tick_enable(void); bl_timer_tick_enable(); @@ -71,13 +71,13 @@ const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { {"wdt-feed", "wdt-feed", cmd_wdt_feed}, {"wdt-disable", "wdt-disable", cmd_wdt_disable}, {"timer-start", "timer-start", cmd_timer_start}, -}; +}; int bl_wdt_cli_init(void) { // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/hal_drv/bl602_hal/bl_wifi.c b/components/hal_drv/bl602_hal/bl_wifi.c index 2e66018e..8dcf0138 100644 --- a/components/hal_drv/bl602_hal/bl_wifi.c +++ b/components/hal_drv/bl602_hal/bl_wifi.c @@ -127,7 +127,7 @@ int bl_wifi_power_table_set(bl_tx_pwr_tbl_t* tx_pwr_tbl) } #endif -int bl_wifi_ap_info_set(uint8_t* ssid, uint8_t ssid_len, +int bl_wifi_ap_info_set(uint8_t* ssid, uint8_t ssid_len, uint8_t* psk, uint8_t psk_len, uint8_t chan) { diff --git a/components/hal_drv/bl602_hal/bl_wifi.h b/components/hal_drv/bl602_hal/bl_wifi.h index 74db5363..2356ead2 100644 --- a/components/hal_drv/bl602_hal/bl_wifi.h +++ b/components/hal_drv/bl602_hal/bl_wifi.h @@ -42,7 +42,7 @@ int bl_wifi_sta_mac_addr_set(uint8_t mac[6]); int bl_wifi_ap_mac_addr_set(uint8_t mac[6]); int bl_wifi_mac_addr_set(uint8_t mac[6]); int bl_wifi_country_code_set(uint8_t country_code); -int bl_wifi_ap_info_set(uint8_t* ssid, uint8_t ssid_len, +int bl_wifi_ap_info_set(uint8_t* ssid, uint8_t ssid_len, uint8_t* psk, uint8_t psk_len, uint8_t chan); int bl_wifi_mac_addr_get(uint8_t mac[6]); diff --git a/components/hal_drv/bl602_hal/hal_adc.c b/components/hal_drv/bl602_hal/hal_adc.c index e29345f0..b8ca9cec 100644 --- a/components/hal_drv/bl602_hal/hal_adc.c +++ b/components/hal_drv/bl602_hal/hal_adc.c @@ -37,14 +37,14 @@ static int check_adc_gpio_valid(int gpio_num) { int i; int gpio_arr[12] = {4, 5, 6, 9, 10, 11, 12, 13, 14, 15}; - + for (i = 0; i < 10; i++) { if (gpio_num == gpio_arr[i]) { return 0; } } - - return -1; + + return -1; } //mode = 0, for normal adc. freq 40HZ~1300HZ. one time sampling one data. @@ -53,19 +53,19 @@ int hal_adc_init(int mode, int freq, int data_num, int gpio_num) { int ret; int buf_size; - + if (mode == 0) { if (freq < 40 || freq > 1300) { blog_error("illegal freq. for mode0, freq 40HZ ~ 1300HZ \r\n"); - + return -1; } } else if (mode == 1) { if (freq < 500 || freq > 16000) { blog_error("illegal freq. for mode1, freq 500HZ ~ 16000HZ \r\n"); - + return -1; - } + } } else { blog_error("illegal mode. \r\n"); @@ -117,7 +117,7 @@ int hal_adc_callback_register(bl_adc_cb_t cb) return 0; } -/* the following function for mode 0*/ +/* the following function for mode 0*/ int hal_adc_add_channel(int gpio_num) { int ret; @@ -130,12 +130,12 @@ int hal_adc_add_channel(int gpio_num) return -1; } - + bl_adc_gpio_init(gpio_num); channel = bl_adc_get_channel_by_gpio(gpio_num); pstctx = bl_dma_find_ctx_by_channel(ADC_DMA_CHANNEL); - pstctx->chan_init_table = pstctx->chan_init_table | (1 << channel); - + pstctx->chan_init_table = pstctx->chan_init_table | (1 << channel); + return 0; } @@ -146,7 +146,7 @@ int32_t hal_adc_get_data(int gpio_num, int raw_flag) uint32_t adc_data[ADC_CHANNEL_MAX]; int32_t data; int channel; - + ret = check_adc_gpio_valid(gpio_num); if (ret < 0) { blog_error("not legal gpio num, adc only support gpio 4,5,6,9,10,11,12,13,14,15 \r\n"); @@ -166,21 +166,21 @@ int32_t hal_adc_get_data(int gpio_num, int raw_flag) blog_error("gpio = %d not init as adc \r\n", gpio_num); return -1; } - + if (pstctx->channel_data == NULL) { blog_error("adc sampling not finish. \r\n"); return -1; } - memcpy((uint8_t*)adc_data, (uint8_t*)(pstctx->channel_data), ADC_CHANNEL_MAX * 4); + memcpy((uint8_t*)adc_data, (uint8_t*)(pstctx->channel_data), ADC_CHANNEL_MAX * 4); data = bl_adc_parse_data(adc_data, ADC_CHANNEL_MAX, channel, raw_flag); return data; } -int32_t hal_prase_adc_data(uint32_t *ptr, int gpio_num, int raw_flag) +int32_t hal_prase_adc_data(uint32_t *ptr, int gpio_num, int raw_flag) { - int32_t data; + int32_t data; int channel; channel = bl_adc_get_channel_by_gpio(gpio_num); @@ -191,7 +191,7 @@ int32_t hal_prase_adc_data(uint32_t *ptr, int gpio_num, int raw_flag) } data = bl_adc_parse_data(ptr, ADC_CHANNEL_MAX, channel, raw_flag); - + return data; } diff --git a/components/hal_drv/bl602_hal/hal_boot2.c b/components/hal_drv/bl602_hal/hal_boot2.c index 793a4d92..7bfc48ac 100644 --- a/components/hal_drv/bl602_hal/hal_boot2.c +++ b/components/hal_drv/bl602_hal/hal_boot2.c @@ -105,7 +105,7 @@ uint32_t hal_boot2_get_flash_addr(void) { extern uint8_t __boot2_flashCfg_src; - return (uint32_t)(&__boot2_flashCfg_src + + return (uint32_t)(&__boot2_flashCfg_src + (sizeof(boot2_partition_table.table.ptEntries[0]) * boot2_partition_table.table.ptTable.entryCnt)); } diff --git a/components/hal_drv/bl602_hal/hal_boot2.h b/components/hal_drv/bl602_hal/hal_boot2.h index 51bf34a6..21cd1cba 100644 --- a/components/hal_drv/bl602_hal/hal_boot2.h +++ b/components/hal_drv/bl602_hal/hal_boot2.h @@ -60,9 +60,9 @@ typedef enum { /** * @brief Error type definition */ -typedef enum +typedef enum { - HAL_SUCCESS = 0, + HAL_SUCCESS = 0, HAL_ERROR = 1, } HAL_Err_Type; diff --git a/components/hal_drv/bl602_hal/hal_hbn.c b/components/hal_drv/bl602_hal/hal_hbn.c index a5f706b9..0438307b 100644 --- a/components/hal_drv/bl602_hal/hal_hbn.c +++ b/components/hal_drv/bl602_hal/hal_hbn.c @@ -33,7 +33,7 @@ #include "bl_sys.h" #include "bl_hbn.h" #include "hal_sys.h" -#include +#include #include #include #include @@ -90,7 +90,7 @@ int hal_hbn_init(uint8_t *pinbuf, uint8_t pinbuf_size) hbn->active = 1; hbn->buflen = pinbuf_size; memcpy(hbn->buf, pinbuf, pinbuf_size); - + if (!hbn_list) { ntf_init(); } diff --git a/components/hal_drv/bl602_hal/hal_hbnram.c b/components/hal_drv/bl602_hal/hal_hbnram.c index 57cf7615..987df6d3 100644 --- a/components/hal_drv/bl602_hal/hal_hbnram.c +++ b/components/hal_drv/bl602_hal/hal_hbnram.c @@ -182,7 +182,7 @@ void print_mem_map(void) uint32_t val; uint32_t len; char keybuf[5]; - + printf("|head-64bytes|\r\n"); memset(keybuf, 0, 5); paddr = (uint8_t *)(HBNRAM_ADDRESS + HBNRAM_HEAD_SIZE); @@ -325,11 +325,11 @@ int hal_hbnram_buffer_set(const char *key, uint8_t *buf, int length) if (length > area_size) { printf("length is too big than alloc size\r\n"); return -1; - } + } if (length % 4 != 0) { count = length % 4; - if (length > 4) { + if (length > 4) { mem_fourbytes_copy(phead + BUF_HEAD_SIZE, buf, length - count); memcpy(tmpbuf, buf + length - count, count); mem_fourbytes_copy(phead + BUF_HEAD_SIZE + length - count, tmpbuf, 4); @@ -340,7 +340,7 @@ int hal_hbnram_buffer_set(const char *key, uint8_t *buf, int length) } else { mem_fourbytes_copy(phead + BUF_HEAD_SIZE, buf, length); } - + sha_check_withctx((uint8_t*)HBNRAM_DATA_ADDR, output, BL_SHA256, SHA_DATA_SIZE, HBNRAM_DATA_SIZE); mem_fourbytes_copy((uint8_t *)(HBNRAM_ADDRESS + MAGIC_SIZE), output, HASH128_SIZE); diff --git a/components/hal_drv/bl602_hal/hal_hwtimer.c b/components/hal_drv/bl602_hal/hal_hwtimer.c index 63702609..ca6b9a7a 100644 --- a/components/hal_drv/bl602_hal/hal_hwtimer.c +++ b/components/hal_drv/bl602_hal/hal_hwtimer.c @@ -39,9 +39,9 @@ #include #include -#define HW_TIMER_CHANNEL TIMER_CH0 +#define HW_TIMER_CHANNEL TIMER_CH0 #define HW_TIMER_IRQn TIMER_CH0_IRQn -#define HD_MS_TO_VAL 40000 +#define HD_MS_TO_VAL 40000 #ifdef HAL_USE_HW_TIMER struct hw_timer_ctx { @@ -55,14 +55,14 @@ static void hwtimer_process(void *ctx) void (*handler)(void) = NULL; hw_timer_t tmpnode; struct hw_timer_ctx *pstctx; - + pstctx = (struct hw_timer_ctx *)ctx; TIMER_IntMask(HW_TIMER_CHANNEL, TIMER_INT_ALL, MASK); TIMER_ClearIntStatus(HW_TIMER_CHANNEL, TIMER_COMP_ID_0); - + utils_dlist_for_each_entry(pstctx->pstqueue, node, hw_timer_t, dlist_item) { - node->calc_time = node->calc_time + 1; + node->calc_time = node->calc_time + 1; if (node->triggle_time <= node->calc_time) { handler = node->handler; if (node->repeat == 0) { @@ -83,7 +83,7 @@ static void hwtimer_process(void *ctx) int hal_hwtimer_init(void) { struct hw_timer_ctx *pstctx; - TIMER_CFG_Type hw_timercfg = + TIMER_CFG_Type hw_timercfg = { TIMER_CH0, /* timer channel 1 */ TIMER_CLKSRC_XTAL, /* timer clock source:bus clock */ @@ -95,7 +95,7 @@ int hal_hwtimer_init(void) 32000000, /* match value 2 */ 0, /* preload value */ }; - + pstctx = pvPortMalloc(sizeof(struct hw_timer_ctx)); if (pstctx == NULL) { @@ -119,7 +119,7 @@ int hal_hwtimer_init(void) return -1; } - + GLB_AHB_Slave1_Reset(BL_AHB_SLAVE1_TMR); TIMER_IntMask(hw_timercfg.timerCh,TIMER_INT_ALL, MASK); TIMER_Disable(hw_timercfg.timerCh); @@ -134,7 +134,7 @@ int hal_hwtimer_init(void) } hw_timer_t *hal_hwtimer_create(uint32_t period, hw_t handler, int repeat) -{ +{ hw_timer_t *pstnode; struct hw_timer_ctx *pstctx; @@ -143,14 +143,14 @@ hw_timer_t *hal_hwtimer_create(uint32_t period, hw_t handler, int repeat) return NULL; } - + bl_irq_ctx_get(TIMER_CH0_IRQn, (void **)&pstctx); if( xSemaphoreTake(pstctx->hwtimer_mux, portMAX_DELAY) == pdTRUE ) { blog_info("get mux success \r\n"); } - TIMER_IntMask(HW_TIMER_CHANNEL, TIMER_INT_ALL, MASK); - + TIMER_IntMask(HW_TIMER_CHANNEL, TIMER_INT_ALL, MASK); + pstnode = pvPortMalloc(sizeof(hw_timer_t)); pstnode->triggle_time = period; pstnode->repeat = repeat; @@ -168,7 +168,7 @@ int hal_hwtimer_delete(hw_timer_t *pstnode) hw_timer_t *node; int ret = 0; struct hw_timer_ctx *pstctx; - + bl_irq_ctx_get(TIMER_CH0_IRQn, (void **)&pstctx); if( xSemaphoreTake(pstctx->hwtimer_mux, portMAX_DELAY) == pdTRUE ) { blog_info("get mux success \r\n"); @@ -189,7 +189,7 @@ int hal_hwtimer_delete(hw_timer_t *pstnode) if (ret == 0) { utils_dlist_del(&(node->dlist_item)); } - + TIMER_IntMask(HW_TIMER_CHANNEL, TIMER_INT_COMP_0, UNMASK); xSemaphoreGive(pstctx->hwtimer_mux); return ret; diff --git a/components/hal_drv/bl602_hal/hal_hwtimer.h b/components/hal_drv/bl602_hal/hal_hwtimer.h index dfb46380..a3a8938e 100644 --- a/components/hal_drv/bl602_hal/hal_hwtimer.h +++ b/components/hal_drv/bl602_hal/hal_hwtimer.h @@ -43,7 +43,7 @@ typedef struct hw_timer { int repeat; hw_t handler; uint32_t triggle_time; - uint32_t calc_time; + uint32_t calc_time; } hw_timer_t; int hal_hwtimer_init(void); diff --git a/components/hal_drv/bl602_hal/hal_i2c.c b/components/hal_drv/bl602_hal/hal_i2c.c index 568ee5fe..efad75a4 100644 --- a/components/hal_drv/bl602_hal/hal_i2c.c +++ b/components/hal_drv/bl602_hal/hal_i2c.c @@ -80,14 +80,14 @@ static void i2c_transferbytes(i2c_msg_t *pstmsg) I2C_IntMask(pstmsg->i2cx, I2C_TX_FIFO_READY_INT, MASK); return; } else { - } + } } else if ((pstmsg->direct == I2C_M_READ) && (pstmsg->event = EV_I2C_RXF_INT)){ if (pstmsg->idex < pstmsg->len) { - do_read_data(pstmsg); + do_read_data(pstmsg); } else { I2C_IntMask(pstmsg->i2cx, I2C_RX_FIFO_READY_INT, MASK); return; - } + } } else { } @@ -98,9 +98,9 @@ static void i2c_interrupt_entry(void *ctx) { uint32_t tmpval; i2c_msg_t *pstmsg; - + pstmsg = *((i2c_msg_t **)ctx); - + tmpval = BL_RD_REG(I2C_BASE, I2C_INT_STS); if(BL_IS_REG_BIT_SET(tmpval,I2C_RXF_INT)){ pstmsg->event = EV_I2C_RXF_INT; @@ -124,10 +124,10 @@ static void i2c_interrupt_entry(void *ctx) return; } else { blog_error("other interrupt \r\n"); - pstmsg->event = EV_I2C_UNKNOW_INT; + pstmsg->event = EV_I2C_UNKNOW_INT; i2c_callback(pstmsg); } - + i2c_transferbytes(pstmsg); return; } @@ -149,7 +149,7 @@ int i2c_transfer_block(i2c_msg_t *pstmsg) xSemaphoreGive(i2c_hd_handle); xSemaphoreGive(i2c_transfer_handle); - + return pstmsg->event; } @@ -173,7 +173,7 @@ int i2c_transfer_no_block(i2c_msg_t *pstmsg) blog_error("buf alloc failed. len = %ld \r\n", pstmsg->len); } memcpy(pbuf , pstmsg->buf, pstmsg->len); - psttmp->buf = pbuf; + psttmp->buf = pbuf; } else if (pstmsg->direct == I2C_M_READ) { psttmp->buf = pstmsg->buf; } else { @@ -246,11 +246,11 @@ int i2c_transfer_msgs_block(i2c_msg_t *pstmsg, int num, int support_ins) xSemaphoreGive(i2c_insert_handle); } xSemaphoreGive(i2c_msgs_handle); - + return (pstmsg + i - 1)->event; } -int i2c_insert_transfer_msgs(i2c_msg_t *pstmsg, int num) +int i2c_insert_transfer_msgs(i2c_msg_t *pstmsg, int num) { xSemaphoreTake(i2c_insert_handle, portMAX_DELAY); xSemaphoreTake(i2c_loop_handle, portMAX_DELAY); @@ -264,7 +264,7 @@ int i2c_insert_transfer_msgs(i2c_msg_t *pstmsg, int num) } int i2c_transfer_onemsg_no_block(i2c_msg_t *pstmsg) -{ +{ i2c_transfer_no_block(pstmsg); return 0; } @@ -273,10 +273,10 @@ int hal_i2c_init(int i2cx, int freq) { i2c_gpio_init(i2cx); i2c_set_freq(freq, i2cx); - I2C_Disable(i2cx); + I2C_Disable(i2cx); bl_irq_enable(I2C_IRQn); I2C_IntMask(i2cx, I2C_INT_ALL, MASK); - + i2c_hd_handle = xSemaphoreCreateBinary(); i2c_msgs_handle = xSemaphoreCreateMutex(); i2c_transfer_handle = xSemaphoreCreateBinary(); @@ -294,7 +294,7 @@ int hal_i2c_init(int i2cx, int freq) xSemaphoreGive(i2c_insert_handle); bl_irq_register_with_ctx(I2C_IRQn, i2c_interrupt_entry, &gpstmsg); - return 0; + return 0; } int hal_i2c_read_block(int address, char *data, int length, int subaddr_len, int subaddr) diff --git a/components/hal_drv/bl602_hal/hal_i2c.h b/components/hal_drv/bl602_hal/hal_i2c.h index 3e92f067..425860c6 100644 --- a/components/hal_drv/bl602_hal/hal_i2c.h +++ b/components/hal_drv/bl602_hal/hal_i2c.h @@ -36,7 +36,7 @@ #define EV_I2C_TXF_INT 1 #define EV_I2C_RXF_INT 3 #define EV_I2C_FER_INT 4 -#define EV_I2C_ARB_INT 5 +#define EV_I2C_ARB_INT 5 #define EV_I2C_NAK_INT 6 #define EV_I2C_UNKNOW_INT 0xff diff --git a/components/hal_drv/bl602_hal/hal_ir.c b/components/hal_drv/bl602_hal/hal_ir.c index 60bf96cb..6de9b8f3 100644 --- a/components/hal_drv/bl602_hal/hal_ir.c +++ b/components/hal_drv/bl602_hal/hal_ir.c @@ -61,7 +61,7 @@ int hal_ir_init_from_dts(uint32_t fdt_input, uint32_t dtb_offset) uint8_t pin = 0; uint16_t interval = NULL; - + addr_prop = fdt_getprop(fdt, dtb_offset, "ctrltype", &lentmp); if (addr_prop == NULL) { log_info("do not find ctrltype \r\n"); @@ -100,14 +100,14 @@ int hal_ir_init_from_dts(uint32_t fdt_input, uint32_t dtb_offset) } } } - + //TODO clean out ctrltype bl_ir_init(pin, ctrltype); return 0; } -int hal_irled_init(int chip_type) +int hal_irled_init(int chip_type) { if (chip_type != 0 && chip_type != 1) { blog_error("not correct chip type \r\n"); @@ -116,8 +116,8 @@ int hal_irled_init(int chip_type) } bl_irled_gpio_init(); - bl_irled_init(chip_type); - + bl_irled_init(chip_type); + g_chip_type = chip_type; return 0; @@ -140,7 +140,7 @@ int hal_irled_send_data(int data_num, uint32_t *buf) } else { reset_us = UCS1903_RESET_US; } - + if (bl_timer_now_us64() - last_us < reset_us) { bl_timer_delay_us(reset_us - (bl_timer_now_us64() - last_us)); } @@ -154,4 +154,4 @@ int hal_irled_send_data(int data_num, uint32_t *buf) last_us = bl_timer_now_us64(); return 0; -} +} diff --git a/components/hal_drv/bl602_hal/hal_pds.c b/components/hal_drv/bl602_hal/hal_pds.c index a9826046..42e4dea1 100644 --- a/components/hal_drv/bl602_hal/hal_pds.c +++ b/components/hal_drv/bl602_hal/hal_pds.c @@ -33,7 +33,7 @@ void hal_pds_init(void) { bl_pds_init(); - + #if 0 /* RTC is started by bl_rtc_init() in bl_rtc.c */ HBN_Clear_RTC_Counter(); HBN_Enable_RTC_Counter(); @@ -56,20 +56,20 @@ uint32_t hal_pds_enter_with_time_compensation(uint32_t pdsLevel, uint32_t pdsSle uint32_t rtcLowAfterSleep, rtcHighAfterSleep; uint32_t actualSleepDuration_32768cycles; uint32_t actualSleepDuration_ms; - + HBN_Get_RTC_Timer_Val(&rtcLowBeforeSleep, &rtcHighBeforeSleep); - + bl_pds_enter(pdsLevel, pdsSleepCycles); - + HBN_Get_RTC_Timer_Val(&rtcLowAfterSleep, &rtcHighAfterSleep); - + CHECK_PARAM((rtcHighAfterSleep - rtcHighBeforeSleep) <= 1); // make sure sleep less than 1 hour (2^32 us > 1 hour) - + actualSleepDuration_32768cycles = (rtcLowAfterSleep - rtcLowBeforeSleep); - + actualSleepDuration_ms = (actualSleepDuration_32768cycles>>5)-(actualSleepDuration_32768cycles>>11)-(actualSleepDuration_32768cycles>>12); - + vTaskStepTick(actualSleepDuration_ms); - + return actualSleepDuration_ms; } diff --git a/components/hal_drv/bl602_hal/hal_spi.c b/components/hal_drv/bl602_hal/hal_spi.c index c9fa5458..b7e34fec 100644 --- a/components/hal_drv/bl602_hal/hal_spi.c +++ b/components/hal_drv/bl602_hal/hal_spi.c @@ -100,7 +100,7 @@ static void hal_gpio_init(spi_hw_t *arg) gpiopins[1] = arg->pin_clk; gpiopins[2] = arg->pin_mosi; gpiopins[3] = arg->pin_miso; - + GLB_GPIO_Func_Init(GPIO_FUN_SPI,gpiopins,sizeof(gpiopins)/sizeof(gpiopins[0])); if (arg->mode == 0) { @@ -162,7 +162,7 @@ static int lli_list_init(DMA_LLI_Ctrl_Type **pptxlli, DMA_LLI_Ctrl_Type **pprxll dmactrl.SI = DMA_MINC_ENABLE; dmactrl.DI = DMA_MINC_DISABLE; - + if (i == count - 1) { dmactrl.I = 1; } else { @@ -199,7 +199,7 @@ static void hal_spi_dma_init(spi_hw_t *arg) SPI_FifoCfg_Type fifocfg; SPI_ID_Type spi_id; uint8_t clk_div; - + spi_id = hw_arg->ssp_id; /* clock */ @@ -264,7 +264,7 @@ static void hal_spi_dma_init(spi_hw_t *arg) DMA_IntMask(hw_arg->tx_dma_ch, DMA_INT_ERR, UNMASK); DMA_IntMask(hw_arg->rx_dma_ch, DMA_INT_ALL, MASK); - DMA_IntMask(hw_arg->rx_dma_ch, DMA_INT_TCOMPLETED, UNMASK); + DMA_IntMask(hw_arg->rx_dma_ch, DMA_INT_TCOMPLETED, UNMASK); DMA_IntMask(hw_arg->rx_dma_ch, DMA_INT_ERR, UNMASK); bl_irq_enable(DMA_ALL_IRQn); @@ -289,7 +289,7 @@ static void hal_spi_dma_trans(spi_hw_t *arg, uint8_t *TxData, uint8_t *RxData, u } txllicfg.dir = DMA_TRNS_M2P; - txllicfg.srcPeriph = DMA_REQ_NONE; + txllicfg.srcPeriph = DMA_REQ_NONE; txllicfg.dstPeriph = DMA_REQ_SPI_TX; rxllicfg.dir = DMA_TRNS_P2M; diff --git a/components/hal_drv/bl602_hal/hal_uart.c b/components/hal_drv/bl602_hal/hal_uart.c index 383d6b10..36b3eb3c 100644 --- a/components/hal_drv/bl602_hal/hal_uart.c +++ b/components/hal_drv/bl602_hal/hal_uart.c @@ -83,7 +83,7 @@ static void uart_dev_setdef(uart_dev_t **pdev, uint8_t id) (*pdev)->port = id; (*pdev)->read_block_flag = UART_READ_CFG_NOBLOCK; - + (*pdev)->config.baud_rate = 115200; (*pdev)->config.data_width = DATA_WIDTH_8BIT; (*pdev)->config.parity = NO_PARITY; @@ -446,7 +446,7 @@ int vfs_uart_init(uint32_t fdt, uint32_t dtb_uart_offset) int32_t hal_uart_send_flush(uart_dev_t *uart, uint32_t timeout) { - bl_uart_flush(uart->port); + bl_uart_flush(uart->port); return 0; } diff --git a/components/network/ble/ble_common.mk b/components/network/ble/ble_common.mk index 9037a7a1..f810efa0 100644 --- a/components/network/ble/ble_common.mk +++ b/components/network/ble/ble_common.mk @@ -137,7 +137,7 @@ CFLAGS += -DCONFIG_BT_L2CAP_DYNAMIC_CHANNEL \ -DCONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS \ -DCONFIG_BT_BONDABLE \ -DCONFIG_BT_HCI_VS_EVT_USER \ - -DCONFIG_BT_ASSERT + -DCONFIG_BT_ASSERT ifneq ($(CONFIG_DISABLE_BT_SMP), 1) CFLAGS += -DCONFIG_BT_SMP \ @@ -228,20 +228,20 @@ ifeq ($(CONFIG_BT_MESH_MODEL),1) CFLAGS += -DCONFIG_BT_MESH_MODEL ifeq ($(CONFIG_BT_MESH_MODEL_GEN_SRV),1) CFLAGS += -DCONFIG_BT_MESH_MODEL_GEN_SRV -endif +endif ifeq ($(CONFIG_BT_MESH_MODEL_GEN_CLI),1) CFLAGS += -DCONFIG_BT_MESH_MODEL_GEN_CLI -endif +endif ifeq ($(CONFIG_BT_MESH_MODEL_LIGHT_SRV),1) CFLAGS += -DCONFIG_BT_MESH_MODEL_LIGHT_SRV -endif +endif ifeq ($(CONFIG_BT_MESH_MODEL_LIGHT_CLI),1) CFLAGS += -DCONFIG_BT_MESH_MODEL_LIGHT_CLI endif else ifeq ($(CONFIG_BT_MESH_MODEL_GEN_SRV),1) CFLAGS += -DCONFIG_BT_MESH_MODEL_GEN_SRV -endif +endif endif endif diff --git a/components/network/ble/blemesh/bouffalo.mk b/components/network/ble/blemesh/bouffalo.mk index 978083c9..9bae30bd 100644 --- a/components/network/ble/blemesh/bouffalo.mk +++ b/components/network/ble/blemesh/bouffalo.mk @@ -14,7 +14,7 @@ endif ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src COMPONENT_SRCS := src/access.c \ src/adv.c \ src/beacon.c \ @@ -43,7 +43,7 @@ endif ifeq ($(CONFIG_BT_MESH_MODEL), 0) ifeq ($(CONFIG_BT_MESH_MODEL_GEN_SRV),1) COMPONENT_SRCS += src/mesh_models/server/common_srv.c \ - src/mesh_models/server/gen_srv.c + src/mesh_models/server/gen_srv.c endif endif diff --git a/components/network/ble/blemesh/src/access.c b/components/network/ble/blemesh/src/access.c index ba36e42c..14000194 100644 --- a/components/network/ble/blemesh/src/access.c +++ b/components/network/ble/blemesh/src/access.c @@ -46,16 +46,16 @@ static const struct bt_mesh_comp *dev_comp; static u16_t dev_primary_addr; static const struct { - const u16_t id; - int (*const init)(struct bt_mesh_model *model, bool primary); + const u16_t id; + int (*const init)(struct bt_mesh_model *model, bool primary); } model_init[] = { - { BT_MESH_MODEL_ID_CFG_SRV, bt_mesh_cfg_srv_init }, - { BT_MESH_MODEL_ID_HEALTH_SRV, bt_mesh_health_srv_init }, + { BT_MESH_MODEL_ID_CFG_SRV, bt_mesh_cfg_srv_init }, + { BT_MESH_MODEL_ID_HEALTH_SRV, bt_mesh_health_srv_init }, #if defined(CONFIG_BT_MESH_CFG_CLI) - { BT_MESH_MODEL_ID_CFG_CLI, bt_mesh_cfg_cli_init }, + { BT_MESH_MODEL_ID_CFG_CLI, bt_mesh_cfg_cli_init }, #endif #if defined(CONFIG_BT_MESH_HEALTH_CLI) - { BT_MESH_MODEL_ID_HEALTH_CLI, bt_mesh_health_cli_init }, + { BT_MESH_MODEL_ID_HEALTH_CLI, bt_mesh_health_cli_init }, #endif #if defined(CONFIG_BT_MESH_MODEL) #if defined(CONFIG_BT_MESH_MODEL_GEN_CLI) @@ -110,725 +110,725 @@ static const struct { }; void bt_mesh_model_foreach(void (*func)(struct bt_mesh_model *mod, - struct bt_mesh_elem *elem, - bool vnd, bool primary, - void *user_data), - void *user_data) + struct bt_mesh_elem *elem, + bool vnd, bool primary, + void *user_data), + void *user_data) { - int i, j; + int i, j; - for (i = 0; i < dev_comp->elem_count; i++) { - struct bt_mesh_elem *elem = &dev_comp->elem[i]; + for (i = 0; i < dev_comp->elem_count; i++) { + struct bt_mesh_elem *elem = &dev_comp->elem[i]; - for (j = 0; j < elem->model_count; j++) { - struct bt_mesh_model *model = &elem->models[j]; + for (j = 0; j < elem->model_count; j++) { + struct bt_mesh_model *model = &elem->models[j]; - func(model, elem, false, i == 0, user_data); - } + func(model, elem, false, i == 0, user_data); + } - for (j = 0; j < elem->vnd_model_count; j++) { - struct bt_mesh_model *model = &elem->vnd_models[j]; + for (j = 0; j < elem->vnd_model_count; j++) { + struct bt_mesh_model *model = &elem->vnd_models[j]; - func(model, elem, true, i == 0, user_data); - } - } + func(model, elem, true, i == 0, user_data); + } + } } s32_t bt_mesh_model_pub_period_get(struct bt_mesh_model *mod) { - int period; + int period; - if (!mod->pub) { - return 0; - } + if (!mod->pub) { + return 0; + } - switch (mod->pub->period >> 6) { - case 0x00: - /* 1 step is 100 ms */ - period = K_MSEC((mod->pub->period & BIT_MASK(6)) * 100U); - break; - case 0x01: - /* 1 step is 1 second */ - period = K_SECONDS(mod->pub->period & BIT_MASK(6)); - break; - case 0x02: - /* 1 step is 10 seconds */ - period = K_SECONDS((mod->pub->period & BIT_MASK(6)) * 10U); - break; - case 0x03: - /* 1 step is 10 minutes */ - period = K_MINUTES((mod->pub->period & BIT_MASK(6)) * 10U); - break; - default: - CODE_UNREACHABLE; - } + switch (mod->pub->period >> 6) { + case 0x00: + /* 1 step is 100 ms */ + period = K_MSEC((mod->pub->period & BIT_MASK(6)) * 100U); + break; + case 0x01: + /* 1 step is 1 second */ + period = K_SECONDS(mod->pub->period & BIT_MASK(6)); + break; + case 0x02: + /* 1 step is 10 seconds */ + period = K_SECONDS((mod->pub->period & BIT_MASK(6)) * 10U); + break; + case 0x03: + /* 1 step is 10 minutes */ + period = K_MINUTES((mod->pub->period & BIT_MASK(6)) * 10U); + break; + default: + CODE_UNREACHABLE; + } - if (mod->pub->fast_period) { - return period >> mod->pub->period_div; - } else { - return period; - } + if (mod->pub->fast_period) { + return period >> mod->pub->period_div; + } else { + return period; + } } static s32_t next_period(struct bt_mesh_model *mod) { - struct bt_mesh_model_pub *pub = mod->pub; - u32_t elapsed, period; + struct bt_mesh_model_pub *pub = mod->pub; + u32_t elapsed, period; - period = bt_mesh_model_pub_period_get(mod); - if (!period) { - return 0; - } + period = bt_mesh_model_pub_period_get(mod); + if (!period) { + return 0; + } - elapsed = k_uptime_get_32() - pub->period_start; + elapsed = k_uptime_get_32() - pub->period_start; - BT_DBG("Publishing took %ums", elapsed); + BT_DBG("Publishing took %ums", elapsed); - if (elapsed > period) { - BT_WARN("Publication sending took longer than the period"); - /* Return smallest positive number since 0 means disabled */ - return K_MSEC(1); - } + if (elapsed > period) { + BT_WARN("Publication sending took longer than the period"); + /* Return smallest positive number since 0 means disabled */ + return K_MSEC(1); + } - return period - elapsed; + return period - elapsed; } static void publish_sent(int err, void *user_data) { - struct bt_mesh_model *mod = user_data; - s32_t delay; + struct bt_mesh_model *mod = user_data; + s32_t delay; - BT_DBG("err %d", err); + BT_DBG("err %d", err); - if (mod->pub->count) { - delay = BT_MESH_PUB_TRANSMIT_INT(mod->pub->retransmit); - } else { - delay = next_period(mod); - } + if (mod->pub->count) { + delay = BT_MESH_PUB_TRANSMIT_INT(mod->pub->retransmit); + } else { + delay = next_period(mod); + } - if (delay) { - BT_DBG("Publishing next time in %dms", delay); - k_delayed_work_submit(&mod->pub->timer, delay); - } + if (delay) { + BT_DBG("Publishing next time in %dms", delay); + k_delayed_work_submit(&mod->pub->timer, delay); + } } static void publish_start(u16_t duration, int err, void *user_data) { - struct bt_mesh_model *mod = user_data; - struct bt_mesh_model_pub *pub = mod->pub; + struct bt_mesh_model *mod = user_data; + struct bt_mesh_model_pub *pub = mod->pub; - if (err) { - BT_ERR("Failed to publish: err %d", err); - return; - } + if (err) { + BT_ERR("Failed to publish: err %d", err); + return; + } - /* Initialize the timestamp for the beginning of a new period */ - if (pub->count == BT_MESH_PUB_TRANSMIT_COUNT(pub->retransmit)) { - pub->period_start = k_uptime_get_32(); - } + /* Initialize the timestamp for the beginning of a new period */ + if (pub->count == BT_MESH_PUB_TRANSMIT_COUNT(pub->retransmit)) { + pub->period_start = k_uptime_get_32(); + } } static const struct bt_mesh_send_cb pub_sent_cb = { - .start = publish_start, - .end = publish_sent, + .start = publish_start, + .end = publish_sent, }; static int publish_retransmit(struct bt_mesh_model *mod) { - NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); - struct bt_mesh_model_pub *pub = mod->pub; - struct bt_mesh_app_key *key; - struct bt_mesh_msg_ctx ctx = { - .addr = pub->addr, - .send_ttl = pub->ttl, - }; - struct bt_mesh_net_tx tx = { - .ctx = &ctx, - .src = bt_mesh_model_elem(mod)->addr, - .xmit = bt_mesh_net_transmit_get(), - .friend_cred = pub->cred, - }; + NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); + struct bt_mesh_model_pub *pub = mod->pub; + struct bt_mesh_app_key *key; + struct bt_mesh_msg_ctx ctx = { + .addr = pub->addr, + .send_ttl = pub->ttl, + }; + struct bt_mesh_net_tx tx = { + .ctx = &ctx, + .src = bt_mesh_model_elem(mod)->addr, + .xmit = bt_mesh_net_transmit_get(), + .friend_cred = pub->cred, + }; - key = bt_mesh_app_key_find(pub->key); - if (!key) { - return -EADDRNOTAVAIL; - } + key = bt_mesh_app_key_find(pub->key); + if (!key) { + return -EADDRNOTAVAIL; + } - tx.sub = bt_mesh_subnet_get(key->net_idx); + tx.sub = bt_mesh_subnet_get(key->net_idx); - ctx.net_idx = key->net_idx; - ctx.app_idx = key->app_idx; + ctx.net_idx = key->net_idx; + ctx.app_idx = key->app_idx; - net_buf_simple_add_mem(&sdu, pub->msg->data, pub->msg->len); + net_buf_simple_add_mem(&sdu, pub->msg->data, pub->msg->len); - pub->count--; + pub->count--; - return bt_mesh_trans_send(&tx, &sdu, &pub_sent_cb, mod); + return bt_mesh_trans_send(&tx, &sdu, &pub_sent_cb, mod); } static void mod_publish(struct k_work *work) { - struct bt_mesh_model_pub *pub = CONTAINER_OF(work, - struct bt_mesh_model_pub, - timer.work); - s32_t period_ms; - int err; + struct bt_mesh_model_pub *pub = CONTAINER_OF(work, + struct bt_mesh_model_pub, + timer.work); + s32_t period_ms; + int err; - BT_DBG(""); + BT_DBG(""); - period_ms = bt_mesh_model_pub_period_get(pub->mod); - BT_DBG("period %u ms", period_ms); + period_ms = bt_mesh_model_pub_period_get(pub->mod); + BT_DBG("period %u ms", period_ms); - if (pub->count) { - err = publish_retransmit(pub->mod); - if (err) { - BT_ERR("Failed to retransmit (err %d)", err); + if (pub->count) { + err = publish_retransmit(pub->mod); + if (err) { + BT_ERR("Failed to retransmit (err %d)", err); - pub->count = 0U; + pub->count = 0U; - /* Continue with normal publication */ - if (period_ms) { - k_delayed_work_submit(&pub->timer, period_ms); - } - } + /* Continue with normal publication */ + if (period_ms) { + k_delayed_work_submit(&pub->timer, period_ms); + } + } - return; - } + return; + } - if (!period_ms) { - return; - } + if (!period_ms) { + return; + } - __ASSERT_NO_MSG(pub->update != NULL); + __ASSERT_NO_MSG(pub->update != NULL); - err = pub->update(pub->mod); - if (err) { - BT_ERR("Failed to update publication message"); - return; - } + err = pub->update(pub->mod); + if (err) { + BT_ERR("Failed to update publication message"); + return; + } - err = bt_mesh_model_publish(pub->mod); - if (err) { - BT_ERR("Publishing failed (err %d)", err); - } + err = bt_mesh_model_publish(pub->mod); + if (err) { + BT_ERR("Publishing failed (err %d)", err); + } } struct bt_mesh_elem *bt_mesh_model_elem(struct bt_mesh_model *mod) { - return &dev_comp->elem[mod->elem_idx]; + return &dev_comp->elem[mod->elem_idx]; } struct bt_mesh_model *bt_mesh_model_get(bool vnd, u8_t elem_idx, u8_t mod_idx) { - struct bt_mesh_elem *elem; + struct bt_mesh_elem *elem; - if (elem_idx >= dev_comp->elem_count) { - BT_ERR("Invalid element index %u", elem_idx); - return NULL; - } + if (elem_idx >= dev_comp->elem_count) { + BT_ERR("Invalid element index %u", elem_idx); + return NULL; + } - elem = &dev_comp->elem[elem_idx]; + elem = &dev_comp->elem[elem_idx]; - if (vnd) { - if (mod_idx >= elem->vnd_model_count) { - BT_ERR("Invalid vendor model index %u", mod_idx); - return NULL; - } + if (vnd) { + if (mod_idx >= elem->vnd_model_count) { + BT_ERR("Invalid vendor model index %u", mod_idx); + return NULL; + } - return &elem->vnd_models[mod_idx]; - } else { - if (mod_idx >= elem->model_count) { - BT_ERR("Invalid SIG model index %u", mod_idx); - return NULL; - } + return &elem->vnd_models[mod_idx]; + } else { + if (mod_idx >= elem->model_count) { + BT_ERR("Invalid SIG model index %u", mod_idx); + return NULL; + } - return &elem->models[mod_idx]; - } + return &elem->models[mod_idx]; + } } static void mod_init(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, - bool vnd, bool primary, void *user_data) + bool vnd, bool primary, void *user_data) { - int i; + int i; - if (mod->pub) { - mod->pub->mod = mod; - k_delayed_work_init(&mod->pub->timer, mod_publish); - } + if (mod->pub) { + mod->pub->mod = mod; + k_delayed_work_init(&mod->pub->timer, mod_publish); + } - for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { - mod->keys[i] = BT_MESH_KEY_UNUSED; - } + for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { + mod->keys[i] = BT_MESH_KEY_UNUSED; + } - mod->elem_idx = elem - dev_comp->elem; - if (vnd) { - mod->mod_idx = mod - elem->vnd_models; - } else { - mod->mod_idx = mod - elem->models; - } + mod->elem_idx = elem - dev_comp->elem; + if (vnd) { + mod->mod_idx = mod - elem->vnd_models; + } else { + mod->mod_idx = mod - elem->models; + } - if (vnd) { - return; - } + if (vnd) { + return; + } - for (i = 0; i < ARRAY_SIZE(model_init); i++) { - if (model_init[i].id == mod->id) { - model_init[i].init(mod, primary); - } - } + for (i = 0; i < ARRAY_SIZE(model_init); i++) { + if (model_init[i].id == mod->id) { + model_init[i].init(mod, primary); + } + } } int bt_mesh_comp_register(const struct bt_mesh_comp *comp) { - /* There must be at least one element */ - if (!comp->elem_count) { - return -EINVAL; - } + /* There must be at least one element */ + if (!comp->elem_count) { + return -EINVAL; + } - dev_comp = comp; + dev_comp = comp; - bt_mesh_model_foreach(mod_init, NULL); + bt_mesh_model_foreach(mod_init, NULL); - return 0; + return 0; } void bt_mesh_comp_provision(u16_t addr) { - int i; + int i; - dev_primary_addr = addr; + dev_primary_addr = addr; - BT_DBG("addr 0x%04x elem_count %zu", addr, dev_comp->elem_count); + BT_DBG("addr 0x%04x elem_count %zu", addr, dev_comp->elem_count); - for (i = 0; i < dev_comp->elem_count; i++) { - struct bt_mesh_elem *elem = &dev_comp->elem[i]; + for (i = 0; i < dev_comp->elem_count; i++) { + struct bt_mesh_elem *elem = &dev_comp->elem[i]; - elem->addr = addr++; + elem->addr = addr++; - BT_DBG("addr 0x%04x mod_count %u vnd_mod_count %u", - elem->addr, elem->model_count, elem->vnd_model_count); - } + BT_DBG("addr 0x%04x mod_count %u vnd_mod_count %u", + elem->addr, elem->model_count, elem->vnd_model_count); + } } void bt_mesh_comp_unprovision(void) { - BT_DBG(""); + BT_DBG(""); - dev_primary_addr = BT_MESH_ADDR_UNASSIGNED; + dev_primary_addr = BT_MESH_ADDR_UNASSIGNED; - bt_mesh_model_foreach(mod_init, NULL); + bt_mesh_model_foreach(mod_init, NULL); } u16_t bt_mesh_primary_addr(void) { - return dev_primary_addr; + return dev_primary_addr; } u16_t *bt_mesh_model_find_group(struct bt_mesh_model *mod, u16_t addr) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (mod->groups[i] == addr) { - return &mod->groups[i]; - } - } + for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (mod->groups[i] == addr) { + return &mod->groups[i]; + } + } - return NULL; + return NULL; } static struct bt_mesh_model *bt_mesh_elem_find_group(struct bt_mesh_elem *elem, - u16_t group_addr) + u16_t group_addr) { - struct bt_mesh_model *model; - u16_t *match; - int i; + struct bt_mesh_model *model; + u16_t *match; + int i; - for (i = 0; i < elem->model_count; i++) { - model = &elem->models[i]; + for (i = 0; i < elem->model_count; i++) { + model = &elem->models[i]; - match = bt_mesh_model_find_group(model, group_addr); - if (match) { - return model; - } - } + match = bt_mesh_model_find_group(model, group_addr); + if (match) { + return model; + } + } - for (i = 0; i < elem->vnd_model_count; i++) { - model = &elem->vnd_models[i]; + for (i = 0; i < elem->vnd_model_count; i++) { + model = &elem->vnd_models[i]; - match = bt_mesh_model_find_group(model, group_addr); - if (match) { - return model; - } - } + match = bt_mesh_model_find_group(model, group_addr); + if (match) { + return model; + } + } - return NULL; + return NULL; } struct bt_mesh_elem *bt_mesh_elem_find(u16_t addr) { - int i; + int i; - for (i = 0; i < dev_comp->elem_count; i++) { - struct bt_mesh_elem *elem = &dev_comp->elem[i]; + for (i = 0; i < dev_comp->elem_count; i++) { + struct bt_mesh_elem *elem = &dev_comp->elem[i]; - if (BT_MESH_ADDR_IS_GROUP(addr) || - BT_MESH_ADDR_IS_VIRTUAL(addr)) { - if (bt_mesh_elem_find_group(elem, addr)) { - return elem; - } - } else if (elem->addr == addr) { - return elem; - } - } + if (BT_MESH_ADDR_IS_GROUP(addr) || + BT_MESH_ADDR_IS_VIRTUAL(addr)) { + if (bt_mesh_elem_find_group(elem, addr)) { + return elem; + } + } else if (elem->addr == addr) { + return elem; + } + } - return NULL; + return NULL; } u8_t bt_mesh_elem_count(void) { - return dev_comp->elem_count; + return dev_comp->elem_count; } static bool model_has_key(struct bt_mesh_model *mod, u16_t key) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { - if (mod->keys[i] == key) { - return true; - } - } + for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { + if (mod->keys[i] == key) { + return true; + } + } - return false; + return false; } static const struct bt_mesh_model_op *find_op(struct bt_mesh_model *models, - u8_t model_count, u16_t dst, - u16_t app_idx, u32_t opcode, - struct bt_mesh_model **model) + u8_t model_count, u16_t dst, + u16_t app_idx, u32_t opcode, + struct bt_mesh_model **model) { - u8_t i; + u8_t i; - for (i = 0U; i < model_count; i++) { - const struct bt_mesh_model_op *op; + for (i = 0U; i < model_count; i++) { + const struct bt_mesh_model_op *op; - *model = &models[i]; + *model = &models[i]; - if (BT_MESH_ADDR_IS_GROUP(dst) || - BT_MESH_ADDR_IS_VIRTUAL(dst)) { - if (!bt_mesh_model_find_group(*model, dst)) { - continue; - } - } + if (BT_MESH_ADDR_IS_GROUP(dst) || + BT_MESH_ADDR_IS_VIRTUAL(dst)) { + if (!bt_mesh_model_find_group(*model, dst)) { + continue; + } + } - if (!model_has_key(*model, app_idx)) { - continue; - } + if (!model_has_key(*model, app_idx)) { + continue; + } - for (op = (*model)->op; op->func; op++) { - if (op->opcode == opcode) { - return op; - } - } - } + for (op = (*model)->op; op->func; op++) { + if (op->opcode == opcode) { + return op; + } + } + } - *model = NULL; - return NULL; + *model = NULL; + return NULL; } static int get_opcode(struct net_buf_simple *buf, u32_t *opcode) { - switch (buf->data[0] >> 6) { - case 0x00: - case 0x01: - if (buf->data[0] == 0x7f) { - BT_ERR("Ignoring RFU OpCode"); - return -EINVAL; - } + switch (buf->data[0] >> 6) { + case 0x00: + case 0x01: + if (buf->data[0] == 0x7f) { + BT_ERR("Ignoring RFU OpCode"); + return -EINVAL; + } - *opcode = net_buf_simple_pull_u8(buf); - return 0; - case 0x02: - if (buf->len < 2) { - BT_ERR("Too short payload for 2-octet OpCode"); - return -EINVAL; - } + *opcode = net_buf_simple_pull_u8(buf); + return 0; + case 0x02: + if (buf->len < 2) { + BT_ERR("Too short payload for 2-octet OpCode"); + return -EINVAL; + } - *opcode = net_buf_simple_pull_be16(buf); - return 0; - case 0x03: - if (buf->len < 3) { - BT_ERR("Too short payload for 3-octet OpCode"); - return -EINVAL; - } + *opcode = net_buf_simple_pull_be16(buf); + return 0; + case 0x03: + if (buf->len < 3) { + BT_ERR("Too short payload for 3-octet OpCode"); + return -EINVAL; + } - *opcode = net_buf_simple_pull_u8(buf) << 16; - *opcode |= net_buf_simple_pull_le16(buf); - return 0; - } + *opcode = net_buf_simple_pull_u8(buf) << 16; + *opcode |= net_buf_simple_pull_le16(buf); + return 0; + } - CODE_UNREACHABLE; + CODE_UNREACHABLE; } bool bt_mesh_fixed_group_match(u16_t addr) { - /* Check for fixed group addresses */ - switch (addr) { - case BT_MESH_ADDR_ALL_NODES: - return true; - case BT_MESH_ADDR_PROXIES: - /* TODO: Proxy not yet supported */ - return false; - case BT_MESH_ADDR_FRIENDS: - return (bt_mesh_friend_get() == BT_MESH_FRIEND_ENABLED); - case BT_MESH_ADDR_RELAYS: - return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED); - default: - return false; - } + /* Check for fixed group addresses */ + switch (addr) { + case BT_MESH_ADDR_ALL_NODES: + return true; + case BT_MESH_ADDR_PROXIES: + /* TODO: Proxy not yet supported */ + return false; + case BT_MESH_ADDR_FRIENDS: + return (bt_mesh_friend_get() == BT_MESH_FRIEND_ENABLED); + case BT_MESH_ADDR_RELAYS: + return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED); + default: + return false; + } } void bt_mesh_model_recv(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf) { - struct bt_mesh_model *models, *model; - const struct bt_mesh_model_op *op; - u32_t opcode; - u8_t count; - int i; + struct bt_mesh_model *models, *model; + const struct bt_mesh_model_op *op; + u32_t opcode; + u8_t count; + int i; - BT_DBG("app_idx 0x%04x src 0x%04x dst 0x%04x", rx->ctx.app_idx, - rx->ctx.addr, rx->ctx.recv_dst); - BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("app_idx 0x%04x src 0x%04x dst 0x%04x", rx->ctx.app_idx, + rx->ctx.addr, rx->ctx.recv_dst); + BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); - if (get_opcode(buf, &opcode) < 0) { - BT_WARN("Unable to decode OpCode"); - return; - } + if (get_opcode(buf, &opcode) < 0) { + BT_WARN("Unable to decode OpCode"); + return; + } - BT_DBG("OpCode 0x%08x", opcode); + BT_DBG("OpCode 0x%08x", opcode); - for (i = 0; i < dev_comp->elem_count; i++) { - struct bt_mesh_elem *elem = &dev_comp->elem[i]; + for (i = 0; i < dev_comp->elem_count; i++) { + struct bt_mesh_elem *elem = &dev_comp->elem[i]; - if (BT_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) { - if (elem->addr != rx->ctx.recv_dst) { - continue; - } - } else if (BT_MESH_ADDR_IS_GROUP(rx->ctx.recv_dst) || - BT_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) { - /* find_op() will do proper model/group matching */ - } else if (i != 0 || - !bt_mesh_fixed_group_match(rx->ctx.recv_dst)) { - continue; - } + if (BT_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) { + if (elem->addr != rx->ctx.recv_dst) { + continue; + } + } else if (BT_MESH_ADDR_IS_GROUP(rx->ctx.recv_dst) || + BT_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) { + /* find_op() will do proper model/group matching */ + } else if (i != 0 || + !bt_mesh_fixed_group_match(rx->ctx.recv_dst)) { + continue; + } - /* SIG models cannot contain 3-byte (vendor) OpCodes, and - * vendor models cannot contain SIG (1- or 2-byte) OpCodes, so - * we only need to do the lookup in one of the model lists. - */ - if (opcode < 0x10000) { - models = elem->models; - count = elem->model_count; - } else { - models = elem->vnd_models; - count = elem->vnd_model_count; - } + /* SIG models cannot contain 3-byte (vendor) OpCodes, and + * vendor models cannot contain SIG (1- or 2-byte) OpCodes, so + * we only need to do the lookup in one of the model lists. + */ + if (opcode < 0x10000) { + models = elem->models; + count = elem->model_count; + } else { + models = elem->vnd_models; + count = elem->vnd_model_count; + } - op = find_op(models, count, rx->ctx.recv_dst, rx->ctx.app_idx, - opcode, &model); - if (op) { - struct net_buf_simple_state state; + op = find_op(models, count, rx->ctx.recv_dst, rx->ctx.app_idx, + opcode, &model); + if (op) { + struct net_buf_simple_state state; - if (buf->len < op->min_len) { - BT_ERR("Too short message for OpCode 0x%08x", - opcode); - continue; - } + if (buf->len < op->min_len) { + BT_ERR("Too short message for OpCode 0x%08x", + opcode); + continue; + } - rx->ctx.recv_op = opcode; - rx->ctx.model = model; - rx->ctx.srv_send = true; + rx->ctx.recv_op = opcode; + rx->ctx.model = model; + rx->ctx.srv_send = true; - /* The callback will likely parse the buffer, so - * store the parsing state in case multiple models - * receive the message. - */ - net_buf_simple_save(buf, &state); - op->func(model, &rx->ctx, buf); - net_buf_simple_restore(buf, &state); + /* The callback will likely parse the buffer, so + * store the parsing state in case multiple models + * receive the message. + */ + net_buf_simple_save(buf, &state); + op->func(model, &rx->ctx, buf); + net_buf_simple_restore(buf, &state); - } else { - BT_DBG("No OpCode 0x%08x for elem %d", opcode, i); - } - } + } else { + BT_DBG("No OpCode 0x%08x for elem %d", opcode, i); + } + } } void bt_mesh_model_msg_init(struct net_buf_simple *msg, u32_t opcode) { - net_buf_simple_init(msg, 0); + net_buf_simple_init(msg, 0); - if (opcode < 0x100) { - /* 1-byte OpCode */ - net_buf_simple_add_u8(msg, opcode); - return; - } + if (opcode < 0x100) { + /* 1-byte OpCode */ + net_buf_simple_add_u8(msg, opcode); + return; + } - if (opcode < 0x10000) { - /* 2-byte OpCode */ - net_buf_simple_add_be16(msg, opcode); - return; - } + if (opcode < 0x10000) { + /* 2-byte OpCode */ + net_buf_simple_add_be16(msg, opcode); + return; + } - /* 3-byte OpCode */ - net_buf_simple_add_u8(msg, ((opcode >> 16) & 0xff)); - net_buf_simple_add_le16(msg, opcode & 0xffff); + /* 3-byte OpCode */ + net_buf_simple_add_u8(msg, ((opcode >> 16) & 0xff)); + net_buf_simple_add_le16(msg, opcode & 0xffff); } static int model_send(struct bt_mesh_model *model, - struct bt_mesh_net_tx *tx, bool implicit_bind, - struct net_buf_simple *msg, - const struct bt_mesh_send_cb *cb, void *cb_data) + struct bt_mesh_net_tx *tx, bool implicit_bind, + struct net_buf_simple *msg, + const struct bt_mesh_send_cb *cb, void *cb_data) { - BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->ctx->net_idx, - tx->ctx->app_idx, tx->ctx->addr); - BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->ctx->net_idx, + tx->ctx->app_idx, tx->ctx->addr); + BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len)); - if (!bt_mesh_is_provisioned()) { - BT_ERR("Local node is not yet provisioned"); - return -EAGAIN; - } + if (!bt_mesh_is_provisioned()) { + BT_ERR("Local node is not yet provisioned"); + return -EAGAIN; + } - if (net_buf_simple_tailroom(msg) < 4) { - BT_ERR("Not enough tailroom for TransMIC"); - return -EINVAL; - } + if (net_buf_simple_tailroom(msg) < 4) { + BT_ERR("Not enough tailroom for TransMIC"); + return -EINVAL; + } - if (msg->len > BT_MESH_TX_SDU_MAX - 4) { - BT_ERR("Too big message"); - return -EMSGSIZE; - } + if (msg->len > BT_MESH_TX_SDU_MAX - 4) { + BT_ERR("Too big message"); + return -EMSGSIZE; + } - if (!implicit_bind && !model_has_key(model, tx->ctx->app_idx)) { - BT_ERR("Model not bound to AppKey 0x%04x", tx->ctx->app_idx); - return -EINVAL; - } + if (!implicit_bind && !model_has_key(model, tx->ctx->app_idx)) { + BT_ERR("Model not bound to AppKey 0x%04x", tx->ctx->app_idx); + return -EINVAL; + } - return bt_mesh_trans_send(tx, msg, cb, cb_data); + return bt_mesh_trans_send(tx, msg, cb, cb_data); } int bt_mesh_model_send(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *msg, - const struct bt_mesh_send_cb *cb, void *cb_data) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *msg, + const struct bt_mesh_send_cb *cb, void *cb_data) { - struct bt_mesh_net_tx tx = { - .sub = bt_mesh_subnet_get(ctx->net_idx), - .ctx = ctx, - .src = bt_mesh_model_elem(model)->addr, - .xmit = bt_mesh_net_transmit_get(), - .friend_cred = 0, - }; + struct bt_mesh_net_tx tx = { + .sub = bt_mesh_subnet_get(ctx->net_idx), + .ctx = ctx, + .src = bt_mesh_model_elem(model)->addr, + .xmit = bt_mesh_net_transmit_get(), + .friend_cred = 0, + }; - return model_send(model, &tx, false, msg, cb, cb_data); + return model_send(model, &tx, false, msg, cb, cb_data); } int bt_mesh_model_publish(struct bt_mesh_model *model) { - NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); - struct bt_mesh_model_pub *pub = model->pub; - struct bt_mesh_app_key *key; - struct bt_mesh_msg_ctx ctx = { - }; - struct bt_mesh_net_tx tx = { - .ctx = &ctx, - .src = bt_mesh_model_elem(model)->addr, - .xmit = bt_mesh_net_transmit_get(), - }; - int err; + NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); + struct bt_mesh_model_pub *pub = model->pub; + struct bt_mesh_app_key *key; + struct bt_mesh_msg_ctx ctx = { + }; + struct bt_mesh_net_tx tx = { + .ctx = &ctx, + .src = bt_mesh_model_elem(model)->addr, + .xmit = bt_mesh_net_transmit_get(), + }; + int err; - BT_DBG(""); + BT_DBG(""); - if (!pub) { - return -ENOTSUP; - } + if (!pub) { + return -ENOTSUP; + } - if (pub->addr == BT_MESH_ADDR_UNASSIGNED) { - return -EADDRNOTAVAIL; - } + if (pub->addr == BT_MESH_ADDR_UNASSIGNED) { + return -EADDRNOTAVAIL; + } - key = bt_mesh_app_key_find(pub->key); - if (!key) { - return -EADDRNOTAVAIL; - } + key = bt_mesh_app_key_find(pub->key); + if (!key) { + return -EADDRNOTAVAIL; + } - if (pub->msg->len + 4 > BT_MESH_TX_SDU_MAX) { - BT_ERR("Message does not fit maximum SDU size"); - return -EMSGSIZE; - } + if (pub->msg->len + 4 > BT_MESH_TX_SDU_MAX) { + BT_ERR("Message does not fit maximum SDU size"); + return -EMSGSIZE; + } - if (pub->count) { - BT_WARN("Clearing publish retransmit timer"); - k_delayed_work_cancel(&pub->timer); - } + if (pub->count) { + BT_WARN("Clearing publish retransmit timer"); + k_delayed_work_cancel(&pub->timer); + } - net_buf_simple_add_mem(&sdu, pub->msg->data, pub->msg->len); + net_buf_simple_add_mem(&sdu, pub->msg->data, pub->msg->len); - ctx.addr = pub->addr; - ctx.send_ttl = pub->ttl; - ctx.net_idx = key->net_idx; - ctx.app_idx = key->app_idx; + ctx.addr = pub->addr; + ctx.send_ttl = pub->ttl; + ctx.net_idx = key->net_idx; + ctx.app_idx = key->app_idx; - tx.friend_cred = pub->cred; - tx.sub = bt_mesh_subnet_get(ctx.net_idx), + tx.friend_cred = pub->cred; + tx.sub = bt_mesh_subnet_get(ctx.net_idx), - pub->count = BT_MESH_PUB_TRANSMIT_COUNT(pub->retransmit); + pub->count = BT_MESH_PUB_TRANSMIT_COUNT(pub->retransmit); - BT_DBG("Publish Retransmit Count %u Interval %ums", pub->count, - BT_MESH_PUB_TRANSMIT_INT(pub->retransmit)); + BT_DBG("Publish Retransmit Count %u Interval %ums", pub->count, + BT_MESH_PUB_TRANSMIT_INT(pub->retransmit)); - err = model_send(model, &tx, true, &sdu, &pub_sent_cb, model); - if (err) { - /* Don't try retransmissions for this publish attempt */ - pub->count = 0U; - /* Make sure the publish timer gets reset */ - publish_sent(err, model); - return err; - } + err = model_send(model, &tx, true, &sdu, &pub_sent_cb, model); + if (err) { + /* Don't try retransmissions for this publish attempt */ + pub->count = 0U; + /* Make sure the publish timer gets reset */ + publish_sent(err, model); + return err; + } - return 0; + return 0; } struct bt_mesh_model *bt_mesh_model_find_vnd(struct bt_mesh_elem *elem, - u16_t company, u16_t id) + u16_t company, u16_t id) { - u8_t i; + u8_t i; - for (i = 0U; i < elem->vnd_model_count; i++) { - if (elem->vnd_models[i].vnd.company == company && - elem->vnd_models[i].vnd.id == id) { - return &elem->vnd_models[i]; - } - } + for (i = 0U; i < elem->vnd_model_count; i++) { + if (elem->vnd_models[i].vnd.company == company && + elem->vnd_models[i].vnd.id == id) { + return &elem->vnd_models[i]; + } + } - return NULL; + return NULL; } struct bt_mesh_model *bt_mesh_model_find(struct bt_mesh_elem *elem, - u16_t id) + u16_t id) { - u8_t i; + u8_t i; - for (i = 0U; i < elem->model_count; i++) { - if (elem->models[i].id == id) { - return &elem->models[i]; - } - } + for (i = 0U; i < elem->model_count; i++) { + if (elem->models[i].id == id) { + return &elem->models[i]; + } + } - return NULL; + return NULL; } const struct bt_mesh_comp *bt_mesh_comp_get(void) { - return dev_comp; + return dev_comp; } diff --git a/components/network/ble/blemesh/src/access.h b/components/network/ble/blemesh/src/access.h index b9d85258..bd9caaf8 100644 --- a/components/network/ble/blemesh/src/access.h +++ b/components/network/ble/blemesh/src/access.h @@ -16,9 +16,9 @@ enum { - BT_MESH_MOD_BIND_PENDING = BIT(0), - BT_MESH_MOD_SUB_PENDING = BIT(1), - BT_MESH_MOD_PUB_PENDING = BIT(2), + BT_MESH_MOD_BIND_PENDING = BIT(0), + BT_MESH_MOD_SUB_PENDING = BIT(1), + BT_MESH_MOD_PUB_PENDING = BIT(2), }; void bt_mesh_elem_register(struct bt_mesh_elem *elem, u8_t count); @@ -29,19 +29,19 @@ u8_t bt_mesh_elem_count(void); struct bt_mesh_elem *bt_mesh_elem_find(u16_t addr); struct bt_mesh_model *bt_mesh_model_find_vnd(struct bt_mesh_elem *elem, - u16_t company, u16_t id); + u16_t company, u16_t id); struct bt_mesh_model *bt_mesh_model_find(struct bt_mesh_elem *elem, - u16_t id); + u16_t id); u16_t *bt_mesh_model_find_group(struct bt_mesh_model *mod, u16_t addr); bool bt_mesh_fixed_group_match(u16_t addr); void bt_mesh_model_foreach(void (*func)(struct bt_mesh_model *mod, - struct bt_mesh_elem *elem, - bool vnd, bool primary, - void *user_data), - void *user_data); + struct bt_mesh_elem *elem, + bool vnd, bool primary, + void *user_data), + void *user_data); s32_t bt_mesh_model_pub_period_get(struct bt_mesh_model *mod); diff --git a/components/network/ble/blemesh/src/adv.c b/components/network/ble/blemesh/src/adv.c index 3dd0db99..308f4c89 100644 --- a/components/network/ble/blemesh/src/adv.c +++ b/components/network/ble/blemesh/src/adv.c @@ -63,267 +63,267 @@ static K_THREAD_STACK_DEFINE(adv_thread_stack, ADV_STACK_SIZE); #endif static const u8_t adv_type[] = { - [BT_MESH_ADV_PROV] = BT_DATA_MESH_PROV, - [BT_MESH_ADV_DATA] = BT_DATA_MESH_MESSAGE, - [BT_MESH_ADV_BEACON] = BT_DATA_MESH_BEACON, - [BT_MESH_ADV_URI] = BT_DATA_URI, + [BT_MESH_ADV_PROV] = BT_DATA_MESH_PROV, + [BT_MESH_ADV_DATA] = BT_DATA_MESH_MESSAGE, + [BT_MESH_ADV_BEACON] = BT_DATA_MESH_BEACON, + [BT_MESH_ADV_URI] = BT_DATA_URI, }; NET_BUF_POOL_DEFINE(adv_buf_pool, CONFIG_BT_MESH_ADV_BUF_COUNT, - BT_MESH_ADV_DATA_SIZE, BT_MESH_ADV_USER_DATA_SIZE, NULL); + BT_MESH_ADV_DATA_SIZE, BT_MESH_ADV_USER_DATA_SIZE, NULL); static struct bt_mesh_adv adv_pool[CONFIG_BT_MESH_ADV_BUF_COUNT]; static struct bt_mesh_adv *adv_alloc(int id) { - return &adv_pool[id]; + return &adv_pool[id]; } static inline void adv_send_start(u16_t duration, int err, - const struct bt_mesh_send_cb *cb, - void *cb_data) + const struct bt_mesh_send_cb *cb, + void *cb_data) { - if (cb && cb->start) { - cb->start(duration, err, cb_data); - } + if (cb && cb->start) { + cb->start(duration, err, cb_data); + } } static inline void adv_send_end(int err, const struct bt_mesh_send_cb *cb, - void *cb_data) + void *cb_data) { - if (cb && cb->end) { - cb->end(err, cb_data); - } + if (cb && cb->end) { + cb->end(err, cb_data); + } } static inline void adv_send(struct net_buf *buf) { - const s32_t adv_int_min = ((bt_dev.hci_version >= BT_HCI_VERSION_5_0) ? - ADV_INT_FAST_MS : ADV_INT_DEFAULT_MS); - const struct bt_mesh_send_cb *cb = BT_MESH_ADV(buf)->cb; - void *cb_data = BT_MESH_ADV(buf)->cb_data; - struct bt_le_adv_param param; - u16_t duration, adv_int; - struct bt_data ad; - int err; + const s32_t adv_int_min = ((bt_dev.hci_version >= BT_HCI_VERSION_5_0) ? + ADV_INT_FAST_MS : ADV_INT_DEFAULT_MS); + const struct bt_mesh_send_cb *cb = BT_MESH_ADV(buf)->cb; + void *cb_data = BT_MESH_ADV(buf)->cb_data; + struct bt_le_adv_param param; + u16_t duration, adv_int; + struct bt_data ad; + int err; - adv_int = MAX(adv_int_min, - BT_MESH_TRANSMIT_INT(BT_MESH_ADV(buf)->xmit)); - duration = (MESH_SCAN_WINDOW_MS + - ((BT_MESH_TRANSMIT_COUNT(BT_MESH_ADV(buf)->xmit) + 1) * - (adv_int + 10))); + adv_int = MAX(adv_int_min, + BT_MESH_TRANSMIT_INT(BT_MESH_ADV(buf)->xmit)); + duration = (MESH_SCAN_WINDOW_MS + + ((BT_MESH_TRANSMIT_COUNT(BT_MESH_ADV(buf)->xmit) + 1) * + (adv_int + 10))); - BT_DBG("type %u len %u: %s", BT_MESH_ADV(buf)->type, - buf->len, bt_hex(buf->data, buf->len)); - BT_DBG("count %u interval %ums duration %ums", - BT_MESH_TRANSMIT_COUNT(BT_MESH_ADV(buf)->xmit) + 1, adv_int, - duration); + BT_DBG("type %u len %u: %s", BT_MESH_ADV(buf)->type, + buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("count %u interval %ums duration %ums", + BT_MESH_TRANSMIT_COUNT(BT_MESH_ADV(buf)->xmit) + 1, adv_int, + duration); - ad.type = adv_type[BT_MESH_ADV(buf)->type]; - ad.data_len = buf->len; - ad.data = buf->data; + ad.type = adv_type[BT_MESH_ADV(buf)->type]; + ad.data_len = buf->len; + ad.data = buf->data; - if (IS_ENABLED(CONFIG_BT_MESH_DEBUG_USE_ID_ADDR)) { - param.options = BT_LE_ADV_OPT_USE_IDENTITY; - } else { - param.options = 0U; - } + if (IS_ENABLED(CONFIG_BT_MESH_DEBUG_USE_ID_ADDR)) { + param.options = BT_LE_ADV_OPT_USE_IDENTITY; + } else { + param.options = 0U; + } - param.id = BT_ID_DEFAULT; - param.interval_min = ADV_SCAN_UNIT(adv_int); - param.interval_max = param.interval_min; + param.id = BT_ID_DEFAULT; + param.interval_min = ADV_SCAN_UNIT(adv_int); + param.interval_max = param.interval_min; - err = bt_le_adv_start(¶m, &ad, 1, NULL, 0); - net_buf_unref(buf); - adv_send_start(duration, err, cb, cb_data); - if (err) { - BT_ERR("Advertising failed: err %d", err); - return; - } + err = bt_le_adv_start(¶m, &ad, 1, NULL, 0); + net_buf_unref(buf); + adv_send_start(duration, err, cb, cb_data); + if (err) { + BT_ERR("Advertising failed: err %d", err); + return; + } - BT_DBG("Advertising started. Sleeping %u ms", duration); + BT_DBG("Advertising started. Sleeping %u ms", duration); - k_sleep(K_MSEC(duration)); + k_sleep(K_MSEC(duration)); - err = bt_le_adv_stop(); + err = bt_le_adv_stop(); - adv_send_end(err, cb, cb_data); - if (err) { - BT_ERR("Stopping advertising failed: err %d", err); - return; - } + adv_send_end(err, cb, cb_data); + if (err) { + BT_ERR("Stopping advertising failed: err %d", err); + return; + } - BT_DBG("Advertising stopped"); + BT_DBG("Advertising stopped"); } #if !defined(BFLB_BLE) static void adv_stack_dump(const struct k_thread *thread, void *user_data) { #if defined(CONFIG_THREAD_STACK_INFO) - stack_analyze((char *)user_data, (char *)thread->stack_info.start, - thread->stack_info.size); + stack_analyze((char *)user_data, (char *)thread->stack_info.start, + thread->stack_info.size); #endif } #endif static void adv_thread(void *p1) { - BT_DBG("started"); + BT_DBG("started"); UNUSED(p1); - - while (1) { - struct net_buf *buf; - if (IS_ENABLED(CONFIG_BT_MESH_PROXY)) { - buf = net_buf_get(&adv_queue, K_NO_WAIT); - while (!buf) { - s32_t timeout; + while (1) { + struct net_buf *buf; + + if (IS_ENABLED(CONFIG_BT_MESH_PROXY)) { + buf = net_buf_get(&adv_queue, K_NO_WAIT); + while (!buf) { + s32_t timeout; + + timeout = bt_mesh_proxy_adv_start(); + BT_DBG("Proxy Advertising up to %d ms", + timeout); + buf = net_buf_get(&adv_queue, timeout); + bt_mesh_proxy_adv_stop(); + } + } else { + buf = net_buf_get(&adv_queue, K_FOREVER); + } - timeout = bt_mesh_proxy_adv_start(); - BT_DBG("Proxy Advertising up to %d ms", - timeout); - buf = net_buf_get(&adv_queue, timeout); - bt_mesh_proxy_adv_stop(); - } - } else { - buf = net_buf_get(&adv_queue, K_FOREVER); - } - if (!buf) { - continue; - } + continue; + } - /* busy == 0 means this was canceled */ - if (BT_MESH_ADV(buf)->busy) { - BT_MESH_ADV(buf)->busy = 0U; - adv_send(buf); - } else { - net_buf_unref(buf); - } + /* busy == 0 means this was canceled */ + if (BT_MESH_ADV(buf)->busy) { + BT_MESH_ADV(buf)->busy = 0U; + adv_send(buf); + } else { + net_buf_unref(buf); + } #if !defined(BFLB_BLE) - STACK_ANALYZE("adv stack", adv_thread_stack); - k_thread_foreach(adv_stack_dump, "BT_MESH"); + STACK_ANALYZE("adv stack", adv_thread_stack); + k_thread_foreach(adv_stack_dump, "BT_MESH"); #endif - /* Give other threads a chance to run */ - k_yield(); - } + /* Give other threads a chance to run */ + k_yield(); + } } void bt_mesh_adv_update(void) { - BT_DBG(""); + BT_DBG(""); #if defined(BFLB_BLE) struct net_buf *buf; - - //in order to post the adv thread to make it handle the enqueued msg, enqueue a beacon packet to adv queue, - //and set busy bit as 0 to make adv thread directly ignore this beacon packet. + + //in order to post the adv thread to make it handle the enqueued msg, enqueue a beacon packet to adv queue, + //and set busy bit as 0 to make adv thread directly ignore this beacon packet. buf = bt_mesh_adv_create(BT_MESH_ADV_BEACON, 0, - K_NO_WAIT); + K_NO_WAIT); BT_MESH_ADV(buf)->busy = 0; net_buf_put(&adv_queue, net_buf_ref(buf)); #else - k_fifo_cancel_wait(&adv_queue); + k_fifo_cancel_wait(&adv_queue); #endif } struct net_buf *bt_mesh_adv_create_from_pool(struct net_buf_pool *pool, - bt_mesh_adv_alloc_t get_id, - enum bt_mesh_adv_type type, - u8_t xmit, s32_t timeout) + bt_mesh_adv_alloc_t get_id, + enum bt_mesh_adv_type type, + u8_t xmit, s32_t timeout) { - struct bt_mesh_adv *adv; - struct net_buf *buf; + struct bt_mesh_adv *adv; + struct net_buf *buf; - if (atomic_test_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) { - BT_WARN("Refusing to allocate buffer while suspended"); - return NULL; - } - buf = net_buf_alloc(pool, timeout); - if (!buf) { - return NULL; - } + if (atomic_test_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) { + BT_WARN("Refusing to allocate buffer while suspended"); + return NULL; + } + buf = net_buf_alloc(pool, timeout); + if (!buf) { + return NULL; + } - adv = get_id(net_buf_id(buf)); - BT_MESH_ADV(buf) = adv; + adv = get_id(net_buf_id(buf)); + BT_MESH_ADV(buf) = adv; - (void)memset(adv, 0, sizeof(*adv)); + (void)memset(adv, 0, sizeof(*adv)); - adv->type = type; - adv->xmit = xmit; + adv->type = type; + adv->xmit = xmit; - return buf; + return buf; } struct net_buf *bt_mesh_adv_create(enum bt_mesh_adv_type type, u8_t xmit, - s32_t timeout) + s32_t timeout) { - return bt_mesh_adv_create_from_pool(&adv_buf_pool, adv_alloc, type, - xmit, timeout); + return bt_mesh_adv_create_from_pool(&adv_buf_pool, adv_alloc, type, + xmit, timeout); } void bt_mesh_adv_send(struct net_buf *buf, const struct bt_mesh_send_cb *cb, - void *cb_data) + void *cb_data) { - BT_DBG("type 0x%02x len %u: %s", BT_MESH_ADV(buf)->type, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("type 0x%02x len %u: %s", BT_MESH_ADV(buf)->type, buf->len, + bt_hex(buf->data, buf->len)); - BT_MESH_ADV(buf)->cb = cb; - BT_MESH_ADV(buf)->cb_data = cb_data; - BT_MESH_ADV(buf)->busy = 1U; + BT_MESH_ADV(buf)->cb = cb; + BT_MESH_ADV(buf)->cb_data = cb_data; + BT_MESH_ADV(buf)->busy = 1U; - net_buf_put(&adv_queue, net_buf_ref(buf)); + net_buf_put(&adv_queue, net_buf_ref(buf)); } static void bt_mesh_scan_cb(const bt_addr_le_t *addr, s8_t rssi, - u8_t adv_type, struct net_buf_simple *buf) + u8_t adv_type, struct net_buf_simple *buf) { - if (adv_type != BT_LE_ADV_NONCONN_IND) { - return; - } + if (adv_type != BT_LE_ADV_NONCONN_IND) { + return; + } - BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); - while (buf->len > 1) { - struct net_buf_simple_state state; - u8_t len, type; + while (buf->len > 1) { + struct net_buf_simple_state state; + u8_t len, type; - len = net_buf_simple_pull_u8(buf); - /* Check for early termination */ - if (len == 0U) { - return; - } + len = net_buf_simple_pull_u8(buf); + /* Check for early termination */ + if (len == 0U) { + return; + } - if (len > buf->len) { - BT_WARN("AD malformed"); - return; - } + if (len > buf->len) { + BT_WARN("AD malformed"); + return; + } - net_buf_simple_save(buf, &state); + net_buf_simple_save(buf, &state); - type = net_buf_simple_pull_u8(buf); + type = net_buf_simple_pull_u8(buf); - buf->len = len - 1; + buf->len = len - 1; - switch (type) { - case BT_DATA_MESH_MESSAGE: - bt_mesh_net_recv(buf, rssi, BT_MESH_NET_IF_ADV); - break; + switch (type) { + case BT_DATA_MESH_MESSAGE: + bt_mesh_net_recv(buf, rssi, BT_MESH_NET_IF_ADV); + break; #if defined(CONFIG_BT_MESH_PB_ADV) - case BT_DATA_MESH_PROV: - bt_mesh_pb_adv_recv(buf); - break; + case BT_DATA_MESH_PROV: + bt_mesh_pb_adv_recv(buf); + break; #endif - case BT_DATA_MESH_BEACON: - bt_mesh_beacon_recv(buf); - break; - default: - break; - } + case BT_DATA_MESH_BEACON: + bt_mesh_beacon_recv(buf); + break; + default: + break; + } - net_buf_simple_restore(buf, &state); - net_buf_simple_pull(buf, len); - } + net_buf_simple_restore(buf, &state); + net_buf_simple_pull(buf, len); + } } void bt_mesh_adv_init(void) @@ -333,45 +333,45 @@ void bt_mesh_adv_init(void) k_fifo_init(&adv_queue, 20); k_thread_create(&adv_thread_data, "BT Mesh adv", CONFIG_MESH_ADV_STACK_SIZE, adv_thread, CONFIG_BT_MESH_ADV_PRIO); -#else - k_thread_create(&adv_thread_data, adv_thread_stack, - K_THREAD_STACK_SIZEOF(adv_thread_stack), adv_thread, - NULL, NULL, NULL, K_PRIO_COOP(7), 0, K_NO_WAIT); - k_thread_name_set(&adv_thread_data, "BT Mesh adv"); +#else + k_thread_create(&adv_thread_data, adv_thread_stack, + K_THREAD_STACK_SIZEOF(adv_thread_stack), adv_thread, + NULL, NULL, NULL, K_PRIO_COOP(7), 0, K_NO_WAIT); + k_thread_name_set(&adv_thread_data, "BT Mesh adv"); #endif } int bt_mesh_scan_enable(void) { - struct bt_le_scan_param scan_param = { - .type = BT_HCI_LE_SCAN_PASSIVE, - .filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE, - .interval = MESH_SCAN_INTERVAL, - .window = MESH_SCAN_WINDOW }; - int err; + struct bt_le_scan_param scan_param = { + .type = BT_HCI_LE_SCAN_PASSIVE, + .filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE, + .interval = MESH_SCAN_INTERVAL, + .window = MESH_SCAN_WINDOW }; + int err; - BT_DBG(""); + BT_DBG(""); - err = bt_le_scan_start(&scan_param, bt_mesh_scan_cb); - if (err && err != -EALREADY) { - BT_ERR("starting scan failed (err %d)", err); - return err; - } + err = bt_le_scan_start(&scan_param, bt_mesh_scan_cb); + if (err && err != -EALREADY) { + BT_ERR("starting scan failed (err %d)", err); + return err; + } - return 0; + return 0; } int bt_mesh_scan_disable(void) { - int err; + int err; - BT_DBG(""); + BT_DBG(""); - err = bt_le_scan_stop(); - if (err && err != -EALREADY) { - BT_ERR("stopping scan failed (err %d)", err); - return err; - } + err = bt_le_scan_stop(); + if (err && err != -EALREADY) { + BT_ERR("stopping scan failed (err %d)", err); + return err; + } - return 0; + return 0; } diff --git a/components/network/ble/blemesh/src/adv.h b/components/network/ble/blemesh/src/adv.h index cbec64cd..bd533ab0 100644 --- a/components/network/ble/blemesh/src/adv.h +++ b/components/network/ble/blemesh/src/adv.h @@ -17,47 +17,47 @@ #define BT_MESH_ADV(buf) (*(struct bt_mesh_adv **)net_buf_user_data(buf)) enum bt_mesh_adv_type { - BT_MESH_ADV_PROV, - BT_MESH_ADV_DATA, - BT_MESH_ADV_BEACON, - BT_MESH_ADV_URI, + BT_MESH_ADV_PROV, + BT_MESH_ADV_DATA, + BT_MESH_ADV_BEACON, + BT_MESH_ADV_URI, }; typedef void (*bt_mesh_adv_func_t)(struct net_buf *buf, u16_t duration, - int err, void *user_data); + int err, void *user_data); struct bt_mesh_adv { - const struct bt_mesh_send_cb *cb; - void *cb_data; + const struct bt_mesh_send_cb *cb; + void *cb_data; - u8_t type:2, - busy:1; - u8_t xmit; + u8_t type:2, + busy:1; + u8_t xmit; - union { - /* Address, used e.g. for Friend Queue messages */ - u16_t addr; + union { + /* Address, used e.g. for Friend Queue messages */ + u16_t addr; - /* For transport layer segment sending */ - struct { - u8_t attempts; - } seg; - }; + /* For transport layer segment sending */ + struct { + u8_t attempts; + } seg; + }; }; typedef struct bt_mesh_adv *(*bt_mesh_adv_alloc_t)(int id); /* xmit_count: Number of retransmissions, i.e. 0 == 1 transmission */ struct net_buf *bt_mesh_adv_create(enum bt_mesh_adv_type type, u8_t xmit, - s32_t timeout); + s32_t timeout); struct net_buf *bt_mesh_adv_create_from_pool(struct net_buf_pool *pool, - bt_mesh_adv_alloc_t get_id, - enum bt_mesh_adv_type type, - u8_t xmit, s32_t timeout); + bt_mesh_adv_alloc_t get_id, + enum bt_mesh_adv_type type, + u8_t xmit, s32_t timeout); void bt_mesh_adv_send(struct net_buf *buf, const struct bt_mesh_send_cb *cb, - void *cb_data); + void *cb_data); void bt_mesh_adv_update(void); diff --git a/components/network/ble/blemesh/src/beacon.c b/components/network/ble/blemesh/src/beacon.c index 2b44581f..84de146b 100644 --- a/components/network/ble/blemesh/src/beacon.c +++ b/components/network/ble/blemesh/src/beacon.c @@ -43,398 +43,398 @@ static struct k_delayed_work beacon_timer; static struct bt_mesh_subnet *cache_check(u8_t data[21]) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - if (!memcmp(sub->beacon_cache, data, 21)) { - return sub; - } - } + if (!memcmp(sub->beacon_cache, data, 21)) { + return sub; + } + } - return NULL; + return NULL; } static void cache_add(u8_t data[21], struct bt_mesh_subnet *sub) { - memcpy(sub->beacon_cache, data, 21); + memcpy(sub->beacon_cache, data, 21); } static void beacon_complete(int err, void *user_data) { - struct bt_mesh_subnet *sub = user_data; + struct bt_mesh_subnet *sub = user_data; - BT_DBG("err %d", err); + BT_DBG("err %d", err); - sub->beacon_sent = k_uptime_get_32(); + sub->beacon_sent = k_uptime_get_32(); } void bt_mesh_beacon_create(struct bt_mesh_subnet *sub, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - u8_t flags = bt_mesh_net_flags(sub); - struct bt_mesh_subnet_keys *keys; + u8_t flags = bt_mesh_net_flags(sub); + struct bt_mesh_subnet_keys *keys; - net_buf_simple_add_u8(buf, BEACON_TYPE_SECURE); + net_buf_simple_add_u8(buf, BEACON_TYPE_SECURE); - if (sub->kr_flag) { - keys = &sub->keys[1]; - } else { - keys = &sub->keys[0]; - } + if (sub->kr_flag) { + keys = &sub->keys[1]; + } else { + keys = &sub->keys[0]; + } - net_buf_simple_add_u8(buf, flags); + net_buf_simple_add_u8(buf, flags); - /* Network ID */ - net_buf_simple_add_mem(buf, keys->net_id, 8); + /* Network ID */ + net_buf_simple_add_mem(buf, keys->net_id, 8); - /* IV Index */ - net_buf_simple_add_be32(buf, bt_mesh.iv_index); + /* IV Index */ + net_buf_simple_add_be32(buf, bt_mesh.iv_index); - net_buf_simple_add_mem(buf, sub->auth, 8); + net_buf_simple_add_mem(buf, sub->auth, 8); - BT_DBG("net_idx 0x%04x flags 0x%02x NetID %s", sub->net_idx, - flags, bt_hex(keys->net_id, 8)); - BT_DBG("IV Index 0x%08x Auth %s", bt_mesh.iv_index, - bt_hex(sub->auth, 8)); + BT_DBG("net_idx 0x%04x flags 0x%02x NetID %s", sub->net_idx, + flags, bt_hex(keys->net_id, 8)); + BT_DBG("IV Index 0x%08x Auth %s", bt_mesh.iv_index, + bt_hex(sub->auth, 8)); } /* If the interval has passed or is within 5 seconds from now send a beacon */ #define BEACON_THRESHOLD(sub) (K_SECONDS(10 * ((sub)->beacons_last + 1)) - \ - K_SECONDS(5)) + K_SECONDS(5)) static int secure_beacon_send(void) { - static const struct bt_mesh_send_cb send_cb = { - .end = beacon_complete, - }; - u32_t now = k_uptime_get_32(); - int i; + static const struct bt_mesh_send_cb send_cb = { + .end = beacon_complete, + }; + u32_t now = k_uptime_get_32(); + int i; - BT_DBG(""); + BT_DBG(""); - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - struct net_buf *buf; - u32_t time_diff; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + struct net_buf *buf; + u32_t time_diff; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - time_diff = now - sub->beacon_sent; - if (time_diff < K_SECONDS(600) && - time_diff < BEACON_THRESHOLD(sub)) { - continue; - } + time_diff = now - sub->beacon_sent; + if (time_diff < K_SECONDS(600) && + time_diff < BEACON_THRESHOLD(sub)) { + continue; + } - buf = bt_mesh_adv_create(BT_MESH_ADV_BEACON, PROV_XMIT, - K_NO_WAIT); - if (!buf) { - BT_ERR("Unable to allocate beacon buffer"); - return -ENOBUFS; - } + buf = bt_mesh_adv_create(BT_MESH_ADV_BEACON, PROV_XMIT, + K_NO_WAIT); + if (!buf) { + BT_ERR("Unable to allocate beacon buffer"); + return -ENOBUFS; + } - bt_mesh_beacon_create(sub, &buf->b); + bt_mesh_beacon_create(sub, &buf->b); #ifdef CONFIG_BT_MESH_PTS - static u32_t pts_cnt = 0; - BT_PTS("[PTS] Sending secure network beacon (Flags = 0x%02X, IV Index = 0x%08X) %u", bt_mesh_net_flags(sub), bt_mesh.iv_index, ++pts_cnt); + static u32_t pts_cnt = 0; + BT_PTS("[PTS] Sending secure network beacon (Flags = 0x%02X, IV Index = 0x%08X) %u", bt_mesh_net_flags(sub), bt_mesh.iv_index, ++pts_cnt); #endif - bt_mesh_adv_send(buf, &send_cb, sub); - net_buf_unref(buf); - } + bt_mesh_adv_send(buf, &send_cb, sub); + net_buf_unref(buf); + } - return 0; + return 0; } static int unprovisioned_beacon_send(void) { #if defined(CONFIG_BT_MESH_PB_ADV) - const struct bt_mesh_prov *prov; - u8_t uri_hash[16] = { 0 }; - struct net_buf *buf; - u16_t oob_info; + const struct bt_mesh_prov *prov; + u8_t uri_hash[16] = { 0 }; + struct net_buf *buf; + u16_t oob_info; - BT_DBG(""); + BT_DBG(""); - buf = bt_mesh_adv_create(BT_MESH_ADV_BEACON, UNPROV_XMIT, K_NO_WAIT); - if (!buf) { - BT_ERR("Unable to allocate beacon buffer"); - return -ENOBUFS; - } + buf = bt_mesh_adv_create(BT_MESH_ADV_BEACON, UNPROV_XMIT, K_NO_WAIT); + if (!buf) { + BT_ERR("Unable to allocate beacon buffer"); + return -ENOBUFS; + } - prov = bt_mesh_prov_get(); + prov = bt_mesh_prov_get(); - net_buf_add_u8(buf, BEACON_TYPE_UNPROVISIONED); - net_buf_add_mem(buf, prov->uuid, 16); + net_buf_add_u8(buf, BEACON_TYPE_UNPROVISIONED); + net_buf_add_mem(buf, prov->uuid, 16); - if (prov->uri && bt_mesh_s1(prov->uri, uri_hash) == 0) { - oob_info = prov->oob_info | BT_MESH_PROV_OOB_URI; - } else { - oob_info = prov->oob_info; - } + if (prov->uri && bt_mesh_s1(prov->uri, uri_hash) == 0) { + oob_info = prov->oob_info | BT_MESH_PROV_OOB_URI; + } else { + oob_info = prov->oob_info; + } - net_buf_add_be16(buf, oob_info); + net_buf_add_be16(buf, oob_info); #if defined(BFLB_BLE) if(prov->uri) #endif - net_buf_add_mem(buf, uri_hash, 4); + net_buf_add_mem(buf, uri_hash, 4); #ifdef CONFIG_BT_MESH_PTS - static u32_t pts_cnt = 0; - BT_PTS("[PTS] Sending unprovisioned device beacon %u", ++pts_cnt); + static u32_t pts_cnt = 0; + BT_PTS("[PTS] Sending unprovisioned device beacon %u", ++pts_cnt); #endif - bt_mesh_adv_send(buf, NULL, NULL); - net_buf_unref(buf); + bt_mesh_adv_send(buf, NULL, NULL); + net_buf_unref(buf); - if (prov->uri) { - size_t len; + if (prov->uri) { + size_t len; - buf = bt_mesh_adv_create(BT_MESH_ADV_URI, UNPROV_XMIT, - K_NO_WAIT); - if (!buf) { - BT_ERR("Unable to allocate URI buffer"); - return -ENOBUFS; - } + buf = bt_mesh_adv_create(BT_MESH_ADV_URI, UNPROV_XMIT, + K_NO_WAIT); + if (!buf) { + BT_ERR("Unable to allocate URI buffer"); + return -ENOBUFS; + } - len = strlen(prov->uri); - if (net_buf_tailroom(buf) < len) { - BT_WARN("Too long URI to fit advertising data"); - } else { - net_buf_add_mem(buf, prov->uri, len); - bt_mesh_adv_send(buf, NULL, NULL); - } + len = strlen(prov->uri); + if (net_buf_tailroom(buf) < len) { + BT_WARN("Too long URI to fit advertising data"); + } else { + net_buf_add_mem(buf, prov->uri, len); + bt_mesh_adv_send(buf, NULL, NULL); + } - net_buf_unref(buf); - } + net_buf_unref(buf); + } #endif /* CONFIG_BT_MESH_PB_ADV */ - return 0; + return 0; } static void update_beacon_observation(void) { - static bool first_half; - int i; + static bool first_half; + int i; - /* Observation period is 20 seconds, whereas the beacon timer - * runs every 10 seconds. We process what's happened during the - * window only after the seconnd half. - */ - first_half = !first_half; - if (first_half) { - return; - } + /* Observation period is 20 seconds, whereas the beacon timer + * runs every 10 seconds. We process what's happened during the + * window only after the seconnd half. + */ + first_half = !first_half; + if (first_half) { + return; + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - sub->beacons_last = sub->beacons_cur; - sub->beacons_cur = 0U; - } + sub->beacons_last = sub->beacons_cur; + sub->beacons_cur = 0U; + } } static void beacon_send(struct k_work *work) { - /* Don't send anything if we have an active provisioning link */ - if (IS_ENABLED(CONFIG_BT_MESH_PROV) && bt_prov_active()) { - k_delayed_work_submit(&beacon_timer, UNPROVISIONED_INTERVAL); - return; - } + /* Don't send anything if we have an active provisioning link */ + if (IS_ENABLED(CONFIG_BT_MESH_PROV) && bt_prov_active()) { + k_delayed_work_submit(&beacon_timer, UNPROVISIONED_INTERVAL); + return; + } - BT_DBG(""); + BT_DBG(""); - if (bt_mesh_is_provisioned()) { - update_beacon_observation(); - secure_beacon_send(); + if (bt_mesh_is_provisioned()) { + update_beacon_observation(); + secure_beacon_send(); - /* Only resubmit if beaconing is still enabled */ - if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED || - atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) { - k_delayed_work_submit(&beacon_timer, - PROVISIONED_INTERVAL); - } - } else { - unprovisioned_beacon_send(); - k_delayed_work_submit(&beacon_timer, UNPROVISIONED_INTERVAL); - } + /* Only resubmit if beaconing is still enabled */ + if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED || + atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) { + k_delayed_work_submit(&beacon_timer, + PROVISIONED_INTERVAL); + } + } else { + unprovisioned_beacon_send(); + k_delayed_work_submit(&beacon_timer, UNPROVISIONED_INTERVAL); + } } static void secure_beacon_recv(struct net_buf_simple *buf) { - u8_t *data, *net_id, *auth; - struct bt_mesh_subnet *sub; - u32_t iv_index; - bool new_key, kr_change, iv_change; - u8_t flags; + u8_t *data, *net_id, *auth; + struct bt_mesh_subnet *sub; + u32_t iv_index; + bool new_key, kr_change, iv_change; + u8_t flags; - if (buf->len < 21) { - BT_ERR("Too short secure beacon (len %u)", buf->len); - return; - } + if (buf->len < 21) { + BT_ERR("Too short secure beacon (len %u)", buf->len); + return; + } - sub = cache_check(buf->data); - if (sub) { - /* We've seen this beacon before - just update the stats */ - goto update_stats; - } + sub = cache_check(buf->data); + if (sub) { + /* We've seen this beacon before - just update the stats */ + goto update_stats; + } - /* So we can add to the cache if auth matches */ - data = buf->data; + /* So we can add to the cache if auth matches */ + data = buf->data; - flags = net_buf_simple_pull_u8(buf); - net_id = net_buf_simple_pull_mem(buf, 8); - iv_index = net_buf_simple_pull_be32(buf); - auth = buf->data; + flags = net_buf_simple_pull_u8(buf); + net_id = net_buf_simple_pull_mem(buf, 8); + iv_index = net_buf_simple_pull_be32(buf); + auth = buf->data; #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Secure network beacon received"); - BT_PTS("[PTS] - Flags: [0x%02X]", flags); - BT_PTS("[PTS] - IV Index: [0x%08X]", iv_index); + BT_PTS("[PTS] Secure network beacon received"); + BT_PTS("[PTS] - Flags: [0x%02X]", flags); + BT_PTS("[PTS] - IV Index: [0x%08X]", iv_index); #endif - BT_DBG("flags 0x%02x id %s iv_index 0x%08x", - flags, bt_hex(net_id, 8), iv_index); + BT_DBG("flags 0x%02x id %s iv_index 0x%08x", + flags, bt_hex(net_id, 8), iv_index); - sub = bt_mesh_subnet_find(net_id, flags, iv_index, auth, &new_key); - if (!sub) { - BT_DBG("No subnet that matched beacon"); - return; - } + sub = bt_mesh_subnet_find(net_id, flags, iv_index, auth, &new_key); + if (!sub) { + BT_DBG("No subnet that matched beacon"); + return; + } - if (sub->kr_phase == BT_MESH_KR_PHASE_2 && !new_key) { - BT_WARN("Ignoring Phase 2 KR Update secured using old key"); - return; - } + if (sub->kr_phase == BT_MESH_KR_PHASE_2 && !new_key) { + BT_WARN("Ignoring Phase 2 KR Update secured using old key"); + return; + } - cache_add(data, sub); + cache_add(data, sub); - /* If we have NetKey0 accept initiation only from it */ - if (bt_mesh_subnet_get(BT_MESH_KEY_PRIMARY) && - sub->net_idx != BT_MESH_KEY_PRIMARY) { + /* If we have NetKey0 accept initiation only from it */ + if (bt_mesh_subnet_get(BT_MESH_KEY_PRIMARY) && + sub->net_idx != BT_MESH_KEY_PRIMARY) { #if !defined(BFLB_BLE_MESH_PATCH_IGNORE_SECURE_BEACON) - BT_WARN("Ignoring secure beacon on non-primary subnet"); - goto update_stats; + BT_WARN("Ignoring secure beacon on non-primary subnet"); + goto update_stats; #else - if (iv_index > bt_mesh.iv_index) { - goto update_stats; - } + if (iv_index > bt_mesh.iv_index) { + goto update_stats; + } #endif - } + } - BT_DBG("net_idx 0x%04x iv_index 0x%08x, current iv_index 0x%08x", - sub->net_idx, iv_index, bt_mesh.iv_index); + BT_DBG("net_idx 0x%04x iv_index 0x%08x, current iv_index 0x%08x", + sub->net_idx, iv_index, bt_mesh.iv_index); - if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR) && - (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) == - BT_MESH_IV_UPDATE(flags))) { - bt_mesh_beacon_ivu_initiator(false); - } + if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR) && + (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) == + BT_MESH_IV_UPDATE(flags))) { + bt_mesh_beacon_ivu_initiator(false); + } - iv_change = bt_mesh_net_iv_update(iv_index, BT_MESH_IV_UPDATE(flags)); + iv_change = bt_mesh_net_iv_update(iv_index, BT_MESH_IV_UPDATE(flags)); - kr_change = bt_mesh_kr_update(sub, BT_MESH_KEY_REFRESH(flags), new_key); - if (kr_change) { - bt_mesh_net_beacon_update(sub); - } + kr_change = bt_mesh_kr_update(sub, BT_MESH_KEY_REFRESH(flags), new_key); + if (kr_change) { + bt_mesh_net_beacon_update(sub); + } - if (iv_change) { - /* Update all subnets */ - bt_mesh_net_sec_update(NULL); - } else if (kr_change) { - /* Key Refresh without IV Update only impacts one subnet */ - bt_mesh_net_sec_update(sub); - } + if (iv_change) { + /* Update all subnets */ + bt_mesh_net_sec_update(NULL); + } else if (kr_change) { + /* Key Refresh without IV Update only impacts one subnet */ + bt_mesh_net_sec_update(sub); + } update_stats: - if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED && - sub->beacons_cur < 0xff) { - sub->beacons_cur++; - } + if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED && + sub->beacons_cur < 0xff) { + sub->beacons_cur++; + } } void bt_mesh_beacon_recv(struct net_buf_simple *buf) { - u8_t type; + u8_t type; - BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); - if (buf->len < 1) { - BT_ERR("Too short beacon"); - return; - } + if (buf->len < 1) { + BT_ERR("Too short beacon"); + return; + } - type = net_buf_simple_pull_u8(buf); - switch (type) { - case BEACON_TYPE_UNPROVISIONED: - BT_DBG("Ignoring unprovisioned device beacon"); - break; - case BEACON_TYPE_SECURE: - secure_beacon_recv(buf); - break; - default: - BT_WARN("Unknown beacon type 0x%02x", type); - break; - } + type = net_buf_simple_pull_u8(buf); + switch (type) { + case BEACON_TYPE_UNPROVISIONED: + BT_DBG("Ignoring unprovisioned device beacon"); + break; + case BEACON_TYPE_SECURE: + secure_beacon_recv(buf); + break; + default: + BT_WARN("Unknown beacon type 0x%02x", type); + break; + } } void bt_mesh_beacon_init(void) { - k_delayed_work_init(&beacon_timer, beacon_send); + k_delayed_work_init(&beacon_timer, beacon_send); } void bt_mesh_beacon_ivu_initiator(bool enable) { - atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_INITIATOR, enable); + atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_INITIATOR, enable); - if (enable) { - k_work_submit(&beacon_timer.work); - } else if (bt_mesh_beacon_get() == BT_MESH_BEACON_DISABLED) { - k_delayed_work_cancel(&beacon_timer); - } + if (enable) { + k_work_submit(&beacon_timer.work); + } else if (bt_mesh_beacon_get() == BT_MESH_BEACON_DISABLED) { + k_delayed_work_cancel(&beacon_timer); + } } void bt_mesh_beacon_enable(void) { - int i; + int i; - if (!bt_mesh_is_provisioned()) { - k_work_submit(&beacon_timer.work); - return; - } + if (!bt_mesh_is_provisioned()) { + k_work_submit(&beacon_timer.work); + return; + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - sub->beacons_last = 0U; - sub->beacons_cur = 0U; + sub->beacons_last = 0U; + sub->beacons_cur = 0U; - bt_mesh_net_beacon_update(sub); - } + bt_mesh_net_beacon_update(sub); + } - k_work_submit(&beacon_timer.work); + k_work_submit(&beacon_timer.work); } void bt_mesh_beacon_disable(void) { - if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) { - k_delayed_work_cancel(&beacon_timer); - } + if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) { + k_delayed_work_cancel(&beacon_timer); + } } diff --git a/components/network/ble/blemesh/src/beacon.h b/components/network/ble/blemesh/src/beacon.h index e1b3911c..c755065e 100644 --- a/components/network/ble/blemesh/src/beacon.h +++ b/components/network/ble/blemesh/src/beacon.h @@ -16,7 +16,7 @@ void bt_mesh_beacon_ivu_initiator(bool enable); void bt_mesh_beacon_recv(struct net_buf_simple *buf); void bt_mesh_beacon_create(struct bt_mesh_subnet *sub, - struct net_buf_simple *buf); + struct net_buf_simple *buf); void bt_mesh_beacon_init(void); diff --git a/components/network/ble/blemesh/src/cfg_cli.c b/components/network/ble/blemesh/src/cfg_cli.c index 3d15c1b1..601c1e1c 100644 --- a/components/network/ble/blemesh/src/cfg_cli.c +++ b/components/network/ble/blemesh/src/cfg_cli.c @@ -29,8 +29,8 @@ #define CID_NVAL 0xffff struct comp_data { - u8_t *status; - struct net_buf_simple *comp; + u8_t *status; + struct net_buf_simple *comp; }; static s32_t msg_timeout = K_SECONDS(2); @@ -38,1408 +38,1408 @@ static s32_t msg_timeout = K_SECONDS(2); static struct bt_mesh_cfg_cli *cli; static void comp_data_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct comp_data *param; - size_t to_copy; + struct comp_data *param; + size_t to_copy; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_DEV_COMP_DATA_STATUS) { - BT_WARN("Unexpected Composition Data Status"); - return; - } + if (cli->op_pending != OP_DEV_COMP_DATA_STATUS) { + BT_WARN("Unexpected Composition Data Status"); + return; + } - param = cli->op_param; + param = cli->op_param; - *(param->status) = net_buf_simple_pull_u8(buf); - to_copy = MIN(net_buf_simple_tailroom(param->comp), buf->len); - net_buf_simple_add_mem(param->comp, buf->data, to_copy); + *(param->status) = net_buf_simple_pull_u8(buf); + to_copy = MIN(net_buf_simple_tailroom(param->comp), buf->len); + net_buf_simple_add_mem(param->comp, buf->data, to_copy); - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } static void state_status_u8(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf, - u32_t expect_status) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf, + u32_t expect_status) { - u8_t *status; + u8_t *status; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != expect_status) { - BT_WARN("Unexpected Status (0x%08x != 0x%08x)", - cli->op_pending, expect_status); - return; - } + if (cli->op_pending != expect_status) { + BT_WARN("Unexpected Status (0x%08x != 0x%08x)", + cli->op_pending, expect_status); + return; + } - status = cli->op_param; - *status = net_buf_simple_pull_u8(buf); + status = cli->op_param; + *status = net_buf_simple_pull_u8(buf); - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } static void beacon_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - state_status_u8(model, ctx, buf, OP_BEACON_STATUS); + state_status_u8(model, ctx, buf, OP_BEACON_STATUS); } static void ttl_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - state_status_u8(model, ctx, buf, OP_DEFAULT_TTL_STATUS); + state_status_u8(model, ctx, buf, OP_DEFAULT_TTL_STATUS); } static void friend_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - state_status_u8(model, ctx, buf, OP_FRIEND_STATUS); + state_status_u8(model, ctx, buf, OP_FRIEND_STATUS); } static void gatt_proxy_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - state_status_u8(model, ctx, buf, OP_GATT_PROXY_STATUS); + state_status_u8(model, ctx, buf, OP_GATT_PROXY_STATUS); } struct relay_param { - u8_t *status; - u8_t *transmit; + u8_t *status; + u8_t *transmit; }; static void relay_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct relay_param *param; + struct relay_param *param; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_RELAY_STATUS) { - BT_WARN("Unexpected Relay Status message"); - return; - } + if (cli->op_pending != OP_RELAY_STATUS) { + BT_WARN("Unexpected Relay Status message"); + return; + } - param = cli->op_param; - *param->status = net_buf_simple_pull_u8(buf); - *param->transmit = net_buf_simple_pull_u8(buf); + param = cli->op_param; + *param->status = net_buf_simple_pull_u8(buf); + *param->transmit = net_buf_simple_pull_u8(buf); - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } struct net_key_param { - u8_t *status; - u16_t net_idx; + u8_t *status; + u16_t net_idx; }; static void net_key_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct net_key_param *param; - u16_t net_idx, app_idx; - u8_t status; + struct net_key_param *param; + u16_t net_idx, app_idx; + u8_t status; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_NET_KEY_STATUS) { - BT_WARN("Unexpected Net Key Status message"); - return; - } + if (cli->op_pending != OP_NET_KEY_STATUS) { + BT_WARN("Unexpected Net Key Status message"); + return; + } - status = net_buf_simple_pull_u8(buf); - key_idx_unpack(buf, &net_idx, &app_idx); + status = net_buf_simple_pull_u8(buf); + key_idx_unpack(buf, &net_idx, &app_idx); - param = cli->op_param; - if (param->net_idx != net_idx) { - BT_WARN("Net Key Status key index does not match"); - return; - } + param = cli->op_param; + if (param->net_idx != net_idx) { + BT_WARN("Net Key Status key index does not match"); + return; + } - if (param->status) { - *param->status = status; - } + if (param->status) { + *param->status = status; + } - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } struct app_key_param { - u8_t *status; - u16_t net_idx; - u16_t app_idx; + u8_t *status; + u16_t net_idx; + u16_t app_idx; }; static void app_key_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct app_key_param *param; - u16_t net_idx, app_idx; - u8_t status; + struct app_key_param *param; + u16_t net_idx, app_idx; + u8_t status; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_APP_KEY_STATUS) { - BT_WARN("Unexpected App Key Status message"); - return; - } + if (cli->op_pending != OP_APP_KEY_STATUS) { + BT_WARN("Unexpected App Key Status message"); + return; + } - status = net_buf_simple_pull_u8(buf); - key_idx_unpack(buf, &net_idx, &app_idx); + status = net_buf_simple_pull_u8(buf); + key_idx_unpack(buf, &net_idx, &app_idx); - param = cli->op_param; - if (param->net_idx != net_idx || param->app_idx != app_idx) { - BT_WARN("App Key Status key indices did not match"); - return; - } + param = cli->op_param; + if (param->net_idx != net_idx || param->app_idx != app_idx) { + BT_WARN("App Key Status key indices did not match"); + return; + } - if (param->status) { - *param->status = status; - } + if (param->status) { + *param->status = status; + } - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } struct mod_app_param { - u8_t *status; - u16_t elem_addr; - u16_t mod_app_idx; - u16_t mod_id; - u16_t cid; + u8_t *status; + u16_t elem_addr; + u16_t mod_app_idx; + u16_t mod_id; + u16_t cid; }; static void mod_app_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, mod_app_idx, mod_id, cid; - struct mod_app_param *param; - u8_t status; + u16_t elem_addr, mod_app_idx, mod_id, cid; + struct mod_app_param *param; + u8_t status; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_MOD_APP_STATUS) { - BT_WARN("Unexpected Model App Status message"); - return; - } + if (cli->op_pending != OP_MOD_APP_STATUS) { + BT_WARN("Unexpected Model App Status message"); + return; + } - status = net_buf_simple_pull_u8(buf); - elem_addr = net_buf_simple_pull_le16(buf); - mod_app_idx = net_buf_simple_pull_le16(buf); + status = net_buf_simple_pull_u8(buf); + elem_addr = net_buf_simple_pull_le16(buf); + mod_app_idx = net_buf_simple_pull_le16(buf); - if (buf->len >= 4U) { - cid = net_buf_simple_pull_le16(buf); - } else { - cid = CID_NVAL; - } + if (buf->len >= 4U) { + cid = net_buf_simple_pull_le16(buf); + } else { + cid = CID_NVAL; + } - mod_id = net_buf_simple_pull_le16(buf); + mod_id = net_buf_simple_pull_le16(buf); - param = cli->op_param; - if (param->elem_addr != elem_addr || - param->mod_app_idx != mod_app_idx || param->mod_id != mod_id || - param->cid != cid) { - BT_WARN("Model App Status parameters did not match"); - return; - } + param = cli->op_param; + if (param->elem_addr != elem_addr || + param->mod_app_idx != mod_app_idx || param->mod_id != mod_id || + param->cid != cid) { + BT_WARN("Model App Status parameters did not match"); + return; + } - if (param->status) { - *param->status = status; - } + if (param->status) { + *param->status = status; + } - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } struct mod_pub_param { - u16_t mod_id; - u16_t cid; - u16_t elem_addr; - u8_t *status; - struct bt_mesh_cfg_mod_pub *pub; + u16_t mod_id; + u16_t cid; + u16_t elem_addr; + u8_t *status; + struct bt_mesh_cfg_mod_pub *pub; }; static void mod_pub_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t mod_id, cid, elem_addr; - struct mod_pub_param *param; - u8_t status; + u16_t mod_id, cid, elem_addr; + struct mod_pub_param *param; + u8_t status; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_MOD_PUB_STATUS) { - BT_WARN("Unexpected Model Pub Status message"); - return; - } + if (cli->op_pending != OP_MOD_PUB_STATUS) { + BT_WARN("Unexpected Model Pub Status message"); + return; + } - param = cli->op_param; - if (param->cid != CID_NVAL) { - if (buf->len < 14) { - BT_WARN("Unexpected Mod Pub Status with SIG Model"); - return; - } + param = cli->op_param; + if (param->cid != CID_NVAL) { + if (buf->len < 14) { + BT_WARN("Unexpected Mod Pub Status with SIG Model"); + return; + } - cid = sys_get_le16(&buf->data[10]); - mod_id = sys_get_le16(&buf->data[12]); - } else { - if (buf->len > 12) { - BT_WARN("Unexpected Mod Pub Status with Vendor Model"); - return; - } + cid = sys_get_le16(&buf->data[10]); + mod_id = sys_get_le16(&buf->data[12]); + } else { + if (buf->len > 12) { + BT_WARN("Unexpected Mod Pub Status with Vendor Model"); + return; + } - cid = CID_NVAL; - mod_id = sys_get_le16(&buf->data[10]); - } + cid = CID_NVAL; + mod_id = sys_get_le16(&buf->data[10]); + } - if (mod_id != param->mod_id || cid != param->cid) { - BT_WARN("Mod Pub Model ID or Company ID mismatch"); - return; - } + if (mod_id != param->mod_id || cid != param->cid) { + BT_WARN("Mod Pub Model ID or Company ID mismatch"); + return; + } - status = net_buf_simple_pull_u8(buf); + status = net_buf_simple_pull_u8(buf); - elem_addr = net_buf_simple_pull_le16(buf); - if (elem_addr != param->elem_addr) { - BT_WARN("Model Pub Status for unexpected element (0x%04x)", - elem_addr); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (elem_addr != param->elem_addr) { + BT_WARN("Model Pub Status for unexpected element (0x%04x)", + elem_addr); + return; + } - if (param->status) { - *param->status = status; - } + if (param->status) { + *param->status = status; + } - if (param->pub) { - param->pub->addr = net_buf_simple_pull_le16(buf); - param->pub->app_idx = net_buf_simple_pull_le16(buf); - param->pub->cred_flag = (param->pub->app_idx & BIT(12)); - param->pub->app_idx &= BIT_MASK(12); - param->pub->ttl = net_buf_simple_pull_u8(buf); - param->pub->period = net_buf_simple_pull_u8(buf); - param->pub->transmit = net_buf_simple_pull_u8(buf); - } + if (param->pub) { + param->pub->addr = net_buf_simple_pull_le16(buf); + param->pub->app_idx = net_buf_simple_pull_le16(buf); + param->pub->cred_flag = (param->pub->app_idx & BIT(12)); + param->pub->app_idx &= BIT_MASK(12); + param->pub->ttl = net_buf_simple_pull_u8(buf); + param->pub->period = net_buf_simple_pull_u8(buf); + param->pub->transmit = net_buf_simple_pull_u8(buf); + } - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } struct mod_sub_param { - u8_t *status; - u16_t elem_addr; - u16_t *sub_addr; - u16_t *expect_sub; - u16_t mod_id; - u16_t cid; + u8_t *status; + u16_t elem_addr; + u16_t *sub_addr; + u16_t *expect_sub; + u16_t mod_id; + u16_t cid; }; static void mod_sub_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, sub_addr, mod_id, cid; - struct mod_sub_param *param; - u8_t status; + u16_t elem_addr, sub_addr, mod_id, cid; + struct mod_sub_param *param; + u8_t status; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_MOD_SUB_STATUS) { - BT_WARN("Unexpected Model Subscription Status message"); - return; - } + if (cli->op_pending != OP_MOD_SUB_STATUS) { + BT_WARN("Unexpected Model Subscription Status message"); + return; + } - status = net_buf_simple_pull_u8(buf); - elem_addr = net_buf_simple_pull_le16(buf); - sub_addr = net_buf_simple_pull_le16(buf); + status = net_buf_simple_pull_u8(buf); + elem_addr = net_buf_simple_pull_le16(buf); + sub_addr = net_buf_simple_pull_le16(buf); - if (buf->len >= 4U) { - cid = net_buf_simple_pull_le16(buf); - } else { - cid = CID_NVAL; - } + if (buf->len >= 4U) { + cid = net_buf_simple_pull_le16(buf); + } else { + cid = CID_NVAL; + } - mod_id = net_buf_simple_pull_le16(buf); + mod_id = net_buf_simple_pull_le16(buf); - param = cli->op_param; - if (param->elem_addr != elem_addr || param->mod_id != mod_id || - (param->expect_sub && *param->expect_sub != sub_addr) || - param->cid != cid) { - BT_WARN("Model Subscription Status parameters did not match"); - return; - } + param = cli->op_param; + if (param->elem_addr != elem_addr || param->mod_id != mod_id || + (param->expect_sub && *param->expect_sub != sub_addr) || + param->cid != cid) { + BT_WARN("Model Subscription Status parameters did not match"); + return; + } - if (param->sub_addr) { - *param->sub_addr = sub_addr; - } + if (param->sub_addr) { + *param->sub_addr = sub_addr; + } - if (param->status) { - *param->status = status; - } + if (param->status) { + *param->status = status; + } - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } struct hb_sub_param { - u8_t *status; - struct bt_mesh_cfg_hb_sub *sub; + u8_t *status; + struct bt_mesh_cfg_hb_sub *sub; }; static void hb_sub_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct hb_sub_param *param; + struct hb_sub_param *param; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_HEARTBEAT_SUB_STATUS) { - BT_WARN("Unexpected Heartbeat Subscription Status message"); - return; - } + if (cli->op_pending != OP_HEARTBEAT_SUB_STATUS) { + BT_WARN("Unexpected Heartbeat Subscription Status message"); + return; + } - param = cli->op_param; + param = cli->op_param; - *param->status = net_buf_simple_pull_u8(buf); + *param->status = net_buf_simple_pull_u8(buf); - param->sub->src = net_buf_simple_pull_le16(buf); - param->sub->dst = net_buf_simple_pull_le16(buf); - param->sub->period = net_buf_simple_pull_u8(buf); - param->sub->count = net_buf_simple_pull_u8(buf); - param->sub->min = net_buf_simple_pull_u8(buf); - param->sub->max = net_buf_simple_pull_u8(buf); + param->sub->src = net_buf_simple_pull_le16(buf); + param->sub->dst = net_buf_simple_pull_le16(buf); + param->sub->period = net_buf_simple_pull_u8(buf); + param->sub->count = net_buf_simple_pull_u8(buf); + param->sub->min = net_buf_simple_pull_u8(buf); + param->sub->max = net_buf_simple_pull_u8(buf); - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } struct hb_pub_param { - u8_t *status; - struct bt_mesh_cfg_hb_pub *pub; + u8_t *status; + struct bt_mesh_cfg_hb_pub *pub; }; static void hb_pub_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct hb_pub_param *param; + struct hb_pub_param *param; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (cli->op_pending != OP_HEARTBEAT_PUB_STATUS) { - BT_WARN("Unexpected Heartbeat Publication Status message"); - return; - } + if (cli->op_pending != OP_HEARTBEAT_PUB_STATUS) { + BT_WARN("Unexpected Heartbeat Publication Status message"); + return; + } - param = cli->op_param; + param = cli->op_param; - *param->status = net_buf_simple_pull_u8(buf); + *param->status = net_buf_simple_pull_u8(buf); - if (param->pub) { - param->pub->dst = net_buf_simple_pull_le16(buf); - param->pub->count = net_buf_simple_pull_u8(buf); - param->pub->period = net_buf_simple_pull_u8(buf); - param->pub->ttl = net_buf_simple_pull_u8(buf); - param->pub->feat = net_buf_simple_pull_u8(buf); - param->pub->net_idx = net_buf_simple_pull_u8(buf); - } + if (param->pub) { + param->pub->dst = net_buf_simple_pull_le16(buf); + param->pub->count = net_buf_simple_pull_u8(buf); + param->pub->period = net_buf_simple_pull_u8(buf); + param->pub->ttl = net_buf_simple_pull_u8(buf); + param->pub->feat = net_buf_simple_pull_u8(buf); + param->pub->net_idx = net_buf_simple_pull_u8(buf); + } - k_sem_give(&cli->op_sync); + k_sem_give(&cli->op_sync); } const struct bt_mesh_model_op bt_mesh_cfg_cli_op[] = { - { OP_DEV_COMP_DATA_STATUS, 15, comp_data_status }, - { OP_BEACON_STATUS, 1, beacon_status }, - { OP_DEFAULT_TTL_STATUS, 1, ttl_status }, - { OP_FRIEND_STATUS, 1, friend_status }, - { OP_GATT_PROXY_STATUS, 1, gatt_proxy_status }, - { OP_RELAY_STATUS, 2, relay_status }, - { OP_NET_KEY_STATUS, 3, net_key_status }, - { OP_APP_KEY_STATUS, 4, app_key_status }, - { OP_MOD_APP_STATUS, 7, mod_app_status }, - { OP_MOD_PUB_STATUS, 12, mod_pub_status }, - { OP_MOD_SUB_STATUS, 7, mod_sub_status }, - { OP_HEARTBEAT_SUB_STATUS, 9, hb_sub_status }, - { OP_HEARTBEAT_PUB_STATUS, 10, hb_pub_status }, - BT_MESH_MODEL_OP_END, + { OP_DEV_COMP_DATA_STATUS, 15, comp_data_status }, + { OP_BEACON_STATUS, 1, beacon_status }, + { OP_DEFAULT_TTL_STATUS, 1, ttl_status }, + { OP_FRIEND_STATUS, 1, friend_status }, + { OP_GATT_PROXY_STATUS, 1, gatt_proxy_status }, + { OP_RELAY_STATUS, 2, relay_status }, + { OP_NET_KEY_STATUS, 3, net_key_status }, + { OP_APP_KEY_STATUS, 4, app_key_status }, + { OP_MOD_APP_STATUS, 7, mod_app_status }, + { OP_MOD_PUB_STATUS, 12, mod_pub_status }, + { OP_MOD_SUB_STATUS, 7, mod_sub_status }, + { OP_HEARTBEAT_SUB_STATUS, 9, hb_sub_status }, + { OP_HEARTBEAT_PUB_STATUS, 10, hb_pub_status }, + BT_MESH_MODEL_OP_END, }; static int cli_prepare(void *param, u32_t op) { - if (!cli) { - BT_ERR("No available Configuration Client context!"); - return -EINVAL; - } + if (!cli) { + BT_ERR("No available Configuration Client context!"); + return -EINVAL; + } - if (cli->op_pending) { - BT_WARN("Another synchronous operation pending"); - return -EBUSY; - } + if (cli->op_pending) { + BT_WARN("Another synchronous operation pending"); + return -EBUSY; + } - cli->op_param = param; - cli->op_pending = op; + cli->op_param = param; + cli->op_pending = op; - return 0; + return 0; } static void cli_reset(void) { - cli->op_pending = 0U; - cli->op_param = NULL; + cli->op_pending = 0U; + cli->op_param = NULL; } static int cli_wait(void) { - int err; + int err; - err = k_sem_take(&cli->op_sync, msg_timeout); + err = k_sem_take(&cli->op_sync, msg_timeout); - cli_reset(); + cli_reset(); - return err; + return err; } int bt_mesh_cfg_comp_data_get(u16_t net_idx, u16_t addr, u8_t page, - u8_t *status, struct net_buf_simple *comp) + u8_t *status, struct net_buf_simple *comp) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct comp_data param = { - .status = status, - .comp = comp, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct comp_data param = { + .status = status, + .comp = comp, + }; + int err; - err = cli_prepare(¶m, OP_DEV_COMP_DATA_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_DEV_COMP_DATA_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_DEV_COMP_DATA_GET); - net_buf_simple_add_u8(&msg, page); + bt_mesh_model_msg_init(&msg, OP_DEV_COMP_DATA_GET); + net_buf_simple_add_u8(&msg, page); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } static int get_state_u8(u16_t net_idx, u16_t addr, u32_t op, u32_t rsp, - u8_t *val) + u8_t *val) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + int err; - err = cli_prepare(val, rsp); - if (err) { - return err; - } + err = cli_prepare(val, rsp); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, op); + bt_mesh_model_msg_init(&msg, op); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } static int set_state_u8(u16_t net_idx, u16_t addr, u32_t op, u32_t rsp, - u8_t new_val, u8_t *val) + u8_t new_val, u8_t *val) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + int err; - err = cli_prepare(val, rsp); - if (err) { - return err; - } + err = cli_prepare(val, rsp); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, op); - net_buf_simple_add_u8(&msg, new_val); + bt_mesh_model_msg_init(&msg, op); + net_buf_simple_add_u8(&msg, new_val); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_beacon_get(u16_t net_idx, u16_t addr, u8_t *status) { - return get_state_u8(net_idx, addr, OP_BEACON_GET, OP_BEACON_STATUS, - status); + return get_state_u8(net_idx, addr, OP_BEACON_GET, OP_BEACON_STATUS, + status); } int bt_mesh_cfg_beacon_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status) { - return set_state_u8(net_idx, addr, OP_BEACON_SET, OP_BEACON_STATUS, - val, status); + return set_state_u8(net_idx, addr, OP_BEACON_SET, OP_BEACON_STATUS, + val, status); } int bt_mesh_cfg_ttl_get(u16_t net_idx, u16_t addr, u8_t *ttl) { - return get_state_u8(net_idx, addr, OP_DEFAULT_TTL_GET, - OP_DEFAULT_TTL_STATUS, ttl); + return get_state_u8(net_idx, addr, OP_DEFAULT_TTL_GET, + OP_DEFAULT_TTL_STATUS, ttl); } int bt_mesh_cfg_ttl_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *ttl) { - return set_state_u8(net_idx, addr, OP_DEFAULT_TTL_SET, - OP_DEFAULT_TTL_STATUS, val, ttl); + return set_state_u8(net_idx, addr, OP_DEFAULT_TTL_SET, + OP_DEFAULT_TTL_STATUS, val, ttl); } int bt_mesh_cfg_friend_get(u16_t net_idx, u16_t addr, u8_t *status) { - return get_state_u8(net_idx, addr, OP_FRIEND_GET, - OP_FRIEND_STATUS, status); + return get_state_u8(net_idx, addr, OP_FRIEND_GET, + OP_FRIEND_STATUS, status); } int bt_mesh_cfg_friend_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status) { - return set_state_u8(net_idx, addr, OP_FRIEND_SET, OP_FRIEND_STATUS, - val, status); + return set_state_u8(net_idx, addr, OP_FRIEND_SET, OP_FRIEND_STATUS, + val, status); } int bt_mesh_cfg_gatt_proxy_get(u16_t net_idx, u16_t addr, u8_t *status) { - return get_state_u8(net_idx, addr, OP_GATT_PROXY_GET, - OP_GATT_PROXY_STATUS, status); + return get_state_u8(net_idx, addr, OP_GATT_PROXY_GET, + OP_GATT_PROXY_STATUS, status); } int bt_mesh_cfg_gatt_proxy_set(u16_t net_idx, u16_t addr, u8_t val, - u8_t *status) + u8_t *status) { - return set_state_u8(net_idx, addr, OP_GATT_PROXY_SET, - OP_GATT_PROXY_STATUS, val, status); + return set_state_u8(net_idx, addr, OP_GATT_PROXY_SET, + OP_GATT_PROXY_STATUS, val, status); } int bt_mesh_cfg_relay_get(u16_t net_idx, u16_t addr, u8_t *status, - u8_t *transmit) + u8_t *transmit) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct relay_param param = { - .status = status, - .transmit = transmit, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct relay_param param = { + .status = status, + .transmit = transmit, + }; + int err; - err = cli_prepare(¶m, OP_RELAY_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_RELAY_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_RELAY_GET); + bt_mesh_model_msg_init(&msg, OP_RELAY_GET); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_relay_set(u16_t net_idx, u16_t addr, u8_t new_relay, - u8_t new_transmit, u8_t *status, u8_t *transmit) + u8_t new_transmit, u8_t *status, u8_t *transmit) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct relay_param param = { - .status = status, - .transmit = transmit, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct relay_param param = { + .status = status, + .transmit = transmit, + }; + int err; - err = cli_prepare(¶m, OP_RELAY_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_RELAY_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_RELAY_SET); - net_buf_simple_add_u8(&msg, new_relay); - net_buf_simple_add_u8(&msg, new_transmit); + bt_mesh_model_msg_init(&msg, OP_RELAY_SET); + net_buf_simple_add_u8(&msg, new_relay); + net_buf_simple_add_u8(&msg, new_transmit); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_net_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, - const u8_t net_key[16], u8_t *status) + const u8_t net_key[16], u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 18 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct net_key_param param = { - .status = status, - .net_idx = key_net_idx, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 18 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct net_key_param param = { + .status = status, + .net_idx = key_net_idx, + }; + int err; - err = cli_prepare(¶m, OP_NET_KEY_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_NET_KEY_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_NET_KEY_ADD); - net_buf_simple_add_le16(&msg, key_net_idx); - net_buf_simple_add_mem(&msg, net_key, 16); + bt_mesh_model_msg_init(&msg, OP_NET_KEY_ADD); + net_buf_simple_add_le16(&msg, key_net_idx); + net_buf_simple_add_mem(&msg, net_key, 16); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_app_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, - u16_t key_app_idx, const u8_t app_key[16], - u8_t *status) + u16_t key_app_idx, const u8_t app_key[16], + u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 1 + 19 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct app_key_param param = { - .status = status, - .net_idx = key_net_idx, - .app_idx = key_app_idx, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 1 + 19 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct app_key_param param = { + .status = status, + .net_idx = key_net_idx, + .app_idx = key_app_idx, + }; + int err; - err = cli_prepare(¶m, OP_APP_KEY_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_APP_KEY_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_APP_KEY_ADD); - key_idx_pack(&msg, key_net_idx, key_app_idx); - net_buf_simple_add_mem(&msg, app_key, 16); + bt_mesh_model_msg_init(&msg, OP_APP_KEY_ADD); + key_idx_pack(&msg, key_net_idx, key_app_idx); + net_buf_simple_add_mem(&msg, app_key, 16); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } static int mod_app_bind(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_app_idx, u16_t mod_id, u16_t cid, - u8_t *status) + u16_t mod_app_idx, u16_t mod_id, u16_t cid, + u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 8 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct mod_app_param param = { - .status = status, - .elem_addr = elem_addr, - .mod_app_idx = mod_app_idx, - .mod_id = mod_id, - .cid = cid, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 8 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct mod_app_param param = { + .status = status, + .elem_addr = elem_addr, + .mod_app_idx = mod_app_idx, + .mod_id = mod_id, + .cid = cid, + }; + int err; - err = cli_prepare(¶m, OP_MOD_APP_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_MOD_APP_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_MOD_APP_BIND); - net_buf_simple_add_le16(&msg, elem_addr); - net_buf_simple_add_le16(&msg, mod_app_idx); + bt_mesh_model_msg_init(&msg, OP_MOD_APP_BIND); + net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_le16(&msg, mod_app_idx); - if (cid != CID_NVAL) { - net_buf_simple_add_le16(&msg, cid); - } + if (cid != CID_NVAL) { + net_buf_simple_add_le16(&msg, cid); + } - net_buf_simple_add_le16(&msg, mod_id); + net_buf_simple_add_le16(&msg, mod_id); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_mod_app_bind(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_app_idx, u16_t mod_id, u8_t *status) + u16_t mod_app_idx, u16_t mod_id, u8_t *status) { - return mod_app_bind(net_idx, addr, elem_addr, mod_app_idx, mod_id, - CID_NVAL, status); + return mod_app_bind(net_idx, addr, elem_addr, mod_app_idx, mod_id, + CID_NVAL, status); } int bt_mesh_cfg_mod_app_bind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_app_idx, u16_t mod_id, u16_t cid, - u8_t *status) + u16_t mod_app_idx, u16_t mod_id, u16_t cid, + u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_app_bind(net_idx, addr, elem_addr, mod_app_idx, mod_id, cid, - status); + return mod_app_bind(net_idx, addr, elem_addr, mod_app_idx, mod_id, cid, + status); } static int mod_sub(u32_t op, u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u16_t cid, u8_t *status) + u16_t sub_addr, u16_t mod_id, u16_t cid, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 8 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct mod_sub_param param = { - .status = status, - .elem_addr = elem_addr, - .expect_sub = &sub_addr, - .mod_id = mod_id, - .cid = cid, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 8 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct mod_sub_param param = { + .status = status, + .elem_addr = elem_addr, + .expect_sub = &sub_addr, + .mod_id = mod_id, + .cid = cid, + }; + int err; - err = cli_prepare(¶m, OP_MOD_SUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_MOD_SUB_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, op); - net_buf_simple_add_le16(&msg, elem_addr); - net_buf_simple_add_le16(&msg, sub_addr); + bt_mesh_model_msg_init(&msg, op); + net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_le16(&msg, sub_addr); - if (cid != CID_NVAL) { - net_buf_simple_add_le16(&msg, cid); - } + if (cid != CID_NVAL) { + net_buf_simple_add_le16(&msg, cid); + } - net_buf_simple_add_le16(&msg, mod_id); + net_buf_simple_add_le16(&msg, mod_id); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_mod_sub_add(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u8_t *status) + u16_t sub_addr, u16_t mod_id, u8_t *status) { - return mod_sub(OP_MOD_SUB_ADD, net_idx, addr, elem_addr, sub_addr, - mod_id, CID_NVAL, status); + return mod_sub(OP_MOD_SUB_ADD, net_idx, addr, elem_addr, sub_addr, + mod_id, CID_NVAL, status); } int bt_mesh_cfg_mod_sub_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u16_t cid, - u8_t *status) + u16_t sub_addr, u16_t mod_id, u16_t cid, + u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_sub(OP_MOD_SUB_ADD, net_idx, addr, elem_addr, sub_addr, - mod_id, cid, status); + return mod_sub(OP_MOD_SUB_ADD, net_idx, addr, elem_addr, sub_addr, + mod_id, cid, status); } int bt_mesh_cfg_mod_sub_del(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u8_t *status) + u16_t sub_addr, u16_t mod_id, u8_t *status) { - return mod_sub(OP_MOD_SUB_DEL, net_idx, addr, elem_addr, sub_addr, - mod_id, CID_NVAL, status); + return mod_sub(OP_MOD_SUB_DEL, net_idx, addr, elem_addr, sub_addr, + mod_id, CID_NVAL, status); } int bt_mesh_cfg_mod_sub_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u16_t cid, - u8_t *status) + u16_t sub_addr, u16_t mod_id, u16_t cid, + u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_sub(OP_MOD_SUB_DEL, net_idx, addr, elem_addr, sub_addr, - mod_id, cid, status); + return mod_sub(OP_MOD_SUB_DEL, net_idx, addr, elem_addr, sub_addr, + mod_id, cid, status); } int bt_mesh_cfg_mod_sub_overwrite(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u8_t *status) + u16_t sub_addr, u16_t mod_id, u8_t *status) { - return mod_sub(OP_MOD_SUB_OVERWRITE, net_idx, addr, elem_addr, - sub_addr, mod_id, CID_NVAL, status); + return mod_sub(OP_MOD_SUB_OVERWRITE, net_idx, addr, elem_addr, + sub_addr, mod_id, CID_NVAL, status); } int bt_mesh_cfg_mod_sub_overwrite_vnd(u16_t net_idx, u16_t addr, - u16_t elem_addr, u16_t sub_addr, - u16_t mod_id, u16_t cid, u8_t *status) + u16_t elem_addr, u16_t sub_addr, + u16_t mod_id, u16_t cid, u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_sub(OP_MOD_SUB_OVERWRITE, net_idx, addr, elem_addr, - sub_addr, mod_id, cid, status); + return mod_sub(OP_MOD_SUB_OVERWRITE, net_idx, addr, elem_addr, + sub_addr, mod_id, cid, status); } static int mod_sub_va(u32_t op, u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, u16_t cid, - u16_t *virt_addr, u8_t *status) + const u8_t label[16], u16_t mod_id, u16_t cid, + u16_t *virt_addr, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 22 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct mod_sub_param param = { - .status = status, - .elem_addr = elem_addr, - .sub_addr = virt_addr, - .mod_id = mod_id, - .cid = cid, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 22 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct mod_sub_param param = { + .status = status, + .elem_addr = elem_addr, + .sub_addr = virt_addr, + .mod_id = mod_id, + .cid = cid, + }; + int err; - err = cli_prepare(¶m, OP_MOD_SUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_MOD_SUB_STATUS); + if (err) { + return err; + } - BT_DBG("net_idx 0x%04x addr 0x%04x elem_addr 0x%04x label %s", - net_idx, addr, elem_addr, label); - BT_DBG("mod_id 0x%04x cid 0x%04x", mod_id, cid); + BT_DBG("net_idx 0x%04x addr 0x%04x elem_addr 0x%04x label %s", + net_idx, addr, elem_addr, label); + BT_DBG("mod_id 0x%04x cid 0x%04x", mod_id, cid); - bt_mesh_model_msg_init(&msg, op); - net_buf_simple_add_le16(&msg, elem_addr); - net_buf_simple_add_mem(&msg, label, 16); + bt_mesh_model_msg_init(&msg, op); + net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_mem(&msg, label, 16); - if (cid != CID_NVAL) { - net_buf_simple_add_le16(&msg, cid); - } + if (cid != CID_NVAL) { + net_buf_simple_add_le16(&msg, cid); + } - net_buf_simple_add_le16(&msg, mod_id); + net_buf_simple_add_le16(&msg, mod_id); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_mod_sub_va_add(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t *virt_addr, u8_t *status) + const u8_t label[16], u16_t mod_id, + u16_t *virt_addr, u8_t *status) { - return mod_sub_va(OP_MOD_SUB_VA_ADD, net_idx, addr, elem_addr, label, - mod_id, CID_NVAL, virt_addr, status); + return mod_sub_va(OP_MOD_SUB_VA_ADD, net_idx, addr, elem_addr, label, + mod_id, CID_NVAL, virt_addr, status); } int bt_mesh_cfg_mod_sub_va_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t cid, u16_t *virt_addr, u8_t *status) + const u8_t label[16], u16_t mod_id, + u16_t cid, u16_t *virt_addr, u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_sub_va(OP_MOD_SUB_VA_ADD, net_idx, addr, elem_addr, label, - mod_id, cid, virt_addr, status); + return mod_sub_va(OP_MOD_SUB_VA_ADD, net_idx, addr, elem_addr, label, + mod_id, cid, virt_addr, status); } int bt_mesh_cfg_mod_sub_va_del(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t *virt_addr, u8_t *status) + const u8_t label[16], u16_t mod_id, + u16_t *virt_addr, u8_t *status) { - return mod_sub_va(OP_MOD_SUB_VA_DEL, net_idx, addr, elem_addr, label, - mod_id, CID_NVAL, virt_addr, status); + return mod_sub_va(OP_MOD_SUB_VA_DEL, net_idx, addr, elem_addr, label, + mod_id, CID_NVAL, virt_addr, status); } int bt_mesh_cfg_mod_sub_va_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t cid, u16_t *virt_addr, u8_t *status) + const u8_t label[16], u16_t mod_id, + u16_t cid, u16_t *virt_addr, u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_sub_va(OP_MOD_SUB_VA_DEL, net_idx, addr, elem_addr, label, - mod_id, cid, virt_addr, status); + return mod_sub_va(OP_MOD_SUB_VA_DEL, net_idx, addr, elem_addr, label, + mod_id, cid, virt_addr, status); } int bt_mesh_cfg_mod_sub_va_overwrite(u16_t net_idx, u16_t addr, - u16_t elem_addr, const u8_t label[16], - u16_t mod_id, u16_t *virt_addr, - u8_t *status) + u16_t elem_addr, const u8_t label[16], + u16_t mod_id, u16_t *virt_addr, + u8_t *status) { - return mod_sub_va(OP_MOD_SUB_VA_OVERWRITE, net_idx, addr, elem_addr, - label, mod_id, CID_NVAL, virt_addr, status); + return mod_sub_va(OP_MOD_SUB_VA_OVERWRITE, net_idx, addr, elem_addr, + label, mod_id, CID_NVAL, virt_addr, status); } int bt_mesh_cfg_mod_sub_va_overwrite_vnd(u16_t net_idx, u16_t addr, - u16_t elem_addr, const u8_t label[16], - u16_t mod_id, u16_t cid, - u16_t *virt_addr, u8_t *status) + u16_t elem_addr, const u8_t label[16], + u16_t mod_id, u16_t cid, + u16_t *virt_addr, u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_sub_va(OP_MOD_SUB_VA_OVERWRITE, net_idx, addr, elem_addr, - label, mod_id, cid, virt_addr, status); + return mod_sub_va(OP_MOD_SUB_VA_OVERWRITE, net_idx, addr, elem_addr, + label, mod_id, cid, virt_addr, status); } static int mod_pub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, u16_t cid, - struct bt_mesh_cfg_mod_pub *pub, u8_t *status) + u16_t mod_id, u16_t cid, + struct bt_mesh_cfg_mod_pub *pub, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 6 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct mod_pub_param param = { - .mod_id = mod_id, - .cid = cid, - .elem_addr = elem_addr, - .status = status, - .pub = pub, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 6 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct mod_pub_param param = { + .mod_id = mod_id, + .cid = cid, + .elem_addr = elem_addr, + .status = status, + .pub = pub, + }; + int err; - err = cli_prepare(¶m, OP_MOD_PUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_MOD_PUB_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_MOD_PUB_GET); + bt_mesh_model_msg_init(&msg, OP_MOD_PUB_GET); - net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_le16(&msg, elem_addr); - if (cid != CID_NVAL) { - net_buf_simple_add_le16(&msg, cid); - } + if (cid != CID_NVAL) { + net_buf_simple_add_le16(&msg, cid); + } - net_buf_simple_add_le16(&msg, mod_id); + net_buf_simple_add_le16(&msg, mod_id); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_mod_pub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, - u8_t *status) + u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, + u8_t *status) { - return mod_pub_get(net_idx, addr, elem_addr, mod_id, CID_NVAL, - pub, status); + return mod_pub_get(net_idx, addr, elem_addr, mod_id, CID_NVAL, + pub, status); } int bt_mesh_cfg_mod_pub_get_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, u16_t cid, - struct bt_mesh_cfg_mod_pub *pub, u8_t *status) + u16_t mod_id, u16_t cid, + struct bt_mesh_cfg_mod_pub *pub, u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_pub_get(net_idx, addr, elem_addr, mod_id, cid, pub, status); + return mod_pub_get(net_idx, addr, elem_addr, mod_id, cid, pub, status); } static int mod_pub_set(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, u16_t cid, - struct bt_mesh_cfg_mod_pub *pub, u8_t *status) + u16_t mod_id, u16_t cid, + struct bt_mesh_cfg_mod_pub *pub, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 13 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct mod_pub_param param = { - .mod_id = mod_id, - .cid = cid, - .elem_addr = elem_addr, - .status = status, - .pub = pub, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 13 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct mod_pub_param param = { + .mod_id = mod_id, + .cid = cid, + .elem_addr = elem_addr, + .status = status, + .pub = pub, + }; + int err; - err = cli_prepare(¶m, OP_MOD_PUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_MOD_PUB_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_MOD_PUB_SET); + bt_mesh_model_msg_init(&msg, OP_MOD_PUB_SET); - net_buf_simple_add_le16(&msg, elem_addr); - net_buf_simple_add_le16(&msg, pub->addr); - net_buf_simple_add_le16(&msg, (pub->app_idx & (pub->cred_flag << 12))); - net_buf_simple_add_u8(&msg, pub->ttl); - net_buf_simple_add_u8(&msg, pub->period); - net_buf_simple_add_u8(&msg, pub->transmit); + net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_le16(&msg, pub->addr); + net_buf_simple_add_le16(&msg, (pub->app_idx & (pub->cred_flag << 12))); + net_buf_simple_add_u8(&msg, pub->ttl); + net_buf_simple_add_u8(&msg, pub->period); + net_buf_simple_add_u8(&msg, pub->transmit); - if (cid != CID_NVAL) { - net_buf_simple_add_le16(&msg, cid); - } + if (cid != CID_NVAL) { + net_buf_simple_add_le16(&msg, cid); + } - net_buf_simple_add_le16(&msg, mod_id); + net_buf_simple_add_le16(&msg, mod_id); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_mod_pub_set(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, - u8_t *status) + u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, + u8_t *status) { - return mod_pub_set(net_idx, addr, elem_addr, mod_id, CID_NVAL, - pub, status); + return mod_pub_set(net_idx, addr, elem_addr, mod_id, CID_NVAL, + pub, status); } int bt_mesh_cfg_mod_pub_set_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, u16_t cid, - struct bt_mesh_cfg_mod_pub *pub, u8_t *status) + u16_t mod_id, u16_t cid, + struct bt_mesh_cfg_mod_pub *pub, u8_t *status) { - if (cid == CID_NVAL) { - return -EINVAL; - } + if (cid == CID_NVAL) { + return -EINVAL; + } - return mod_pub_set(net_idx, addr, elem_addr, mod_id, cid, pub, status); + return mod_pub_set(net_idx, addr, elem_addr, mod_id, cid, pub, status); } int bt_mesh_cfg_hb_sub_set(u16_t net_idx, u16_t addr, - struct bt_mesh_cfg_hb_sub *sub, u8_t *status) + struct bt_mesh_cfg_hb_sub *sub, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct hb_sub_param param = { - .status = status, - .sub = sub, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct hb_sub_param param = { + .status = status, + .sub = sub, + }; + int err; - err = cli_prepare(¶m, OP_HEARTBEAT_SUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEARTBEAT_SUB_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_SET); - net_buf_simple_add_le16(&msg, sub->src); - net_buf_simple_add_le16(&msg, sub->dst); - net_buf_simple_add_u8(&msg, sub->period); + bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_SET); + net_buf_simple_add_le16(&msg, sub->src); + net_buf_simple_add_le16(&msg, sub->dst); + net_buf_simple_add_u8(&msg, sub->period); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_hb_sub_get(u16_t net_idx, u16_t addr, - struct bt_mesh_cfg_hb_sub *sub, u8_t *status) + struct bt_mesh_cfg_hb_sub *sub, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct hb_sub_param param = { - .status = status, - .sub = sub, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct hb_sub_param param = { + .status = status, + .sub = sub, + }; + int err; - err = cli_prepare(¶m, OP_HEARTBEAT_SUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEARTBEAT_SUB_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_GET); + bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_GET); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_hb_pub_set(u16_t net_idx, u16_t addr, - const struct bt_mesh_cfg_hb_pub *pub, u8_t *status) + const struct bt_mesh_cfg_hb_pub *pub, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct hb_pub_param param = { - .status = status, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct hb_pub_param param = { + .status = status, + }; + int err; - err = cli_prepare(¶m, OP_HEARTBEAT_PUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEARTBEAT_PUB_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_SET); - net_buf_simple_add_le16(&msg, pub->dst); - net_buf_simple_add_u8(&msg, pub->count); - net_buf_simple_add_u8(&msg, pub->period); - net_buf_simple_add_u8(&msg, pub->ttl); - net_buf_simple_add_le16(&msg, pub->feat); - net_buf_simple_add_le16(&msg, pub->net_idx); + bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_SET); + net_buf_simple_add_le16(&msg, pub->dst); + net_buf_simple_add_u8(&msg, pub->count); + net_buf_simple_add_u8(&msg, pub->period); + net_buf_simple_add_u8(&msg, pub->ttl); + net_buf_simple_add_le16(&msg, pub->feat); + net_buf_simple_add_le16(&msg, pub->net_idx); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_cfg_hb_pub_get(u16_t net_idx, u16_t addr, - struct bt_mesh_cfg_hb_pub *pub, u8_t *status) + struct bt_mesh_cfg_hb_pub *pub, u8_t *status) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = BT_MESH_KEY_DEV, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct hb_pub_param param = { - .status = status, - .pub = pub, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = BT_MESH_KEY_DEV, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct hb_pub_param param = { + .status = status, + .pub = pub, + }; + int err; - err = cli_prepare(¶m, OP_HEARTBEAT_PUB_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEARTBEAT_PUB_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_GET); + bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_GET); - err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!status) { - cli_reset(); - return 0; - } + if (!status) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } s32_t bt_mesh_cfg_cli_timeout_get(void) { - return msg_timeout; + return msg_timeout; } void bt_mesh_cfg_cli_timeout_set(s32_t timeout) { - msg_timeout = timeout; + msg_timeout = timeout; } int bt_mesh_cfg_cli_init(struct bt_mesh_model *model, bool primary) { - BT_DBG("primary %u", primary); + BT_DBG("primary %u", primary); - if (!primary) { - BT_ERR("Configuration Client only allowed in primary element"); - return -EINVAL; - } + if (!primary) { + BT_ERR("Configuration Client only allowed in primary element"); + return -EINVAL; + } - if (!model->user_data) { - BT_ERR("No Configuration Client context provided"); - return -EINVAL; - } + if (!model->user_data) { + BT_ERR("No Configuration Client context provided"); + return -EINVAL; + } - cli = model->user_data; - cli->model = model; + cli = model->user_data; + cli->model = model; - /* Configuration Model security is device-key based */ - model->keys[0] = BT_MESH_KEY_DEV; + /* Configuration Model security is device-key based */ + model->keys[0] = BT_MESH_KEY_DEV; - k_sem_init(&cli->op_sync, 0, 1); + k_sem_init(&cli->op_sync, 0, 1); - return 0; + return 0; } diff --git a/components/network/ble/blemesh/src/cfg_srv.c b/components/network/ble/blemesh/src/cfg_srv.c index b145a32f..8792ad7c 100644 --- a/components/network/ble/blemesh/src/cfg_srv.c +++ b/components/network/ble/blemesh/src/cfg_srv.c @@ -43,472 +43,472 @@ static struct bt_mesh_cfg_srv *conf; static struct label { - u16_t ref; - u16_t addr; - u8_t uuid[16]; + u16_t ref; + u16_t addr; + u8_t uuid[16]; } labels[CONFIG_BT_MESH_LABEL_COUNT]; static int comp_add_elem(struct net_buf_simple *buf, struct bt_mesh_elem *elem, - bool primary) + bool primary) { - struct bt_mesh_model *mod; - int i; + struct bt_mesh_model *mod; + int i; - if (net_buf_simple_tailroom(buf) < - 4 + (elem->model_count * 2U) + (elem->vnd_model_count * 2U)) { - BT_ERR("Too large device composition"); - return -E2BIG; - } + if (net_buf_simple_tailroom(buf) < + 4 + (elem->model_count * 2U) + (elem->vnd_model_count * 2U)) { + BT_ERR("Too large device composition"); + return -E2BIG; + } - net_buf_simple_add_le16(buf, elem->loc); + net_buf_simple_add_le16(buf, elem->loc); - net_buf_simple_add_u8(buf, elem->model_count); - net_buf_simple_add_u8(buf, elem->vnd_model_count); + net_buf_simple_add_u8(buf, elem->model_count); + net_buf_simple_add_u8(buf, elem->vnd_model_count); - for (i = 0; i < elem->model_count; i++) { - mod = &elem->models[i]; - net_buf_simple_add_le16(buf, mod->id); - } + for (i = 0; i < elem->model_count; i++) { + mod = &elem->models[i]; + net_buf_simple_add_le16(buf, mod->id); + } - for (i = 0; i < elem->vnd_model_count; i++) { - mod = &elem->vnd_models[i]; - net_buf_simple_add_le16(buf, mod->vnd.company); - net_buf_simple_add_le16(buf, mod->vnd.id); - } + for (i = 0; i < elem->vnd_model_count; i++) { + mod = &elem->vnd_models[i]; + net_buf_simple_add_le16(buf, mod->vnd.company); + net_buf_simple_add_le16(buf, mod->vnd.id); + } - return 0; + return 0; } static int comp_get_page_0(struct net_buf_simple *buf) { - u16_t feat = 0U; - const struct bt_mesh_comp *comp; - int i; + u16_t feat = 0U; + const struct bt_mesh_comp *comp; + int i; - comp = bt_mesh_comp_get(); + comp = bt_mesh_comp_get(); - if (IS_ENABLED(CONFIG_BT_MESH_RELAY)) { - feat |= BT_MESH_FEAT_RELAY; - } + if (IS_ENABLED(CONFIG_BT_MESH_RELAY)) { + feat |= BT_MESH_FEAT_RELAY; + } - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { - feat |= BT_MESH_FEAT_PROXY; - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { + feat |= BT_MESH_FEAT_PROXY; + } - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - feat |= BT_MESH_FEAT_FRIEND; - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + feat |= BT_MESH_FEAT_FRIEND; + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - feat |= BT_MESH_FEAT_LOW_POWER; - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + feat |= BT_MESH_FEAT_LOW_POWER; + } - net_buf_simple_add_le16(buf, comp->cid); - net_buf_simple_add_le16(buf, comp->pid); - net_buf_simple_add_le16(buf, comp->vid); - net_buf_simple_add_le16(buf, CONFIG_BT_MESH_CRPL); - net_buf_simple_add_le16(buf, feat); + net_buf_simple_add_le16(buf, comp->cid); + net_buf_simple_add_le16(buf, comp->pid); + net_buf_simple_add_le16(buf, comp->vid); + net_buf_simple_add_le16(buf, CONFIG_BT_MESH_CRPL); + net_buf_simple_add_le16(buf, feat); - for (i = 0; i < comp->elem_count; i++) { - int err; + for (i = 0; i < comp->elem_count; i++) { + int err; - err = comp_add_elem(buf, &comp->elem[i], i == 0); - if (err) { - return err; - } - } + err = comp_add_elem(buf, &comp->elem[i], i == 0); + if (err) { + return err; + } + } - return 0; + return 0; } static void dev_comp_data_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); - u8_t page; + NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); + u8_t page; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - page = net_buf_simple_pull_u8(buf); - if (page != 0U) { - BT_WARN("Composition page %u not available", page); - page = 0U; - } + page = net_buf_simple_pull_u8(buf); + if (page != 0U) { + BT_WARN("Composition page %u not available", page); + page = 0U; + } - bt_mesh_model_msg_init(&sdu, OP_DEV_COMP_DATA_STATUS); + bt_mesh_model_msg_init(&sdu, OP_DEV_COMP_DATA_STATUS); - net_buf_simple_add_u8(&sdu, page); - if (comp_get_page_0(&sdu) < 0) { - BT_ERR("Unable to get composition page 0"); - return; - } + net_buf_simple_add_u8(&sdu, page); + if (comp_get_page_0(&sdu) < 0) { + BT_ERR("Unable to get composition page 0"); + return; + } - if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { - BT_ERR("Unable to send Device Composition Status response"); - } + if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { + BT_ERR("Unable to send Device Composition Status response"); + } } static struct bt_mesh_model *get_model(struct bt_mesh_elem *elem, - struct net_buf_simple *buf, bool *vnd) + struct net_buf_simple *buf, bool *vnd) { - if (buf->len < 4) { - u16_t id; + if (buf->len < 4) { + u16_t id; - id = net_buf_simple_pull_le16(buf); + id = net_buf_simple_pull_le16(buf); - BT_DBG("ID 0x%04x addr 0x%04x", id, elem->addr); + BT_DBG("ID 0x%04x addr 0x%04x", id, elem->addr); - *vnd = false; + *vnd = false; - return bt_mesh_model_find(elem, id); - } else { - u16_t company, id; + return bt_mesh_model_find(elem, id); + } else { + u16_t company, id; - company = net_buf_simple_pull_le16(buf); - id = net_buf_simple_pull_le16(buf); + company = net_buf_simple_pull_le16(buf); + id = net_buf_simple_pull_le16(buf); - BT_DBG("Company 0x%04x ID 0x%04x addr 0x%04x", company, id, - elem->addr); + BT_DBG("Company 0x%04x ID 0x%04x addr 0x%04x", company, id, + elem->addr); - *vnd = true; + *vnd = true; - return bt_mesh_model_find_vnd(elem, company, id); - } + return bt_mesh_model_find_vnd(elem, company, id); + } } static bool app_key_is_valid(u16_t app_idx) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { - struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { + struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - if (key->net_idx != BT_MESH_KEY_UNUSED && - key->app_idx == app_idx) { - return true; - } - } + if (key->net_idx != BT_MESH_KEY_UNUSED && + key->app_idx == app_idx) { + return true; + } + } - return false; + return false; } static u8_t _mod_pub_set(struct bt_mesh_model *model, u16_t pub_addr, - u16_t app_idx, u8_t cred_flag, u8_t ttl, u8_t period, - u8_t retransmit, bool store) + u16_t app_idx, u8_t cred_flag, u8_t ttl, u8_t period, + u8_t retransmit, bool store) { - if (!model->pub) { - return STATUS_NVAL_PUB_PARAM; - } + if (!model->pub) { + return STATUS_NVAL_PUB_PARAM; + } - if (!IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && cred_flag) { - return STATUS_FEAT_NOT_SUPP; - } + if (!IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && cred_flag) { + return STATUS_FEAT_NOT_SUPP; + } - if (!model->pub->update && period) { - return STATUS_NVAL_PUB_PARAM; - } + if (!model->pub->update && period) { + return STATUS_NVAL_PUB_PARAM; + } - if (pub_addr == BT_MESH_ADDR_UNASSIGNED) { - if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) { - return STATUS_SUCCESS; - } + if (pub_addr == BT_MESH_ADDR_UNASSIGNED) { + if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) { + return STATUS_SUCCESS; + } - model->pub->addr = BT_MESH_ADDR_UNASSIGNED; - model->pub->key = 0U; - model->pub->cred = 0U; - model->pub->ttl = 0U; - model->pub->period = 0U; - model->pub->retransmit = 0U; - model->pub->count = 0U; + model->pub->addr = BT_MESH_ADDR_UNASSIGNED; + model->pub->key = 0U; + model->pub->cred = 0U; + model->pub->ttl = 0U; + model->pub->period = 0U; + model->pub->retransmit = 0U; + model->pub->count = 0U; - if (model->pub->update) { - k_delayed_work_cancel(&model->pub->timer); - } + if (model->pub->update) { + k_delayed_work_cancel(&model->pub->timer); + } - if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { - bt_mesh_store_mod_pub(model); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { + bt_mesh_store_mod_pub(model); + } - return STATUS_SUCCESS; - } + return STATUS_SUCCESS; + } - if (!bt_mesh_app_key_find(app_idx)) { - return STATUS_INVALID_APPKEY; - } + if (!bt_mesh_app_key_find(app_idx)) { + return STATUS_INVALID_APPKEY; + } - model->pub->addr = pub_addr; - model->pub->key = app_idx; - model->pub->cred = cred_flag; - model->pub->ttl = ttl; - model->pub->period = period; - model->pub->retransmit = retransmit; + model->pub->addr = pub_addr; + model->pub->key = app_idx; + model->pub->cred = cred_flag; + model->pub->ttl = ttl; + model->pub->period = period; + model->pub->retransmit = retransmit; - if (model->pub->update) { - s32_t period_ms; + if (model->pub->update) { + s32_t period_ms; - period_ms = bt_mesh_model_pub_period_get(model); - BT_DBG("period %u ms", period_ms); + period_ms = bt_mesh_model_pub_period_get(model); + BT_DBG("period %u ms", period_ms); - if (period_ms) { - k_delayed_work_submit(&model->pub->timer, period_ms); - } else { - k_delayed_work_cancel(&model->pub->timer); - } - } + if (period_ms) { + k_delayed_work_submit(&model->pub->timer, period_ms); + } else { + k_delayed_work_cancel(&model->pub->timer); + } + } - if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { - bt_mesh_store_mod_pub(model); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { + bt_mesh_store_mod_pub(model); + } - return STATUS_SUCCESS; + return STATUS_SUCCESS; } static u8_t mod_bind(struct bt_mesh_model *model, u16_t key_idx) { - int i; + int i; - BT_DBG("model %p key_idx 0x%03x", model, key_idx); + BT_DBG("model %p key_idx 0x%03x", model, key_idx); - if (!app_key_is_valid(key_idx)) { - return STATUS_INVALID_APPKEY; - } + if (!app_key_is_valid(key_idx)) { + return STATUS_INVALID_APPKEY; + } - for (i = 0; i < ARRAY_SIZE(model->keys); i++) { - /* Treat existing binding as success */ - if (model->keys[i] == key_idx) { - return STATUS_SUCCESS; - } - } + for (i = 0; i < ARRAY_SIZE(model->keys); i++) { + /* Treat existing binding as success */ + if (model->keys[i] == key_idx) { + return STATUS_SUCCESS; + } + } - for (i = 0; i < ARRAY_SIZE(model->keys); i++) { - if (model->keys[i] == BT_MESH_KEY_UNUSED) { - model->keys[i] = key_idx; + for (i = 0; i < ARRAY_SIZE(model->keys); i++) { + if (model->keys[i] == BT_MESH_KEY_UNUSED) { + model->keys[i] = key_idx; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_bind(model); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_bind(model); + } - return STATUS_SUCCESS; - } - } + return STATUS_SUCCESS; + } + } - return STATUS_INSUFF_RESOURCES; + return STATUS_INSUFF_RESOURCES; } static u8_t mod_unbind(struct bt_mesh_model *model, u16_t key_idx, bool store) { - int i; + int i; - BT_DBG("model %p key_idx 0x%03x store %u", model, key_idx, store); + BT_DBG("model %p key_idx 0x%03x store %u", model, key_idx, store); - if (!app_key_is_valid(key_idx)) { - return STATUS_INVALID_APPKEY; - } + if (!app_key_is_valid(key_idx)) { + return STATUS_INVALID_APPKEY; + } - for (i = 0; i < ARRAY_SIZE(model->keys); i++) { - if (model->keys[i] != key_idx) { - continue; - } + for (i = 0; i < ARRAY_SIZE(model->keys); i++) { + if (model->keys[i] != key_idx) { + continue; + } - model->keys[i] = BT_MESH_KEY_UNUSED; + model->keys[i] = BT_MESH_KEY_UNUSED; - if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { - bt_mesh_store_mod_bind(model); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { + bt_mesh_store_mod_bind(model); + } - if (model->pub && model->pub->key == key_idx) { - _mod_pub_set(model, BT_MESH_ADDR_UNASSIGNED, - 0, 0, 0, 0, 0, store); - } - } + if (model->pub && model->pub->key == key_idx) { + _mod_pub_set(model, BT_MESH_ADDR_UNASSIGNED, + 0, 0, 0, 0, 0, store); + } + } - return STATUS_SUCCESS; + return STATUS_SUCCESS; } struct bt_mesh_app_key *bt_mesh_app_key_alloc(u16_t app_idx) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { - struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { + struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - if (key->net_idx == BT_MESH_KEY_UNUSED) { - return key; - } - } + if (key->net_idx == BT_MESH_KEY_UNUSED) { + return key; + } + } - return NULL; + return NULL; } static u8_t app_key_set(u16_t net_idx, u16_t app_idx, const u8_t val[16], - bool update) + bool update) { - struct bt_mesh_app_keys *keys; - struct bt_mesh_app_key *key; - struct bt_mesh_subnet *sub; + struct bt_mesh_app_keys *keys; + struct bt_mesh_app_key *key; + struct bt_mesh_subnet *sub; - BT_DBG("net_idx 0x%04x app_idx %04x update %u val %s", - net_idx, app_idx, update, bt_hex(val, 16)); + BT_DBG("net_idx 0x%04x app_idx %04x update %u val %s", + net_idx, app_idx, update, bt_hex(val, 16)); - sub = bt_mesh_subnet_get(net_idx); - if (!sub) { - return STATUS_INVALID_NETKEY; - } + sub = bt_mesh_subnet_get(net_idx); + if (!sub) { + return STATUS_INVALID_NETKEY; + } - key = bt_mesh_app_key_find(app_idx); - if (update) { - if (!key) { - return STATUS_INVALID_APPKEY; - } + key = bt_mesh_app_key_find(app_idx); + if (update) { + if (!key) { + return STATUS_INVALID_APPKEY; + } - if (key->net_idx != net_idx) { - return STATUS_INVALID_BINDING; - } + if (key->net_idx != net_idx) { + return STATUS_INVALID_BINDING; + } - keys = &key->keys[1]; + keys = &key->keys[1]; - /* The AppKey Update message shall generate an error when node - * is in normal operation, Phase 2, or Phase 3 or in Phase 1 - * when the AppKey Update message on a valid AppKeyIndex when - * the AppKey value is different. - */ - if (sub->kr_phase != BT_MESH_KR_PHASE_1) { - return STATUS_CANNOT_UPDATE; - } + /* The AppKey Update message shall generate an error when node + * is in normal operation, Phase 2, or Phase 3 or in Phase 1 + * when the AppKey Update message on a valid AppKeyIndex when + * the AppKey value is different. + */ + if (sub->kr_phase != BT_MESH_KR_PHASE_1) { + return STATUS_CANNOT_UPDATE; + } - if (key->updated) { - if (memcmp(keys->val, val, 16)) { - return STATUS_CANNOT_UPDATE; - } else { - return STATUS_SUCCESS; - } - } + if (key->updated) { + if (memcmp(keys->val, val, 16)) { + return STATUS_CANNOT_UPDATE; + } else { + return STATUS_SUCCESS; + } + } - key->updated = true; - } else { - if (key) { - if (key->net_idx == net_idx && - !memcmp(key->keys[0].val, val, 16)) { - return STATUS_SUCCESS; - } + key->updated = true; + } else { + if (key) { + if (key->net_idx == net_idx && + !memcmp(key->keys[0].val, val, 16)) { + return STATUS_SUCCESS; + } - if (key->net_idx == net_idx) { - return STATUS_IDX_ALREADY_STORED; - } else { - return STATUS_INVALID_NETKEY; - } - } + if (key->net_idx == net_idx) { + return STATUS_IDX_ALREADY_STORED; + } else { + return STATUS_INVALID_NETKEY; + } + } - key = bt_mesh_app_key_alloc(app_idx); - if (!key) { - return STATUS_INSUFF_RESOURCES; - } + key = bt_mesh_app_key_alloc(app_idx); + if (!key) { + return STATUS_INSUFF_RESOURCES; + } - keys = &key->keys[0]; - } + keys = &key->keys[0]; + } - if (bt_mesh_app_id(val, &keys->id)) { - if (update) { - key->updated = false; - } + if (bt_mesh_app_id(val, &keys->id)) { + if (update) { + key->updated = false; + } - return STATUS_STORAGE_FAIL; - } + return STATUS_STORAGE_FAIL; + } - BT_DBG("app_idx 0x%04x AID 0x%02x", app_idx, keys->id); + BT_DBG("app_idx 0x%04x AID 0x%02x", app_idx, keys->id); - key->net_idx = net_idx; - key->app_idx = app_idx; - memcpy(keys->val, val, 16); + key->net_idx = net_idx; + key->app_idx = app_idx; + memcpy(keys->val, val, 16); - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - BT_DBG("Storing AppKey persistently"); - bt_mesh_store_app_key(key); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + BT_DBG("Storing AppKey persistently"); + bt_mesh_store_app_key(key); + } - return STATUS_SUCCESS; + return STATUS_SUCCESS; } static void app_key_add(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); - u16_t key_net_idx, key_app_idx; - u8_t status; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); + u16_t key_net_idx, key_app_idx; + u8_t status; - key_idx_unpack(buf, &key_net_idx, &key_app_idx); + key_idx_unpack(buf, &key_net_idx, &key_app_idx); - BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx); + BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx); - bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS); + bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS); - status = app_key_set(key_net_idx, key_app_idx, buf->data, false); - BT_DBG("status 0x%02x", status); - net_buf_simple_add_u8(&msg, status); + status = app_key_set(key_net_idx, key_app_idx, buf->data, false); + BT_DBG("status 0x%02x", status); + net_buf_simple_add_u8(&msg, status); - key_idx_pack(&msg, key_net_idx, key_app_idx); + key_idx_pack(&msg, key_net_idx, key_app_idx); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send App Key Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send App Key Status response"); + } } static void app_key_update(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); - u16_t key_net_idx, key_app_idx; - u8_t status; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); + u16_t key_net_idx, key_app_idx; + u8_t status; - key_idx_unpack(buf, &key_net_idx, &key_app_idx); + key_idx_unpack(buf, &key_net_idx, &key_app_idx); - BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx); + BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx); - bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS); + bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS); - status = app_key_set(key_net_idx, key_app_idx, buf->data, true); - BT_DBG("status 0x%02x", status); - net_buf_simple_add_u8(&msg, status); + status = app_key_set(key_net_idx, key_app_idx, buf->data, true); + BT_DBG("status 0x%02x", status); + net_buf_simple_add_u8(&msg, status); - key_idx_pack(&msg, key_net_idx, key_app_idx); + key_idx_pack(&msg, key_net_idx, key_app_idx); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send App Key Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send App Key Status response"); + } } struct unbind_data { - u16_t app_idx; - bool store; + u16_t app_idx; + bool store; }; static void _mod_unbind(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, - bool vnd, bool primary, void *user_data) + bool vnd, bool primary, void *user_data) { - struct unbind_data *data = user_data; + struct unbind_data *data = user_data; - mod_unbind(mod, data->app_idx, data->store); + mod_unbind(mod, data->app_idx, data->store); } void bt_mesh_app_key_del(struct bt_mesh_app_key *key, bool store) { - struct unbind_data data = { .app_idx = key->app_idx, .store = store }; + struct unbind_data data = { .app_idx = key->app_idx, .store = store }; - BT_DBG("AppIdx 0x%03x store %u", key->app_idx, store); + BT_DBG("AppIdx 0x%03x store %u", key->app_idx, store); - bt_mesh_model_foreach(_mod_unbind, &data); + bt_mesh_model_foreach(_mod_unbind, &data); - if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { - bt_mesh_clear_app_key(key); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { + bt_mesh_clear_app_key(key); + } - key->net_idx = BT_MESH_KEY_UNUSED; - (void)memset(key->keys, 0, sizeof(key->keys)); + key->net_idx = BT_MESH_KEY_UNUSED; + (void)memset(key->keys, 0, sizeof(key->keys)); #if defined(BFLB_BLE_MESH_PATCH_DEL_APPKEY) key->app_idx = BT_MESH_KEY_UNUSED; key->updated = false; @@ -516,3050 +516,3050 @@ void bt_mesh_app_key_del(struct bt_mesh_app_key *key, bool store) } static void app_key_del(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); - u16_t key_net_idx, key_app_idx; - struct bt_mesh_app_key *key; - u8_t status; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); + u16_t key_net_idx, key_app_idx; + struct bt_mesh_app_key *key; + u8_t status; - key_idx_unpack(buf, &key_net_idx, &key_app_idx); + key_idx_unpack(buf, &key_net_idx, &key_app_idx); - BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx); + BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx); - if (!bt_mesh_subnet_get(key_net_idx)) { - status = STATUS_INVALID_NETKEY; - goto send_status; - } + if (!bt_mesh_subnet_get(key_net_idx)) { + status = STATUS_INVALID_NETKEY; + goto send_status; + } - key = bt_mesh_app_key_find(key_app_idx); - if (!key) { - /* Treat as success since the client might have missed a - * previous response and is resending the request. - */ - status = STATUS_SUCCESS; - goto send_status; - } + key = bt_mesh_app_key_find(key_app_idx); + if (!key) { + /* Treat as success since the client might have missed a + * previous response and is resending the request. + */ + status = STATUS_SUCCESS; + goto send_status; + } - if (key->net_idx != key_net_idx) { - status = STATUS_INVALID_BINDING; - goto send_status; - } + if (key->net_idx != key_net_idx) { + status = STATUS_INVALID_BINDING; + goto send_status; + } - bt_mesh_app_key_del(key, true); - status = STATUS_SUCCESS; + bt_mesh_app_key_del(key, true); + status = STATUS_SUCCESS; send_status: - bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS); + bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS); - net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_u8(&msg, status); - key_idx_pack(&msg, key_net_idx, key_app_idx); + key_idx_pack(&msg, key_net_idx, key_app_idx); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send App Key Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send App Key Status response"); + } } /* Index list length: 3 bytes for every pair and 2 bytes for an odd idx */ #define IDX_LEN(num) (((num) / 2) * 3 + ((num) % 2) * 2) static void app_key_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4 + - IDX_LEN(CONFIG_BT_MESH_APP_KEY_COUNT)); - u16_t get_idx, i, prev; - u8_t status; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4 + + IDX_LEN(CONFIG_BT_MESH_APP_KEY_COUNT)); + u16_t get_idx, i, prev; + u8_t status; - get_idx = net_buf_simple_pull_le16(buf); - if (get_idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", get_idx); - return; - } + get_idx = net_buf_simple_pull_le16(buf); + if (get_idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", get_idx); + return; + } - BT_DBG("idx 0x%04x", get_idx); + BT_DBG("idx 0x%04x", get_idx); - bt_mesh_model_msg_init(&msg, OP_APP_KEY_LIST); + bt_mesh_model_msg_init(&msg, OP_APP_KEY_LIST); - if (!bt_mesh_subnet_get(get_idx)) { - status = STATUS_INVALID_NETKEY; - } else { - status = STATUS_SUCCESS; - } + if (!bt_mesh_subnet_get(get_idx)) { + status = STATUS_INVALID_NETKEY; + } else { + status = STATUS_SUCCESS; + } - net_buf_simple_add_u8(&msg, status); - net_buf_simple_add_le16(&msg, get_idx); + net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_le16(&msg, get_idx); - if (status != STATUS_SUCCESS) { - goto send_status; - } + if (status != STATUS_SUCCESS) { + goto send_status; + } - prev = BT_MESH_KEY_UNUSED; - for (i = 0U; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { - struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; + prev = BT_MESH_KEY_UNUSED; + for (i = 0U; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { + struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - if (key->net_idx != get_idx) { - continue; - } + if (key->net_idx != get_idx) { + continue; + } - if (prev == BT_MESH_KEY_UNUSED) { - prev = key->app_idx; - continue; - } + if (prev == BT_MESH_KEY_UNUSED) { + prev = key->app_idx; + continue; + } - key_idx_pack(&msg, prev, key->app_idx); - prev = BT_MESH_KEY_UNUSED; - } + key_idx_pack(&msg, prev, key->app_idx); + prev = BT_MESH_KEY_UNUSED; + } - if (prev != BT_MESH_KEY_UNUSED) { - net_buf_simple_add_le16(&msg, prev); - } + if (prev != BT_MESH_KEY_UNUSED) { + net_buf_simple_add_le16(&msg, prev); + } send_status: - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send AppKey List"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send AppKey List"); + } } static void beacon_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - bt_mesh_model_msg_init(&msg, OP_BEACON_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_beacon_get()); + bt_mesh_model_msg_init(&msg, OP_BEACON_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_beacon_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Config Beacon Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Config Beacon Status response"); + } } static void beacon_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_cfg_srv *cfg = model->user_data; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_cfg_srv *cfg = model->user_data; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (!cfg) { - BT_WARN("No Configuration Server context available"); - } else if (buf->data[0] == 0x00 || buf->data[0] == 0x01) { - if (buf->data[0] != cfg->beacon) { - cfg->beacon = buf->data[0]; + if (!cfg) { + BT_WARN("No Configuration Server context available"); + } else if (buf->data[0] == 0x00 || buf->data[0] == 0x01) { + if (buf->data[0] != cfg->beacon) { + cfg->beacon = buf->data[0]; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_cfg(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_cfg(); + } - if (cfg->beacon) { - bt_mesh_beacon_enable(); - } else { - bt_mesh_beacon_disable(); - } - } - } else { - BT_WARN("Invalid Config Beacon value 0x%02x", buf->data[0]); - return; - } + if (cfg->beacon) { + bt_mesh_beacon_enable(); + } else { + bt_mesh_beacon_disable(); + } + } + } else { + BT_WARN("Invalid Config Beacon value 0x%02x", buf->data[0]); + return; + } - bt_mesh_model_msg_init(&msg, OP_BEACON_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_beacon_get()); + bt_mesh_model_msg_init(&msg, OP_BEACON_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_beacon_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Config Beacon Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Config Beacon Status response"); + } } static void default_ttl_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - bt_mesh_model_msg_init(&msg, OP_DEFAULT_TTL_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_default_ttl_get()); + bt_mesh_model_msg_init(&msg, OP_DEFAULT_TTL_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_default_ttl_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Default TTL Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Default TTL Status response"); + } } static void default_ttl_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_cfg_srv *cfg = model->user_data; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_cfg_srv *cfg = model->user_data; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (!cfg) { - BT_WARN("No Configuration Server context available"); - } else if (buf->data[0] <= BT_MESH_TTL_MAX && buf->data[0] != 0x01) { - if (cfg->default_ttl != buf->data[0]) { - cfg->default_ttl = buf->data[0]; + if (!cfg) { + BT_WARN("No Configuration Server context available"); + } else if (buf->data[0] <= BT_MESH_TTL_MAX && buf->data[0] != 0x01) { + if (cfg->default_ttl != buf->data[0]) { + cfg->default_ttl = buf->data[0]; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_cfg(); - } - } - } else { - BT_WARN("Prohibited Default TTL value 0x%02x", buf->data[0]); - return; - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_cfg(); + } + } + } else { + BT_WARN("Prohibited Default TTL value 0x%02x", buf->data[0]); + return; + } - bt_mesh_model_msg_init(&msg, OP_DEFAULT_TTL_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_default_ttl_get()); + bt_mesh_model_msg_init(&msg, OP_DEFAULT_TTL_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_default_ttl_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Default TTL Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Default TTL Status response"); + } } static void send_gatt_proxy_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx) + struct bt_mesh_msg_ctx *ctx) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - bt_mesh_model_msg_init(&msg, OP_GATT_PROXY_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_gatt_proxy_get()); + bt_mesh_model_msg_init(&msg, OP_GATT_PROXY_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_gatt_proxy_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send GATT Proxy Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send GATT Proxy Status"); + } } static void gatt_proxy_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - send_gatt_proxy_status(model, ctx); + send_gatt_proxy_status(model, ctx); } static void gatt_proxy_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_cfg_srv *cfg = model->user_data; + struct bt_mesh_cfg_srv *cfg = model->user_data; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (buf->data[0] != 0x00 && buf->data[0] != 0x01) { - BT_WARN("Invalid GATT Proxy value 0x%02x", buf->data[0]); - return; - } + if (buf->data[0] != 0x00 && buf->data[0] != 0x01) { + BT_WARN("Invalid GATT Proxy value 0x%02x", buf->data[0]); + return; + } - if (!IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) || - bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_NOT_SUPPORTED) { - goto send_status; - } + if (!IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) || + bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_NOT_SUPPORTED) { + goto send_status; + } - if (!cfg) { - BT_WARN("No Configuration Server context available"); - goto send_status; - } + if (!cfg) { + BT_WARN("No Configuration Server context available"); + goto send_status; + } - BT_DBG("GATT Proxy 0x%02x -> 0x%02x", cfg->gatt_proxy, buf->data[0]); + BT_DBG("GATT Proxy 0x%02x -> 0x%02x", cfg->gatt_proxy, buf->data[0]); - if (cfg->gatt_proxy == buf->data[0]) { - goto send_status; - } + if (cfg->gatt_proxy == buf->data[0]) { + goto send_status; + } - cfg->gatt_proxy = buf->data[0]; + cfg->gatt_proxy = buf->data[0]; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_cfg(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_cfg(); + } - if (cfg->gatt_proxy == BT_MESH_GATT_PROXY_DISABLED) { - int i; + if (cfg->gatt_proxy == BT_MESH_GATT_PROXY_DISABLED) { + int i; - /* Section 4.2.11.1: "When the GATT Proxy state is set to - * 0x00, the Node Identity state for all subnets shall be set - * to 0x00 and shall not be changed." - */ - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + /* Section 4.2.11.1: "When the GATT Proxy state is set to + * 0x00, the Node Identity state for all subnets shall be set + * to 0x00 and shall not be changed." + */ + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx != BT_MESH_KEY_UNUSED) { - bt_mesh_proxy_identity_stop(sub); - } - } + if (sub->net_idx != BT_MESH_KEY_UNUSED) { + bt_mesh_proxy_identity_stop(sub); + } + } - /* Section 4.2.11: "Upon transition from GATT Proxy state 0x01 - * to GATT Proxy state 0x00 the GATT Bearer Server shall - * disconnect all GATT Bearer Clients. - */ - bt_mesh_proxy_gatt_disconnect(); - } + /* Section 4.2.11: "Upon transition from GATT Proxy state 0x01 + * to GATT Proxy state 0x00 the GATT Bearer Server shall + * disconnect all GATT Bearer Clients. + */ + bt_mesh_proxy_gatt_disconnect(); + } - bt_mesh_adv_update(); + bt_mesh_adv_update(); - if (cfg->hb_pub.feat & BT_MESH_FEAT_PROXY) { - bt_mesh_heartbeat_send(); - } + if (cfg->hb_pub.feat & BT_MESH_FEAT_PROXY) { + bt_mesh_heartbeat_send(); + } send_status: - send_gatt_proxy_status(model, ctx); + send_gatt_proxy_status(model, ctx); } static void net_transmit_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - bt_mesh_model_msg_init(&msg, OP_NET_TRANSMIT_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_net_transmit_get()); + bt_mesh_model_msg_init(&msg, OP_NET_TRANSMIT_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_net_transmit_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Config Network Transmit Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Config Network Transmit Status"); + } } static void net_transmit_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_cfg_srv *cfg = model->user_data; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_cfg_srv *cfg = model->user_data; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - BT_DBG("Transmit 0x%02x (count %u interval %ums)", buf->data[0], - BT_MESH_TRANSMIT_COUNT(buf->data[0]), - BT_MESH_TRANSMIT_INT(buf->data[0])); + BT_DBG("Transmit 0x%02x (count %u interval %ums)", buf->data[0], + BT_MESH_TRANSMIT_COUNT(buf->data[0]), + BT_MESH_TRANSMIT_INT(buf->data[0])); - if (!cfg) { - BT_WARN("No Configuration Server context available"); - } else { - cfg->net_transmit = buf->data[0]; + if (!cfg) { + BT_WARN("No Configuration Server context available"); + } else { + cfg->net_transmit = buf->data[0]; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_cfg(); - } - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_cfg(); + } + } - bt_mesh_model_msg_init(&msg, OP_NET_TRANSMIT_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_net_transmit_get()); + bt_mesh_model_msg_init(&msg, OP_NET_TRANSMIT_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_net_transmit_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Network Transmit Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Network Transmit Status"); + } } static void relay_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - bt_mesh_model_msg_init(&msg, OP_RELAY_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_relay_get()); - net_buf_simple_add_u8(&msg, bt_mesh_relay_retransmit_get()); + bt_mesh_model_msg_init(&msg, OP_RELAY_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_relay_get()); + net_buf_simple_add_u8(&msg, bt_mesh_relay_retransmit_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Config Relay Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Config Relay Status response"); + } } static void relay_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); - struct bt_mesh_cfg_srv *cfg = model->user_data; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); + struct bt_mesh_cfg_srv *cfg = model->user_data; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (!cfg) { - BT_WARN("No Configuration Server context available"); - } else if (buf->data[0] == 0x00 || buf->data[0] == 0x01) { - bool change; + if (!cfg) { + BT_WARN("No Configuration Server context available"); + } else if (buf->data[0] == 0x00 || buf->data[0] == 0x01) { + bool change; - if (cfg->relay == BT_MESH_RELAY_NOT_SUPPORTED) { - change = false; - } else { - change = (cfg->relay != buf->data[0]); - cfg->relay = buf->data[0]; - cfg->relay_retransmit = buf->data[1]; + if (cfg->relay == BT_MESH_RELAY_NOT_SUPPORTED) { + change = false; + } else { + change = (cfg->relay != buf->data[0]); + cfg->relay = buf->data[0]; + cfg->relay_retransmit = buf->data[1]; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_cfg(); - } - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_cfg(); + } + } - BT_DBG("Relay 0x%02x (%s) xmit 0x%02x (count %u interval %u)", - cfg->relay, change ? "changed" : "not changed", - cfg->relay_retransmit, - BT_MESH_TRANSMIT_COUNT(cfg->relay_retransmit), - BT_MESH_TRANSMIT_INT(cfg->relay_retransmit)); + BT_DBG("Relay 0x%02x (%s) xmit 0x%02x (count %u interval %u)", + cfg->relay, change ? "changed" : "not changed", + cfg->relay_retransmit, + BT_MESH_TRANSMIT_COUNT(cfg->relay_retransmit), + BT_MESH_TRANSMIT_INT(cfg->relay_retransmit)); - if ((cfg->hb_pub.feat & BT_MESH_FEAT_RELAY) && change) { - bt_mesh_heartbeat_send(); - } - } else { - BT_WARN("Invalid Relay value 0x%02x", buf->data[0]); - return; - } + if ((cfg->hb_pub.feat & BT_MESH_FEAT_RELAY) && change) { + bt_mesh_heartbeat_send(); + } + } else { + BT_WARN("Invalid Relay value 0x%02x", buf->data[0]); + return; + } - bt_mesh_model_msg_init(&msg, OP_RELAY_STATUS); - net_buf_simple_add_u8(&msg, bt_mesh_relay_get()); - net_buf_simple_add_u8(&msg, bt_mesh_relay_retransmit_get()); + bt_mesh_model_msg_init(&msg, OP_RELAY_STATUS); + net_buf_simple_add_u8(&msg, bt_mesh_relay_get()); + net_buf_simple_add_u8(&msg, bt_mesh_relay_retransmit_get()); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Relay Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Relay Status response"); + } } static void send_mod_pub_status(struct bt_mesh_model *cfg_mod, - struct bt_mesh_msg_ctx *ctx, - u16_t elem_addr, u16_t pub_addr, - bool vnd, struct bt_mesh_model *mod, - u8_t status, u8_t *mod_id) + struct bt_mesh_msg_ctx *ctx, + u16_t elem_addr, u16_t pub_addr, + bool vnd, struct bt_mesh_model *mod, + u8_t status, u8_t *mod_id) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 14 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 14 + 4); - bt_mesh_model_msg_init(&msg, OP_MOD_PUB_STATUS); + bt_mesh_model_msg_init(&msg, OP_MOD_PUB_STATUS); - net_buf_simple_add_u8(&msg, status); - net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_le16(&msg, elem_addr); - if (status != STATUS_SUCCESS) { - (void)memset(net_buf_simple_add(&msg, 7), 0, 7); - } else { - u16_t idx_cred; + if (status != STATUS_SUCCESS) { + (void)memset(net_buf_simple_add(&msg, 7), 0, 7); + } else { + u16_t idx_cred; - net_buf_simple_add_le16(&msg, pub_addr); + net_buf_simple_add_le16(&msg, pub_addr); - idx_cred = mod->pub->key | (u16_t)mod->pub->cred << 12; - net_buf_simple_add_le16(&msg, idx_cred); - net_buf_simple_add_u8(&msg, mod->pub->ttl); - net_buf_simple_add_u8(&msg, mod->pub->period); - net_buf_simple_add_u8(&msg, mod->pub->retransmit); - } + idx_cred = mod->pub->key | (u16_t)mod->pub->cred << 12; + net_buf_simple_add_le16(&msg, idx_cred); + net_buf_simple_add_u8(&msg, mod->pub->ttl); + net_buf_simple_add_u8(&msg, mod->pub->period); + net_buf_simple_add_u8(&msg, mod->pub->retransmit); + } - if (vnd) { - memcpy(net_buf_simple_add(&msg, 4), mod_id, 4); - } else { - memcpy(net_buf_simple_add(&msg, 2), mod_id, 2); - } + if (vnd) { + memcpy(net_buf_simple_add(&msg, 4), mod_id, 4); + } else { + memcpy(net_buf_simple_add(&msg, 2), mod_id, 2); + } - if (bt_mesh_model_send(cfg_mod, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Model Publication Status"); - } + if (bt_mesh_model_send(cfg_mod, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Model Publication Status"); + } } static void mod_pub_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, pub_addr = 0U; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id, status; - bool vnd; + u16_t elem_addr, pub_addr = 0U; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id, status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - mod_id = buf->data; + mod_id = buf->data; - BT_DBG("elem_addr 0x%04x", elem_addr); + BT_DBG("elem_addr 0x%04x", elem_addr); - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - if (!mod->pub) { - status = STATUS_NVAL_PUB_PARAM; - goto send_status; - } + if (!mod->pub) { + status = STATUS_NVAL_PUB_PARAM; + goto send_status; + } - pub_addr = mod->pub->addr; - status = STATUS_SUCCESS; + pub_addr = mod->pub->addr; + status = STATUS_SUCCESS; send_status: - send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, - status, mod_id); + send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, + status, mod_id); } static void mod_pub_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u8_t retransmit, status, pub_ttl, pub_period, cred_flag; - u16_t elem_addr, pub_addr, pub_app_idx; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id; - bool vnd; + u8_t retransmit, status, pub_ttl, pub_period, cred_flag; + u16_t elem_addr, pub_addr, pub_app_idx; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - pub_addr = net_buf_simple_pull_le16(buf); - pub_app_idx = net_buf_simple_pull_le16(buf); - cred_flag = ((pub_app_idx >> 12) & BIT_MASK(1)); - pub_app_idx &= BIT_MASK(12); + pub_addr = net_buf_simple_pull_le16(buf); + pub_app_idx = net_buf_simple_pull_le16(buf); + cred_flag = ((pub_app_idx >> 12) & BIT_MASK(1)); + pub_app_idx &= BIT_MASK(12); - pub_ttl = net_buf_simple_pull_u8(buf); - if (pub_ttl > BT_MESH_TTL_MAX && pub_ttl != BT_MESH_TTL_DEFAULT) { - BT_ERR("Invalid TTL value 0x%02x", pub_ttl); - return; - } + pub_ttl = net_buf_simple_pull_u8(buf); + if (pub_ttl > BT_MESH_TTL_MAX && pub_ttl != BT_MESH_TTL_DEFAULT) { + BT_ERR("Invalid TTL value 0x%02x", pub_ttl); + return; + } - pub_period = net_buf_simple_pull_u8(buf); - retransmit = net_buf_simple_pull_u8(buf); - mod_id = buf->data; + pub_period = net_buf_simple_pull_u8(buf); + retransmit = net_buf_simple_pull_u8(buf); + mod_id = buf->data; - BT_DBG("elem_addr 0x%04x pub_addr 0x%04x cred_flag %u", - elem_addr, pub_addr, cred_flag); - BT_DBG("pub_app_idx 0x%03x, pub_ttl %u pub_period 0x%02x", - pub_app_idx, pub_ttl, pub_period); - BT_DBG("retransmit 0x%02x (count %u interval %ums)", retransmit, - BT_MESH_PUB_TRANSMIT_COUNT(retransmit), - BT_MESH_PUB_TRANSMIT_INT(retransmit)); + BT_DBG("elem_addr 0x%04x pub_addr 0x%04x cred_flag %u", + elem_addr, pub_addr, cred_flag); + BT_DBG("pub_app_idx 0x%03x, pub_ttl %u pub_period 0x%02x", + pub_app_idx, pub_ttl, pub_period); + BT_DBG("retransmit 0x%02x (count %u interval %ums)", retransmit, + BT_MESH_PUB_TRANSMIT_COUNT(retransmit), + BT_MESH_PUB_TRANSMIT_INT(retransmit)); - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, pub_ttl, - pub_period, retransmit, true); + status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, pub_ttl, + pub_period, retransmit, true); send_status: - send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, - status, mod_id); + send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, + status, mod_id); } #if CONFIG_BT_MESH_LABEL_COUNT > 0 static u8_t va_add(u8_t *label_uuid, u16_t *addr) { - struct label *free_slot = NULL; - int i; + struct label *free_slot = NULL; + int i; - for (i = 0; i < ARRAY_SIZE(labels); i++) { - if (!labels[i].ref) { - free_slot = &labels[i]; - continue; - } + for (i = 0; i < ARRAY_SIZE(labels); i++) { + if (!labels[i].ref) { + free_slot = &labels[i]; + continue; + } - if (!memcmp(labels[i].uuid, label_uuid, 16)) { - *addr = labels[i].addr; - labels[i].ref++; - return STATUS_SUCCESS; - } - } + if (!memcmp(labels[i].uuid, label_uuid, 16)) { + *addr = labels[i].addr; + labels[i].ref++; + return STATUS_SUCCESS; + } + } - if (!free_slot) { - return STATUS_INSUFF_RESOURCES; - } + if (!free_slot) { + return STATUS_INSUFF_RESOURCES; + } - if (bt_mesh_virtual_addr(label_uuid, addr) < 0) { - return STATUS_UNSPECIFIED; - } + if (bt_mesh_virtual_addr(label_uuid, addr) < 0) { + return STATUS_UNSPECIFIED; + } - free_slot->ref = 1U; - free_slot->addr = *addr; - memcpy(free_slot->uuid, label_uuid, 16); + free_slot->ref = 1U; + free_slot->addr = *addr; + memcpy(free_slot->uuid, label_uuid, 16); - return STATUS_SUCCESS; + return STATUS_SUCCESS; } static u8_t va_del(u8_t *label_uuid, u16_t *addr) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(labels); i++) { - if (!memcmp(labels[i].uuid, label_uuid, 16)) { - if (addr) { - *addr = labels[i].addr; - } + for (i = 0; i < ARRAY_SIZE(labels); i++) { + if (!memcmp(labels[i].uuid, label_uuid, 16)) { + if (addr) { + *addr = labels[i].addr; + } - labels[i].ref--; - return STATUS_SUCCESS; - } - } + labels[i].ref--; + return STATUS_SUCCESS; + } + } - if (addr) { - *addr = BT_MESH_ADDR_UNASSIGNED; - } + if (addr) { + *addr = BT_MESH_ADDR_UNASSIGNED; + } - return STATUS_CANNOT_REMOVE; + return STATUS_CANNOT_REMOVE; } static size_t mod_sub_list_clear(struct bt_mesh_model *mod) { - u8_t *label_uuid; - size_t clear_count; - int i; + u8_t *label_uuid; + size_t clear_count; + int i; - /* Unref stored labels related to this model */ - for (i = 0, clear_count = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (!BT_MESH_ADDR_IS_VIRTUAL(mod->groups[i])) { - if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { - mod->groups[i] = BT_MESH_ADDR_UNASSIGNED; - clear_count++; - } + /* Unref stored labels related to this model */ + for (i = 0, clear_count = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (!BT_MESH_ADDR_IS_VIRTUAL(mod->groups[i])) { + if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { + mod->groups[i] = BT_MESH_ADDR_UNASSIGNED; + clear_count++; + } - continue; - } + continue; + } - label_uuid = bt_mesh_label_uuid_get(mod->groups[i]); + label_uuid = bt_mesh_label_uuid_get(mod->groups[i]); - mod->groups[i] = BT_MESH_ADDR_UNASSIGNED; - clear_count++; + mod->groups[i] = BT_MESH_ADDR_UNASSIGNED; + clear_count++; - if (label_uuid) { - va_del(label_uuid, NULL); - } else { - BT_ERR("Label UUID not found"); - } - } + if (label_uuid) { + va_del(label_uuid, NULL); + } else { + BT_ERR("Label UUID not found"); + } + } - return clear_count; + return clear_count; } static void mod_pub_va_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u8_t retransmit, status, pub_ttl, pub_period, cred_flag; - u16_t elem_addr, pub_addr, pub_app_idx; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *label_uuid; - u8_t *mod_id; - bool vnd; + u8_t retransmit, status, pub_ttl, pub_period, cred_flag; + u16_t elem_addr, pub_addr, pub_app_idx; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *label_uuid; + u8_t *mod_id; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - label_uuid = net_buf_simple_pull_mem(buf, 16); - pub_app_idx = net_buf_simple_pull_le16(buf); - cred_flag = ((pub_app_idx >> 12) & BIT_MASK(1)); - pub_app_idx &= BIT_MASK(12); - pub_ttl = net_buf_simple_pull_u8(buf); - if (pub_ttl > BT_MESH_TTL_MAX && pub_ttl != BT_MESH_TTL_DEFAULT) { - BT_ERR("Invalid TTL value 0x%02x", pub_ttl); - return; - } + label_uuid = net_buf_simple_pull_mem(buf, 16); + pub_app_idx = net_buf_simple_pull_le16(buf); + cred_flag = ((pub_app_idx >> 12) & BIT_MASK(1)); + pub_app_idx &= BIT_MASK(12); + pub_ttl = net_buf_simple_pull_u8(buf); + if (pub_ttl > BT_MESH_TTL_MAX && pub_ttl != BT_MESH_TTL_DEFAULT) { + BT_ERR("Invalid TTL value 0x%02x", pub_ttl); + return; + } - pub_period = net_buf_simple_pull_u8(buf); - retransmit = net_buf_simple_pull_u8(buf); - mod_id = buf->data; + pub_period = net_buf_simple_pull_u8(buf); + retransmit = net_buf_simple_pull_u8(buf); + mod_id = buf->data; - BT_DBG("elem_addr 0x%04x cred_flag %u", elem_addr, cred_flag); - BT_DBG("pub_app_idx 0x%03x, pub_ttl %u pub_period 0x%02x", - pub_app_idx, pub_ttl, pub_period); - BT_DBG("retransmit 0x%02x (count %u interval %ums)", retransmit, - BT_MESH_PUB_TRANSMIT_COUNT(retransmit), - BT_MESH_PUB_TRANSMIT_INT(retransmit)); + BT_DBG("elem_addr 0x%04x cred_flag %u", elem_addr, cred_flag); + BT_DBG("pub_app_idx 0x%03x, pub_ttl %u pub_period 0x%02x", + pub_app_idx, pub_ttl, pub_period); + BT_DBG("retransmit 0x%02x (count %u interval %ums)", retransmit, + BT_MESH_PUB_TRANSMIT_COUNT(retransmit), + BT_MESH_PUB_TRANSMIT_INT(retransmit)); - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - pub_addr = 0U; - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + pub_addr = 0U; + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - pub_addr = 0U; - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + pub_addr = 0U; + status = STATUS_INVALID_MODEL; + goto send_status; + } #if !defined(BFLB_BLE_MESH_PATCH_MOD_PUB_VA_SET) - status = va_add(label_uuid, &pub_addr); - if (status == STATUS_SUCCESS) { - status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, - pub_ttl, pub_period, retransmit, true); - } + status = va_add(label_uuid, &pub_addr); + if (status == STATUS_SUCCESS) { + status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, + pub_ttl, pub_period, retransmit, true); + } #else - if (bt_mesh_virtual_addr(label_uuid, &pub_addr) < 0) { - pub_addr = 0U; - status = STATUS_UNSPECIFIED; - goto send_status; - } - - status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, - pub_ttl, pub_period, retransmit, true); - if (status == STATUS_SUCCESS) { - status = va_add(label_uuid, &pub_addr); - } + if (bt_mesh_virtual_addr(label_uuid, &pub_addr) < 0) { + pub_addr = 0U; + status = STATUS_UNSPECIFIED; + goto send_status; + } + + status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, + pub_ttl, pub_period, retransmit, true); + if (status == STATUS_SUCCESS) { + status = va_add(label_uuid, &pub_addr); + } #endif send_status: - send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, - status, mod_id); + send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, + status, mod_id); } #else static size_t mod_sub_list_clear(struct bt_mesh_model *mod) { - size_t clear_count; - int i; + size_t clear_count; + int i; - /* Unref stored labels related to this model */ - for (i = 0, clear_count = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { - mod->groups[i] = BT_MESH_ADDR_UNASSIGNED; - clear_count++; - } - } + /* Unref stored labels related to this model */ + for (i = 0, clear_count = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { + mod->groups[i] = BT_MESH_ADDR_UNASSIGNED; + clear_count++; + } + } - return clear_count; + return clear_count; } static void mod_pub_va_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u8_t *mod_id, status; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u16_t elem_addr, pub_addr = 0U; - bool vnd; + u8_t *mod_id, status; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u16_t elem_addr, pub_addr = 0U; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - net_buf_simple_pull(buf, 16); - mod_id = net_buf_simple_pull(buf, 4); + net_buf_simple_pull(buf, 16); + mod_id = net_buf_simple_pull(buf, 4); - BT_DBG("elem_addr 0x%04x", elem_addr); + BT_DBG("elem_addr 0x%04x", elem_addr); - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - if (!mod->pub) { - status = STATUS_NVAL_PUB_PARAM; - goto send_status; - } + if (!mod->pub) { + status = STATUS_NVAL_PUB_PARAM; + goto send_status; + } - pub_addr = mod->pub->addr; - status = STATUS_INSUFF_RESOURCES; + pub_addr = mod->pub->addr; + status = STATUS_INSUFF_RESOURCES; send_status: - send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, - status, mod_id); + send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, + status, mod_id); } #endif /* CONFIG_BT_MESH_LABEL_COUNT > 0 */ static void send_mod_sub_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, u8_t status, - u16_t elem_addr, u16_t sub_addr, u8_t *mod_id, - bool vnd) + struct bt_mesh_msg_ctx *ctx, u8_t status, + u16_t elem_addr, u16_t sub_addr, u8_t *mod_id, + bool vnd) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); - BT_DBG("status 0x%02x elem_addr 0x%04x sub_addr 0x%04x", status, - elem_addr, sub_addr); + BT_DBG("status 0x%02x elem_addr 0x%04x sub_addr 0x%04x", status, + elem_addr, sub_addr); - bt_mesh_model_msg_init(&msg, OP_MOD_SUB_STATUS); + bt_mesh_model_msg_init(&msg, OP_MOD_SUB_STATUS); - net_buf_simple_add_u8(&msg, status); - net_buf_simple_add_le16(&msg, elem_addr); - net_buf_simple_add_le16(&msg, sub_addr); + net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_le16(&msg, sub_addr); - if (vnd) { - memcpy(net_buf_simple_add(&msg, 4), mod_id, 4); - } else { - memcpy(net_buf_simple_add(&msg, 2), mod_id, 2); - } + if (vnd) { + memcpy(net_buf_simple_add(&msg, 4), mod_id, 4); + } else { + memcpy(net_buf_simple_add(&msg, 2), mod_id, 2); + } - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Model Subscription Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Model Subscription Status"); + } } static void mod_sub_add(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, sub_addr; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id; - u8_t status; - bool vnd; - int i; + u16_t elem_addr, sub_addr; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id; + u8_t status; + bool vnd; + int i; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - sub_addr = net_buf_simple_pull_le16(buf); + sub_addr = net_buf_simple_pull_le16(buf); - BT_DBG("elem_addr 0x%04x, sub_addr 0x%04x", elem_addr, sub_addr); + BT_DBG("elem_addr 0x%04x, sub_addr 0x%04x", elem_addr, sub_addr); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) { - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) { + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - if (bt_mesh_model_find_group(mod, sub_addr)) { - /* Tried to add existing subscription */ - BT_DBG("found existing subscription"); - status = STATUS_SUCCESS; - goto send_status; - } + if (bt_mesh_model_find_group(mod, sub_addr)) { + /* Tried to add existing subscription */ + BT_DBG("found existing subscription"); + status = STATUS_SUCCESS; + goto send_status; + } - for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (mod->groups[i] == BT_MESH_ADDR_UNASSIGNED) { - mod->groups[i] = sub_addr; - break; - } - } + for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (mod->groups[i] == BT_MESH_ADDR_UNASSIGNED) { + mod->groups[i] = sub_addr; + break; + } + } - if (i == ARRAY_SIZE(mod->groups)) { - status = STATUS_INSUFF_RESOURCES; - } else { - status = STATUS_SUCCESS; + if (i == ARRAY_SIZE(mod->groups)) { + status = STATUS_INSUFF_RESOURCES; + } else { + status = STATUS_SUCCESS; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_sub(mod); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_sub(mod); + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_add(sub_addr); - } - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_add(sub_addr); + } + } send_status: - send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, - mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, + mod_id, vnd); } static void mod_sub_del(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, sub_addr; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id; - u16_t *match; - u8_t status; - bool vnd; + u16_t elem_addr, sub_addr; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id; + u16_t *match; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - sub_addr = net_buf_simple_pull_le16(buf); + sub_addr = net_buf_simple_pull_le16(buf); - BT_DBG("elem_addr 0x%04x sub_addr 0x%04x", elem_addr, sub_addr); + BT_DBG("elem_addr 0x%04x sub_addr 0x%04x", elem_addr, sub_addr); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) { - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) { + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - /* An attempt to remove a non-existing address shall be treated - * as a success. - */ - status = STATUS_SUCCESS; + /* An attempt to remove a non-existing address shall be treated + * as a success. + */ + status = STATUS_SUCCESS; - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_del(&sub_addr, 1); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_del(&sub_addr, 1); + } - match = bt_mesh_model_find_group(mod, sub_addr); - if (match) { - *match = BT_MESH_ADDR_UNASSIGNED; + match = bt_mesh_model_find_group(mod, sub_addr); + if (match) { + *match = BT_MESH_ADDR_UNASSIGNED; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_sub(mod); - } - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_sub(mod); + } + } send_status: - send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, - mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, + mod_id, vnd); } static void mod_sub_overwrite(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, sub_addr; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id; - u8_t status; - bool vnd; + u16_t elem_addr, sub_addr; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - sub_addr = net_buf_simple_pull_le16(buf); + sub_addr = net_buf_simple_pull_le16(buf); - BT_DBG("elem_addr 0x%04x sub_addr 0x%04x", elem_addr, sub_addr); + BT_DBG("elem_addr 0x%04x sub_addr 0x%04x", elem_addr, sub_addr); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) { - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) { + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups)); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups)); + } - mod_sub_list_clear(mod); + mod_sub_list_clear(mod); - if (ARRAY_SIZE(mod->groups) > 0) { - mod->groups[0] = sub_addr; - status = STATUS_SUCCESS; + if (ARRAY_SIZE(mod->groups) > 0) { + mod->groups[0] = sub_addr; + status = STATUS_SUCCESS; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_sub(mod); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_sub(mod); + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_add(sub_addr); - } - } else { - status = STATUS_INSUFF_RESOURCES; - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_add(sub_addr); + } + } else { + status = STATUS_INSUFF_RESOURCES; + } send_status: - send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, - mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, + mod_id, vnd); } static void mod_sub_del_all(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u16_t elem_addr; - u8_t *mod_id; - u8_t status; - bool vnd; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u16_t elem_addr; + u8_t *mod_id; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - BT_DBG("elem_addr 0x%04x", elem_addr); + BT_DBG("elem_addr 0x%04x", elem_addr); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups)); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups)); + } - mod_sub_list_clear(mod); + mod_sub_list_clear(mod); - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_sub(mod); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_sub(mod); + } - status = STATUS_SUCCESS; + status = STATUS_SUCCESS; send_status: - send_mod_sub_status(model, ctx, status, elem_addr, - BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, + BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); } static void mod_sub_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4 + - CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2); - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u16_t addr, id; - int i; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4 + + CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2); + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u16_t addr, id; + int i; - addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(addr)) { - BT_WARN("Prohibited element address"); - return; - } + addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(addr)) { + BT_WARN("Prohibited element address"); + return; + } - id = net_buf_simple_pull_le16(buf); + id = net_buf_simple_pull_le16(buf); - BT_DBG("addr 0x%04x id 0x%04x", addr, id); + BT_DBG("addr 0x%04x id 0x%04x", addr, id); - bt_mesh_model_msg_init(&msg, OP_MOD_SUB_LIST); + bt_mesh_model_msg_init(&msg, OP_MOD_SUB_LIST); - elem = bt_mesh_elem_find(addr); - if (!elem) { - net_buf_simple_add_u8(&msg, STATUS_INVALID_ADDRESS); - net_buf_simple_add_le16(&msg, addr); - net_buf_simple_add_le16(&msg, id); - goto send_list; - } + elem = bt_mesh_elem_find(addr); + if (!elem) { + net_buf_simple_add_u8(&msg, STATUS_INVALID_ADDRESS); + net_buf_simple_add_le16(&msg, addr); + net_buf_simple_add_le16(&msg, id); + goto send_list; + } - mod = bt_mesh_model_find(elem, id); - if (!mod) { - net_buf_simple_add_u8(&msg, STATUS_INVALID_MODEL); - net_buf_simple_add_le16(&msg, addr); - net_buf_simple_add_le16(&msg, id); - goto send_list; - } + mod = bt_mesh_model_find(elem, id); + if (!mod) { + net_buf_simple_add_u8(&msg, STATUS_INVALID_MODEL); + net_buf_simple_add_le16(&msg, addr); + net_buf_simple_add_le16(&msg, id); + goto send_list; + } - net_buf_simple_add_u8(&msg, STATUS_SUCCESS); + net_buf_simple_add_u8(&msg, STATUS_SUCCESS); - net_buf_simple_add_le16(&msg, addr); - net_buf_simple_add_le16(&msg, id); + net_buf_simple_add_le16(&msg, addr); + net_buf_simple_add_le16(&msg, id); - for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { - net_buf_simple_add_le16(&msg, mod->groups[i]); - } - } + for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { + net_buf_simple_add_le16(&msg, mod->groups[i]); + } + } send_list: - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Model Subscription List"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Model Subscription List"); + } } static void mod_sub_get_vnd(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 7 + 4 + - CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2); - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u16_t company, addr, id; - int i; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 7 + 4 + + CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2); + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u16_t company, addr, id; + int i; - addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(addr)) { - BT_WARN("Prohibited element address"); - return; - } + addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(addr)) { + BT_WARN("Prohibited element address"); + return; + } - company = net_buf_simple_pull_le16(buf); - id = net_buf_simple_pull_le16(buf); + company = net_buf_simple_pull_le16(buf); + id = net_buf_simple_pull_le16(buf); - BT_DBG("addr 0x%04x company 0x%04x id 0x%04x", addr, company, id); + BT_DBG("addr 0x%04x company 0x%04x id 0x%04x", addr, company, id); - bt_mesh_model_msg_init(&msg, OP_MOD_SUB_LIST_VND); + bt_mesh_model_msg_init(&msg, OP_MOD_SUB_LIST_VND); - elem = bt_mesh_elem_find(addr); - if (!elem) { - net_buf_simple_add_u8(&msg, STATUS_INVALID_ADDRESS); - net_buf_simple_add_le16(&msg, addr); - net_buf_simple_add_le16(&msg, company); - net_buf_simple_add_le16(&msg, id); - goto send_list; - } + elem = bt_mesh_elem_find(addr); + if (!elem) { + net_buf_simple_add_u8(&msg, STATUS_INVALID_ADDRESS); + net_buf_simple_add_le16(&msg, addr); + net_buf_simple_add_le16(&msg, company); + net_buf_simple_add_le16(&msg, id); + goto send_list; + } - mod = bt_mesh_model_find_vnd(elem, company, id); - if (!mod) { - net_buf_simple_add_u8(&msg, STATUS_INVALID_MODEL); - net_buf_simple_add_le16(&msg, addr); - net_buf_simple_add_le16(&msg, company); - net_buf_simple_add_le16(&msg, id); - goto send_list; - } + mod = bt_mesh_model_find_vnd(elem, company, id); + if (!mod) { + net_buf_simple_add_u8(&msg, STATUS_INVALID_MODEL); + net_buf_simple_add_le16(&msg, addr); + net_buf_simple_add_le16(&msg, company); + net_buf_simple_add_le16(&msg, id); + goto send_list; + } - net_buf_simple_add_u8(&msg, STATUS_SUCCESS); + net_buf_simple_add_u8(&msg, STATUS_SUCCESS); - net_buf_simple_add_le16(&msg, addr); - net_buf_simple_add_le16(&msg, company); - net_buf_simple_add_le16(&msg, id); + net_buf_simple_add_le16(&msg, addr); + net_buf_simple_add_le16(&msg, company); + net_buf_simple_add_le16(&msg, id); - for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { - net_buf_simple_add_le16(&msg, mod->groups[i]); - } - } + for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { + net_buf_simple_add_le16(&msg, mod->groups[i]); + } + } send_list: - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Vendor Model Subscription List"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Vendor Model Subscription List"); + } } #if CONFIG_BT_MESH_LABEL_COUNT > 0 static void mod_sub_va_add(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, sub_addr; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *label_uuid; - u8_t *mod_id; - u8_t status; - bool vnd; - int i; + u16_t elem_addr, sub_addr; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *label_uuid; + u8_t *mod_id; + u8_t status; + bool vnd; + int i; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - label_uuid = net_buf_simple_pull_mem(buf, 16); + label_uuid = net_buf_simple_pull_mem(buf, 16); - BT_DBG("elem_addr 0x%04x", elem_addr); + BT_DBG("elem_addr 0x%04x", elem_addr); - mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - sub_addr = BT_MESH_ADDR_UNASSIGNED; - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + mod_id = buf->data; + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + sub_addr = BT_MESH_ADDR_UNASSIGNED; + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - sub_addr = BT_MESH_ADDR_UNASSIGNED; - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + sub_addr = BT_MESH_ADDR_UNASSIGNED; + status = STATUS_INVALID_MODEL; + goto send_status; + } - status = va_add(label_uuid, &sub_addr); - if (status != STATUS_SUCCESS) { - goto send_status; - } + status = va_add(label_uuid, &sub_addr); + if (status != STATUS_SUCCESS) { + goto send_status; + } - if (bt_mesh_model_find_group(mod, sub_addr)) { - /* Tried to add existing subscription */ - status = STATUS_SUCCESS; - goto send_status; - } + if (bt_mesh_model_find_group(mod, sub_addr)) { + /* Tried to add existing subscription */ + status = STATUS_SUCCESS; + goto send_status; + } - for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (mod->groups[i] == BT_MESH_ADDR_UNASSIGNED) { - mod->groups[i] = sub_addr; - break; - } - } + for (i = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (mod->groups[i] == BT_MESH_ADDR_UNASSIGNED) { + mod->groups[i] = sub_addr; + break; + } + } - if (i == ARRAY_SIZE(mod->groups)) { - status = STATUS_INSUFF_RESOURCES; - } else { - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_add(sub_addr); - } + if (i == ARRAY_SIZE(mod->groups)) { + status = STATUS_INSUFF_RESOURCES; + } else { + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_add(sub_addr); + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_sub(mod); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_sub(mod); + } - status = STATUS_SUCCESS; - } + status = STATUS_SUCCESS; + } send_status: - send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, - mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, + mod_id, vnd); } static void mod_sub_va_del(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, sub_addr; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *label_uuid; - u8_t *mod_id; - u16_t *match; - u8_t status; - bool vnd; + u16_t elem_addr, sub_addr; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *label_uuid; + u8_t *mod_id; + u16_t *match; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - label_uuid = net_buf_simple_pull_mem(buf, 16); + label_uuid = net_buf_simple_pull_mem(buf, 16); - BT_DBG("elem_addr 0x%04x", elem_addr); + BT_DBG("elem_addr 0x%04x", elem_addr); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - sub_addr = BT_MESH_ADDR_UNASSIGNED; - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + sub_addr = BT_MESH_ADDR_UNASSIGNED; + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - sub_addr = BT_MESH_ADDR_UNASSIGNED; - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + sub_addr = BT_MESH_ADDR_UNASSIGNED; + status = STATUS_INVALID_MODEL; + goto send_status; + } - status = va_del(label_uuid, &sub_addr); - if (sub_addr == BT_MESH_ADDR_UNASSIGNED) { - goto send_status; - } + status = va_del(label_uuid, &sub_addr); + if (sub_addr == BT_MESH_ADDR_UNASSIGNED) { + goto send_status; + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_del(&sub_addr, 1); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_del(&sub_addr, 1); + } - match = bt_mesh_model_find_group(mod, sub_addr); - if (match) { - *match = BT_MESH_ADDR_UNASSIGNED; + match = bt_mesh_model_find_group(mod, sub_addr); + if (match) { + *match = BT_MESH_ADDR_UNASSIGNED; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_sub(mod); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_sub(mod); + } - status = STATUS_SUCCESS; - } else { - status = STATUS_CANNOT_REMOVE; - } + status = STATUS_SUCCESS; + } else { + status = STATUS_CANNOT_REMOVE; + } send_status: - send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, - mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, + mod_id, vnd); } static void mod_sub_va_overwrite(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u16_t elem_addr, sub_addr = BT_MESH_ADDR_UNASSIGNED; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *label_uuid; - u8_t *mod_id; - u8_t status; - bool vnd; + u16_t elem_addr, sub_addr = BT_MESH_ADDR_UNASSIGNED; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *label_uuid; + u8_t *mod_id; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - label_uuid = net_buf_simple_pull_mem(buf, 16); + label_uuid = net_buf_simple_pull_mem(buf, 16); - BT_DBG("elem_addr 0x%04x", elem_addr); + BT_DBG("elem_addr 0x%04x", elem_addr); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups)); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups)); + } - mod_sub_list_clear(mod); + mod_sub_list_clear(mod); - if (ARRAY_SIZE(mod->groups) > 0) { - status = va_add(label_uuid, &sub_addr); - if (status == STATUS_SUCCESS) { - mod->groups[0] = sub_addr; + if (ARRAY_SIZE(mod->groups) > 0) { + status = va_add(label_uuid, &sub_addr); + if (status == STATUS_SUCCESS) { + mod->groups[0] = sub_addr; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_mod_sub(mod); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_mod_sub(mod); + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_group_add(sub_addr); - } - } - } else { - status = STATUS_INSUFF_RESOURCES; - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_group_add(sub_addr); + } + } + } else { + status = STATUS_INSUFF_RESOURCES; + } send_status: - send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, - mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, + mod_id, vnd); } #else static void mod_sub_va_add(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u16_t elem_addr; - u8_t *mod_id; - u8_t status; - bool vnd; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u16_t elem_addr; + u8_t *mod_id; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - net_buf_simple_pull(buf, 16); + net_buf_simple_pull(buf, 16); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - status = STATUS_INSUFF_RESOURCES; + status = STATUS_INSUFF_RESOURCES; send_status: - send_mod_sub_status(model, ctx, status, elem_addr, - BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, + BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); } static void mod_sub_va_del(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_elem *elem; - u16_t elem_addr; - u8_t *mod_id; - u8_t status; - bool vnd; + struct bt_mesh_elem *elem; + u16_t elem_addr; + u8_t *mod_id; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - net_buf_simple_pull(buf, 16); + net_buf_simple_pull(buf, 16); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - if (!get_model(elem, buf, &vnd)) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + if (!get_model(elem, buf, &vnd)) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - status = STATUS_INSUFF_RESOURCES; + status = STATUS_INSUFF_RESOURCES; send_status: - send_mod_sub_status(model, ctx, status, elem_addr, - BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, + BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); } static void mod_sub_va_overwrite(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_elem *elem; - u16_t elem_addr; - u8_t *mod_id; - u8_t status; - bool vnd; + struct bt_mesh_elem *elem; + u16_t elem_addr; + u8_t *mod_id; + u8_t status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - net_buf_simple_pull(buf, 18); + net_buf_simple_pull(buf, 18); - mod_id = buf->data; + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - if (!get_model(elem, buf, &vnd)) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + if (!get_model(elem, buf, &vnd)) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - status = STATUS_INSUFF_RESOURCES; + status = STATUS_INSUFF_RESOURCES; send_status: - send_mod_sub_status(model, ctx, status, elem_addr, - BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); + send_mod_sub_status(model, ctx, status, elem_addr, + BT_MESH_ADDR_UNASSIGNED, mod_id, vnd); } #endif /* CONFIG_BT_MESH_LABEL_COUNT > 0 */ static void send_net_key_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - u16_t idx, u8_t status) + struct bt_mesh_msg_ctx *ctx, + u16_t idx, u8_t status) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4); - bt_mesh_model_msg_init(&msg, OP_NET_KEY_STATUS); + bt_mesh_model_msg_init(&msg, OP_NET_KEY_STATUS); - net_buf_simple_add_u8(&msg, status); - net_buf_simple_add_le16(&msg, idx); + net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_le16(&msg, idx); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send NetKey Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send NetKey Status"); + } } static void net_key_add(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_subnet *sub; - u16_t idx; - int err; + struct bt_mesh_subnet *sub; + u16_t idx; + int err; - idx = net_buf_simple_pull_le16(buf); - if (idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", idx); - return; - } + idx = net_buf_simple_pull_le16(buf); + if (idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", idx); + return; + } - BT_DBG("idx 0x%04x", idx); + BT_DBG("idx 0x%04x", idx); - sub = bt_mesh_subnet_get(idx); - if (!sub) { - int i; + sub = bt_mesh_subnet_get(idx); + if (!sub) { + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - if (bt_mesh.sub[i].net_idx == BT_MESH_KEY_UNUSED) { - sub = &bt_mesh.sub[i]; - break; - } - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + if (bt_mesh.sub[i].net_idx == BT_MESH_KEY_UNUSED) { + sub = &bt_mesh.sub[i]; + break; + } + } - if (!sub) { - send_net_key_status(model, ctx, idx, - STATUS_INSUFF_RESOURCES); - return; - } - } + if (!sub) { + send_net_key_status(model, ctx, idx, + STATUS_INSUFF_RESOURCES); + return; + } + } - /* Check for already existing subnet */ - if (sub->net_idx == idx) { - u8_t status; + /* Check for already existing subnet */ + if (sub->net_idx == idx) { + u8_t status; - if (memcmp(buf->data, sub->keys[0].net, 16)) { - status = STATUS_IDX_ALREADY_STORED; - } else { - status = STATUS_SUCCESS; - } + if (memcmp(buf->data, sub->keys[0].net, 16)) { + status = STATUS_IDX_ALREADY_STORED; + } else { + status = STATUS_SUCCESS; + } - send_net_key_status(model, ctx, idx, status); - return; - } + send_net_key_status(model, ctx, idx, status); + return; + } - err = bt_mesh_net_keys_create(&sub->keys[0], buf->data); - if (err) { - send_net_key_status(model, ctx, idx, STATUS_UNSPECIFIED); - return; - } + err = bt_mesh_net_keys_create(&sub->keys[0], buf->data); + if (err) { + send_net_key_status(model, ctx, idx, STATUS_UNSPECIFIED); + return; + } - sub->net_idx = idx; + sub->net_idx = idx; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - BT_DBG("Storing NetKey persistently"); - bt_mesh_store_subnet(sub); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + BT_DBG("Storing NetKey persistently"); + bt_mesh_store_subnet(sub); + } - /* Make sure we have valid beacon data to be sent */ - bt_mesh_net_beacon_update(sub); + /* Make sure we have valid beacon data to be sent */ + bt_mesh_net_beacon_update(sub); - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { - sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; - bt_mesh_proxy_beacon_send(sub); - bt_mesh_adv_update(); - } else { - sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED; - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { + sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; + bt_mesh_proxy_beacon_send(sub); + bt_mesh_adv_update(); + } else { + sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED; + } - send_net_key_status(model, ctx, idx, STATUS_SUCCESS); + send_net_key_status(model, ctx, idx, STATUS_SUCCESS); } static void net_key_update(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_subnet *sub; - u16_t idx; - int err; + struct bt_mesh_subnet *sub; + u16_t idx; + int err; - idx = net_buf_simple_pull_le16(buf); - if (idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", idx); - return; - } + idx = net_buf_simple_pull_le16(buf); + if (idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", idx); + return; + } - BT_DBG("idx 0x%04x", idx); + BT_DBG("idx 0x%04x", idx); - sub = bt_mesh_subnet_get(idx); - if (!sub) { - send_net_key_status(model, ctx, idx, STATUS_INVALID_NETKEY); - return; - } + sub = bt_mesh_subnet_get(idx); + if (!sub) { + send_net_key_status(model, ctx, idx, STATUS_INVALID_NETKEY); + return; + } - /* The node shall successfully process a NetKey Update message on a - * valid NetKeyIndex when the NetKey value is different and the Key - * Refresh procedure has not been started, or when the NetKey value is - * the same in Phase 1. The NetKey Update message shall generate an - * error when the node is in Phase 2, or Phase 3. - */ - switch (sub->kr_phase) { - case BT_MESH_KR_NORMAL: - if (!memcmp(buf->data, sub->keys[0].net, 16)) { - return; - } - break; - case BT_MESH_KR_PHASE_1: - if (!memcmp(buf->data, sub->keys[1].net, 16)) { - send_net_key_status(model, ctx, idx, STATUS_SUCCESS); - return; - } - /* fall through */ - __attribute__((fallthrough)); - case BT_MESH_KR_PHASE_2: - case BT_MESH_KR_PHASE_3: - send_net_key_status(model, ctx, idx, STATUS_CANNOT_UPDATE); - return; - } + /* The node shall successfully process a NetKey Update message on a + * valid NetKeyIndex when the NetKey value is different and the Key + * Refresh procedure has not been started, or when the NetKey value is + * the same in Phase 1. The NetKey Update message shall generate an + * error when the node is in Phase 2, or Phase 3. + */ + switch (sub->kr_phase) { + case BT_MESH_KR_NORMAL: + if (!memcmp(buf->data, sub->keys[0].net, 16)) { + return; + } + break; + case BT_MESH_KR_PHASE_1: + if (!memcmp(buf->data, sub->keys[1].net, 16)) { + send_net_key_status(model, ctx, idx, STATUS_SUCCESS); + return; + } + /* fall through */ + __attribute__((fallthrough)); + case BT_MESH_KR_PHASE_2: + case BT_MESH_KR_PHASE_3: + send_net_key_status(model, ctx, idx, STATUS_CANNOT_UPDATE); + return; + } - err = bt_mesh_net_keys_create(&sub->keys[1], buf->data); - if (!err && (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || - IS_ENABLED(CONFIG_BT_MESH_FRIEND))) { - err = friend_cred_update(sub); - } + err = bt_mesh_net_keys_create(&sub->keys[1], buf->data); + if (!err && (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || + IS_ENABLED(CONFIG_BT_MESH_FRIEND))) { + err = friend_cred_update(sub); + } - if (err) { - send_net_key_status(model, ctx, idx, STATUS_UNSPECIFIED); - return; - } + if (err) { + send_net_key_status(model, ctx, idx, STATUS_UNSPECIFIED); + return; + } #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Key Refresh: Normal -> Phase 1"); + BT_PTS("[PTS] Key Refresh: Normal -> Phase 1"); #endif - sub->kr_phase = BT_MESH_KR_PHASE_1; + sub->kr_phase = BT_MESH_KR_PHASE_1; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - BT_DBG("Storing NetKey persistently"); - bt_mesh_store_subnet(sub); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + BT_DBG("Storing NetKey persistently"); + bt_mesh_store_subnet(sub); + } - bt_mesh_net_beacon_update(sub); + bt_mesh_net_beacon_update(sub); - send_net_key_status(model, ctx, idx, STATUS_SUCCESS); + send_net_key_status(model, ctx, idx, STATUS_SUCCESS); } static void hb_pub_disable(struct bt_mesh_cfg_srv *cfg) { - BT_DBG(""); + BT_DBG(""); - cfg->hb_pub.dst = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_pub.count = 0U; - cfg->hb_pub.ttl = 0U; - cfg->hb_pub.period = 0U; + cfg->hb_pub.dst = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_pub.count = 0U; + cfg->hb_pub.ttl = 0U; + cfg->hb_pub.period = 0U; - k_delayed_work_cancel(&cfg->hb_pub.timer); + k_delayed_work_cancel(&cfg->hb_pub.timer); } static void net_key_del(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_subnet *sub; - u16_t del_idx; - u8_t status; + struct bt_mesh_subnet *sub; + u16_t del_idx; + u8_t status; - del_idx = net_buf_simple_pull_le16(buf); - if (del_idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", del_idx); - return; - } + del_idx = net_buf_simple_pull_le16(buf); + if (del_idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", del_idx); + return; + } - BT_DBG("idx 0x%04x", del_idx); + BT_DBG("idx 0x%04x", del_idx); - sub = bt_mesh_subnet_get(del_idx); - if (!sub) { - /* This could be a retry of a previous attempt that had its - * response lost, so pretend that it was a success. - */ - status = STATUS_SUCCESS; - goto send_status; - } + sub = bt_mesh_subnet_get(del_idx); + if (!sub) { + /* This could be a retry of a previous attempt that had its + * response lost, so pretend that it was a success. + */ + status = STATUS_SUCCESS; + goto send_status; + } - /* The key that the message was encrypted with cannot be removed. - * The NetKey List must contain a minimum of one NetKey. - */ - if (ctx->net_idx == del_idx) { - status = STATUS_CANNOT_REMOVE; - goto send_status; - } + /* The key that the message was encrypted with cannot be removed. + * The NetKey List must contain a minimum of one NetKey. + */ + if (ctx->net_idx == del_idx) { + status = STATUS_CANNOT_REMOVE; + goto send_status; + } - bt_mesh_subnet_del(sub, true); - status = STATUS_SUCCESS; + bt_mesh_subnet_del(sub, true); + status = STATUS_SUCCESS; send_status: - send_net_key_status(model, ctx, del_idx, status); + send_net_key_status(model, ctx, del_idx, status); } static void net_key_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, - 2 + 4 + IDX_LEN(CONFIG_BT_MESH_SUBNET_COUNT)); - u16_t prev, i; + NET_BUF_SIMPLE_DEFINE(msg, + 2 + 4 + IDX_LEN(CONFIG_BT_MESH_SUBNET_COUNT)); + u16_t prev, i; - bt_mesh_model_msg_init(&msg, OP_NET_KEY_LIST); + bt_mesh_model_msg_init(&msg, OP_NET_KEY_LIST); - prev = BT_MESH_KEY_UNUSED; - for (i = 0U; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + prev = BT_MESH_KEY_UNUSED; + for (i = 0U; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - if (prev == BT_MESH_KEY_UNUSED) { - prev = sub->net_idx; - continue; - } + if (prev == BT_MESH_KEY_UNUSED) { + prev = sub->net_idx; + continue; + } - key_idx_pack(&msg, prev, sub->net_idx); - prev = BT_MESH_KEY_UNUSED; - } + key_idx_pack(&msg, prev, sub->net_idx); + prev = BT_MESH_KEY_UNUSED; + } - if (prev != BT_MESH_KEY_UNUSED) { - net_buf_simple_add_le16(&msg, prev); - } + if (prev != BT_MESH_KEY_UNUSED) { + net_buf_simple_add_le16(&msg, prev); + } - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send NetKey List"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send NetKey List"); + } } static void node_identity_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); - struct bt_mesh_subnet *sub; - u8_t node_id; - u16_t idx; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); + struct bt_mesh_subnet *sub; + u8_t node_id; + u16_t idx; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - idx = net_buf_simple_pull_le16(buf); - if (idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", idx); - return; - } + idx = net_buf_simple_pull_le16(buf); + if (idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", idx); + return; + } - bt_mesh_model_msg_init(&msg, OP_NODE_IDENTITY_STATUS); + bt_mesh_model_msg_init(&msg, OP_NODE_IDENTITY_STATUS); - sub = bt_mesh_subnet_get(idx); - if (!sub) { - net_buf_simple_add_u8(&msg, STATUS_INVALID_NETKEY); - node_id = 0x00; - } else { - net_buf_simple_add_u8(&msg, STATUS_SUCCESS); - node_id = sub->node_id; - } + sub = bt_mesh_subnet_get(idx); + if (!sub) { + net_buf_simple_add_u8(&msg, STATUS_INVALID_NETKEY); + node_id = 0x00; + } else { + net_buf_simple_add_u8(&msg, STATUS_SUCCESS); + node_id = sub->node_id; + } - net_buf_simple_add_le16(&msg, idx); - net_buf_simple_add_u8(&msg, node_id); + net_buf_simple_add_le16(&msg, idx); + net_buf_simple_add_u8(&msg, node_id); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Node Identity Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Node Identity Status"); + } } static void node_identity_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); - struct bt_mesh_subnet *sub; - u8_t node_id; - u16_t idx; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); + struct bt_mesh_subnet *sub; + u8_t node_id; + u16_t idx; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - idx = net_buf_simple_pull_le16(buf); - if (idx > 0xfff) { - BT_WARN("Invalid NetKeyIndex 0x%04x", idx); - return; - } + idx = net_buf_simple_pull_le16(buf); + if (idx > 0xfff) { + BT_WARN("Invalid NetKeyIndex 0x%04x", idx); + return; + } - node_id = net_buf_simple_pull_u8(buf); - if (node_id != 0x00 && node_id != 0x01) { - BT_WARN("Invalid Node ID value 0x%02x", node_id); - return; - } + node_id = net_buf_simple_pull_u8(buf); + if (node_id != 0x00 && node_id != 0x01) { + BT_WARN("Invalid Node ID value 0x%02x", node_id); + return; + } - bt_mesh_model_msg_init(&msg, OP_NODE_IDENTITY_STATUS); + bt_mesh_model_msg_init(&msg, OP_NODE_IDENTITY_STATUS); - sub = bt_mesh_subnet_get(idx); - if (!sub) { - net_buf_simple_add_u8(&msg, STATUS_INVALID_NETKEY); - net_buf_simple_add_le16(&msg, idx); - net_buf_simple_add_u8(&msg, node_id); - } else { - net_buf_simple_add_u8(&msg, STATUS_SUCCESS); - net_buf_simple_add_le16(&msg, idx); + sub = bt_mesh_subnet_get(idx); + if (!sub) { + net_buf_simple_add_u8(&msg, STATUS_INVALID_NETKEY); + net_buf_simple_add_le16(&msg, idx); + net_buf_simple_add_u8(&msg, node_id); + } else { + net_buf_simple_add_u8(&msg, STATUS_SUCCESS); + net_buf_simple_add_le16(&msg, idx); - /* Section 4.2.11.1: "When the GATT Proxy state is set to - * 0x00, the Node Identity state for all subnets shall be set - * to 0x00 and shall not be changed." - */ - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && - bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { - if (node_id) { - bt_mesh_proxy_identity_start(sub); - } else { - bt_mesh_proxy_identity_stop(sub); - } - bt_mesh_adv_update(); - } + /* Section 4.2.11.1: "When the GATT Proxy state is set to + * 0x00, the Node Identity state for all subnets shall be set + * to 0x00 and shall not be changed." + */ + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && + bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { + if (node_id) { + bt_mesh_proxy_identity_start(sub); + } else { + bt_mesh_proxy_identity_stop(sub); + } + bt_mesh_adv_update(); + } - net_buf_simple_add_u8(&msg, sub->node_id); - } + net_buf_simple_add_u8(&msg, sub->node_id); + } - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Node Identity Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Node Identity Status"); + } } static void create_mod_app_status(struct net_buf_simple *msg, - struct bt_mesh_model *mod, bool vnd, - u16_t elem_addr, u16_t app_idx, - u8_t status, u8_t *mod_id) + struct bt_mesh_model *mod, bool vnd, + u16_t elem_addr, u16_t app_idx, + u8_t status, u8_t *mod_id) { - bt_mesh_model_msg_init(msg, OP_MOD_APP_STATUS); + bt_mesh_model_msg_init(msg, OP_MOD_APP_STATUS); - net_buf_simple_add_u8(msg, status); - net_buf_simple_add_le16(msg, elem_addr); - net_buf_simple_add_le16(msg, app_idx); + net_buf_simple_add_u8(msg, status); + net_buf_simple_add_le16(msg, elem_addr); + net_buf_simple_add_le16(msg, app_idx); - if (vnd) { - memcpy(net_buf_simple_add(msg, 4), mod_id, 4); - } else { - memcpy(net_buf_simple_add(msg, 2), mod_id, 2); - } + if (vnd) { + memcpy(net_buf_simple_add(msg, 4), mod_id, 4); + } else { + memcpy(net_buf_simple_add(msg, 2), mod_id, 2); + } } static void mod_app_bind(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); - u16_t elem_addr, key_app_idx; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id, status; - bool vnd; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); + u16_t elem_addr, key_app_idx; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id, status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - key_app_idx = net_buf_simple_pull_le16(buf); - mod_id = buf->data; + key_app_idx = net_buf_simple_pull_le16(buf); + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - /* Configuration Server only allows device key based access */ - if (model == mod) { - BT_ERR("Client tried to bind AppKey to Configuration Model"); - status = STATUS_CANNOT_BIND; - goto send_status; - } + /* Configuration Server only allows device key based access */ + if (model == mod) { + BT_ERR("Client tried to bind AppKey to Configuration Model"); + status = STATUS_CANNOT_BIND; + goto send_status; + } - status = mod_bind(mod, key_app_idx); + status = mod_bind(mod, key_app_idx); #if defined (CONFIG_BT_TESTING) - if (/*IS_ENABLED(CONFIG_BT_TESTING) && */status == STATUS_SUCCESS) { - bt_test_mesh_model_bound(ctx->addr, mod, key_app_idx); - } + if (/*IS_ENABLED(CONFIG_BT_TESTING) && */status == STATUS_SUCCESS) { + bt_test_mesh_model_bound(ctx->addr, mod, key_app_idx); + } #endif - -send_status: - BT_DBG("status 0x%02x", status); - create_mod_app_status(&msg, mod, vnd, elem_addr, key_app_idx, status, - mod_id); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Model App Bind Status response"); - } +send_status: + BT_DBG("status 0x%02x", status); + create_mod_app_status(&msg, mod, vnd, elem_addr, key_app_idx, status, + mod_id); + + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Model App Bind Status response"); + } } static void mod_app_unbind(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); - u16_t elem_addr, key_app_idx; - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id, status; - bool vnd; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); + u16_t elem_addr, key_app_idx; + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id, status; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - key_app_idx = net_buf_simple_pull_le16(buf); - mod_id = buf->data; + key_app_idx = net_buf_simple_pull_le16(buf); + mod_id = buf->data; - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_status; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_status; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_status; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_status; + } - status = mod_unbind(mod, key_app_idx, true); + status = mod_unbind(mod, key_app_idx, true); #if defined (CONFIG_BT_TESTING) - if (/*IS_ENABLED(CONFIG_BT_TESTING) && */status == STATUS_SUCCESS) { - bt_test_mesh_model_unbound(ctx->addr, mod, key_app_idx); - } + if (/*IS_ENABLED(CONFIG_BT_TESTING) && */status == STATUS_SUCCESS) { + bt_test_mesh_model_unbound(ctx->addr, mod, key_app_idx); + } #endif send_status: - BT_DBG("status 0x%02x", status); - create_mod_app_status(&msg, mod, vnd, elem_addr, key_app_idx, status, - mod_id); + BT_DBG("status 0x%02x", status); + create_mod_app_status(&msg, mod, vnd, elem_addr, key_app_idx, status, + mod_id); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Model App Unbind Status response"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Model App Unbind Status response"); + } } #define KEY_LIST_LEN (CONFIG_BT_MESH_MODEL_KEY_COUNT * 2) static void mod_app_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + KEY_LIST_LEN + 4); - struct bt_mesh_model *mod; - struct bt_mesh_elem *elem; - u8_t *mod_id, status; - u16_t elem_addr; - bool vnd; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + KEY_LIST_LEN + 4); + struct bt_mesh_model *mod; + struct bt_mesh_elem *elem; + u8_t *mod_id, status; + u16_t elem_addr; + bool vnd; - elem_addr = net_buf_simple_pull_le16(buf); - if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { - BT_WARN("Prohibited element address"); - return; - } + elem_addr = net_buf_simple_pull_le16(buf); + if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) { + BT_WARN("Prohibited element address"); + return; + } - mod_id = buf->data; + mod_id = buf->data; - BT_DBG("elem_addr 0x%04x", elem_addr); + BT_DBG("elem_addr 0x%04x", elem_addr); - elem = bt_mesh_elem_find(elem_addr); - if (!elem) { - mod = NULL; - vnd = (buf->len == 4U); - status = STATUS_INVALID_ADDRESS; - goto send_list; - } + elem = bt_mesh_elem_find(elem_addr); + if (!elem) { + mod = NULL; + vnd = (buf->len == 4U); + status = STATUS_INVALID_ADDRESS; + goto send_list; + } - mod = get_model(elem, buf, &vnd); - if (!mod) { - status = STATUS_INVALID_MODEL; - goto send_list; - } + mod = get_model(elem, buf, &vnd); + if (!mod) { + status = STATUS_INVALID_MODEL; + goto send_list; + } - status = STATUS_SUCCESS; + status = STATUS_SUCCESS; send_list: - if (vnd) { - bt_mesh_model_msg_init(&msg, OP_VND_MOD_APP_LIST); - } else { - bt_mesh_model_msg_init(&msg, OP_SIG_MOD_APP_LIST); - } + if (vnd) { + bt_mesh_model_msg_init(&msg, OP_VND_MOD_APP_LIST); + } else { + bt_mesh_model_msg_init(&msg, OP_SIG_MOD_APP_LIST); + } - net_buf_simple_add_u8(&msg, status); - net_buf_simple_add_le16(&msg, elem_addr); + net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_le16(&msg, elem_addr); - if (vnd) { - net_buf_simple_add_mem(&msg, mod_id, 4); - } else { - net_buf_simple_add_mem(&msg, mod_id, 2); - } + if (vnd) { + net_buf_simple_add_mem(&msg, mod_id, 4); + } else { + net_buf_simple_add_mem(&msg, mod_id, 2); + } - if (mod) { - int i; + if (mod) { + int i; - for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { - if (mod->keys[i] != BT_MESH_KEY_UNUSED) { - net_buf_simple_add_le16(&msg, mod->keys[i]); - } - } - } + for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { + if (mod->keys[i] != BT_MESH_KEY_UNUSED) { + net_buf_simple_add_le16(&msg, mod->keys[i]); + } + } + } - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Model Application List message"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Model Application List message"); + } } static void node_reset(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - bt_mesh_model_msg_init(&msg, OP_NODE_RESET_STATUS); + bt_mesh_model_msg_init(&msg, OP_NODE_RESET_STATUS); - /* Send the response first since we wont have any keys left to - * send it later. - */ - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Node Reset Status"); - } + /* Send the response first since we wont have any keys left to + * send it later. + */ + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Node Reset Status"); + } #if defined(BFLB_BLE) - /*Fix issue:for proxy node, OP_NODE_RESET_STATUS cannot be sent out because le link is disconnected + /*Fix issue:for proxy node, OP_NODE_RESET_STATUS cannot be sent out because le link is disconnected *before sending OP_NODE_RESET_STATUS. *delay the task to make node reset later to make sure OP_NODE_RESET_STATUS can be sent out. */ vTaskDelay(500); #endif - bt_mesh_reset(); + bt_mesh_reset(); } static void send_friend_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx) + struct bt_mesh_msg_ctx *ctx) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_cfg_srv *cfg = model->user_data; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_cfg_srv *cfg = model->user_data; - bt_mesh_model_msg_init(&msg, OP_FRIEND_STATUS); - net_buf_simple_add_u8(&msg, cfg->frnd); + bt_mesh_model_msg_init(&msg, OP_FRIEND_STATUS); + net_buf_simple_add_u8(&msg, cfg->frnd); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Friend Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Friend Status"); + } } static void friend_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - send_friend_status(model, ctx); + send_friend_status(model, ctx); } static void friend_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_cfg_srv *cfg = model->user_data; + struct bt_mesh_cfg_srv *cfg = model->user_data; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (buf->data[0] != 0x00 && buf->data[0] != 0x01) { - BT_WARN("Invalid Friend value 0x%02x", buf->data[0]); - return; - } + if (buf->data[0] != 0x00 && buf->data[0] != 0x01) { + BT_WARN("Invalid Friend value 0x%02x", buf->data[0]); + return; + } - if (!cfg) { - BT_WARN("No Configuration Server context available"); - goto send_status; - } + if (!cfg) { + BT_WARN("No Configuration Server context available"); + goto send_status; + } - BT_DBG("Friend 0x%02x -> 0x%02x", cfg->frnd, buf->data[0]); + BT_DBG("Friend 0x%02x -> 0x%02x", cfg->frnd, buf->data[0]); - if (cfg->frnd == buf->data[0]) { - goto send_status; - } + if (cfg->frnd == buf->data[0]) { + goto send_status; + } - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - cfg->frnd = buf->data[0]; + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + cfg->frnd = buf->data[0]; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_cfg(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_cfg(); + } - if (cfg->frnd == BT_MESH_FRIEND_DISABLED) { - bt_mesh_friend_clear_net_idx(BT_MESH_KEY_ANY); - } - } + if (cfg->frnd == BT_MESH_FRIEND_DISABLED) { + bt_mesh_friend_clear_net_idx(BT_MESH_KEY_ANY); + } + } - if (cfg->hb_pub.feat & BT_MESH_FEAT_FRIEND) { - bt_mesh_heartbeat_send(); - } + if (cfg->hb_pub.feat & BT_MESH_FEAT_FRIEND) { + bt_mesh_heartbeat_send(); + } send_status: - send_friend_status(model, ctx); + send_friend_status(model, ctx); } static void lpn_timeout_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4); - struct bt_mesh_friend *frnd; - u16_t lpn_addr; - s32_t timeout; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4); + struct bt_mesh_friend *frnd; + u16_t lpn_addr; + s32_t timeout; - lpn_addr = net_buf_simple_pull_le16(buf); + lpn_addr = net_buf_simple_pull_le16(buf); - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x lpn_addr 0x%02x", - ctx->net_idx, ctx->app_idx, ctx->addr, lpn_addr); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x lpn_addr 0x%02x", + ctx->net_idx, ctx->app_idx, ctx->addr, lpn_addr); - if (!BT_MESH_ADDR_IS_UNICAST(lpn_addr)) { - BT_WARN("Invalid LPNAddress; ignoring msg"); - return; - } + if (!BT_MESH_ADDR_IS_UNICAST(lpn_addr)) { + BT_WARN("Invalid LPNAddress; ignoring msg"); + return; + } - bt_mesh_model_msg_init(&msg, OP_LPN_TIMEOUT_STATUS); - net_buf_simple_add_le16(&msg, lpn_addr); + bt_mesh_model_msg_init(&msg, OP_LPN_TIMEOUT_STATUS); + net_buf_simple_add_le16(&msg, lpn_addr); - if (!IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - timeout = 0; - goto send_rsp; - } + if (!IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + timeout = 0; + goto send_rsp; + } - frnd = bt_mesh_friend_find(BT_MESH_KEY_ANY, lpn_addr, true, true); - if (!frnd) { - timeout = 0; - goto send_rsp; - } + frnd = bt_mesh_friend_find(BT_MESH_KEY_ANY, lpn_addr, true, true); + if (!frnd) { + timeout = 0; + goto send_rsp; + } - timeout = k_delayed_work_remaining_get(&frnd->timer) / 100; + timeout = k_delayed_work_remaining_get(&frnd->timer) / 100; send_rsp: - net_buf_simple_add_u8(&msg, timeout); - net_buf_simple_add_u8(&msg, timeout >> 8); - net_buf_simple_add_u8(&msg, timeout >> 16); + net_buf_simple_add_u8(&msg, timeout); + net_buf_simple_add_u8(&msg, timeout >> 8); + net_buf_simple_add_u8(&msg, timeout >> 16); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send LPN PollTimeout Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send LPN PollTimeout Status"); + } } static void send_krp_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - u16_t idx, u8_t phase, u8_t status) + struct bt_mesh_msg_ctx *ctx, + u16_t idx, u8_t phase, u8_t status) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4); - bt_mesh_model_msg_init(&msg, OP_KRP_STATUS); + bt_mesh_model_msg_init(&msg, OP_KRP_STATUS); - net_buf_simple_add_u8(&msg, status); - net_buf_simple_add_le16(&msg, idx); - net_buf_simple_add_u8(&msg, phase); + net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_le16(&msg, idx); + net_buf_simple_add_u8(&msg, phase); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Key Refresh State Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Key Refresh State Status"); + } } static void krp_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_subnet *sub; - u16_t idx; + struct bt_mesh_subnet *sub; + u16_t idx; - idx = net_buf_simple_pull_le16(buf); - if (idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", idx); - return; - } + idx = net_buf_simple_pull_le16(buf); + if (idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", idx); + return; + } - BT_DBG("idx 0x%04x", idx); + BT_DBG("idx 0x%04x", idx); - sub = bt_mesh_subnet_get(idx); - if (!sub) { - send_krp_status(model, ctx, idx, 0x00, STATUS_INVALID_NETKEY); - } else { - send_krp_status(model, ctx, idx, sub->kr_phase, - STATUS_SUCCESS); - } + sub = bt_mesh_subnet_get(idx); + if (!sub) { + send_krp_status(model, ctx, idx, 0x00, STATUS_INVALID_NETKEY); + } else { + send_krp_status(model, ctx, idx, sub->kr_phase, + STATUS_SUCCESS); + } } static void krp_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_subnet *sub; - u8_t phase; - u16_t idx; + struct bt_mesh_subnet *sub; + u8_t phase; + u16_t idx; - idx = net_buf_simple_pull_le16(buf); - phase = net_buf_simple_pull_u8(buf); + idx = net_buf_simple_pull_le16(buf); + phase = net_buf_simple_pull_u8(buf); - if (idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", idx); - return; - } + if (idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", idx); + return; + } - BT_DBG("idx 0x%04x transition 0x%02x", idx, phase); + BT_DBG("idx 0x%04x transition 0x%02x", idx, phase); - sub = bt_mesh_subnet_get(idx); - if (!sub) { - send_krp_status(model, ctx, idx, 0x00, STATUS_INVALID_NETKEY); - return; - } + sub = bt_mesh_subnet_get(idx); + if (!sub) { + send_krp_status(model, ctx, idx, 0x00, STATUS_INVALID_NETKEY); + return; + } - BT_DBG("%u -> %u", sub->kr_phase, phase); + BT_DBG("%u -> %u", sub->kr_phase, phase); - if (phase < BT_MESH_KR_PHASE_2 || phase > BT_MESH_KR_PHASE_3 || - (sub->kr_phase == BT_MESH_KR_NORMAL && - phase == BT_MESH_KR_PHASE_2)) { - BT_WARN("Prohibited transition %u -> %u", sub->kr_phase, phase); - return; - } + if (phase < BT_MESH_KR_PHASE_2 || phase > BT_MESH_KR_PHASE_3 || + (sub->kr_phase == BT_MESH_KR_NORMAL && + phase == BT_MESH_KR_PHASE_2)) { + BT_WARN("Prohibited transition %u -> %u", sub->kr_phase, phase); + return; + } - if (sub->kr_phase == BT_MESH_KR_PHASE_1 && - phase == BT_MESH_KR_PHASE_2) { + if (sub->kr_phase == BT_MESH_KR_PHASE_1 && + phase == BT_MESH_KR_PHASE_2) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Key Refresh: Phase 1 -> Phase 2"); + BT_PTS("[PTS] Key Refresh: Phase 1 -> Phase 2"); #endif - sub->kr_phase = BT_MESH_KR_PHASE_2; - sub->kr_flag = 1; - bt_mesh_net_beacon_update(sub); - } else if ((sub->kr_phase == BT_MESH_KR_PHASE_1 || - sub->kr_phase == BT_MESH_KR_PHASE_2) && - phase == BT_MESH_KR_PHASE_3) { - bt_mesh_net_revoke_keys(sub); - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || - IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - friend_cred_refresh(ctx->net_idx); - } + sub->kr_phase = BT_MESH_KR_PHASE_2; + sub->kr_flag = 1; + bt_mesh_net_beacon_update(sub); + } else if ((sub->kr_phase == BT_MESH_KR_PHASE_1 || + sub->kr_phase == BT_MESH_KR_PHASE_2) && + phase == BT_MESH_KR_PHASE_3) { + bt_mesh_net_revoke_keys(sub); + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || + IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + friend_cred_refresh(ctx->net_idx); + } #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Key Refresh: Phase %d -> Normal", sub->kr_phase); + BT_PTS("[PTS] Key Refresh: Phase %d -> Normal", sub->kr_phase); #endif - sub->kr_phase = BT_MESH_KR_NORMAL; - sub->kr_flag = 0; - bt_mesh_net_beacon_update(sub); - } + sub->kr_phase = BT_MESH_KR_NORMAL; + sub->kr_flag = 0; + bt_mesh_net_beacon_update(sub); + } - send_krp_status(model, ctx, idx, sub->kr_phase, STATUS_SUCCESS); + send_krp_status(model, ctx, idx, sub->kr_phase, STATUS_SUCCESS); } static u8_t hb_log(u16_t val) { - if (!val) { - return 0x00; - } else if (val == 0xffff) { - return 0xff; - } else { - return 32 - __builtin_clz(val); - } + if (!val) { + return 0x00; + } else if (val == 0xffff) { + return 0xff; + } else { + return 32 - __builtin_clz(val); + } } static u8_t hb_pub_count_log(u16_t val) { - if (!val) { - return 0x00; - } else if (val == 0x01) { - return 0x01; - } else if (val == 0xffff) { - return 0xff; - } else { - return 32 - __builtin_clz(val - 1) + 1; - } + if (!val) { + return 0x00; + } else if (val == 0x01) { + return 0x01; + } else if (val == 0xffff) { + return 0xff; + } else { + return 32 - __builtin_clz(val - 1) + 1; + } } static u16_t hb_pwr2(u8_t val, u8_t sub) { - if (!val) { - return 0x0000; - } else if (val == 0xff || val == 0x11) { - return 0xffff; - } else { - return (1 << (val - sub)); - } + if (!val) { + return 0x0000; + } else if (val == 0xff || val == 0x11) { + return 0xffff; + } else { + return (1 << (val - sub)); + } } struct hb_pub_param { - u16_t dst; - u8_t count_log; - u8_t period_log; - u8_t ttl; - u16_t feat; - u16_t net_idx; + u16_t dst; + u8_t count_log; + u8_t period_log; + u8_t ttl; + u16_t feat; + u16_t net_idx; } __packed; static void hb_pub_send_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, u8_t status, - struct hb_pub_param *orig_msg) + struct bt_mesh_msg_ctx *ctx, u8_t status, + struct hb_pub_param *orig_msg) { - /* Needed size: opcode (1 byte) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 1 + 10 + 4); - struct bt_mesh_cfg_srv *cfg = model->user_data; + /* Needed size: opcode (1 byte) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 1 + 10 + 4); + struct bt_mesh_cfg_srv *cfg = model->user_data; - BT_DBG("src 0x%04x status 0x%02x", ctx->addr, status); + BT_DBG("src 0x%04x status 0x%02x", ctx->addr, status); - bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_STATUS); + bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_STATUS); - net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_u8(&msg, status); - if (orig_msg) { - memcpy(net_buf_simple_add(&msg, sizeof(*orig_msg)), orig_msg, - sizeof(*orig_msg)); - goto send; - } + if (orig_msg) { + memcpy(net_buf_simple_add(&msg, sizeof(*orig_msg)), orig_msg, + sizeof(*orig_msg)); + goto send; + } - net_buf_simple_add_le16(&msg, cfg->hb_pub.dst); - net_buf_simple_add_u8(&msg, hb_pub_count_log(cfg->hb_pub.count)); - net_buf_simple_add_u8(&msg, cfg->hb_pub.period); - net_buf_simple_add_u8(&msg, cfg->hb_pub.ttl); - net_buf_simple_add_le16(&msg, cfg->hb_pub.feat); - net_buf_simple_add_le16(&msg, cfg->hb_pub.net_idx); + net_buf_simple_add_le16(&msg, cfg->hb_pub.dst); + net_buf_simple_add_u8(&msg, hb_pub_count_log(cfg->hb_pub.count)); + net_buf_simple_add_u8(&msg, cfg->hb_pub.period); + net_buf_simple_add_u8(&msg, cfg->hb_pub.ttl); + net_buf_simple_add_le16(&msg, cfg->hb_pub.feat); + net_buf_simple_add_le16(&msg, cfg->hb_pub.net_idx); send: - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Heartbeat Publication Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Heartbeat Publication Status"); + } } static void heartbeat_pub_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG("src 0x%04x", ctx->addr); + BT_DBG("src 0x%04x", ctx->addr); - hb_pub_send_status(model, ctx, STATUS_SUCCESS, NULL); + hb_pub_send_status(model, ctx, STATUS_SUCCESS, NULL); } static void heartbeat_pub_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct hb_pub_param *param = (void *)buf->data; - struct bt_mesh_cfg_srv *cfg = model->user_data; - u16_t dst, feat, idx; - u8_t status; + struct hb_pub_param *param = (void *)buf->data; + struct bt_mesh_cfg_srv *cfg = model->user_data; + u16_t dst, feat, idx; + u8_t status; - BT_DBG("src 0x%04x", ctx->addr); + BT_DBG("src 0x%04x", ctx->addr); - dst = sys_le16_to_cpu(param->dst); - /* All other address types but virtual are valid */ - if (BT_MESH_ADDR_IS_VIRTUAL(dst)) { - status = STATUS_INVALID_ADDRESS; - goto failed; - } + dst = sys_le16_to_cpu(param->dst); + /* All other address types but virtual are valid */ + if (BT_MESH_ADDR_IS_VIRTUAL(dst)) { + status = STATUS_INVALID_ADDRESS; + goto failed; + } - if (param->count_log > 0x11 && param->count_log != 0xff) { - status = STATUS_CANNOT_SET; - goto failed; - } + if (param->count_log > 0x11 && param->count_log != 0xff) { + status = STATUS_CANNOT_SET; + goto failed; + } - if (param->period_log > 0x10) { - status = STATUS_CANNOT_SET; - goto failed; - } + if (param->period_log > 0x10) { + status = STATUS_CANNOT_SET; + goto failed; + } - if (param->ttl > BT_MESH_TTL_MAX && param->ttl != BT_MESH_TTL_DEFAULT) { - BT_ERR("Invalid TTL value 0x%02x", param->ttl); - return; - } + if (param->ttl > BT_MESH_TTL_MAX && param->ttl != BT_MESH_TTL_DEFAULT) { + BT_ERR("Invalid TTL value 0x%02x", param->ttl); + return; + } - feat = sys_le16_to_cpu(param->feat); + feat = sys_le16_to_cpu(param->feat); - idx = sys_le16_to_cpu(param->net_idx); - if (idx > 0xfff) { - BT_ERR("Invalid NetKeyIndex 0x%04x", idx); - return; - } + idx = sys_le16_to_cpu(param->net_idx); + if (idx > 0xfff) { + BT_ERR("Invalid NetKeyIndex 0x%04x", idx); + return; + } - if (!bt_mesh_subnet_get(idx)) { - status = STATUS_INVALID_NETKEY; - goto failed; - } + if (!bt_mesh_subnet_get(idx)) { + status = STATUS_INVALID_NETKEY; + goto failed; + } - cfg->hb_pub.dst = dst; - cfg->hb_pub.period = param->period_log; - cfg->hb_pub.feat = feat & BT_MESH_FEAT_SUPPORTED; - cfg->hb_pub.net_idx = idx; + cfg->hb_pub.dst = dst; + cfg->hb_pub.period = param->period_log; + cfg->hb_pub.feat = feat & BT_MESH_FEAT_SUPPORTED; + cfg->hb_pub.net_idx = idx; - if (dst == BT_MESH_ADDR_UNASSIGNED) { - hb_pub_disable(cfg); - } else { - /* 2^(n-1) */ - cfg->hb_pub.count = hb_pwr2(param->count_log, 1); - cfg->hb_pub.ttl = param->ttl; + if (dst == BT_MESH_ADDR_UNASSIGNED) { + hb_pub_disable(cfg); + } else { + /* 2^(n-1) */ + cfg->hb_pub.count = hb_pwr2(param->count_log, 1); + cfg->hb_pub.ttl = param->ttl; - BT_DBG("period %u ms", hb_pwr2(param->period_log, 1) * 1000U); + BT_DBG("period %u ms", hb_pwr2(param->period_log, 1) * 1000U); - /* The first Heartbeat message shall be published as soon - * as possible after the Heartbeat Publication Period state - * has been configured for periodic publishing. - */ - if (param->period_log && param->count_log) { + /* The first Heartbeat message shall be published as soon + * as possible after the Heartbeat Publication Period state + * has been configured for periodic publishing. + */ + if (param->period_log && param->count_log) { #ifndef CONFIG_BT_MESH_PTS - k_work_submit(&cfg->hb_pub.timer.work); + k_work_submit(&cfg->hb_pub.timer.work); #else - k_delayed_work_submit(&cfg->hb_pub.timer.work, 1000); + k_delayed_work_submit(&cfg->hb_pub.timer.work, 1000); #endif - } else { - k_delayed_work_cancel(&cfg->hb_pub.timer); - } - } + } else { + k_delayed_work_cancel(&cfg->hb_pub.timer); + } + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_hb_pub(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_hb_pub(); + } - hb_pub_send_status(model, ctx, STATUS_SUCCESS, NULL); + hb_pub_send_status(model, ctx, STATUS_SUCCESS, NULL); - return; + return; failed: - hb_pub_send_status(model, ctx, status, param); + hb_pub_send_status(model, ctx, status, param); } static void hb_sub_send_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, u8_t status) + struct bt_mesh_msg_ctx *ctx, u8_t status) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); - struct bt_mesh_cfg_srv *cfg = model->user_data; - u16_t period; - s64_t uptime; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4); + struct bt_mesh_cfg_srv *cfg = model->user_data; + u16_t period; + s64_t uptime; - BT_DBG("src 0x%04x status 0x%02x", ctx->addr, status); + BT_DBG("src 0x%04x status 0x%02x", ctx->addr, status); - uptime = k_uptime_get(); - if (uptime > cfg->hb_sub.expiry) { - period = 0U; - } else { - period = (cfg->hb_sub.expiry - uptime) / 1000; - } + uptime = k_uptime_get(); + if (uptime > cfg->hb_sub.expiry) { + period = 0U; + } else { + period = (cfg->hb_sub.expiry - uptime) / 1000; + } - bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_STATUS); + bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_STATUS); - net_buf_simple_add_u8(&msg, status); - net_buf_simple_add_le16(&msg, cfg->hb_sub.src); - net_buf_simple_add_le16(&msg, cfg->hb_sub.dst); - net_buf_simple_add_u8(&msg, hb_log(period)); - net_buf_simple_add_u8(&msg, hb_log(cfg->hb_sub.count)); - net_buf_simple_add_u8(&msg, cfg->hb_sub.min_hops); - net_buf_simple_add_u8(&msg, cfg->hb_sub.max_hops); + net_buf_simple_add_u8(&msg, status); + net_buf_simple_add_le16(&msg, cfg->hb_sub.src); + net_buf_simple_add_le16(&msg, cfg->hb_sub.dst); + net_buf_simple_add_u8(&msg, hb_log(period)); + net_buf_simple_add_u8(&msg, hb_log(cfg->hb_sub.count)); + net_buf_simple_add_u8(&msg, cfg->hb_sub.min_hops); + net_buf_simple_add_u8(&msg, cfg->hb_sub.max_hops); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Heartbeat Subscription Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Heartbeat Subscription Status"); + } } static void heartbeat_sub_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG("src 0x%04x", ctx->addr); + BT_DBG("src 0x%04x", ctx->addr); #if defined(BFLB_BLE_MESH_PATCH_HEARTBEAT_SUB_GET) - struct bt_mesh_cfg_srv *cfg = model->user_data; + struct bt_mesh_cfg_srv *cfg = model->user_data; - if (cfg->hb_sub.src == BT_MESH_ADDR_UNASSIGNED || - cfg->hb_sub.dst == BT_MESH_ADDR_UNASSIGNED) { - cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.min_hops = 0U; - cfg->hb_sub.max_hops = 0U; - cfg->hb_sub.count = 0U; - } + if (cfg->hb_sub.src == BT_MESH_ADDR_UNASSIGNED || + cfg->hb_sub.dst == BT_MESH_ADDR_UNASSIGNED) { + cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.min_hops = 0U; + cfg->hb_sub.max_hops = 0U; + cfg->hb_sub.count = 0U; + } #endif - hb_sub_send_status(model, ctx, STATUS_SUCCESS); + hb_sub_send_status(model, ctx, STATUS_SUCCESS); } static void heartbeat_sub_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_cfg_srv *cfg = model->user_data; - u16_t sub_src, sub_dst; - u8_t sub_period; - s32_t period_ms; + struct bt_mesh_cfg_srv *cfg = model->user_data; + u16_t sub_src, sub_dst; + u8_t sub_period; + s32_t period_ms; - BT_DBG("src 0x%04x", ctx->addr); + BT_DBG("src 0x%04x", ctx->addr); - sub_src = net_buf_simple_pull_le16(buf); - sub_dst = net_buf_simple_pull_le16(buf); - sub_period = net_buf_simple_pull_u8(buf); + sub_src = net_buf_simple_pull_le16(buf); + sub_dst = net_buf_simple_pull_le16(buf); + sub_period = net_buf_simple_pull_u8(buf); - BT_DBG("sub_src 0x%04x sub_dst 0x%04x period 0x%02x", - sub_src, sub_dst, sub_period); + BT_DBG("sub_src 0x%04x sub_dst 0x%04x period 0x%02x", + sub_src, sub_dst, sub_period); - if (sub_src != BT_MESH_ADDR_UNASSIGNED && - !BT_MESH_ADDR_IS_UNICAST(sub_src)) { - BT_WARN("Prohibited source address"); - return; - } + if (sub_src != BT_MESH_ADDR_UNASSIGNED && + !BT_MESH_ADDR_IS_UNICAST(sub_src)) { + BT_WARN("Prohibited source address"); + return; + } - if (BT_MESH_ADDR_IS_VIRTUAL(sub_dst) || BT_MESH_ADDR_IS_RFU(sub_dst) || - (BT_MESH_ADDR_IS_UNICAST(sub_dst) && - sub_dst != bt_mesh_primary_addr())) { - BT_WARN("Prohibited destination address"); - return; - } + if (BT_MESH_ADDR_IS_VIRTUAL(sub_dst) || BT_MESH_ADDR_IS_RFU(sub_dst) || + (BT_MESH_ADDR_IS_UNICAST(sub_dst) && + sub_dst != bt_mesh_primary_addr())) { + BT_WARN("Prohibited destination address"); + return; + } - if (sub_period > 0x11) { - BT_WARN("Prohibited subscription period 0x%02x", sub_period); - return; - } + if (sub_period > 0x11) { + BT_WARN("Prohibited subscription period 0x%02x", sub_period); + return; + } - if (sub_src == BT_MESH_ADDR_UNASSIGNED || - sub_dst == BT_MESH_ADDR_UNASSIGNED || - sub_period == 0x00) { - /* Only an explicit address change to unassigned should - * trigger clearing of the values according to - * MESH/NODE/CFG/HBS/BV-02-C. - */ + if (sub_src == BT_MESH_ADDR_UNASSIGNED || + sub_dst == BT_MESH_ADDR_UNASSIGNED || + sub_period == 0x00) { + /* Only an explicit address change to unassigned should + * trigger clearing of the values according to + * MESH/NODE/CFG/HBS/BV-02-C. + */ #if !defined(BFLB_BLE_MESH_PATCH_HEARTBEAT_SUB_SET) - if (sub_src == BT_MESH_ADDR_UNASSIGNED || - sub_dst == BT_MESH_ADDR_UNASSIGNED) { - cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.min_hops = BT_MESH_TTL_MAX; - cfg->hb_sub.max_hops = 0U; - cfg->hb_sub.count = 0U; - } + if (sub_src == BT_MESH_ADDR_UNASSIGNED || + sub_dst == BT_MESH_ADDR_UNASSIGNED) { + cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.min_hops = BT_MESH_TTL_MAX; + cfg->hb_sub.max_hops = 0U; + cfg->hb_sub.count = 0U; + } #else - cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.min_hops = BT_MESH_TTL_MAX; + cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.min_hops = BT_MESH_TTL_MAX; #endif - period_ms = 0; - } else { - cfg->hb_sub.src = sub_src; - cfg->hb_sub.dst = sub_dst; - cfg->hb_sub.min_hops = BT_MESH_TTL_MAX; - cfg->hb_sub.max_hops = 0U; - cfg->hb_sub.count = 0U; - period_ms = hb_pwr2(sub_period, 1) * 1000U; - } + period_ms = 0; + } else { + cfg->hb_sub.src = sub_src; + cfg->hb_sub.dst = sub_dst; + cfg->hb_sub.min_hops = BT_MESH_TTL_MAX; + cfg->hb_sub.max_hops = 0U; + cfg->hb_sub.count = 0U; + period_ms = hb_pwr2(sub_period, 1) * 1000U; + } - /* Let the transport layer know it needs to handle this address */ - bt_mesh_set_hb_sub_dst(cfg->hb_sub.dst); + /* Let the transport layer know it needs to handle this address */ + bt_mesh_set_hb_sub_dst(cfg->hb_sub.dst); - BT_DBG("period_ms %u", period_ms); + BT_DBG("period_ms %u", period_ms); - if (period_ms) { - cfg->hb_sub.expiry = k_uptime_get() + period_ms; - } else { - cfg->hb_sub.expiry = 0; - } + if (period_ms) { + cfg->hb_sub.expiry = k_uptime_get() + period_ms; + } else { + cfg->hb_sub.expiry = 0; + } - hb_sub_send_status(model, ctx, STATUS_SUCCESS); + hb_sub_send_status(model, ctx, STATUS_SUCCESS); - /* MESH/NODE/CFG/HBS/BV-01-C expects the MinHops to be 0x7f after - * disabling subscription, but 0x00 for subsequent Get requests. - */ - if (!period_ms) { - cfg->hb_sub.min_hops = 0U; - } + /* MESH/NODE/CFG/HBS/BV-01-C expects the MinHops to be 0x7f after + * disabling subscription, but 0x00 for subsequent Get requests. + */ + if (!period_ms) { + cfg->hb_sub.min_hops = 0U; + } } const struct bt_mesh_model_op bt_mesh_cfg_srv_op[] = { - { OP_DEV_COMP_DATA_GET, 1, dev_comp_data_get }, - { OP_APP_KEY_ADD, 19, app_key_add }, - { OP_APP_KEY_UPDATE, 19, app_key_update }, - { OP_APP_KEY_DEL, 3, app_key_del }, - { OP_APP_KEY_GET, 2, app_key_get }, - { OP_BEACON_GET, 0, beacon_get }, - { OP_BEACON_SET, 1, beacon_set }, - { OP_DEFAULT_TTL_GET, 0, default_ttl_get }, - { OP_DEFAULT_TTL_SET, 1, default_ttl_set }, - { OP_GATT_PROXY_GET, 0, gatt_proxy_get }, - { OP_GATT_PROXY_SET, 1, gatt_proxy_set }, - { OP_NET_TRANSMIT_GET, 0, net_transmit_get }, - { OP_NET_TRANSMIT_SET, 1, net_transmit_set }, - { OP_RELAY_GET, 0, relay_get }, - { OP_RELAY_SET, 2, relay_set }, - { OP_MOD_PUB_GET, 4, mod_pub_get }, - { OP_MOD_PUB_SET, 11, mod_pub_set }, - { OP_MOD_PUB_VA_SET, 24, mod_pub_va_set }, - { OP_MOD_SUB_ADD, 6, mod_sub_add }, - { OP_MOD_SUB_VA_ADD, 20, mod_sub_va_add }, - { OP_MOD_SUB_DEL, 6, mod_sub_del }, - { OP_MOD_SUB_VA_DEL, 20, mod_sub_va_del }, - { OP_MOD_SUB_OVERWRITE, 6, mod_sub_overwrite }, - { OP_MOD_SUB_VA_OVERWRITE, 20, mod_sub_va_overwrite }, - { OP_MOD_SUB_DEL_ALL, 4, mod_sub_del_all }, - { OP_MOD_SUB_GET, 4, mod_sub_get }, - { OP_MOD_SUB_GET_VND, 6, mod_sub_get_vnd }, - { OP_NET_KEY_ADD, 18, net_key_add }, - { OP_NET_KEY_UPDATE, 18, net_key_update }, - { OP_NET_KEY_DEL, 2, net_key_del }, - { OP_NET_KEY_GET, 0, net_key_get }, - { OP_NODE_IDENTITY_GET, 2, node_identity_get }, - { OP_NODE_IDENTITY_SET, 3, node_identity_set }, - { OP_MOD_APP_BIND, 6, mod_app_bind }, - { OP_MOD_APP_UNBIND, 6, mod_app_unbind }, - { OP_SIG_MOD_APP_GET, 4, mod_app_get }, - { OP_VND_MOD_APP_GET, 6, mod_app_get }, - { OP_NODE_RESET, 0, node_reset }, - { OP_FRIEND_GET, 0, friend_get }, - { OP_FRIEND_SET, 1, friend_set }, - { OP_LPN_TIMEOUT_GET, 2, lpn_timeout_get }, - { OP_KRP_GET, 2, krp_get }, - { OP_KRP_SET, 3, krp_set }, - { OP_HEARTBEAT_PUB_GET, 0, heartbeat_pub_get }, - { OP_HEARTBEAT_PUB_SET, 9, heartbeat_pub_set }, - { OP_HEARTBEAT_SUB_GET, 0, heartbeat_sub_get }, - { OP_HEARTBEAT_SUB_SET, 5, heartbeat_sub_set }, - BT_MESH_MODEL_OP_END, + { OP_DEV_COMP_DATA_GET, 1, dev_comp_data_get }, + { OP_APP_KEY_ADD, 19, app_key_add }, + { OP_APP_KEY_UPDATE, 19, app_key_update }, + { OP_APP_KEY_DEL, 3, app_key_del }, + { OP_APP_KEY_GET, 2, app_key_get }, + { OP_BEACON_GET, 0, beacon_get }, + { OP_BEACON_SET, 1, beacon_set }, + { OP_DEFAULT_TTL_GET, 0, default_ttl_get }, + { OP_DEFAULT_TTL_SET, 1, default_ttl_set }, + { OP_GATT_PROXY_GET, 0, gatt_proxy_get }, + { OP_GATT_PROXY_SET, 1, gatt_proxy_set }, + { OP_NET_TRANSMIT_GET, 0, net_transmit_get }, + { OP_NET_TRANSMIT_SET, 1, net_transmit_set }, + { OP_RELAY_GET, 0, relay_get }, + { OP_RELAY_SET, 2, relay_set }, + { OP_MOD_PUB_GET, 4, mod_pub_get }, + { OP_MOD_PUB_SET, 11, mod_pub_set }, + { OP_MOD_PUB_VA_SET, 24, mod_pub_va_set }, + { OP_MOD_SUB_ADD, 6, mod_sub_add }, + { OP_MOD_SUB_VA_ADD, 20, mod_sub_va_add }, + { OP_MOD_SUB_DEL, 6, mod_sub_del }, + { OP_MOD_SUB_VA_DEL, 20, mod_sub_va_del }, + { OP_MOD_SUB_OVERWRITE, 6, mod_sub_overwrite }, + { OP_MOD_SUB_VA_OVERWRITE, 20, mod_sub_va_overwrite }, + { OP_MOD_SUB_DEL_ALL, 4, mod_sub_del_all }, + { OP_MOD_SUB_GET, 4, mod_sub_get }, + { OP_MOD_SUB_GET_VND, 6, mod_sub_get_vnd }, + { OP_NET_KEY_ADD, 18, net_key_add }, + { OP_NET_KEY_UPDATE, 18, net_key_update }, + { OP_NET_KEY_DEL, 2, net_key_del }, + { OP_NET_KEY_GET, 0, net_key_get }, + { OP_NODE_IDENTITY_GET, 2, node_identity_get }, + { OP_NODE_IDENTITY_SET, 3, node_identity_set }, + { OP_MOD_APP_BIND, 6, mod_app_bind }, + { OP_MOD_APP_UNBIND, 6, mod_app_unbind }, + { OP_SIG_MOD_APP_GET, 4, mod_app_get }, + { OP_VND_MOD_APP_GET, 6, mod_app_get }, + { OP_NODE_RESET, 0, node_reset }, + { OP_FRIEND_GET, 0, friend_get }, + { OP_FRIEND_SET, 1, friend_set }, + { OP_LPN_TIMEOUT_GET, 2, lpn_timeout_get }, + { OP_KRP_GET, 2, krp_get }, + { OP_KRP_SET, 3, krp_set }, + { OP_HEARTBEAT_PUB_GET, 0, heartbeat_pub_get }, + { OP_HEARTBEAT_PUB_SET, 9, heartbeat_pub_set }, + { OP_HEARTBEAT_SUB_GET, 0, heartbeat_sub_get }, + { OP_HEARTBEAT_SUB_SET, 5, heartbeat_sub_set }, + BT_MESH_MODEL_OP_END, }; static void hb_publish(struct k_work *work) { - struct bt_mesh_cfg_srv *cfg = CONTAINER_OF(work, - struct bt_mesh_cfg_srv, - hb_pub.timer.work); - struct bt_mesh_subnet *sub; - u16_t period_ms; + struct bt_mesh_cfg_srv *cfg = CONTAINER_OF(work, + struct bt_mesh_cfg_srv, + hb_pub.timer.work); + struct bt_mesh_subnet *sub; + u16_t period_ms; - BT_DBG("hb_pub.count: %u", cfg->hb_pub.count); + BT_DBG("hb_pub.count: %u", cfg->hb_pub.count); - sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx); - if (!sub) { - BT_ERR("No matching subnet for idx 0x%02x", - cfg->hb_pub.net_idx); - cfg->hb_pub.dst = BT_MESH_ADDR_UNASSIGNED; - return; - } + sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx); + if (!sub) { + BT_ERR("No matching subnet for idx 0x%02x", + cfg->hb_pub.net_idx); + cfg->hb_pub.dst = BT_MESH_ADDR_UNASSIGNED; + return; + } - if (cfg->hb_pub.count == 0U) { - return; - } + if (cfg->hb_pub.count == 0U) { + return; + } - period_ms = hb_pwr2(cfg->hb_pub.period, 1) * 1000U; - if (period_ms && cfg->hb_pub.count > 1) { - k_delayed_work_submit(&cfg->hb_pub.timer, period_ms); - } + period_ms = hb_pwr2(cfg->hb_pub.period, 1) * 1000U; + if (period_ms && cfg->hb_pub.count > 1) { + k_delayed_work_submit(&cfg->hb_pub.timer, period_ms); + } - bt_mesh_heartbeat_send(); + bt_mesh_heartbeat_send(); - if (cfg->hb_pub.count != 0xffff) { - cfg->hb_pub.count--; - } + if (cfg->hb_pub.count != 0xffff) { + cfg->hb_pub.count--; + } } static bool conf_is_valid(struct bt_mesh_cfg_srv *cfg) { - if (cfg->relay > 0x02) { - return false; - } + if (cfg->relay > 0x02) { + return false; + } - if (cfg->beacon > 0x01) { - return false; - } + if (cfg->beacon > 0x01) { + return false; + } - if (cfg->default_ttl > BT_MESH_TTL_MAX) { - return false; - } + if (cfg->default_ttl > BT_MESH_TTL_MAX) { + return false; + } - return true; + return true; } int bt_mesh_cfg_srv_init(struct bt_mesh_model *model, bool primary) { - struct bt_mesh_cfg_srv *cfg = model->user_data; + struct bt_mesh_cfg_srv *cfg = model->user_data; - if (!cfg) { - BT_ERR("No Configuration Server context provided"); - return -EINVAL; - } + if (!cfg) { + BT_ERR("No Configuration Server context provided"); + return -EINVAL; + } - if (!conf_is_valid(cfg)) { - BT_ERR("Invalid values in configuration"); - return -EINVAL; - } + if (!conf_is_valid(cfg)) { + BT_ERR("Invalid values in configuration"); + return -EINVAL; + } - /* Configuration Model security is device-key based */ - model->keys[0] = BT_MESH_KEY_DEV; + /* Configuration Model security is device-key based */ + model->keys[0] = BT_MESH_KEY_DEV; - if (!IS_ENABLED(CONFIG_BT_MESH_RELAY)) { - cfg->relay = BT_MESH_RELAY_NOT_SUPPORTED; - } + if (!IS_ENABLED(CONFIG_BT_MESH_RELAY)) { + cfg->relay = BT_MESH_RELAY_NOT_SUPPORTED; + } - if (!IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - cfg->frnd = BT_MESH_FRIEND_NOT_SUPPORTED; - } + if (!IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + cfg->frnd = BT_MESH_FRIEND_NOT_SUPPORTED; + } - if (!IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { - cfg->gatt_proxy = BT_MESH_GATT_PROXY_NOT_SUPPORTED; - } + if (!IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { + cfg->gatt_proxy = BT_MESH_GATT_PROXY_NOT_SUPPORTED; + } - k_delayed_work_init(&cfg->hb_pub.timer, hb_publish); - cfg->hb_pub.net_idx = BT_MESH_KEY_UNUSED; - cfg->hb_sub.expiry = 0; + k_delayed_work_init(&cfg->hb_pub.timer, hb_publish); + cfg->hb_pub.net_idx = BT_MESH_KEY_UNUSED; + cfg->hb_sub.expiry = 0; - cfg->model = model; + cfg->model = model; - conf = cfg; + conf = cfg; - return 0; + return 0; } static void mod_reset(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, - bool vnd, bool primary, void *user_data) + bool vnd, bool primary, void *user_data) { - size_t clear_count; + size_t clear_count; - /* Clear model state that isn't otherwise cleared. E.g. AppKey - * binding and model publication is cleared as a consequence - * of removing all app keys, however model subscription clearing - * must be taken care of here. - */ + /* Clear model state that isn't otherwise cleared. E.g. AppKey + * binding and model publication is cleared as a consequence + * of removing all app keys, however model subscription clearing + * must be taken care of here. + */ - clear_count = mod_sub_list_clear(mod); + clear_count = mod_sub_list_clear(mod); - if (IS_ENABLED(CONFIG_BT_SETTINGS) && clear_count) { - bt_mesh_store_mod_sub(mod); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && clear_count) { + bt_mesh_store_mod_sub(mod); + } } void bt_mesh_cfg_reset(void) { - struct bt_mesh_cfg_srv *cfg = conf; - int i; + struct bt_mesh_cfg_srv *cfg = conf; + int i; - BT_DBG(""); + BT_DBG(""); - if (!cfg) { - return; - } + if (!cfg) { + return; + } - bt_mesh_set_hb_sub_dst(BT_MESH_ADDR_UNASSIGNED); + bt_mesh_set_hb_sub_dst(BT_MESH_ADDR_UNASSIGNED); - cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; - cfg->hb_sub.expiry = 0; + cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED; + cfg->hb_sub.expiry = 0; - /* Delete all net keys, which also takes care of all app keys which - * are associated with each net key. - */ - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + /* Delete all net keys, which also takes care of all app keys which + * are associated with each net key. + */ + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx != BT_MESH_KEY_UNUSED) { - bt_mesh_subnet_del(sub, true); - } - } + if (sub->net_idx != BT_MESH_KEY_UNUSED) { + bt_mesh_subnet_del(sub, true); + } + } - bt_mesh_model_foreach(mod_reset, NULL); + bt_mesh_model_foreach(mod_reset, NULL); - (void)memset(labels, 0, sizeof(labels)); + (void)memset(labels, 0, sizeof(labels)); } void bt_mesh_heartbeat(u16_t src, u16_t dst, u8_t hops, u16_t feat) { - struct bt_mesh_cfg_srv *cfg = conf; + struct bt_mesh_cfg_srv *cfg = conf; - if (!cfg) { - BT_WARN("No configuaration server context available"); - return; - } + if (!cfg) { + BT_WARN("No configuaration server context available"); + return; + } - if (src != cfg->hb_sub.src || dst != cfg->hb_sub.dst) { - BT_WARN("No subscription for received heartbeat"); - return; - } + if (src != cfg->hb_sub.src || dst != cfg->hb_sub.dst) { + BT_WARN("No subscription for received heartbeat"); + return; + } - if (k_uptime_get() > cfg->hb_sub.expiry) { - BT_WARN("Heartbeat subscription period expired"); - return; - } + if (k_uptime_get() > cfg->hb_sub.expiry) { + BT_WARN("Heartbeat subscription period expired"); + return; + } - cfg->hb_sub.min_hops = MIN(cfg->hb_sub.min_hops, hops); - cfg->hb_sub.max_hops = MAX(cfg->hb_sub.max_hops, hops); + cfg->hb_sub.min_hops = MIN(cfg->hb_sub.min_hops, hops); + cfg->hb_sub.max_hops = MAX(cfg->hb_sub.max_hops, hops); - if (cfg->hb_sub.count < 0xffff) { - cfg->hb_sub.count++; - } + if (cfg->hb_sub.count < 0xffff) { + cfg->hb_sub.count++; + } - BT_DBG("src 0x%04x dst 0x%04x hops %u min %u max %u count %u", src, - dst, hops, cfg->hb_sub.min_hops, cfg->hb_sub.max_hops, - cfg->hb_sub.count); + BT_DBG("src 0x%04x dst 0x%04x hops %u min %u max %u count %u", src, + dst, hops, cfg->hb_sub.min_hops, cfg->hb_sub.max_hops, + cfg->hb_sub.count); - if (cfg->hb_sub.func) { - cfg->hb_sub.func(src, dst, hops, feat); - } + if (cfg->hb_sub.func) { + cfg->hb_sub.func(src, dst, hops, feat); + } } u8_t bt_mesh_net_transmit_get(void) { - if (conf) { - return conf->net_transmit; - } + if (conf) { + return conf->net_transmit; + } - return 0; + return 0; } u8_t bt_mesh_relay_get(void) { - if (conf) { - return conf->relay; - } + if (conf) { + return conf->relay; + } - return BT_MESH_RELAY_NOT_SUPPORTED; + return BT_MESH_RELAY_NOT_SUPPORTED; } u8_t bt_mesh_friend_get(void) { - BT_DBG("conf %p conf->frnd 0x%02x", conf, conf->frnd); + BT_DBG("conf %p conf->frnd 0x%02x", conf, conf->frnd); - if (conf) { - return conf->frnd; - } + if (conf) { + return conf->frnd; + } - return BT_MESH_FRIEND_NOT_SUPPORTED; + return BT_MESH_FRIEND_NOT_SUPPORTED; } u8_t bt_mesh_relay_retransmit_get(void) { - if (conf) { - return conf->relay_retransmit; - } + if (conf) { + return conf->relay_retransmit; + } - return 0; + return 0; } u8_t bt_mesh_beacon_get(void) { - if (conf) { - return conf->beacon; - } + if (conf) { + return conf->beacon; + } - return BT_MESH_BEACON_DISABLED; + return BT_MESH_BEACON_DISABLED; } u8_t bt_mesh_gatt_proxy_get(void) { - if (conf) { - return conf->gatt_proxy; - } + if (conf) { + return conf->gatt_proxy; + } - return BT_MESH_GATT_PROXY_NOT_SUPPORTED; + return BT_MESH_GATT_PROXY_NOT_SUPPORTED; } u8_t bt_mesh_default_ttl_get(void) { - if (conf) { - return conf->default_ttl; - } + if (conf) { + return conf->default_ttl; + } - return DEFAULT_TTL; + return DEFAULT_TTL; } u8_t *bt_mesh_label_uuid_get(u16_t addr) { - int i; + int i; - BT_DBG("addr 0x%04x", addr); + BT_DBG("addr 0x%04x", addr); - for (i = 0; i < ARRAY_SIZE(labels); i++) { - if (labels[i].addr == addr) { - BT_DBG("Found Label UUID for 0x%04x: %s", addr, - bt_hex(labels[i].uuid, 16)); - return labels[i].uuid; - } - } + for (i = 0; i < ARRAY_SIZE(labels); i++) { + if (labels[i].addr == addr) { + BT_DBG("Found Label UUID for 0x%04x: %s", addr, + bt_hex(labels[i].uuid, 16)); + return labels[i].uuid; + } + } - BT_WARN("No matching Label UUID for 0x%04x", addr); + BT_WARN("No matching Label UUID for 0x%04x", addr); - return NULL; + return NULL; } struct bt_mesh_hb_pub *bt_mesh_hb_pub_get(void) { - if (!conf) { - return NULL; - } + if (!conf) { + return NULL; + } - return &conf->hb_pub; + return &conf->hb_pub; } void bt_mesh_hb_pub_disable(void) { - if (conf) { - hb_pub_disable(conf); - } + if (conf) { + hb_pub_disable(conf); + } } struct bt_mesh_cfg_srv *bt_mesh_cfg_get(void) { - return conf; + return conf; } void bt_mesh_subnet_del(struct bt_mesh_subnet *sub, bool store) { - int i; + int i; - BT_DBG("NetIdx 0x%03x store %u", sub->net_idx, store); + BT_DBG("NetIdx 0x%03x store %u", sub->net_idx, store); - if (conf && conf->hb_pub.net_idx == sub->net_idx) { - hb_pub_disable(conf); + if (conf && conf->hb_pub.net_idx == sub->net_idx) { + hb_pub_disable(conf); - if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { - bt_mesh_store_hb_pub(); - } - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { + bt_mesh_store_hb_pub(); + } + } - /* Delete any app keys bound to this NetKey index */ - for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { - struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; + /* Delete any app keys bound to this NetKey index */ + for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { + struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - if (key->net_idx == sub->net_idx) { - bt_mesh_app_key_del(key, store); - } - } + if (key->net_idx == sub->net_idx) { + bt_mesh_app_key_del(key, store); + } + } - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - bt_mesh_friend_clear_net_idx(sub->net_idx); - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + bt_mesh_friend_clear_net_idx(sub->net_idx); + } - if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { - bt_mesh_clear_subnet(sub); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { + bt_mesh_clear_subnet(sub); + } - (void)memset(sub, 0, sizeof(*sub)); - sub->net_idx = BT_MESH_KEY_UNUSED; + (void)memset(sub, 0, sizeof(*sub)); + sub->net_idx = BT_MESH_KEY_UNUSED; } diff --git a/components/network/ble/blemesh/src/crypto.c b/components/network/ble/blemesh/src/crypto.c index 4a99e4d6..5fa6486c 100644 --- a/components/network/ble/blemesh/src/crypto.c +++ b/components/network/ble/blemesh/src/crypto.c @@ -34,843 +34,843 @@ #define APP_MIC_LEN(aszmic) ((aszmic) ? 8 : 4) int bt_mesh_aes_cmac(const u8_t key[16], struct bt_mesh_sg *sg, - size_t sg_len, u8_t mac[16]) + size_t sg_len, u8_t mac[16]) { - struct tc_aes_key_sched_struct sched; - struct tc_cmac_struct state; + struct tc_aes_key_sched_struct sched; + struct tc_cmac_struct state; - if (tc_cmac_setup(&state, key, &sched) == TC_CRYPTO_FAIL) { - return -EIO; - } + if (tc_cmac_setup(&state, key, &sched) == TC_CRYPTO_FAIL) { + return -EIO; + } - for (; sg_len; sg_len--, sg++) { - if (tc_cmac_update(&state, sg->data, - sg->len) == TC_CRYPTO_FAIL) { - return -EIO; - } - } + for (; sg_len; sg_len--, sg++) { + if (tc_cmac_update(&state, sg->data, + sg->len) == TC_CRYPTO_FAIL) { + return -EIO; + } + } - if (tc_cmac_final(mac, &state) == TC_CRYPTO_FAIL) { - return -EIO; - } + if (tc_cmac_final(mac, &state) == TC_CRYPTO_FAIL) { + return -EIO; + } - return 0; + return 0; } int bt_mesh_k1(const u8_t *ikm, size_t ikm_len, const u8_t salt[16], - const char *info, u8_t okm[16]) + const char *info, u8_t okm[16]) { - int err; + int err; - err = bt_mesh_aes_cmac_one(salt, ikm, ikm_len, okm); - if (err < 0) { - return err; - } + err = bt_mesh_aes_cmac_one(salt, ikm, ikm_len, okm); + if (err < 0) { + return err; + } - return bt_mesh_aes_cmac_one(okm, info, strlen(info), okm); + return bt_mesh_aes_cmac_one(okm, info, strlen(info), okm); } int bt_mesh_k2(const u8_t n[16], const u8_t *p, size_t p_len, - u8_t net_id[1], u8_t enc_key[16], u8_t priv_key[16]) + u8_t net_id[1], u8_t enc_key[16], u8_t priv_key[16]) { - struct bt_mesh_sg sg[3]; - u8_t salt[16]; - u8_t out[16]; - u8_t t[16]; - u8_t pad; - int err; + struct bt_mesh_sg sg[3]; + u8_t salt[16]; + u8_t out[16]; + u8_t t[16]; + u8_t pad; + int err; - BT_DBG("n %s", bt_hex(n, 16)); - BT_DBG("p %s", bt_hex(p, p_len)); + BT_DBG("n %s", bt_hex(n, 16)); + BT_DBG("p %s", bt_hex(p, p_len)); - err = bt_mesh_s1("smk2", salt); - if (err) { - return err; - } + err = bt_mesh_s1("smk2", salt); + if (err) { + return err; + } - err = bt_mesh_aes_cmac_one(salt, n, 16, t); - if (err) { - return err; - } + err = bt_mesh_aes_cmac_one(salt, n, 16, t); + if (err) { + return err; + } - pad = 0x01; + pad = 0x01; - sg[0].data = NULL; - sg[0].len = 0; - sg[1].data = p; - sg[1].len = p_len; - sg[2].data = &pad; - sg[2].len = sizeof(pad); + sg[0].data = NULL; + sg[0].len = 0; + sg[1].data = p; + sg[1].len = p_len; + sg[2].data = &pad; + sg[2].len = sizeof(pad); - err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out); - if (err) { - return err; - } + err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out); + if (err) { + return err; + } - net_id[0] = out[15] & 0x7f; + net_id[0] = out[15] & 0x7f; - sg[0].data = out; - sg[0].len = sizeof(out); - pad = 0x02; + sg[0].data = out; + sg[0].len = sizeof(out); + pad = 0x02; - err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out); - if (err) { - return err; - } + err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out); + if (err) { + return err; + } - memcpy(enc_key, out, 16); + memcpy(enc_key, out, 16); - pad = 0x03; + pad = 0x03; - err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out); - if (err) { - return err; - } + err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out); + if (err) { + return err; + } - memcpy(priv_key, out, 16); + memcpy(priv_key, out, 16); - BT_DBG("NID 0x%02x enc_key %s", net_id[0], bt_hex(enc_key, 16)); - BT_DBG("priv_key %s", bt_hex(priv_key, 16)); + BT_DBG("NID 0x%02x enc_key %s", net_id[0], bt_hex(enc_key, 16)); + BT_DBG("priv_key %s", bt_hex(priv_key, 16)); - return 0; + return 0; } int bt_mesh_k3(const u8_t n[16], u8_t out[8]) { - u8_t id64[] = { 'i', 'd', '6', '4', 0x01 }; - u8_t tmp[16]; - u8_t t[16]; - int err; + u8_t id64[] = { 'i', 'd', '6', '4', 0x01 }; + u8_t tmp[16]; + u8_t t[16]; + int err; - err = bt_mesh_s1("smk3", tmp); - if (err) { - return err; - } + err = bt_mesh_s1("smk3", tmp); + if (err) { + return err; + } - err = bt_mesh_aes_cmac_one(tmp, n, 16, t); - if (err) { - return err; - } + err = bt_mesh_aes_cmac_one(tmp, n, 16, t); + if (err) { + return err; + } - err = bt_mesh_aes_cmac_one(t, id64, sizeof(id64), tmp); - if (err) { - return err; - } + err = bt_mesh_aes_cmac_one(t, id64, sizeof(id64), tmp); + if (err) { + return err; + } - memcpy(out, tmp + 8, 8); + memcpy(out, tmp + 8, 8); - return 0; + return 0; } int bt_mesh_k4(const u8_t n[16], u8_t out[1]) { - u8_t id6[] = { 'i', 'd', '6', 0x01 }; - u8_t tmp[16]; - u8_t t[16]; - int err; + u8_t id6[] = { 'i', 'd', '6', 0x01 }; + u8_t tmp[16]; + u8_t t[16]; + int err; - err = bt_mesh_s1("smk4", tmp); - if (err) { - return err; - } + err = bt_mesh_s1("smk4", tmp); + if (err) { + return err; + } - err = bt_mesh_aes_cmac_one(tmp, n, 16, t); - if (err) { - return err; - } + err = bt_mesh_aes_cmac_one(tmp, n, 16, t); + if (err) { + return err; + } - err = bt_mesh_aes_cmac_one(t, id6, sizeof(id6), tmp); - if (err) { - return err; - } + err = bt_mesh_aes_cmac_one(t, id6, sizeof(id6), tmp); + if (err) { + return err; + } - out[0] = tmp[15] & BIT_MASK(6); + out[0] = tmp[15] & BIT_MASK(6); - return 0; + return 0; } int bt_mesh_id128(const u8_t n[16], const char *s, u8_t out[16]) { - const char *id128 = "id128\x01"; - u8_t salt[16]; - int err; + const char *id128 = "id128\x01"; + u8_t salt[16]; + int err; - err = bt_mesh_s1(s, salt); - if (err) { - return err; - } + err = bt_mesh_s1(s, salt); + if (err) { + return err; + } - return bt_mesh_k1(n, 16, salt, id128, out); + return bt_mesh_k1(n, 16, salt, id128, out); } static int bt_mesh_ccm_decrypt(const u8_t key[16], u8_t nonce[13], - const u8_t *enc_msg, size_t msg_len, - const u8_t *aad, size_t aad_len, - u8_t *out_msg, size_t mic_size) + const u8_t *enc_msg, size_t msg_len, + const u8_t *aad, size_t aad_len, + u8_t *out_msg, size_t mic_size) { - u8_t msg[16], pmsg[16], cmic[16], cmsg[16], Xn[16], mic[16]; - u16_t last_blk, blk_cnt; - size_t i, j; - int err; + u8_t msg[16], pmsg[16], cmic[16], cmsg[16], Xn[16], mic[16]; + u16_t last_blk, blk_cnt; + size_t i, j; + int err; - if (msg_len < 1 || aad_len >= 0xff00) { - return -EINVAL; - } + if (msg_len < 1 || aad_len >= 0xff00) { + return -EINVAL; + } - /* C_mic = e(AppKey, 0x01 || nonce || 0x0000) */ - pmsg[0] = 0x01; - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(0x0000, pmsg + 14); + /* C_mic = e(AppKey, 0x01 || nonce || 0x0000) */ + pmsg[0] = 0x01; + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(0x0000, pmsg + 14); - err = bt_encrypt_be(key, pmsg, cmic); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, cmic); + if (err) { + return err; + } - /* X_0 = e(AppKey, 0x09 || nonce || length) */ - if (mic_size == sizeof(u64_t)) { - pmsg[0] = 0x19 | (aad_len ? 0x40 : 0x00); - } else { - pmsg[0] = 0x09 | (aad_len ? 0x40 : 0x00); - } + /* X_0 = e(AppKey, 0x09 || nonce || length) */ + if (mic_size == sizeof(u64_t)) { + pmsg[0] = 0x19 | (aad_len ? 0x40 : 0x00); + } else { + pmsg[0] = 0x09 | (aad_len ? 0x40 : 0x00); + } - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(msg_len, pmsg + 14); + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(msg_len, pmsg + 14); - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } - /* If AAD is being used to authenticate, include it here */ - if (aad_len) { - sys_put_be16(aad_len, pmsg); + /* If AAD is being used to authenticate, include it here */ + if (aad_len) { + sys_put_be16(aad_len, pmsg); - for (i = 0; i < sizeof(u16_t); i++) { - pmsg[i] = Xn[i] ^ pmsg[i]; - } + for (i = 0; i < sizeof(u16_t); i++) { + pmsg[i] = Xn[i] ^ pmsg[i]; + } - j = 0; - aad_len += sizeof(u16_t); - while (aad_len > 16) { - do { - pmsg[i] = Xn[i] ^ aad[j]; - i++, j++; - } while (i < 16); + j = 0; + aad_len += sizeof(u16_t); + while (aad_len > 16) { + do { + pmsg[i] = Xn[i] ^ aad[j]; + i++, j++; + } while (i < 16); - aad_len -= 16; - i = 0; + aad_len -= 16; + i = 0; - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } + } - for (; i < aad_len; i++, j++) { - pmsg[i] = Xn[i] ^ aad[j]; - } + for (; i < aad_len; i++, j++) { + pmsg[i] = Xn[i] ^ aad[j]; + } - for (i = aad_len; i < 16; i++) { - pmsg[i] = Xn[i]; - } + for (i = aad_len; i < 16; i++) { + pmsg[i] = Xn[i]; + } - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } + } - last_blk = msg_len % 16; - blk_cnt = (msg_len + 15) / 16; - if (!last_blk) { - last_blk = 16U; - } + last_blk = msg_len % 16; + blk_cnt = (msg_len + 15) / 16; + if (!last_blk) { + last_blk = 16U; + } - for (j = 0; j < blk_cnt; j++) { - if (j + 1 == blk_cnt) { - /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ - pmsg[0] = 0x01; - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(j + 1, pmsg + 14); + for (j = 0; j < blk_cnt; j++) { + if (j + 1 == blk_cnt) { + /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ + pmsg[0] = 0x01; + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(j + 1, pmsg + 14); - err = bt_encrypt_be(key, pmsg, cmsg); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, cmsg); + if (err) { + return err; + } - /* Encrypted = Payload[0-15] ^ C_1 */ - for (i = 0; i < last_blk; i++) { - msg[i] = enc_msg[(j * 16) + i] ^ cmsg[i]; - } + /* Encrypted = Payload[0-15] ^ C_1 */ + for (i = 0; i < last_blk; i++) { + msg[i] = enc_msg[(j * 16) + i] ^ cmsg[i]; + } - memcpy(out_msg + (j * 16), msg, last_blk); + memcpy(out_msg + (j * 16), msg, last_blk); - /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ - for (i = 0; i < last_blk; i++) { - pmsg[i] = Xn[i] ^ msg[i]; - } + /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ + for (i = 0; i < last_blk; i++) { + pmsg[i] = Xn[i] ^ msg[i]; + } - for (i = last_blk; i < 16; i++) { - pmsg[i] = Xn[i] ^ 0x00; - } + for (i = last_blk; i < 16; i++) { + pmsg[i] = Xn[i] ^ 0x00; + } - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } - /* MIC = C_mic ^ X_1 */ - for (i = 0; i < sizeof(mic); i++) { - mic[i] = cmic[i] ^ Xn[i]; - } - } else { - /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ - pmsg[0] = 0x01; - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(j + 1, pmsg + 14); + /* MIC = C_mic ^ X_1 */ + for (i = 0; i < sizeof(mic); i++) { + mic[i] = cmic[i] ^ Xn[i]; + } + } else { + /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ + pmsg[0] = 0x01; + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(j + 1, pmsg + 14); - err = bt_encrypt_be(key, pmsg, cmsg); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, cmsg); + if (err) { + return err; + } - /* Encrypted = Payload[0-15] ^ C_1 */ - for (i = 0; i < 16; i++) { - msg[i] = enc_msg[(j * 16) + i] ^ cmsg[i]; - } + /* Encrypted = Payload[0-15] ^ C_1 */ + for (i = 0; i < 16; i++) { + msg[i] = enc_msg[(j * 16) + i] ^ cmsg[i]; + } - memcpy(out_msg + (j * 16), msg, 16); + memcpy(out_msg + (j * 16), msg, 16); - /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ - for (i = 0; i < 16; i++) { - pmsg[i] = Xn[i] ^ msg[i]; - } + /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ + for (i = 0; i < 16; i++) { + pmsg[i] = Xn[i] ^ msg[i]; + } - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } - } - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } + } + } - if (memcmp(mic, enc_msg + msg_len, mic_size)) { - return -EBADMSG; - } + if (memcmp(mic, enc_msg + msg_len, mic_size)) { + return -EBADMSG; + } - return 0; + return 0; } static int bt_mesh_ccm_encrypt(const u8_t key[16], u8_t nonce[13], - const u8_t *msg, size_t msg_len, - const u8_t *aad, size_t aad_len, - u8_t *out_msg, size_t mic_size) + const u8_t *msg, size_t msg_len, + const u8_t *aad, size_t aad_len, + u8_t *out_msg, size_t mic_size) { - u8_t pmsg[16], cmic[16], cmsg[16], mic[16], Xn[16]; - u16_t blk_cnt, last_blk; - size_t i, j; - int err; + u8_t pmsg[16], cmic[16], cmsg[16], mic[16], Xn[16]; + u16_t blk_cnt, last_blk; + size_t i, j; + int err; - BT_DBG("key %s", bt_hex(key, 16)); - BT_DBG("nonce %s", bt_hex(nonce, 13)); - BT_DBG("msg (len %zu) %s", msg_len, bt_hex(msg, msg_len)); - BT_DBG("aad_len %zu mic_size %zu", aad_len, mic_size); + BT_DBG("key %s", bt_hex(key, 16)); + BT_DBG("nonce %s", bt_hex(nonce, 13)); + BT_DBG("msg (len %zu) %s", msg_len, bt_hex(msg, msg_len)); + BT_DBG("aad_len %zu mic_size %zu", aad_len, mic_size); - /* Unsupported AAD size */ - if (aad_len >= 0xff00) { - return -EINVAL; - } + /* Unsupported AAD size */ + if (aad_len >= 0xff00) { + return -EINVAL; + } - /* C_mic = e(AppKey, 0x01 || nonce || 0x0000) */ - pmsg[0] = 0x01; - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(0x0000, pmsg + 14); + /* C_mic = e(AppKey, 0x01 || nonce || 0x0000) */ + pmsg[0] = 0x01; + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(0x0000, pmsg + 14); - err = bt_encrypt_be(key, pmsg, cmic); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, cmic); + if (err) { + return err; + } - /* X_0 = e(AppKey, 0x09 || nonce || length) */ - if (mic_size == sizeof(u64_t)) { - pmsg[0] = 0x19 | (aad_len ? 0x40 : 0x00); - } else { - pmsg[0] = 0x09 | (aad_len ? 0x40 : 0x00); - } + /* X_0 = e(AppKey, 0x09 || nonce || length) */ + if (mic_size == sizeof(u64_t)) { + pmsg[0] = 0x19 | (aad_len ? 0x40 : 0x00); + } else { + pmsg[0] = 0x09 | (aad_len ? 0x40 : 0x00); + } - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(msg_len, pmsg + 14); + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(msg_len, pmsg + 14); - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } - /* If AAD is being used to authenticate, include it here */ - if (aad_len) { - sys_put_be16(aad_len, pmsg); + /* If AAD is being used to authenticate, include it here */ + if (aad_len) { + sys_put_be16(aad_len, pmsg); - for (i = 0; i < sizeof(u16_t); i++) { - pmsg[i] = Xn[i] ^ pmsg[i]; - } + for (i = 0; i < sizeof(u16_t); i++) { + pmsg[i] = Xn[i] ^ pmsg[i]; + } - j = 0; - aad_len += sizeof(u16_t); - while (aad_len > 16) { - do { - pmsg[i] = Xn[i] ^ aad[j]; - i++, j++; - } while (i < 16); + j = 0; + aad_len += sizeof(u16_t); + while (aad_len > 16) { + do { + pmsg[i] = Xn[i] ^ aad[j]; + i++, j++; + } while (i < 16); - aad_len -= 16; - i = 0; + aad_len -= 16; + i = 0; - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } + } - for (; i < aad_len; i++, j++) { - pmsg[i] = Xn[i] ^ aad[j]; - } + for (; i < aad_len; i++, j++) { + pmsg[i] = Xn[i] ^ aad[j]; + } - for (i = aad_len; i < 16; i++) { - pmsg[i] = Xn[i]; - } + for (i = aad_len; i < 16; i++) { + pmsg[i] = Xn[i]; + } - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } + } - last_blk = msg_len % 16; - blk_cnt = (msg_len + 15) / 16; - if (!last_blk) { - last_blk = 16U; - } + last_blk = msg_len % 16; + blk_cnt = (msg_len + 15) / 16; + if (!last_blk) { + last_blk = 16U; + } - for (j = 0; j < blk_cnt; j++) { - if (j + 1 == blk_cnt) { - /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ - for (i = 0; i < last_blk; i++) { - pmsg[i] = Xn[i] ^ msg[(j * 16) + i]; - } - for (i = last_blk; i < 16; i++) { - pmsg[i] = Xn[i] ^ 0x00; - } + for (j = 0; j < blk_cnt; j++) { + if (j + 1 == blk_cnt) { + /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ + for (i = 0; i < last_blk; i++) { + pmsg[i] = Xn[i] ^ msg[(j * 16) + i]; + } + for (i = last_blk; i < 16; i++) { + pmsg[i] = Xn[i] ^ 0x00; + } - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } - /* MIC = C_mic ^ X_1 */ - for (i = 0; i < sizeof(mic); i++) { - mic[i] = cmic[i] ^ Xn[i]; - } + /* MIC = C_mic ^ X_1 */ + for (i = 0; i < sizeof(mic); i++) { + mic[i] = cmic[i] ^ Xn[i]; + } - /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ - pmsg[0] = 0x01; - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(j + 1, pmsg + 14); + /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ + pmsg[0] = 0x01; + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(j + 1, pmsg + 14); - err = bt_encrypt_be(key, pmsg, cmsg); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, cmsg); + if (err) { + return err; + } - /* Encrypted = Payload[0-15] ^ C_1 */ - for (i = 0; i < last_blk; i++) { - out_msg[(j * 16) + i] = - msg[(j * 16) + i] ^ cmsg[i]; - } - } else { - /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ - for (i = 0; i < 16; i++) { - pmsg[i] = Xn[i] ^ msg[(j * 16) + i]; - } + /* Encrypted = Payload[0-15] ^ C_1 */ + for (i = 0; i < last_blk; i++) { + out_msg[(j * 16) + i] = + msg[(j * 16) + i] ^ cmsg[i]; + } + } else { + /* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */ + for (i = 0; i < 16; i++) { + pmsg[i] = Xn[i] ^ msg[(j * 16) + i]; + } - err = bt_encrypt_be(key, pmsg, Xn); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, Xn); + if (err) { + return err; + } - /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ - pmsg[0] = 0x01; - memcpy(pmsg + 1, nonce, 13); - sys_put_be16(j + 1, pmsg + 14); + /* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */ + pmsg[0] = 0x01; + memcpy(pmsg + 1, nonce, 13); + sys_put_be16(j + 1, pmsg + 14); - err = bt_encrypt_be(key, pmsg, cmsg); - if (err) { - return err; - } + err = bt_encrypt_be(key, pmsg, cmsg); + if (err) { + return err; + } - /* Encrypted = Payload[0-15] ^ C_N */ - for (i = 0; i < 16; i++) { - out_msg[(j * 16) + i] = - msg[(j * 16) + i] ^ cmsg[i]; - } + /* Encrypted = Payload[0-15] ^ C_N */ + for (i = 0; i < 16; i++) { + out_msg[(j * 16) + i] = + msg[(j * 16) + i] ^ cmsg[i]; + } - } - } + } + } - memcpy(out_msg + msg_len, mic, mic_size); + memcpy(out_msg + msg_len, mic, mic_size); - return 0; + return 0; } #if defined(CONFIG_BT_MESH_PROXY) static void create_proxy_nonce(u8_t nonce[13], const u8_t *pdu, - u32_t iv_index) + u32_t iv_index) { - /* Nonce Type */ - nonce[0] = 0x03; + /* Nonce Type */ + nonce[0] = 0x03; - /* Pad */ - nonce[1] = 0x00; + /* Pad */ + nonce[1] = 0x00; - /* Sequence Number */ - nonce[2] = pdu[2]; - nonce[3] = pdu[3]; - nonce[4] = pdu[4]; + /* Sequence Number */ + nonce[2] = pdu[2]; + nonce[3] = pdu[3]; + nonce[4] = pdu[4]; - /* Source Address */ - nonce[5] = pdu[5]; - nonce[6] = pdu[6]; + /* Source Address */ + nonce[5] = pdu[5]; + nonce[6] = pdu[6]; - /* Pad */ - nonce[7] = 0U; - nonce[8] = 0U; + /* Pad */ + nonce[7] = 0U; + nonce[8] = 0U; - /* IV Index */ - sys_put_be32(iv_index, &nonce[9]); + /* IV Index */ + sys_put_be32(iv_index, &nonce[9]); } #endif /* PROXY */ static void create_net_nonce(u8_t nonce[13], const u8_t *pdu, - u32_t iv_index) + u32_t iv_index) { - /* Nonce Type */ - nonce[0] = 0x00; + /* Nonce Type */ + nonce[0] = 0x00; - /* FRND + TTL */ - nonce[1] = pdu[1]; + /* FRND + TTL */ + nonce[1] = pdu[1]; - /* Sequence Number */ - nonce[2] = pdu[2]; - nonce[3] = pdu[3]; - nonce[4] = pdu[4]; + /* Sequence Number */ + nonce[2] = pdu[2]; + nonce[3] = pdu[3]; + nonce[4] = pdu[4]; - /* Source Address */ - nonce[5] = pdu[5]; - nonce[6] = pdu[6]; + /* Source Address */ + nonce[5] = pdu[5]; + nonce[6] = pdu[6]; - /* Pad */ - nonce[7] = 0U; - nonce[8] = 0U; + /* Pad */ + nonce[7] = 0U; + nonce[8] = 0U; - /* IV Index */ - sys_put_be32(iv_index, &nonce[9]); + /* IV Index */ + sys_put_be32(iv_index, &nonce[9]); } int bt_mesh_net_obfuscate(u8_t *pdu, u32_t iv_index, - const u8_t privacy_key[16]) + const u8_t privacy_key[16]) { - u8_t priv_rand[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, }; - u8_t tmp[16]; - int err, i; + u8_t priv_rand[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, }; + u8_t tmp[16]; + int err, i; - BT_DBG("IVIndex %u, PrivacyKey %s", iv_index, bt_hex(privacy_key, 16)); + BT_DBG("IVIndex %u, PrivacyKey %s", iv_index, bt_hex(privacy_key, 16)); - sys_put_be32(iv_index, &priv_rand[5]); - memcpy(&priv_rand[9], &pdu[7], 7); + sys_put_be32(iv_index, &priv_rand[5]); + memcpy(&priv_rand[9], &pdu[7], 7); - BT_DBG("PrivacyRandom %s", bt_hex(priv_rand, 16)); + BT_DBG("PrivacyRandom %s", bt_hex(priv_rand, 16)); - err = bt_encrypt_be(privacy_key, priv_rand, tmp); - if (err) { - return err; - } + err = bt_encrypt_be(privacy_key, priv_rand, tmp); + if (err) { + return err; + } - for (i = 0; i < 6; i++) { - pdu[1 + i] ^= tmp[i]; - } + for (i = 0; i < 6; i++) { + pdu[1 + i] ^= tmp[i]; + } - return 0; + return 0; } int bt_mesh_net_encrypt(const u8_t key[16], struct net_buf_simple *buf, - u32_t iv_index, bool proxy) + u32_t iv_index, bool proxy) { - u8_t mic_len = NET_MIC_LEN(buf->data); - u8_t nonce[13]; - int err; + u8_t mic_len = NET_MIC_LEN(buf->data); + u8_t nonce[13]; + int err; - BT_DBG("IVIndex %u EncKey %s mic_len %u", iv_index, bt_hex(key, 16), - mic_len); - BT_DBG("PDU (len %u) %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("IVIndex %u EncKey %s mic_len %u", iv_index, bt_hex(key, 16), + mic_len); + BT_DBG("PDU (len %u) %s", buf->len, bt_hex(buf->data, buf->len)); #if defined(CONFIG_BT_MESH_PROXY) - if (proxy) { - create_proxy_nonce(nonce, buf->data, iv_index); - } else { - create_net_nonce(nonce, buf->data, iv_index); - } + if (proxy) { + create_proxy_nonce(nonce, buf->data, iv_index); + } else { + create_net_nonce(nonce, buf->data, iv_index); + } #else - create_net_nonce(nonce, buf->data, iv_index); + create_net_nonce(nonce, buf->data, iv_index); #endif - BT_DBG("Nonce %s", bt_hex(nonce, 13)); + BT_DBG("Nonce %s", bt_hex(nonce, 13)); - err = bt_mesh_ccm_encrypt(key, nonce, &buf->data[7], buf->len - 7, - NULL, 0, &buf->data[7], mic_len); - if (!err) { - net_buf_simple_add(buf, mic_len); - } + err = bt_mesh_ccm_encrypt(key, nonce, &buf->data[7], buf->len - 7, + NULL, 0, &buf->data[7], mic_len); + if (!err) { + net_buf_simple_add(buf, mic_len); + } - return err; + return err; } int bt_mesh_net_decrypt(const u8_t key[16], struct net_buf_simple *buf, - u32_t iv_index, bool proxy) + u32_t iv_index, bool proxy) { - u8_t mic_len = NET_MIC_LEN(buf->data); - u8_t nonce[13]; + u8_t mic_len = NET_MIC_LEN(buf->data); + u8_t nonce[13]; - BT_DBG("PDU (%u bytes) %s", buf->len, bt_hex(buf->data, buf->len)); - BT_DBG("iv_index %u, key %s mic_len %u", iv_index, bt_hex(key, 16), - mic_len); + BT_DBG("PDU (%u bytes) %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("iv_index %u, key %s mic_len %u", iv_index, bt_hex(key, 16), + mic_len); #if defined(CONFIG_BT_MESH_PROXY) - if (proxy) { - create_proxy_nonce(nonce, buf->data, iv_index); - } else { - create_net_nonce(nonce, buf->data, iv_index); - } + if (proxy) { + create_proxy_nonce(nonce, buf->data, iv_index); + } else { + create_net_nonce(nonce, buf->data, iv_index); + } #else - create_net_nonce(nonce, buf->data, iv_index); + create_net_nonce(nonce, buf->data, iv_index); #endif - BT_DBG("Nonce %s", bt_hex(nonce, 13)); + BT_DBG("Nonce %s", bt_hex(nonce, 13)); - buf->len -= mic_len; + buf->len -= mic_len; - return bt_mesh_ccm_decrypt(key, nonce, &buf->data[7], buf->len - 7, - NULL, 0, &buf->data[7], mic_len); + return bt_mesh_ccm_decrypt(key, nonce, &buf->data[7], buf->len - 7, + NULL, 0, &buf->data[7], mic_len); } static void create_app_nonce(u8_t nonce[13], bool dev_key, u8_t aszmic, - u16_t src, u16_t dst, u32_t seq_num, - u32_t iv_index) + u16_t src, u16_t dst, u32_t seq_num, + u32_t iv_index) { - if (dev_key) { - nonce[0] = 0x02; - } else { - nonce[0] = 0x01; - } + if (dev_key) { + nonce[0] = 0x02; + } else { + nonce[0] = 0x01; + } - sys_put_be32((seq_num | ((u32_t)aszmic << 31)), &nonce[1]); + sys_put_be32((seq_num | ((u32_t)aszmic << 31)), &nonce[1]); - sys_put_be16(src, &nonce[5]); - sys_put_be16(dst, &nonce[7]); + sys_put_be16(src, &nonce[5]); + sys_put_be16(dst, &nonce[7]); - sys_put_be32(iv_index, &nonce[9]); + sys_put_be32(iv_index, &nonce[9]); } int bt_mesh_app_encrypt(const u8_t key[16], bool dev_key, u8_t aszmic, - struct net_buf_simple *buf, const u8_t *ad, - u16_t src, u16_t dst, u32_t seq_num, u32_t iv_index) + struct net_buf_simple *buf, const u8_t *ad, + u16_t src, u16_t dst, u32_t seq_num, u32_t iv_index) { - u8_t nonce[13]; - int err; + u8_t nonce[13]; + int err; - BT_DBG("AppKey %s", bt_hex(key, 16)); - BT_DBG("dev_key %u src 0x%04x dst 0x%04x", dev_key, src, dst); - BT_DBG("seq_num 0x%08x iv_index 0x%08x", seq_num, iv_index); - BT_DBG("Clear: %s", bt_hex(buf->data, buf->len)); + BT_DBG("AppKey %s", bt_hex(key, 16)); + BT_DBG("dev_key %u src 0x%04x dst 0x%04x", dev_key, src, dst); + BT_DBG("seq_num 0x%08x iv_index 0x%08x", seq_num, iv_index); + BT_DBG("Clear: %s", bt_hex(buf->data, buf->len)); - create_app_nonce(nonce, dev_key, aszmic, src, dst, seq_num, iv_index); + create_app_nonce(nonce, dev_key, aszmic, src, dst, seq_num, iv_index); - BT_DBG("Nonce %s", bt_hex(nonce, 13)); + BT_DBG("Nonce %s", bt_hex(nonce, 13)); - err = bt_mesh_ccm_encrypt(key, nonce, buf->data, buf->len, ad, - ad ? 16 : 0, buf->data, APP_MIC_LEN(aszmic)); - if (!err) { - net_buf_simple_add(buf, APP_MIC_LEN(aszmic)); - BT_DBG("Encr: %s", bt_hex(buf->data, buf->len)); - } + err = bt_mesh_ccm_encrypt(key, nonce, buf->data, buf->len, ad, + ad ? 16 : 0, buf->data, APP_MIC_LEN(aszmic)); + if (!err) { + net_buf_simple_add(buf, APP_MIC_LEN(aszmic)); + BT_DBG("Encr: %s", bt_hex(buf->data, buf->len)); + } - return err; + return err; } int bt_mesh_app_decrypt(const u8_t key[16], bool dev_key, u8_t aszmic, - struct net_buf_simple *buf, struct net_buf_simple *out, - const u8_t *ad, u16_t src, u16_t dst, u32_t seq_num, - u32_t iv_index) + struct net_buf_simple *buf, struct net_buf_simple *out, + const u8_t *ad, u16_t src, u16_t dst, u32_t seq_num, + u32_t iv_index) { - u8_t nonce[13]; - int err; + u8_t nonce[13]; + int err; - BT_DBG("EncData (len %u) %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("EncData (len %u) %s", buf->len, bt_hex(buf->data, buf->len)); - create_app_nonce(nonce, dev_key, aszmic, src, dst, seq_num, iv_index); + create_app_nonce(nonce, dev_key, aszmic, src, dst, seq_num, iv_index); - BT_DBG("AppKey %s", bt_hex(key, 16)); - BT_DBG("Nonce %s", bt_hex(nonce, 13)); + BT_DBG("AppKey %s", bt_hex(key, 16)); + BT_DBG("Nonce %s", bt_hex(nonce, 13)); - err = bt_mesh_ccm_decrypt(key, nonce, buf->data, buf->len, ad, - ad ? 16 : 0, out->data, APP_MIC_LEN(aszmic)); - if (!err) { - net_buf_simple_add(out, buf->len); - } + err = bt_mesh_ccm_decrypt(key, nonce, buf->data, buf->len, ad, + ad ? 16 : 0, out->data, APP_MIC_LEN(aszmic)); + if (!err) { + net_buf_simple_add(out, buf->len); + } - return err; + return err; } /* reversed, 8-bit, poly=0x07 */ static const u8_t crc_table[256] = { - 0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75, - 0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b, - 0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69, - 0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67, + 0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75, + 0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b, + 0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69, + 0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67, - 0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d, - 0x36, 0xa7, 0xd5, 0x44, 0x31, 0xa0, 0xd2, 0x43, - 0x24, 0xb5, 0xc7, 0x56, 0x23, 0xb2, 0xc0, 0x51, - 0x2a, 0xbb, 0xc9, 0x58, 0x2d, 0xbc, 0xce, 0x5f, + 0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d, + 0x36, 0xa7, 0xd5, 0x44, 0x31, 0xa0, 0xd2, 0x43, + 0x24, 0xb5, 0xc7, 0x56, 0x23, 0xb2, 0xc0, 0x51, + 0x2a, 0xbb, 0xc9, 0x58, 0x2d, 0xbc, 0xce, 0x5f, - 0x70, 0xe1, 0x93, 0x02, 0x77, 0xe6, 0x94, 0x05, - 0x7e, 0xef, 0x9d, 0x0c, 0x79, 0xe8, 0x9a, 0x0b, - 0x6c, 0xfd, 0x8f, 0x1e, 0x6b, 0xfa, 0x88, 0x19, - 0x62, 0xf3, 0x81, 0x10, 0x65, 0xf4, 0x86, 0x17, + 0x70, 0xe1, 0x93, 0x02, 0x77, 0xe6, 0x94, 0x05, + 0x7e, 0xef, 0x9d, 0x0c, 0x79, 0xe8, 0x9a, 0x0b, + 0x6c, 0xfd, 0x8f, 0x1e, 0x6b, 0xfa, 0x88, 0x19, + 0x62, 0xf3, 0x81, 0x10, 0x65, 0xf4, 0x86, 0x17, - 0x48, 0xd9, 0xab, 0x3a, 0x4f, 0xde, 0xac, 0x3d, - 0x46, 0xd7, 0xa5, 0x34, 0x41, 0xd0, 0xa2, 0x33, - 0x54, 0xc5, 0xb7, 0x26, 0x53, 0xc2, 0xb0, 0x21, - 0x5a, 0xcb, 0xb9, 0x28, 0x5d, 0xcc, 0xbe, 0x2f, + 0x48, 0xd9, 0xab, 0x3a, 0x4f, 0xde, 0xac, 0x3d, + 0x46, 0xd7, 0xa5, 0x34, 0x41, 0xd0, 0xa2, 0x33, + 0x54, 0xc5, 0xb7, 0x26, 0x53, 0xc2, 0xb0, 0x21, + 0x5a, 0xcb, 0xb9, 0x28, 0x5d, 0xcc, 0xbe, 0x2f, - 0xe0, 0x71, 0x03, 0x92, 0xe7, 0x76, 0x04, 0x95, - 0xee, 0x7f, 0x0d, 0x9c, 0xe9, 0x78, 0x0a, 0x9b, - 0xfc, 0x6d, 0x1f, 0x8e, 0xfb, 0x6a, 0x18, 0x89, - 0xf2, 0x63, 0x11, 0x80, 0xf5, 0x64, 0x16, 0x87, + 0xe0, 0x71, 0x03, 0x92, 0xe7, 0x76, 0x04, 0x95, + 0xee, 0x7f, 0x0d, 0x9c, 0xe9, 0x78, 0x0a, 0x9b, + 0xfc, 0x6d, 0x1f, 0x8e, 0xfb, 0x6a, 0x18, 0x89, + 0xf2, 0x63, 0x11, 0x80, 0xf5, 0x64, 0x16, 0x87, - 0xd8, 0x49, 0x3b, 0xaa, 0xdf, 0x4e, 0x3c, 0xad, - 0xd6, 0x47, 0x35, 0xa4, 0xd1, 0x40, 0x32, 0xa3, - 0xc4, 0x55, 0x27, 0xb6, 0xc3, 0x52, 0x20, 0xb1, - 0xca, 0x5b, 0x29, 0xb8, 0xcd, 0x5c, 0x2e, 0xbf, + 0xd8, 0x49, 0x3b, 0xaa, 0xdf, 0x4e, 0x3c, 0xad, + 0xd6, 0x47, 0x35, 0xa4, 0xd1, 0x40, 0x32, 0xa3, + 0xc4, 0x55, 0x27, 0xb6, 0xc3, 0x52, 0x20, 0xb1, + 0xca, 0x5b, 0x29, 0xb8, 0xcd, 0x5c, 0x2e, 0xbf, - 0x90, 0x01, 0x73, 0xe2, 0x97, 0x06, 0x74, 0xe5, - 0x9e, 0x0f, 0x7d, 0xec, 0x99, 0x08, 0x7a, 0xeb, - 0x8c, 0x1d, 0x6f, 0xfe, 0x8b, 0x1a, 0x68, 0xf9, - 0x82, 0x13, 0x61, 0xf0, 0x85, 0x14, 0x66, 0xf7, + 0x90, 0x01, 0x73, 0xe2, 0x97, 0x06, 0x74, 0xe5, + 0x9e, 0x0f, 0x7d, 0xec, 0x99, 0x08, 0x7a, 0xeb, + 0x8c, 0x1d, 0x6f, 0xfe, 0x8b, 0x1a, 0x68, 0xf9, + 0x82, 0x13, 0x61, 0xf0, 0x85, 0x14, 0x66, 0xf7, - 0xa8, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd, - 0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3, - 0xb4, 0x25, 0x57, 0xc6, 0xb3, 0x22, 0x50, 0xc1, - 0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf + 0xa8, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd, + 0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3, + 0xb4, 0x25, 0x57, 0xc6, 0xb3, 0x22, 0x50, 0xc1, + 0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf }; u8_t bt_mesh_fcs_calc(const u8_t *data, u8_t data_len) { - u8_t fcs = 0xff; + u8_t fcs = 0xff; - while (data_len--) { - fcs = crc_table[fcs ^ *data++]; - } + while (data_len--) { + fcs = crc_table[fcs ^ *data++]; + } - BT_DBG("fcs 0x%02x", 0xff - fcs); + BT_DBG("fcs 0x%02x", 0xff - fcs); - return 0xff - fcs; + return 0xff - fcs; } bool bt_mesh_fcs_check(struct net_buf_simple *buf, u8_t received_fcs) { - const u8_t *data = buf->data; - u16_t data_len = buf->len; - u8_t fcs = 0xff; + const u8_t *data = buf->data; + u16_t data_len = buf->len; + u8_t fcs = 0xff; - while (data_len--) { - fcs = crc_table[fcs ^ *data++]; - } + while (data_len--) { + fcs = crc_table[fcs ^ *data++]; + } - return crc_table[fcs ^ received_fcs] == 0xcf; + return crc_table[fcs ^ received_fcs] == 0xcf; } int bt_mesh_virtual_addr(const u8_t virtual_label[16], u16_t *addr) { - u8_t salt[16]; - u8_t tmp[16]; - int err; + u8_t salt[16]; + u8_t tmp[16]; + int err; - err = bt_mesh_s1("vtad", salt); - if (err) { - return err; - } + err = bt_mesh_s1("vtad", salt); + if (err) { + return err; + } - err = bt_mesh_aes_cmac_one(salt, virtual_label, 16, tmp); - if (err) { - return err; - } + err = bt_mesh_aes_cmac_one(salt, virtual_label, 16, tmp); + if (err) { + return err; + } - *addr = (sys_get_be16(&tmp[14]) & 0x3fff) | 0x8000; + *addr = (sys_get_be16(&tmp[14]) & 0x3fff) | 0x8000; - return 0; + return 0; } int bt_mesh_prov_conf_salt(const u8_t conf_inputs[145], u8_t salt[16]) { - const u8_t conf_salt_key[16] = { 0 }; + const u8_t conf_salt_key[16] = { 0 }; - return bt_mesh_aes_cmac_one(conf_salt_key, conf_inputs, 145, salt); + return bt_mesh_aes_cmac_one(conf_salt_key, conf_inputs, 145, salt); } int bt_mesh_prov_conf_key(const u8_t dhkey[32], const u8_t conf_salt[16], - u8_t conf_key[16]) + u8_t conf_key[16]) { - return bt_mesh_k1(dhkey, 32, conf_salt, "prck", conf_key); + return bt_mesh_k1(dhkey, 32, conf_salt, "prck", conf_key); } int bt_mesh_prov_conf(const u8_t conf_key[16], const u8_t rand[16], - const u8_t auth[16], u8_t conf[16]) + const u8_t auth[16], u8_t conf[16]) { - struct bt_mesh_sg sg[] = { { rand, 16 }, { auth, 16 } }; + struct bt_mesh_sg sg[] = { { rand, 16 }, { auth, 16 } }; - BT_DBG("ConfirmationKey %s", bt_hex(conf_key, 16)); - BT_DBG("RandomDevice %s", bt_hex(rand, 16)); - BT_DBG("AuthValue %s", bt_hex(auth, 16)); + BT_DBG("ConfirmationKey %s", bt_hex(conf_key, 16)); + BT_DBG("RandomDevice %s", bt_hex(rand, 16)); + BT_DBG("AuthValue %s", bt_hex(auth, 16)); - return bt_mesh_aes_cmac(conf_key, sg, ARRAY_SIZE(sg), conf); + return bt_mesh_aes_cmac(conf_key, sg, ARRAY_SIZE(sg), conf); } int bt_mesh_prov_decrypt(const u8_t key[16], u8_t nonce[13], - const u8_t data[25 + 8], u8_t out[25]) + const u8_t data[25 + 8], u8_t out[25]) { - return bt_mesh_ccm_decrypt(key, nonce, data, 25, NULL, 0, out, 8); + return bt_mesh_ccm_decrypt(key, nonce, data, 25, NULL, 0, out, 8); } int bt_mesh_beacon_auth(const u8_t beacon_key[16], u8_t flags, - const u8_t net_id[8], u32_t iv_index, - u8_t auth[8]) + const u8_t net_id[8], u32_t iv_index, + u8_t auth[8]) { - u8_t msg[13], tmp[16]; - int err; + u8_t msg[13], tmp[16]; + int err; - BT_DBG("BeaconKey %s", bt_hex(beacon_key, 16)); - BT_DBG("NetId %s", bt_hex(net_id, 8)); - BT_DBG("IV Index 0x%08x", iv_index); + BT_DBG("BeaconKey %s", bt_hex(beacon_key, 16)); + BT_DBG("NetId %s", bt_hex(net_id, 8)); + BT_DBG("IV Index 0x%08x", iv_index); - msg[0] = flags; - memcpy(&msg[1], net_id, 8); - sys_put_be32(iv_index, &msg[9]); + msg[0] = flags; + memcpy(&msg[1], net_id, 8); + sys_put_be32(iv_index, &msg[9]); - BT_DBG("BeaconMsg %s", bt_hex(msg, sizeof(msg))); + BT_DBG("BeaconMsg %s", bt_hex(msg, sizeof(msg))); - err = bt_mesh_aes_cmac_one(beacon_key, msg, sizeof(msg), tmp); - if (!err) { - memcpy(auth, tmp, 8); - } + err = bt_mesh_aes_cmac_one(beacon_key, msg, sizeof(msg), tmp); + if (!err) { + memcpy(auth, tmp, 8); + } - return err; + return err; } diff --git a/components/network/ble/blemesh/src/crypto.h b/components/network/ble/blemesh/src/crypto.h index ab337938..f7b56b33 100644 --- a/components/network/ble/blemesh/src/crypto.h +++ b/components/network/ble/blemesh/src/crypto.h @@ -9,39 +9,39 @@ #define __CRYPTO_H__ struct bt_mesh_sg { - const void *data; - size_t len; + const void *data; + size_t len; }; int bt_mesh_aes_cmac(const u8_t key[16], struct bt_mesh_sg *sg, - size_t sg_len, u8_t mac[16]); + size_t sg_len, u8_t mac[16]); static inline int bt_mesh_aes_cmac_one(const u8_t key[16], const void *m, - size_t len, u8_t mac[16]) + size_t len, u8_t mac[16]) { - struct bt_mesh_sg sg = { m, len }; + struct bt_mesh_sg sg = { m, len }; - return bt_mesh_aes_cmac(key, &sg, 1, mac); + return bt_mesh_aes_cmac(key, &sg, 1, mac); } static inline bool bt_mesh_s1(const char *m, u8_t salt[16]) { - const u8_t zero[16] = { 0 }; + const u8_t zero[16] = { 0 }; - return bt_mesh_aes_cmac_one(zero, m, strlen(m), salt); + return bt_mesh_aes_cmac_one(zero, m, strlen(m), salt); } int bt_mesh_k1(const u8_t *ikm, size_t ikm_len, const u8_t salt[16], - const char *info, u8_t okm[16]); + const char *info, u8_t okm[16]); #define bt_mesh_k1_str(ikm, ikm_len, salt_str, info, okm) \ ({ \ - const u8_t salt[16] = salt_str; \ - bt_mesh_k1(ikm, ikm_len, salt, info, okm); \ + const u8_t salt[16] = salt_str; \ + bt_mesh_k1(ikm, ikm_len, salt, info, okm); \ }) int bt_mesh_k2(const u8_t n[16], const u8_t *p, size_t p_len, - u8_t net_id[1], u8_t enc_key[16], u8_t priv_key[16]); + u8_t net_id[1], u8_t enc_key[16], u8_t priv_key[16]); int bt_mesh_k3(const u8_t n[16], u8_t out[8]); @@ -50,93 +50,93 @@ int bt_mesh_k4(const u8_t n[16], u8_t out[1]); int bt_mesh_id128(const u8_t n[16], const char *s, u8_t out[16]); static inline int bt_mesh_id_resolving_key(const u8_t net_key[16], - u8_t resolving_key[16]) + u8_t resolving_key[16]) { - return bt_mesh_k1_str(net_key, 16, "smbt", "smbi", resolving_key); + return bt_mesh_k1_str(net_key, 16, "smbt", "smbi", resolving_key); } static inline int bt_mesh_identity_key(const u8_t net_key[16], - u8_t identity_key[16]) + u8_t identity_key[16]) { - return bt_mesh_id128(net_key, "nkik", identity_key); + return bt_mesh_id128(net_key, "nkik", identity_key); } static inline int bt_mesh_beacon_key(const u8_t net_key[16], - u8_t beacon_key[16]) + u8_t beacon_key[16]) { - return bt_mesh_id128(net_key, "nkbk", beacon_key); + return bt_mesh_id128(net_key, "nkbk", beacon_key); } int bt_mesh_beacon_auth(const u8_t beacon_key[16], u8_t flags, - const u8_t net_id[16], u32_t iv_index, - u8_t auth[8]); + const u8_t net_id[16], u32_t iv_index, + u8_t auth[8]); static inline int bt_mesh_app_id(const u8_t app_key[16], u8_t app_id[1]) { - return bt_mesh_k4(app_key, app_id); + return bt_mesh_k4(app_key, app_id); } static inline int bt_mesh_session_key(const u8_t dhkey[32], - const u8_t prov_salt[16], - u8_t session_key[16]) + const u8_t prov_salt[16], + u8_t session_key[16]) { - return bt_mesh_k1(dhkey, 32, prov_salt, "prsk", session_key); + return bt_mesh_k1(dhkey, 32, prov_salt, "prsk", session_key); } static inline int bt_mesh_prov_nonce(const u8_t dhkey[32], - const u8_t prov_salt[16], - u8_t nonce[13]) + const u8_t prov_salt[16], + u8_t nonce[13]) { - u8_t tmp[16]; - int err; + u8_t tmp[16]; + int err; - err = bt_mesh_k1(dhkey, 32, prov_salt, "prsn", tmp); - if (!err) { - memcpy(nonce, tmp + 3, 13); - } + err = bt_mesh_k1(dhkey, 32, prov_salt, "prsn", tmp); + if (!err) { + memcpy(nonce, tmp + 3, 13); + } - return err; + return err; } static inline int bt_mesh_dev_key(const u8_t dhkey[32], - const u8_t prov_salt[16], - u8_t dev_key[16]) + const u8_t prov_salt[16], + u8_t dev_key[16]) { - return bt_mesh_k1(dhkey, 32, prov_salt, "prdk", dev_key); + return bt_mesh_k1(dhkey, 32, prov_salt, "prdk", dev_key); } static inline int bt_mesh_prov_salt(const u8_t conf_salt[16], - const u8_t prov_rand[16], - const u8_t dev_rand[16], - u8_t prov_salt[16]) + const u8_t prov_rand[16], + const u8_t dev_rand[16], + u8_t prov_salt[16]) { - const u8_t prov_salt_key[16] = { 0 }; - struct bt_mesh_sg sg[] = { - { conf_salt, 16 }, - { prov_rand, 16 }, - { dev_rand, 16 }, - }; + const u8_t prov_salt_key[16] = { 0 }; + struct bt_mesh_sg sg[] = { + { conf_salt, 16 }, + { prov_rand, 16 }, + { dev_rand, 16 }, + }; - return bt_mesh_aes_cmac(prov_salt_key, sg, ARRAY_SIZE(sg), prov_salt); + return bt_mesh_aes_cmac(prov_salt_key, sg, ARRAY_SIZE(sg), prov_salt); } int bt_mesh_net_obfuscate(u8_t *pdu, u32_t iv_index, - const u8_t privacy_key[16]); + const u8_t privacy_key[16]); int bt_mesh_net_encrypt(const u8_t key[16], struct net_buf_simple *buf, - u32_t iv_index, bool proxy); + u32_t iv_index, bool proxy); int bt_mesh_net_decrypt(const u8_t key[16], struct net_buf_simple *buf, - u32_t iv_index, bool proxy); + u32_t iv_index, bool proxy); int bt_mesh_app_encrypt(const u8_t key[16], bool dev_key, u8_t aszmic, - struct net_buf_simple *buf, const u8_t *ad, - u16_t src, u16_t dst, u32_t seq_num, u32_t iv_index); + struct net_buf_simple *buf, const u8_t *ad, + u16_t src, u16_t dst, u32_t seq_num, u32_t iv_index); int bt_mesh_app_decrypt(const u8_t key[16], bool dev_key, u8_t aszmic, - struct net_buf_simple *buf, struct net_buf_simple *out, - const u8_t *ad, u16_t src, u16_t dst, u32_t seq_num, - u32_t iv_index); + struct net_buf_simple *buf, struct net_buf_simple *out, + const u8_t *ad, u16_t src, u16_t dst, u32_t seq_num, + u32_t iv_index); u8_t bt_mesh_fcs_calc(const u8_t *data, u8_t data_len); @@ -147,12 +147,12 @@ int bt_mesh_virtual_addr(const u8_t virtual_label[16], u16_t *addr); int bt_mesh_prov_conf_salt(const u8_t conf_inputs[145], u8_t salt[16]); int bt_mesh_prov_conf_key(const u8_t dhkey[32], const u8_t conf_salt[16], - u8_t conf_key[16]); + u8_t conf_key[16]); int bt_mesh_prov_conf(const u8_t conf_key[16], const u8_t rand[16], - const u8_t auth[16], u8_t conf[16]); + const u8_t auth[16], u8_t conf[16]); int bt_mesh_prov_decrypt(const u8_t key[16], u8_t nonce[13], - const u8_t data[25 + 8], u8_t out[25]); + const u8_t data[25 + 8], u8_t out[25]); #endif /*__CRYPTO_H__*/ diff --git a/components/network/ble/blemesh/src/ecb.h b/components/network/ble/blemesh/src/ecb.h index 28fd4404..6532a360 100644 --- a/components/network/ble/blemesh/src/ecb.h +++ b/components/network/ble/blemesh/src/ecb.h @@ -10,21 +10,21 @@ typedef void (*ecb_fp) (u32_t status, u8_t *cipher_be, void *context); struct ecb { - u8_t in_key_be[16]; - u8_t in_clear_text_be[16]; - u8_t out_cipher_text_be[16]; - /* if not null reverse copy into in_key_be */ - u8_t *in_key_le; - /* if not null reverse copy into in_clear_text_be */ - u8_t *in_clear_text_le; - ecb_fp fp_ecb; - void *context; + u8_t in_key_be[16]; + u8_t in_clear_text_be[16]; + u8_t out_cipher_text_be[16]; + /* if not null reverse copy into in_key_be */ + u8_t *in_key_le; + /* if not null reverse copy into in_clear_text_be */ + u8_t *in_clear_text_le; + ecb_fp fp_ecb; + void *context; }; void ecb_encrypt_be(u8_t const *const key_be, u8_t const *const clear_text_be, - u8_t * const cipher_text_be); + u8_t * const cipher_text_be); void ecb_encrypt(u8_t const *const key_le, u8_t const *const clear_text_le, - u8_t * const cipher_text_le, u8_t * const cipher_text_be); + u8_t * const cipher_text_le, u8_t * const cipher_text_be); u32_t ecb_encrypt_nonblocking(struct ecb *ecb); void isr_ecb(void *param); diff --git a/components/network/ble/blemesh/src/foundation.h b/components/network/ble/blemesh/src/foundation.h index 0cf4e95a..02dd0eb3 100644 --- a/components/network/ble/blemesh/src/foundation.h +++ b/components/network/ble/blemesh/src/foundation.h @@ -150,18 +150,18 @@ void bt_mesh_app_key_del(struct bt_mesh_app_key *key, bool store); #include static inline void key_idx_pack(struct net_buf_simple *buf, - u16_t idx1, u16_t idx2) + u16_t idx1, u16_t idx2) { - net_buf_simple_add_le16(buf, idx1 | ((idx2 & 0x00f) << 12)); - net_buf_simple_add_u8(buf, idx2 >> 4); + net_buf_simple_add_le16(buf, idx1 | ((idx2 & 0x00f) << 12)); + net_buf_simple_add_u8(buf, idx2 >> 4); } static inline void key_idx_unpack(struct net_buf_simple *buf, - u16_t *idx1, u16_t *idx2) + u16_t *idx1, u16_t *idx2) { - *idx1 = sys_get_le16(&buf->data[0]) & 0xfff; - *idx2 = sys_get_le16(&buf->data[1]) >> 4; - net_buf_simple_pull(buf, 3); + *idx1 = sys_get_le16(&buf->data[0]) & 0xfff; + *idx2 = sys_get_le16(&buf->data[1]) >> 4; + net_buf_simple_pull(buf, 3); } #endif /*__FOUNDATION_H__*/ diff --git a/components/network/ble/blemesh/src/friend.c b/components/network/ble/blemesh/src/friend.c index dd41d7c5..f9bde175 100644 --- a/components/network/ble/blemesh/src/friend.c +++ b/components/network/ble/blemesh/src/friend.c @@ -35,10 +35,10 @@ * to resend the last sent PDU, which sits separately outside of the queue. */ #define FRIEND_BUF_COUNT ((CONFIG_BT_MESH_FRIEND_QUEUE_SIZE + 1) * \ - CONFIG_BT_MESH_FRIEND_LPN_COUNT) + CONFIG_BT_MESH_FRIEND_LPN_COUNT) #define FRIEND_ADV(buf) CONTAINER_OF(BT_MESH_ADV(buf), \ - struct friend_adv, adv) + struct friend_adv, adv) /* PDUs from Friend to the LPN should only be transmitted once with the * smallest possible interval (20ms). @@ -46,81 +46,81 @@ #define FRIEND_XMIT BT_MESH_TRANSMIT(0, 20) struct friend_pdu_info { - u16_t src; - u16_t dst; + u16_t src; + u16_t dst; - u8_t seq[3]; + u8_t seq[3]; - u8_t ttl:7, - ctl:1; + u8_t ttl:7, + ctl:1; - u32_t iv_index; + u32_t iv_index; }; NET_BUF_POOL_FIXED_DEFINE(friend_buf_pool, FRIEND_BUF_COUNT, - BT_MESH_ADV_DATA_SIZE, NULL); + BT_MESH_ADV_DATA_SIZE, NULL); static struct friend_adv { - struct bt_mesh_adv adv; - u64_t seq_auth; + struct bt_mesh_adv adv; + u64_t seq_auth; } adv_pool[FRIEND_BUF_COUNT]; static struct bt_mesh_adv *adv_alloc(int id) { - return &adv_pool[id].adv; + return &adv_pool[id].adv; } static bool is_lpn_unicast(struct bt_mesh_friend *frnd, u16_t addr) { - if (frnd->lpn == BT_MESH_ADDR_UNASSIGNED) { - return false; - } + if (frnd->lpn == BT_MESH_ADDR_UNASSIGNED) { + return false; + } - return (addr >= frnd->lpn && addr < (frnd->lpn + frnd->num_elem)); + return (addr >= frnd->lpn && addr < (frnd->lpn + frnd->num_elem)); } struct bt_mesh_friend *bt_mesh_friend_find(u16_t net_idx, u16_t lpn_addr, - bool valid, bool established) + bool valid, bool established) { - int i; + int i; - BT_DBG("net_idx 0x%04x lpn_addr 0x%04x", net_idx, lpn_addr); + BT_DBG("net_idx 0x%04x lpn_addr 0x%04x", net_idx, lpn_addr); - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (valid && !frnd->valid) { - continue; - } + if (valid && !frnd->valid) { + continue; + } - if (established && !frnd->established) { - continue; - } + if (established && !frnd->established) { + continue; + } - if (net_idx != BT_MESH_KEY_ANY && frnd->net_idx != net_idx) { - continue; - } + if (net_idx != BT_MESH_KEY_ANY && frnd->net_idx != net_idx) { + continue; + } - if (is_lpn_unicast(frnd, lpn_addr)) { - return frnd; - } - } + if (is_lpn_unicast(frnd, lpn_addr)) { + return frnd; + } + } - return NULL; + return NULL; } static void purge_buffers(sys_slist_t *list) { - while (!sys_slist_is_empty(list)) { - struct net_buf *buf; + while (!sys_slist_is_empty(list)) { + struct net_buf *buf; - buf = (void *)sys_slist_get_not_empty(list); + buf = (void *)sys_slist_get_not_empty(list); - buf->frags = NULL; - buf->flags &= ~NET_BUF_FRAGS; + buf->frags = NULL; + buf->flags &= ~NET_BUF_FRAGS; - net_buf_unref(buf); - } + net_buf_unref(buf); + } } /* Intentionally start a little bit late into the ReceiveWindow when @@ -131,618 +131,618 @@ static void purge_buffers(sys_slist_t *list) static s32_t recv_delay(struct bt_mesh_friend *frnd) { #if CONFIG_BT_MESH_FRIEND_RECV_WIN > 50 - return (s32_t)frnd->recv_delay + (CONFIG_BT_MESH_FRIEND_RECV_WIN / 5); + return (s32_t)frnd->recv_delay + (CONFIG_BT_MESH_FRIEND_RECV_WIN / 5); #else - return frnd->recv_delay; + return frnd->recv_delay; #endif } static void friend_clear(struct bt_mesh_friend *frnd) { - int i; + int i; - BT_DBG("LPN 0x%04x", frnd->lpn); + BT_DBG("LPN 0x%04x", frnd->lpn); - k_delayed_work_cancel(&frnd->timer); + k_delayed_work_cancel(&frnd->timer); - friend_cred_del(frnd->net_idx, frnd->lpn); + friend_cred_del(frnd->net_idx, frnd->lpn); - if (frnd->last) { - /* Cancel the sending if necessary */ - if (frnd->pending_buf) { - BT_MESH_ADV(frnd->last)->busy = 0U; - } + if (frnd->last) { + /* Cancel the sending if necessary */ + if (frnd->pending_buf) { + BT_MESH_ADV(frnd->last)->busy = 0U; + } - net_buf_unref(frnd->last); - frnd->last = NULL; - } + net_buf_unref(frnd->last); + frnd->last = NULL; + } - purge_buffers(&frnd->queue); + purge_buffers(&frnd->queue); - for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) { - struct bt_mesh_friend_seg *seg = &frnd->seg[i]; + for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) { + struct bt_mesh_friend_seg *seg = &frnd->seg[i]; - purge_buffers(&seg->queue); - seg->seg_count = 0U; - } + purge_buffers(&seg->queue); + seg->seg_count = 0U; + } - frnd->valid = 0U; - frnd->established = 0U; - frnd->pending_buf = 0U; - frnd->fsn = 0U; - frnd->queue_size = 0U; - frnd->pending_req = 0U; - (void)memset(frnd->sub_list, 0, sizeof(frnd->sub_list)); + frnd->valid = 0U; + frnd->established = 0U; + frnd->pending_buf = 0U; + frnd->fsn = 0U; + frnd->queue_size = 0U; + frnd->pending_req = 0U; + (void)memset(frnd->sub_list, 0, sizeof(frnd->sub_list)); } void bt_mesh_friend_clear_net_idx(u16_t net_idx) { - int i; + int i; - BT_DBG("net_idx 0x%04x", net_idx); + BT_DBG("net_idx 0x%04x", net_idx); - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (frnd->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (frnd->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - if (net_idx == BT_MESH_KEY_ANY || frnd->net_idx == net_idx) { - friend_clear(frnd); - } - } + if (net_idx == BT_MESH_KEY_ANY || frnd->net_idx == net_idx) { + friend_clear(frnd); + } + } } void bt_mesh_friend_sec_update(u16_t net_idx) { - int i; + int i; - BT_DBG("net_idx 0x%04x", net_idx); + BT_DBG("net_idx 0x%04x", net_idx); - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (frnd->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (frnd->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - if (net_idx == BT_MESH_KEY_ANY || frnd->net_idx == net_idx) { - frnd->sec_update = 1U; - } - } + if (net_idx == BT_MESH_KEY_ANY || frnd->net_idx == net_idx) { + frnd->sec_update = 1U; + } + } } int bt_mesh_friend_clear(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_clear *msg = (void *)buf->data; - struct bt_mesh_friend *frnd; - u16_t lpn_addr, lpn_counter; - struct bt_mesh_net_tx tx = { - .sub = rx->sub, - .ctx = &rx->ctx, - .src = bt_mesh_primary_addr(), - .xmit = bt_mesh_net_transmit_get(), - }; - struct bt_mesh_ctl_friend_clear_confirm cfm; + struct bt_mesh_ctl_friend_clear *msg = (void *)buf->data; + struct bt_mesh_friend *frnd; + u16_t lpn_addr, lpn_counter; + struct bt_mesh_net_tx tx = { + .sub = rx->sub, + .ctx = &rx->ctx, + .src = bt_mesh_primary_addr(), + .xmit = bt_mesh_net_transmit_get(), + }; + struct bt_mesh_ctl_friend_clear_confirm cfm; - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Clear"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Clear"); + return -EINVAL; + } - lpn_addr = sys_be16_to_cpu(msg->lpn_addr); - lpn_counter = sys_be16_to_cpu(msg->lpn_counter); + lpn_addr = sys_be16_to_cpu(msg->lpn_addr); + lpn_counter = sys_be16_to_cpu(msg->lpn_counter); - BT_DBG("LPN addr 0x%04x counter 0x%04x", lpn_addr, lpn_counter); + BT_DBG("LPN addr 0x%04x counter 0x%04x", lpn_addr, lpn_counter); - frnd = bt_mesh_friend_find(rx->sub->net_idx, lpn_addr, false, false); - if (!frnd) { - BT_WARN("No matching LPN addr 0x%04x", lpn_addr); - return 0; - } + frnd = bt_mesh_friend_find(rx->sub->net_idx, lpn_addr, false, false); + if (!frnd) { + BT_WARN("No matching LPN addr 0x%04x", lpn_addr); + return 0; + } - /* A Friend Clear message is considered valid if the result of the - * subtraction of the value of the LPNCounter field of the Friend - * Request message (the one that initiated the friendship) from the - * value of the LPNCounter field of the Friend Clear message, modulo - * 65536, is in the range 0 to 255 inclusive. - */ - if (lpn_counter - frnd->lpn_counter > 255) { - BT_WARN("LPN Counter out of range (old %u new %u)", - frnd->lpn_counter, lpn_counter); - return 0; - } + /* A Friend Clear message is considered valid if the result of the + * subtraction of the value of the LPNCounter field of the Friend + * Request message (the one that initiated the friendship) from the + * value of the LPNCounter field of the Friend Clear message, modulo + * 65536, is in the range 0 to 255 inclusive. + */ + if (lpn_counter - frnd->lpn_counter > 255) { + BT_WARN("LPN Counter out of range (old %u new %u)", + frnd->lpn_counter, lpn_counter); + return 0; + } - tx.ctx->send_ttl = BT_MESH_TTL_MAX; + tx.ctx->send_ttl = BT_MESH_TTL_MAX; - cfm.lpn_addr = msg->lpn_addr; - cfm.lpn_counter = msg->lpn_counter; + cfm.lpn_addr = msg->lpn_addr; + cfm.lpn_counter = msg->lpn_counter; - bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR_CFM, &cfm, - sizeof(cfm), NULL, NULL, NULL); + bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR_CFM, &cfm, + sizeof(cfm), NULL, NULL, NULL); - friend_clear(frnd); + friend_clear(frnd); - return 0; + return 0; } static void friend_sub_add(struct bt_mesh_friend *frnd, u16_t addr) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) { - if (frnd->sub_list[i] == BT_MESH_ADDR_UNASSIGNED) { - frnd->sub_list[i] = addr; - return; - } - } + for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) { + if (frnd->sub_list[i] == BT_MESH_ADDR_UNASSIGNED) { + frnd->sub_list[i] = addr; + return; + } + } - BT_WARN("No space in friend subscription list"); + BT_WARN("No space in friend subscription list"); } static void friend_sub_rem(struct bt_mesh_friend *frnd, u16_t addr) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) { - if (frnd->sub_list[i] == addr) { - frnd->sub_list[i] = BT_MESH_ADDR_UNASSIGNED; - return; - } - } + for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) { + if (frnd->sub_list[i] == addr) { + frnd->sub_list[i] = BT_MESH_ADDR_UNASSIGNED; + return; + } + } } static struct net_buf *create_friend_pdu(struct bt_mesh_friend *frnd, - struct friend_pdu_info *info, - struct net_buf_simple *sdu) + struct friend_pdu_info *info, + struct net_buf_simple *sdu) { - struct bt_mesh_subnet *sub; - const u8_t *enc, *priv; - struct net_buf *buf; - u8_t nid; + struct bt_mesh_subnet *sub; + const u8_t *enc, *priv; + struct net_buf *buf; + u8_t nid; - sub = bt_mesh_subnet_get(frnd->net_idx); - __ASSERT_NO_MSG(sub != NULL); + sub = bt_mesh_subnet_get(frnd->net_idx); + __ASSERT_NO_MSG(sub != NULL); - buf = bt_mesh_adv_create_from_pool(&friend_buf_pool, adv_alloc, - BT_MESH_ADV_DATA, - FRIEND_XMIT, K_NO_WAIT); - if (!buf) { - return NULL; - } + buf = bt_mesh_adv_create_from_pool(&friend_buf_pool, adv_alloc, + BT_MESH_ADV_DATA, + FRIEND_XMIT, K_NO_WAIT); + if (!buf) { + return NULL; + } - BT_MESH_ADV(buf)->addr = info->src; - FRIEND_ADV(buf)->seq_auth = TRANS_SEQ_AUTH_NVAL; + BT_MESH_ADV(buf)->addr = info->src; + FRIEND_ADV(buf)->seq_auth = TRANS_SEQ_AUTH_NVAL; - /* Friend Offer needs master security credentials */ - if (info->ctl && TRANS_CTL_OP(sdu->data) == TRANS_CTL_OP_FRIEND_OFFER) { - enc = sub->keys[sub->kr_flag].enc; - priv = sub->keys[sub->kr_flag].privacy; - nid = sub->keys[sub->kr_flag].nid; - } else { - if (friend_cred_get(sub, frnd->lpn, &nid, &enc, &priv)) { - BT_ERR("friend_cred_get failed"); - goto failed; - } - } + /* Friend Offer needs master security credentials */ + if (info->ctl && TRANS_CTL_OP(sdu->data) == TRANS_CTL_OP_FRIEND_OFFER) { + enc = sub->keys[sub->kr_flag].enc; + priv = sub->keys[sub->kr_flag].privacy; + nid = sub->keys[sub->kr_flag].nid; + } else { + if (friend_cred_get(sub, frnd->lpn, &nid, &enc, &priv)) { + BT_ERR("friend_cred_get failed"); + goto failed; + } + } - net_buf_add_u8(buf, (nid | (info->iv_index & 1) << 7)); + net_buf_add_u8(buf, (nid | (info->iv_index & 1) << 7)); - if (info->ctl) { - net_buf_add_u8(buf, info->ttl | 0x80); - } else { - net_buf_add_u8(buf, info->ttl); - } + if (info->ctl) { + net_buf_add_u8(buf, info->ttl | 0x80); + } else { + net_buf_add_u8(buf, info->ttl); + } - net_buf_add_mem(buf, info->seq, sizeof(info->seq)); + net_buf_add_mem(buf, info->seq, sizeof(info->seq)); - net_buf_add_be16(buf, info->src); - net_buf_add_be16(buf, info->dst); + net_buf_add_be16(buf, info->src); + net_buf_add_be16(buf, info->dst); - net_buf_add_mem(buf, sdu->data, sdu->len); + net_buf_add_mem(buf, sdu->data, sdu->len); - /* We re-encrypt and obfuscate using the received IVI rather than - * the normal TX IVI (which may be different) since the transport - * layer nonce includes the IVI. - */ - if (bt_mesh_net_encrypt(enc, &buf->b, info->iv_index, false)) { - BT_ERR("Re-encrypting failed"); - goto failed; - } + /* We re-encrypt and obfuscate using the received IVI rather than + * the normal TX IVI (which may be different) since the transport + * layer nonce includes the IVI. + */ + if (bt_mesh_net_encrypt(enc, &buf->b, info->iv_index, false)) { + BT_ERR("Re-encrypting failed"); + goto failed; + } - if (bt_mesh_net_obfuscate(buf->data, info->iv_index, priv)) { - BT_ERR("Re-obfuscating failed"); - goto failed; - } + if (bt_mesh_net_obfuscate(buf->data, info->iv_index, priv)) { + BT_ERR("Re-obfuscating failed"); + goto failed; + } - return buf; + return buf; failed: - net_buf_unref(buf); - return NULL; + net_buf_unref(buf); + return NULL; } static struct net_buf *encode_friend_ctl(struct bt_mesh_friend *frnd, - u8_t ctl_op, - struct net_buf_simple *sdu) + u8_t ctl_op, + struct net_buf_simple *sdu) { - struct friend_pdu_info info; - u32_t seq; + struct friend_pdu_info info; + u32_t seq; - BT_DBG("LPN 0x%04x", frnd->lpn); + BT_DBG("LPN 0x%04x", frnd->lpn); - net_buf_simple_push_u8(sdu, TRANS_CTL_HDR(ctl_op, 0)); + net_buf_simple_push_u8(sdu, TRANS_CTL_HDR(ctl_op, 0)); - info.src = bt_mesh_primary_addr(); - info.dst = frnd->lpn; + info.src = bt_mesh_primary_addr(); + info.dst = frnd->lpn; - info.ctl = 1U; - info.ttl = 0U; + info.ctl = 1U; + info.ttl = 0U; - seq = bt_mesh_next_seq(); - info.seq[0] = seq >> 16; - info.seq[1] = seq >> 8; - info.seq[2] = seq; + seq = bt_mesh_next_seq(); + info.seq[0] = seq >> 16; + info.seq[1] = seq >> 8; + info.seq[2] = seq; - info.iv_index = BT_MESH_NET_IVI_TX; + info.iv_index = BT_MESH_NET_IVI_TX; - return create_friend_pdu(frnd, &info, sdu); + return create_friend_pdu(frnd, &info, sdu); } static struct net_buf *encode_update(struct bt_mesh_friend *frnd, u8_t md) { - struct bt_mesh_ctl_friend_update *upd; - NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*upd)); - struct bt_mesh_subnet *sub = bt_mesh_subnet_get(frnd->net_idx); + struct bt_mesh_ctl_friend_update *upd; + NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*upd)); + struct bt_mesh_subnet *sub = bt_mesh_subnet_get(frnd->net_idx); - __ASSERT_NO_MSG(sub != NULL); + __ASSERT_NO_MSG(sub != NULL); - BT_DBG("lpn 0x%04x md 0x%02x", frnd->lpn, md); + BT_DBG("lpn 0x%04x md 0x%02x", frnd->lpn, md); - net_buf_simple_reserve(&sdu, 1); + net_buf_simple_reserve(&sdu, 1); - upd = net_buf_simple_add(&sdu, sizeof(*upd)); - upd->flags = bt_mesh_net_flags(sub); - upd->iv_index = sys_cpu_to_be32(bt_mesh.iv_index); - upd->md = md; + upd = net_buf_simple_add(&sdu, sizeof(*upd)); + upd->flags = bt_mesh_net_flags(sub); + upd->iv_index = sys_cpu_to_be32(bt_mesh.iv_index); + upd->md = md; - return encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_UPDATE, &sdu); + return encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_UPDATE, &sdu); } static void enqueue_sub_cfm(struct bt_mesh_friend *frnd, u8_t xact) { - struct bt_mesh_ctl_friend_sub_confirm *cfm; - NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*cfm)); - struct net_buf *buf; + struct bt_mesh_ctl_friend_sub_confirm *cfm; + NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*cfm)); + struct net_buf *buf; - BT_DBG("lpn 0x%04x xact 0x%02x", frnd->lpn, xact); + BT_DBG("lpn 0x%04x xact 0x%02x", frnd->lpn, xact); - net_buf_simple_reserve(&sdu, 1); + net_buf_simple_reserve(&sdu, 1); - cfm = net_buf_simple_add(&sdu, sizeof(*cfm)); - cfm->xact = xact; + cfm = net_buf_simple_add(&sdu, sizeof(*cfm)); + cfm->xact = xact; - buf = encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_SUB_CFM, &sdu); - if (!buf) { - BT_ERR("Unable to encode Subscription List Confirmation"); - return; - } + buf = encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_SUB_CFM, &sdu); + if (!buf) { + BT_ERR("Unable to encode Subscription List Confirmation"); + return; + } - if (frnd->last) { - BT_DBG("Discarding last PDU"); - net_buf_unref(frnd->last); - } + if (frnd->last) { + BT_DBG("Discarding last PDU"); + net_buf_unref(frnd->last); + } - frnd->last = buf; - frnd->send_last = 1U; + frnd->last = buf; + frnd->send_last = 1U; } static void friend_recv_delay(struct bt_mesh_friend *frnd) { - frnd->pending_req = 1U; - k_delayed_work_submit(&frnd->timer, recv_delay(frnd)); - BT_DBG("Waiting RecvDelay of %d ms", recv_delay(frnd)); + frnd->pending_req = 1U; + k_delayed_work_submit(&frnd->timer, recv_delay(frnd)); + BT_DBG("Waiting RecvDelay of %d ms", recv_delay(frnd)); } int bt_mesh_friend_sub_add(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_friend *frnd; - u8_t xact; + struct bt_mesh_friend *frnd; + u8_t xact; - if (buf->len < BT_MESH_FRIEND_SUB_MIN_LEN) { - BT_WARN("Too short Friend Subscription Add"); - return -EINVAL; - } + if (buf->len < BT_MESH_FRIEND_SUB_MIN_LEN) { + BT_WARN("Too short Friend Subscription Add"); + return -EINVAL; + } - frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, true); - if (!frnd) { - BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr); - return 0; - } + frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, true); + if (!frnd) { + BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr); + return 0; + } - if (frnd->pending_buf) { - BT_WARN("Previous buffer not yet sent!"); - return 0; - } + if (frnd->pending_buf) { + BT_WARN("Previous buffer not yet sent!"); + return 0; + } - friend_recv_delay(frnd); + friend_recv_delay(frnd); - xact = net_buf_simple_pull_u8(buf); + xact = net_buf_simple_pull_u8(buf); - while (buf->len >= 2U) { - friend_sub_add(frnd, net_buf_simple_pull_be16(buf)); - } + while (buf->len >= 2U) { + friend_sub_add(frnd, net_buf_simple_pull_be16(buf)); + } - enqueue_sub_cfm(frnd, xact); + enqueue_sub_cfm(frnd, xact); - return 0; + return 0; } int bt_mesh_friend_sub_rem(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_friend *frnd; - u8_t xact; + struct bt_mesh_friend *frnd; + u8_t xact; - if (buf->len < BT_MESH_FRIEND_SUB_MIN_LEN) { - BT_WARN("Too short Friend Subscription Remove"); - return -EINVAL; - } + if (buf->len < BT_MESH_FRIEND_SUB_MIN_LEN) { + BT_WARN("Too short Friend Subscription Remove"); + return -EINVAL; + } - frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, true); - if (!frnd) { - BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr); - return 0; - } + frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, true); + if (!frnd) { + BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr); + return 0; + } - if (frnd->pending_buf) { - BT_WARN("Previous buffer not yet sent!"); - return 0; - } + if (frnd->pending_buf) { + BT_WARN("Previous buffer not yet sent!"); + return 0; + } - friend_recv_delay(frnd); + friend_recv_delay(frnd); - xact = net_buf_simple_pull_u8(buf); + xact = net_buf_simple_pull_u8(buf); - while (buf->len >= 2U) { - friend_sub_rem(frnd, net_buf_simple_pull_be16(buf)); - } + while (buf->len >= 2U) { + friend_sub_rem(frnd, net_buf_simple_pull_be16(buf)); + } - enqueue_sub_cfm(frnd, xact); + enqueue_sub_cfm(frnd, xact); - return 0; + return 0; } static void enqueue_buf(struct bt_mesh_friend *frnd, struct net_buf *buf) { - net_buf_slist_put(&frnd->queue, buf); - frnd->queue_size++; + net_buf_slist_put(&frnd->queue, buf); + frnd->queue_size++; } static void enqueue_update(struct bt_mesh_friend *frnd, u8_t md) { - struct net_buf *buf; + struct net_buf *buf; - buf = encode_update(frnd, md); - if (!buf) { - BT_ERR("Unable to encode Friend Update"); - return; - } + buf = encode_update(frnd, md); + if (!buf) { + BT_ERR("Unable to encode Friend Update"); + return; + } - frnd->sec_update = 0U; - enqueue_buf(frnd, buf); + frnd->sec_update = 0U; + enqueue_buf(frnd, buf); } int bt_mesh_friend_poll(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_poll *msg = (void *)buf->data; - struct bt_mesh_friend *frnd; + struct bt_mesh_ctl_friend_poll *msg = (void *)buf->data; + struct bt_mesh_friend *frnd; - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Poll"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Poll"); + return -EINVAL; + } - frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, false); - if (!frnd) { - BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr); - return 0; - } + frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, false); + if (!frnd) { + BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr); + return 0; + } - if (msg->fsn & ~1) { - BT_WARN("Prohibited (non-zero) padding bits"); - return -EINVAL; - } + if (msg->fsn & ~1) { + BT_WARN("Prohibited (non-zero) padding bits"); + return -EINVAL; + } - if (frnd->pending_buf) { - BT_WARN("Previous buffer not yet sent"); - return 0; - } + if (frnd->pending_buf) { + BT_WARN("Previous buffer not yet sent"); + return 0; + } - BT_DBG("msg->fsn %u frnd->fsn %u", (msg->fsn & 1), frnd->fsn); + BT_DBG("msg->fsn %u frnd->fsn %u", (msg->fsn & 1), frnd->fsn); - friend_recv_delay(frnd); + friend_recv_delay(frnd); - if (!frnd->established) { - BT_DBG("Friendship established with 0x%04x", frnd->lpn); - frnd->established = 1U; - } + if (!frnd->established) { + BT_DBG("Friendship established with 0x%04x", frnd->lpn); + frnd->established = 1U; + } - if (msg->fsn == frnd->fsn && frnd->last) { - BT_DBG("Re-sending last PDU"); - frnd->send_last = 1U; - } else { - if (frnd->last) { - net_buf_unref(frnd->last); - frnd->last = NULL; - } + if (msg->fsn == frnd->fsn && frnd->last) { + BT_DBG("Re-sending last PDU"); + frnd->send_last = 1U; + } else { + if (frnd->last) { + net_buf_unref(frnd->last); + frnd->last = NULL; + } - frnd->fsn = msg->fsn; + frnd->fsn = msg->fsn; - if (sys_slist_is_empty(&frnd->queue)) { - enqueue_update(frnd, 0); - BT_DBG("Enqueued Friend Update to empty queue"); - } - } + if (sys_slist_is_empty(&frnd->queue)) { + enqueue_update(frnd, 0); + BT_DBG("Enqueued Friend Update to empty queue"); + } + } - return 0; + return 0; } static struct bt_mesh_friend *find_clear(u16_t prev_friend) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (frnd->clear.frnd == prev_friend) { - return frnd; - } - } + if (frnd->clear.frnd == prev_friend) { + return frnd; + } + } - return NULL; + return NULL; } static void friend_clear_sent(int err, void *user_data) { - struct bt_mesh_friend *frnd = user_data; + struct bt_mesh_friend *frnd = user_data; - k_delayed_work_submit(&frnd->clear.timer, - K_SECONDS(frnd->clear.repeat_sec)); - frnd->clear.repeat_sec *= 2U; + k_delayed_work_submit(&frnd->clear.timer, + K_SECONDS(frnd->clear.repeat_sec)); + frnd->clear.repeat_sec *= 2U; } static const struct bt_mesh_send_cb clear_sent_cb = { - .end = friend_clear_sent, + .end = friend_clear_sent, }; static void send_friend_clear(struct bt_mesh_friend *frnd) { - struct bt_mesh_msg_ctx ctx = { - .net_idx = frnd->net_idx, - .app_idx = BT_MESH_KEY_UNUSED, - .addr = frnd->clear.frnd, - .send_ttl = BT_MESH_TTL_MAX, - }; - struct bt_mesh_net_tx tx = { - .sub = &bt_mesh.sub[0], - .ctx = &ctx, - .src = bt_mesh_primary_addr(), - .xmit = bt_mesh_net_transmit_get(), - }; - struct bt_mesh_ctl_friend_clear req = { - .lpn_addr = sys_cpu_to_be16(frnd->lpn), - .lpn_counter = sys_cpu_to_be16(frnd->lpn_counter), - }; + struct bt_mesh_msg_ctx ctx = { + .net_idx = frnd->net_idx, + .app_idx = BT_MESH_KEY_UNUSED, + .addr = frnd->clear.frnd, + .send_ttl = BT_MESH_TTL_MAX, + }; + struct bt_mesh_net_tx tx = { + .sub = &bt_mesh.sub[0], + .ctx = &ctx, + .src = bt_mesh_primary_addr(), + .xmit = bt_mesh_net_transmit_get(), + }; + struct bt_mesh_ctl_friend_clear req = { + .lpn_addr = sys_cpu_to_be16(frnd->lpn), + .lpn_counter = sys_cpu_to_be16(frnd->lpn_counter), + }; - BT_DBG(""); + BT_DBG(""); - bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR, &req, - sizeof(req), NULL, &clear_sent_cb, frnd); + bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR, &req, + sizeof(req), NULL, &clear_sent_cb, frnd); } static void clear_timeout(struct k_work *work) { - struct bt_mesh_friend *frnd = CONTAINER_OF(work, struct bt_mesh_friend, - clear.timer.work); - u32_t duration; + struct bt_mesh_friend *frnd = CONTAINER_OF(work, struct bt_mesh_friend, + clear.timer.work); + u32_t duration; - BT_DBG("LPN 0x%04x (old) Friend 0x%04x", frnd->lpn, frnd->clear.frnd); + BT_DBG("LPN 0x%04x (old) Friend 0x%04x", frnd->lpn, frnd->clear.frnd); - duration = k_uptime_get_32() - frnd->clear.start; - if (duration > 2 * frnd->poll_to) { - BT_DBG("Clear Procedure timer expired"); - frnd->clear.frnd = BT_MESH_ADDR_UNASSIGNED; - return; - } + duration = k_uptime_get_32() - frnd->clear.start; + if (duration > 2 * frnd->poll_to) { + BT_DBG("Clear Procedure timer expired"); + frnd->clear.frnd = BT_MESH_ADDR_UNASSIGNED; + return; + } - send_friend_clear(frnd); + send_friend_clear(frnd); } static void clear_procedure_start(struct bt_mesh_friend *frnd) { - BT_DBG("LPN 0x%04x (old) Friend 0x%04x", frnd->lpn, frnd->clear.frnd); + BT_DBG("LPN 0x%04x (old) Friend 0x%04x", frnd->lpn, frnd->clear.frnd); - frnd->clear.start = k_uptime_get_32() + (2 * frnd->poll_to); - frnd->clear.repeat_sec = 1U; + frnd->clear.start = k_uptime_get_32() + (2 * frnd->poll_to); + frnd->clear.repeat_sec = 1U; - send_friend_clear(frnd); + send_friend_clear(frnd); } int bt_mesh_friend_clear_cfm(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_clear_confirm *msg = (void *)buf->data; - struct bt_mesh_friend *frnd; - u16_t lpn_addr, lpn_counter; + struct bt_mesh_ctl_friend_clear_confirm *msg = (void *)buf->data; + struct bt_mesh_friend *frnd; + u16_t lpn_addr, lpn_counter; - BT_DBG(""); + BT_DBG(""); - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Clear Confirm"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Clear Confirm"); + return -EINVAL; + } - frnd = find_clear(rx->ctx.addr); - if (!frnd) { - BT_WARN("No pending clear procedure for 0x%02x", rx->ctx.addr); - return 0; - } + frnd = find_clear(rx->ctx.addr); + if (!frnd) { + BT_WARN("No pending clear procedure for 0x%02x", rx->ctx.addr); + return 0; + } - lpn_addr = sys_be16_to_cpu(msg->lpn_addr); - if (lpn_addr != frnd->lpn) { - BT_WARN("LPN address mismatch (0x%04x != 0x%04x)", - lpn_addr, frnd->lpn); - return 0; - } + lpn_addr = sys_be16_to_cpu(msg->lpn_addr); + if (lpn_addr != frnd->lpn) { + BT_WARN("LPN address mismatch (0x%04x != 0x%04x)", + lpn_addr, frnd->lpn); + return 0; + } - lpn_counter = sys_be16_to_cpu(msg->lpn_counter); - if (lpn_counter != frnd->lpn_counter) { - BT_WARN("LPN counter mismatch (0x%04x != 0x%04x)", - lpn_counter, frnd->lpn_counter); - return 0; - } + lpn_counter = sys_be16_to_cpu(msg->lpn_counter); + if (lpn_counter != frnd->lpn_counter) { + BT_WARN("LPN counter mismatch (0x%04x != 0x%04x)", + lpn_counter, frnd->lpn_counter); + return 0; + } - k_delayed_work_cancel(&frnd->clear.timer); - frnd->clear.frnd = BT_MESH_ADDR_UNASSIGNED; + k_delayed_work_cancel(&frnd->clear.timer); + frnd->clear.frnd = BT_MESH_ADDR_UNASSIGNED; - return 0; + return 0; } static void enqueue_offer(struct bt_mesh_friend *frnd, s8_t rssi) { - struct bt_mesh_ctl_friend_offer *off; - NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*off)); - struct net_buf *buf; + struct bt_mesh_ctl_friend_offer *off; + NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*off)); + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - net_buf_simple_reserve(&sdu, 1); + net_buf_simple_reserve(&sdu, 1); - off = net_buf_simple_add(&sdu, sizeof(*off)); + off = net_buf_simple_add(&sdu, sizeof(*off)); - off->recv_win = CONFIG_BT_MESH_FRIEND_RECV_WIN, - off->queue_size = CONFIG_BT_MESH_FRIEND_QUEUE_SIZE, - off->sub_list_size = ARRAY_SIZE(frnd->sub_list), - off->rssi = rssi, - off->frnd_counter = sys_cpu_to_be16(frnd->counter); + off->recv_win = CONFIG_BT_MESH_FRIEND_RECV_WIN, + off->queue_size = CONFIG_BT_MESH_FRIEND_QUEUE_SIZE, + off->sub_list_size = ARRAY_SIZE(frnd->sub_list), + off->rssi = rssi, + off->frnd_counter = sys_cpu_to_be16(frnd->counter); - buf = encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_OFFER, &sdu); - if (!buf) { - BT_ERR("Unable to encode Friend Offer"); - return; - } + buf = encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_OFFER, &sdu); + if (!buf) { + BT_ERR("Unable to encode Friend Offer"); + return; + } - frnd->counter++; + frnd->counter++; - if (frnd->last) { - net_buf_unref(frnd->last); - } + if (frnd->last) { + net_buf_unref(frnd->last); + } - frnd->last = buf; - frnd->send_last = 1U; + frnd->last = buf; + frnd->send_last = 1U; } #define RECV_WIN CONFIG_BT_MESH_FRIEND_RECV_WIN @@ -753,691 +753,691 @@ static void enqueue_offer(struct bt_mesh_friend *frnd, s8_t rssi) static s32_t offer_delay(struct bt_mesh_friend *frnd, s8_t rssi, u8_t crit) { - /* Scaling factors. The actual values are 1, 1.5, 2 & 2.5, but we - * want to avoid floating-point arithmetic. - */ - static const u8_t fact[] = { 10, 15, 20, 25 }; - s32_t delay; + /* Scaling factors. The actual values are 1, 1.5, 2 & 2.5, but we + * want to avoid floating-point arithmetic. + */ + static const u8_t fact[] = { 10, 15, 20, 25 }; + s32_t delay; - BT_DBG("ReceiveWindowFactor %u ReceiveWindow %u RSSIFactor %u RSSI %d", - fact[RECV_WIN_FACT(crit)], RECV_WIN, - fact[RSSI_FACT(crit)], rssi); + BT_DBG("ReceiveWindowFactor %u ReceiveWindow %u RSSIFactor %u RSSI %d", + fact[RECV_WIN_FACT(crit)], RECV_WIN, + fact[RSSI_FACT(crit)], rssi); - /* Delay = ReceiveWindowFactor * ReceiveWindow - RSSIFactor * RSSI */ - delay = (s32_t)fact[RECV_WIN_FACT(crit)] * RECV_WIN; - delay -= (s32_t)fact[RSSI_FACT(crit)] * rssi; - delay /= 10; + /* Delay = ReceiveWindowFactor * ReceiveWindow - RSSIFactor * RSSI */ + delay = (s32_t)fact[RECV_WIN_FACT(crit)] * RECV_WIN; + delay -= (s32_t)fact[RSSI_FACT(crit)] * rssi; + delay /= 10; - BT_DBG("Local Delay calculated as %d ms", delay); + BT_DBG("Local Delay calculated as %d ms", delay); - if (delay < 100) { - return K_MSEC(100); - } + if (delay < 100) { + return K_MSEC(100); + } - return K_MSEC(delay); + return K_MSEC(delay); } int bt_mesh_friend_req(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_req *msg = (void *)buf->data; - struct bt_mesh_friend *frnd = NULL; - u32_t poll_to; - int i; + struct bt_mesh_ctl_friend_req *msg = (void *)buf->data; + struct bt_mesh_friend *frnd = NULL; + u32_t poll_to; + int i; - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Request"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Request"); + return -EINVAL; + } - if (msg->recv_delay <= 0x09) { - BT_WARN("Prohibited ReceiveDelay (0x%02x)", msg->recv_delay); - return -EINVAL; - } + if (msg->recv_delay <= 0x09) { + BT_WARN("Prohibited ReceiveDelay (0x%02x)", msg->recv_delay); + return -EINVAL; + } - poll_to = (((u32_t)msg->poll_to[0] << 16) | - ((u32_t)msg->poll_to[1] << 8) | - ((u32_t)msg->poll_to[2])); + poll_to = (((u32_t)msg->poll_to[0] << 16) | + ((u32_t)msg->poll_to[1] << 8) | + ((u32_t)msg->poll_to[2])); - if (poll_to <= 0x000009 || poll_to >= 0x34bc00) { - BT_WARN("Prohibited PollTimeout (0x%06x)", poll_to); - return -EINVAL; - } + if (poll_to <= 0x000009 || poll_to >= 0x34bc00) { + BT_WARN("Prohibited PollTimeout (0x%06x)", poll_to); + return -EINVAL; + } - if (msg->num_elem == 0x00) { - BT_WARN("Prohibited NumElements value (0x00)"); - return -EINVAL; - } + if (msg->num_elem == 0x00) { + BT_WARN("Prohibited NumElements value (0x00)"); + return -EINVAL; + } - if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr + msg->num_elem - 1)) { - BT_WARN("LPN elements stretch outside of unicast range"); - return -EINVAL; - } + if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr + msg->num_elem - 1)) { + BT_WARN("LPN elements stretch outside of unicast range"); + return -EINVAL; + } - if (!MIN_QUEUE_SIZE_LOG(msg->criteria)) { - BT_WARN("Prohibited Minimum Queue Size in Friend Request"); - return -EINVAL; - } + if (!MIN_QUEUE_SIZE_LOG(msg->criteria)) { + BT_WARN("Prohibited Minimum Queue Size in Friend Request"); + return -EINVAL; + } - if (CONFIG_BT_MESH_FRIEND_QUEUE_SIZE < MIN_QUEUE_SIZE(msg->criteria)) { - BT_WARN("We have a too small Friend Queue size (%u < %u)", - CONFIG_BT_MESH_FRIEND_QUEUE_SIZE, - MIN_QUEUE_SIZE(msg->criteria)); - return 0; - } + if (CONFIG_BT_MESH_FRIEND_QUEUE_SIZE < MIN_QUEUE_SIZE(msg->criteria)) { + BT_WARN("We have a too small Friend Queue size (%u < %u)", + CONFIG_BT_MESH_FRIEND_QUEUE_SIZE, + MIN_QUEUE_SIZE(msg->criteria)); + return 0; + } - frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, false); - if (frnd) { - BT_WARN("Existing LPN re-requesting Friendship"); - friend_clear(frnd); - goto init_friend; - } + frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, false); + if (frnd) { + BT_WARN("Existing LPN re-requesting Friendship"); + friend_clear(frnd); + goto init_friend; + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - if (!bt_mesh.frnd[i].valid) { - frnd = &bt_mesh.frnd[i]; - frnd->valid = 1U; - break; - } - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + if (!bt_mesh.frnd[i].valid) { + frnd = &bt_mesh.frnd[i]; + frnd->valid = 1U; + break; + } + } - if (!frnd) { - BT_WARN("No free Friend contexts for new LPN"); - return -ENOMEM; - } + if (!frnd) { + BT_WARN("No free Friend contexts for new LPN"); + return -ENOMEM; + } init_friend: - frnd->lpn = rx->ctx.addr; - frnd->num_elem = msg->num_elem; - frnd->net_idx = rx->sub->net_idx; - frnd->recv_delay = msg->recv_delay; - frnd->poll_to = poll_to * 100U; - frnd->lpn_counter = sys_be16_to_cpu(msg->lpn_counter); - frnd->clear.frnd = sys_be16_to_cpu(msg->prev_addr); + frnd->lpn = rx->ctx.addr; + frnd->num_elem = msg->num_elem; + frnd->net_idx = rx->sub->net_idx; + frnd->recv_delay = msg->recv_delay; + frnd->poll_to = poll_to * 100U; + frnd->lpn_counter = sys_be16_to_cpu(msg->lpn_counter); + frnd->clear.frnd = sys_be16_to_cpu(msg->prev_addr); - BT_DBG("LPN 0x%04x rssi %d recv_delay %u poll_to %ums", - frnd->lpn, rx->ctx.recv_rssi, frnd->recv_delay, frnd->poll_to); + BT_DBG("LPN 0x%04x rssi %d recv_delay %u poll_to %ums", + frnd->lpn, rx->ctx.recv_rssi, frnd->recv_delay, frnd->poll_to); - if (BT_MESH_ADDR_IS_UNICAST(frnd->clear.frnd) && - !bt_mesh_elem_find(frnd->clear.frnd)) { - clear_procedure_start(frnd); - } + if (BT_MESH_ADDR_IS_UNICAST(frnd->clear.frnd) && + !bt_mesh_elem_find(frnd->clear.frnd)) { + clear_procedure_start(frnd); + } - k_delayed_work_submit(&frnd->timer, - offer_delay(frnd, rx->ctx.recv_rssi, - msg->criteria)); + k_delayed_work_submit(&frnd->timer, + offer_delay(frnd, rx->ctx.recv_rssi, + msg->criteria)); - friend_cred_create(rx->sub, frnd->lpn, frnd->lpn_counter, - frnd->counter); + friend_cred_create(rx->sub, frnd->lpn, frnd->lpn_counter, + frnd->counter); - enqueue_offer(frnd, rx->ctx.recv_rssi); + enqueue_offer(frnd, rx->ctx.recv_rssi); - return 0; + return 0; } static struct bt_mesh_friend_seg *get_seg(struct bt_mesh_friend *frnd, - u16_t src, u64_t *seq_auth, - u8_t seg_count) + u16_t src, u64_t *seq_auth, + u8_t seg_count) { - struct bt_mesh_friend_seg *unassigned = NULL; - int i; + struct bt_mesh_friend_seg *unassigned = NULL; + int i; - for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) { - struct bt_mesh_friend_seg *seg = &frnd->seg[i]; - struct net_buf *buf = (void *)sys_slist_peek_head(&seg->queue); + for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) { + struct bt_mesh_friend_seg *seg = &frnd->seg[i]; + struct net_buf *buf = (void *)sys_slist_peek_head(&seg->queue); - if (buf && BT_MESH_ADV(buf)->addr == src && - FRIEND_ADV(buf)->seq_auth == *seq_auth) { - return seg; - } + if (buf && BT_MESH_ADV(buf)->addr == src && + FRIEND_ADV(buf)->seq_auth == *seq_auth) { + return seg; + } - if (!unassigned && !buf) { - unassigned = seg; - } - } + if (!unassigned && !buf) { + unassigned = seg; + } + } - if (unassigned) { - unassigned->seg_count = seg_count; - } + if (unassigned) { + unassigned->seg_count = seg_count; + } - return unassigned; + return unassigned; } static void enqueue_friend_pdu(struct bt_mesh_friend *frnd, - enum bt_mesh_friend_pdu_type type, - u8_t seg_count, struct net_buf *buf) + enum bt_mesh_friend_pdu_type type, + u8_t seg_count, struct net_buf *buf) { - struct bt_mesh_friend_seg *seg; - struct friend_adv *adv; + struct bt_mesh_friend_seg *seg; + struct friend_adv *adv; - BT_DBG("type %u", type); + BT_DBG("type %u", type); - if (type == BT_MESH_FRIEND_PDU_SINGLE) { - if (frnd->sec_update) { - enqueue_update(frnd, 1); - } + if (type == BT_MESH_FRIEND_PDU_SINGLE) { + if (frnd->sec_update) { + enqueue_update(frnd, 1); + } - enqueue_buf(frnd, buf); - return; - } + enqueue_buf(frnd, buf); + return; + } - adv = FRIEND_ADV(buf); - seg = get_seg(frnd, BT_MESH_ADV(buf)->addr, &adv->seq_auth, seg_count); - if (!seg) { - BT_ERR("No free friend segment RX contexts for 0x%04x", - BT_MESH_ADV(buf)->addr); - net_buf_unref(buf); - return; - } + adv = FRIEND_ADV(buf); + seg = get_seg(frnd, BT_MESH_ADV(buf)->addr, &adv->seq_auth, seg_count); + if (!seg) { + BT_ERR("No free friend segment RX contexts for 0x%04x", + BT_MESH_ADV(buf)->addr); + net_buf_unref(buf); + return; + } - net_buf_slist_put(&seg->queue, buf); + net_buf_slist_put(&seg->queue, buf); - if (type == BT_MESH_FRIEND_PDU_COMPLETE) { - if (frnd->sec_update) { - enqueue_update(frnd, 1); - } + if (type == BT_MESH_FRIEND_PDU_COMPLETE) { + if (frnd->sec_update) { + enqueue_update(frnd, 1); + } - /* Only acks should have a valid SeqAuth in the Friend queue - * (otherwise we can't easily detect them there), so clear - * the SeqAuth information from the segments before merging. - */ - SYS_SLIST_FOR_EACH_CONTAINER(&seg->queue, buf, node) { - FRIEND_ADV(buf)->seq_auth = TRANS_SEQ_AUTH_NVAL; - frnd->queue_size++; - } + /* Only acks should have a valid SeqAuth in the Friend queue + * (otherwise we can't easily detect them there), so clear + * the SeqAuth information from the segments before merging. + */ + SYS_SLIST_FOR_EACH_CONTAINER(&seg->queue, buf, node) { + FRIEND_ADV(buf)->seq_auth = TRANS_SEQ_AUTH_NVAL; + frnd->queue_size++; + } - sys_slist_merge_slist(&frnd->queue, &seg->queue); - seg->seg_count = 0U; - } else { - /* Mark the buffer as having more to come after it */ - buf->flags |= NET_BUF_FRAGS; - } + sys_slist_merge_slist(&frnd->queue, &seg->queue); + seg->seg_count = 0U; + } else { + /* Mark the buffer as having more to come after it */ + buf->flags |= NET_BUF_FRAGS; + } } static void buf_send_start(u16_t duration, int err, void *user_data) { - struct bt_mesh_friend *frnd = user_data; + struct bt_mesh_friend *frnd = user_data; - BT_DBG("err %d", err); + BT_DBG("err %d", err); - frnd->pending_buf = 0U; + frnd->pending_buf = 0U; - /* Friend Offer doesn't follow the re-sending semantics */ - if (!frnd->established) { - net_buf_unref(frnd->last); - frnd->last = NULL; - } + /* Friend Offer doesn't follow the re-sending semantics */ + if (!frnd->established) { + net_buf_unref(frnd->last); + frnd->last = NULL; + } } static void buf_send_end(int err, void *user_data) { - struct bt_mesh_friend *frnd = user_data; + struct bt_mesh_friend *frnd = user_data; - BT_DBG("err %d", err); + BT_DBG("err %d", err); - if (frnd->pending_req) { - BT_WARN("Another request before previous completed sending"); - return; - } + if (frnd->pending_req) { + BT_WARN("Another request before previous completed sending"); + return; + } - if (frnd->established) { - k_delayed_work_submit(&frnd->timer, frnd->poll_to); - BT_DBG("Waiting %u ms for next poll", frnd->poll_to); - } else { - /* Friend offer timeout is 1 second */ - k_delayed_work_submit(&frnd->timer, K_SECONDS(1)); - BT_DBG("Waiting for first poll"); - } + if (frnd->established) { + k_delayed_work_submit(&frnd->timer, frnd->poll_to); + BT_DBG("Waiting %u ms for next poll", frnd->poll_to); + } else { + /* Friend offer timeout is 1 second */ + k_delayed_work_submit(&frnd->timer, K_SECONDS(1)); + BT_DBG("Waiting for first poll"); + } } static void friend_timeout(struct k_work *work) { - struct bt_mesh_friend *frnd = CONTAINER_OF(work, struct bt_mesh_friend, - timer.work); - static const struct bt_mesh_send_cb buf_sent_cb = { - .start = buf_send_start, - .end = buf_send_end, - }; + struct bt_mesh_friend *frnd = CONTAINER_OF(work, struct bt_mesh_friend, + timer.work); + static const struct bt_mesh_send_cb buf_sent_cb = { + .start = buf_send_start, + .end = buf_send_end, + }; - __ASSERT_NO_MSG(frnd->pending_buf == 0U); + __ASSERT_NO_MSG(frnd->pending_buf == 0U); - BT_DBG("lpn 0x%04x send_last %u last %p", frnd->lpn, - frnd->send_last, frnd->last); + BT_DBG("lpn 0x%04x send_last %u last %p", frnd->lpn, + frnd->send_last, frnd->last); - if (frnd->send_last && frnd->last) { - BT_DBG("Sending frnd->last %p", frnd->last); - frnd->send_last = 0U; - goto send_last; - } + if (frnd->send_last && frnd->last) { + BT_DBG("Sending frnd->last %p", frnd->last); + frnd->send_last = 0U; + goto send_last; + } - if (frnd->established && !frnd->pending_req) { - BT_WARN("Friendship lost with 0x%04x", frnd->lpn); - friend_clear(frnd); - return; - } + if (frnd->established && !frnd->pending_req) { + BT_WARN("Friendship lost with 0x%04x", frnd->lpn); + friend_clear(frnd); + return; + } - frnd->last = (void *)sys_slist_get(&frnd->queue); - if (!frnd->last) { - BT_WARN("Friendship not established with 0x%04x", frnd->lpn); - friend_clear(frnd); - return; - } + frnd->last = (void *)sys_slist_get(&frnd->queue); + if (!frnd->last) { + BT_WARN("Friendship not established with 0x%04x", frnd->lpn); + friend_clear(frnd); + return; + } - /* Clear the flag we use for segment tracking */ - frnd->last->flags &= ~NET_BUF_FRAGS; - frnd->last->frags = NULL; + /* Clear the flag we use for segment tracking */ + frnd->last->flags &= ~NET_BUF_FRAGS; + frnd->last->frags = NULL; - BT_DBG("Sending buf %p from Friend Queue of LPN 0x%04x", - frnd->last, frnd->lpn); - frnd->queue_size--; + BT_DBG("Sending buf %p from Friend Queue of LPN 0x%04x", + frnd->last, frnd->lpn); + frnd->queue_size--; send_last: - frnd->pending_req = 0U; - frnd->pending_buf = 1U; - bt_mesh_adv_send(frnd->last, &buf_sent_cb, frnd); + frnd->pending_req = 0U; + frnd->pending_buf = 1U; + bt_mesh_adv_send(frnd->last, &buf_sent_cb, frnd); } int bt_mesh_friend_init(void) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - int j; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + int j; - frnd->net_idx = BT_MESH_KEY_UNUSED; + frnd->net_idx = BT_MESH_KEY_UNUSED; - sys_slist_init(&frnd->queue); + sys_slist_init(&frnd->queue); - k_delayed_work_init(&frnd->timer, friend_timeout); - k_delayed_work_init(&frnd->clear.timer, clear_timeout); + k_delayed_work_init(&frnd->timer, friend_timeout); + k_delayed_work_init(&frnd->clear.timer, clear_timeout); - for (j = 0; j < ARRAY_SIZE(frnd->seg); j++) { - sys_slist_init(&frnd->seg[j].queue); - } - } + for (j = 0; j < ARRAY_SIZE(frnd->seg); j++) { + sys_slist_init(&frnd->seg[j].queue); + } + } - return 0; + return 0; } static void friend_purge_old_ack(struct bt_mesh_friend *frnd, u64_t *seq_auth, - u16_t src) + u16_t src) { - sys_snode_t *cur, *prev = NULL; + sys_snode_t *cur, *prev = NULL; - BT_DBG("SeqAuth %llx src 0x%04x", *seq_auth, src); + BT_DBG("SeqAuth %llx src 0x%04x", *seq_auth, src); - for (cur = sys_slist_peek_head(&frnd->queue); - cur != NULL; prev = cur, cur = sys_slist_peek_next(cur)) { - struct net_buf *buf = (void *)cur; + for (cur = sys_slist_peek_head(&frnd->queue); + cur != NULL; prev = cur, cur = sys_slist_peek_next(cur)) { + struct net_buf *buf = (void *)cur; - if (BT_MESH_ADV(buf)->addr == src && - FRIEND_ADV(buf)->seq_auth == *seq_auth) { - BT_DBG("Removing old ack from Friend Queue"); + if (BT_MESH_ADV(buf)->addr == src && + FRIEND_ADV(buf)->seq_auth == *seq_auth) { + BT_DBG("Removing old ack from Friend Queue"); - sys_slist_remove(&frnd->queue, prev, cur); - frnd->queue_size--; - /* Make sure old slist entry state doesn't remain */ - buf->frags = NULL; + sys_slist_remove(&frnd->queue, prev, cur); + frnd->queue_size--; + /* Make sure old slist entry state doesn't remain */ + buf->frags = NULL; - net_buf_unref(buf); - break; - } - } + net_buf_unref(buf); + break; + } + } } static void friend_lpn_enqueue_rx(struct bt_mesh_friend *frnd, - struct bt_mesh_net_rx *rx, - enum bt_mesh_friend_pdu_type type, - u64_t *seq_auth, u8_t seg_count, - struct net_buf_simple *sbuf) + struct bt_mesh_net_rx *rx, + enum bt_mesh_friend_pdu_type type, + u64_t *seq_auth, u8_t seg_count, + struct net_buf_simple *sbuf) { - struct friend_pdu_info info; - struct net_buf *buf; + struct friend_pdu_info info; + struct net_buf *buf; - BT_DBG("LPN 0x%04x queue_size %u", frnd->lpn, frnd->queue_size); + BT_DBG("LPN 0x%04x queue_size %u", frnd->lpn, frnd->queue_size); - if (type == BT_MESH_FRIEND_PDU_SINGLE && seq_auth) { - friend_purge_old_ack(frnd, seq_auth, rx->ctx.addr); - } + if (type == BT_MESH_FRIEND_PDU_SINGLE && seq_auth) { + friend_purge_old_ack(frnd, seq_auth, rx->ctx.addr); + } - info.src = rx->ctx.addr; - info.dst = rx->ctx.recv_dst; + info.src = rx->ctx.addr; + info.dst = rx->ctx.recv_dst; - if (rx->net_if == BT_MESH_NET_IF_LOCAL) { - info.ttl = rx->ctx.recv_ttl; - } else { - info.ttl = rx->ctx.recv_ttl - 1U; - } + if (rx->net_if == BT_MESH_NET_IF_LOCAL) { + info.ttl = rx->ctx.recv_ttl; + } else { + info.ttl = rx->ctx.recv_ttl - 1U; + } - info.ctl = rx->ctl; + info.ctl = rx->ctl; - info.seq[0] = (rx->seq >> 16); - info.seq[1] = (rx->seq >> 8); - info.seq[2] = rx->seq; + info.seq[0] = (rx->seq >> 16); + info.seq[1] = (rx->seq >> 8); + info.seq[2] = rx->seq; - info.iv_index = BT_MESH_NET_IVI_RX(rx); + info.iv_index = BT_MESH_NET_IVI_RX(rx); - buf = create_friend_pdu(frnd, &info, sbuf); - if (!buf) { - BT_ERR("Failed to encode Friend buffer"); - return; - } + buf = create_friend_pdu(frnd, &info, sbuf); + if (!buf) { + BT_ERR("Failed to encode Friend buffer"); + return; + } - if (seq_auth) { - FRIEND_ADV(buf)->seq_auth = *seq_auth; - } + if (seq_auth) { + FRIEND_ADV(buf)->seq_auth = *seq_auth; + } - enqueue_friend_pdu(frnd, type, seg_count, buf); + enqueue_friend_pdu(frnd, type, seg_count, buf); - BT_DBG("Queued message for LPN 0x%04x, queue_size %u", - frnd->lpn, frnd->queue_size); + BT_DBG("Queued message for LPN 0x%04x, queue_size %u", + frnd->lpn, frnd->queue_size); } static void friend_lpn_enqueue_tx(struct bt_mesh_friend *frnd, - struct bt_mesh_net_tx *tx, - enum bt_mesh_friend_pdu_type type, - u64_t *seq_auth, u8_t seg_count, - struct net_buf_simple *sbuf) + struct bt_mesh_net_tx *tx, + enum bt_mesh_friend_pdu_type type, + u64_t *seq_auth, u8_t seg_count, + struct net_buf_simple *sbuf) { - struct friend_pdu_info info; - struct net_buf *buf; - u32_t seq; + struct friend_pdu_info info; + struct net_buf *buf; + u32_t seq; - BT_DBG("LPN 0x%04x", frnd->lpn); + BT_DBG("LPN 0x%04x", frnd->lpn); - if (type == BT_MESH_FRIEND_PDU_SINGLE && seq_auth) { - friend_purge_old_ack(frnd, seq_auth, tx->src); - } + if (type == BT_MESH_FRIEND_PDU_SINGLE && seq_auth) { + friend_purge_old_ack(frnd, seq_auth, tx->src); + } - info.src = tx->src; - info.dst = tx->ctx->addr; + info.src = tx->src; + info.dst = tx->ctx->addr; - info.ttl = tx->ctx->send_ttl; - info.ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED); + info.ttl = tx->ctx->send_ttl; + info.ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED); - seq = bt_mesh_next_seq(); - info.seq[0] = seq >> 16; - info.seq[1] = seq >> 8; - info.seq[2] = seq; + seq = bt_mesh_next_seq(); + info.seq[0] = seq >> 16; + info.seq[1] = seq >> 8; + info.seq[2] = seq; - info.iv_index = BT_MESH_NET_IVI_TX; + info.iv_index = BT_MESH_NET_IVI_TX; - buf = create_friend_pdu(frnd, &info, sbuf); - if (!buf) { - BT_ERR("Failed to encode Friend buffer"); - return; - } + buf = create_friend_pdu(frnd, &info, sbuf); + if (!buf) { + BT_ERR("Failed to encode Friend buffer"); + return; + } - if (seq_auth) { - FRIEND_ADV(buf)->seq_auth = *seq_auth; - } + if (seq_auth) { + FRIEND_ADV(buf)->seq_auth = *seq_auth; + } - enqueue_friend_pdu(frnd, type, seg_count, buf); + enqueue_friend_pdu(frnd, type, seg_count, buf); - BT_DBG("Queued message for LPN 0x%04x", frnd->lpn); + BT_DBG("Queued message for LPN 0x%04x", frnd->lpn); } static bool friend_lpn_matches(struct bt_mesh_friend *frnd, u16_t net_idx, - u16_t addr) + u16_t addr) { - int i; + int i; - if (!frnd->established) { - return false; - } + if (!frnd->established) { + return false; + } - if (net_idx != frnd->net_idx) { - return false; - } + if (net_idx != frnd->net_idx) { + return false; + } - if (BT_MESH_ADDR_IS_UNICAST(addr)) { - return is_lpn_unicast(frnd, addr); - } + if (BT_MESH_ADDR_IS_UNICAST(addr)) { + return is_lpn_unicast(frnd, addr); + } - for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) { - if (frnd->sub_list[i] == addr) { - return true; - } - } + for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) { + if (frnd->sub_list[i] == addr) { + return true; + } + } - return false; + return false; } bool bt_mesh_friend_match(u16_t net_idx, u16_t addr) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (friend_lpn_matches(frnd, net_idx, addr)) { - BT_DBG("LPN 0x%04x matched address 0x%04x", - frnd->lpn, addr); - return true; - } - } + if (friend_lpn_matches(frnd, net_idx, addr)) { + BT_DBG("LPN 0x%04x matched address 0x%04x", + frnd->lpn, addr); + return true; + } + } - BT_DBG("No matching LPN for address 0x%04x", addr); + BT_DBG("No matching LPN for address 0x%04x", addr); - return false; + return false; } static bool friend_queue_has_space(struct bt_mesh_friend *frnd, u16_t addr, - u64_t *seq_auth, u8_t seg_count) + u64_t *seq_auth, u8_t seg_count) { - u32_t total = 0; - int i; + u32_t total = 0; + int i; - if (seg_count > CONFIG_BT_MESH_FRIEND_QUEUE_SIZE) { - return false; - } + if (seg_count > CONFIG_BT_MESH_FRIEND_QUEUE_SIZE) { + return false; + } - for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) { - struct bt_mesh_friend_seg *seg = &frnd->seg[i]; + for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) { + struct bt_mesh_friend_seg *seg = &frnd->seg[i]; - if (seq_auth) { - struct net_buf *buf; + if (seq_auth) { + struct net_buf *buf; - /* If there's a segment queue for this message then the - * space verification has already happened. - */ - buf = (void *)sys_slist_peek_head(&seg->queue); - if (buf && BT_MESH_ADV(buf)->addr == addr && - FRIEND_ADV(buf)->seq_auth == *seq_auth) { - return true; - } - } + /* If there's a segment queue for this message then the + * space verification has already happened. + */ + buf = (void *)sys_slist_peek_head(&seg->queue); + if (buf && BT_MESH_ADV(buf)->addr == addr && + FRIEND_ADV(buf)->seq_auth == *seq_auth) { + return true; + } + } - total += seg->seg_count; - } + total += seg->seg_count; + } - /* If currently pending segments combined with this segmented message - * are more than the Friend Queue Size, then there's no space. This - * is because we don't have a mechanism of aborting already pending - * segmented messages to free up buffers. - */ - return (CONFIG_BT_MESH_FRIEND_QUEUE_SIZE - total) > seg_count; + /* If currently pending segments combined with this segmented message + * are more than the Friend Queue Size, then there's no space. This + * is because we don't have a mechanism of aborting already pending + * segmented messages to free up buffers. + */ + return (CONFIG_BT_MESH_FRIEND_QUEUE_SIZE - total) > seg_count; } bool bt_mesh_friend_queue_has_space(u16_t net_idx, u16_t src, u16_t dst, - u64_t *seq_auth, u8_t seg_count) + u64_t *seq_auth, u8_t seg_count) { - bool someone_has_space = false, friend_match = false; - int i; + bool someone_has_space = false, friend_match = false; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (!friend_lpn_matches(frnd, net_idx, dst)) { - continue; - } + if (!friend_lpn_matches(frnd, net_idx, dst)) { + continue; + } - friend_match = true; + friend_match = true; - if (friend_queue_has_space(frnd, src, seq_auth, seg_count)) { - someone_has_space = true; - } - } + if (friend_queue_has_space(frnd, src, seq_auth, seg_count)) { + someone_has_space = true; + } + } - /* If there were no matched LPNs treat this as success, so the - * transport layer can continue its work. - */ - if (!friend_match) { - return true; - } + /* If there were no matched LPNs treat this as success, so the + * transport layer can continue its work. + */ + if (!friend_match) { + return true; + } - /* From the transport layers perspective it's good enough that at - * least one Friend Queue has space. If there were multiple Friend - * matches then the destination must be a group address, in which - * case e.g. segment acks are not sent. - */ - return someone_has_space; + /* From the transport layers perspective it's good enough that at + * least one Friend Queue has space. If there were multiple Friend + * matches then the destination must be a group address, in which + * case e.g. segment acks are not sent. + */ + return someone_has_space; } static bool friend_queue_prepare_space(struct bt_mesh_friend *frnd, u16_t addr, - u64_t *seq_auth, u8_t seg_count) + u64_t *seq_auth, u8_t seg_count) { - bool pending_segments; - u8_t avail_space; + bool pending_segments; + u8_t avail_space; - if (!friend_queue_has_space(frnd, addr, seq_auth, seg_count)) { - return false; - } + if (!friend_queue_has_space(frnd, addr, seq_auth, seg_count)) { + return false; + } - avail_space = CONFIG_BT_MESH_FRIEND_QUEUE_SIZE - frnd->queue_size; - pending_segments = false; + avail_space = CONFIG_BT_MESH_FRIEND_QUEUE_SIZE - frnd->queue_size; + pending_segments = false; - while (pending_segments || avail_space < seg_count) { - struct net_buf *buf = (void *)sys_slist_get(&frnd->queue); + while (pending_segments || avail_space < seg_count) { + struct net_buf *buf = (void *)sys_slist_get(&frnd->queue); - if (!buf) { - BT_ERR("Unable to free up enough buffers"); - return false; - } + if (!buf) { + BT_ERR("Unable to free up enough buffers"); + return false; + } - frnd->queue_size--; - avail_space++; + frnd->queue_size--; + avail_space++; - pending_segments = (buf->flags & NET_BUF_FRAGS); + pending_segments = (buf->flags & NET_BUF_FRAGS); - /* Make sure old slist entry state doesn't remain */ - buf->frags = NULL; - buf->flags &= ~NET_BUF_FRAGS; + /* Make sure old slist entry state doesn't remain */ + buf->frags = NULL; + buf->flags &= ~NET_BUF_FRAGS; - net_buf_unref(buf); - } + net_buf_unref(buf); + } - return true; + return true; } void bt_mesh_friend_enqueue_rx(struct bt_mesh_net_rx *rx, - enum bt_mesh_friend_pdu_type type, - u64_t *seq_auth, u8_t seg_count, - struct net_buf_simple *sbuf) + enum bt_mesh_friend_pdu_type type, + u64_t *seq_auth, u8_t seg_count, + struct net_buf_simple *sbuf) { - int i; + int i; - if (!rx->friend_match || - (rx->ctx.recv_ttl <= 1U && rx->net_if != BT_MESH_NET_IF_LOCAL) || - bt_mesh_friend_get() != BT_MESH_FRIEND_ENABLED) { - return; - } + if (!rx->friend_match || + (rx->ctx.recv_ttl <= 1U && rx->net_if != BT_MESH_NET_IF_LOCAL) || + bt_mesh_friend_get() != BT_MESH_FRIEND_ENABLED) { + return; + } - BT_DBG("recv_ttl %u net_idx 0x%04x src 0x%04x dst 0x%04x", - rx->ctx.recv_ttl, rx->sub->net_idx, rx->ctx.addr, - rx->ctx.recv_dst); + BT_DBG("recv_ttl %u net_idx 0x%04x src 0x%04x dst 0x%04x", + rx->ctx.recv_ttl, rx->sub->net_idx, rx->ctx.addr, + rx->ctx.recv_dst); - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (!friend_lpn_matches(frnd, rx->sub->net_idx, - rx->ctx.recv_dst)) { - continue; - } + if (!friend_lpn_matches(frnd, rx->sub->net_idx, + rx->ctx.recv_dst)) { + continue; + } - if (!friend_queue_prepare_space(frnd, rx->ctx.addr, seq_auth, - seg_count)) { - continue; - } + if (!friend_queue_prepare_space(frnd, rx->ctx.addr, seq_auth, + seg_count)) { + continue; + } - friend_lpn_enqueue_rx(frnd, rx, type, seq_auth, seg_count, - sbuf); - } + friend_lpn_enqueue_rx(frnd, rx, type, seq_auth, seg_count, + sbuf); + } } bool bt_mesh_friend_enqueue_tx(struct bt_mesh_net_tx *tx, - enum bt_mesh_friend_pdu_type type, - u64_t *seq_auth, u8_t seg_count, - struct net_buf_simple *sbuf) + enum bt_mesh_friend_pdu_type type, + u64_t *seq_auth, u8_t seg_count, + struct net_buf_simple *sbuf) { - bool matched = false; - int i; + bool matched = false; + int i; - if (!bt_mesh_friend_match(tx->sub->net_idx, tx->ctx->addr) || - bt_mesh_friend_get() != BT_MESH_FRIEND_ENABLED) { - return matched; - } + if (!bt_mesh_friend_match(tx->sub->net_idx, tx->ctx->addr) || + bt_mesh_friend_get() != BT_MESH_FRIEND_ENABLED) { + return matched; + } - BT_DBG("net_idx 0x%04x dst 0x%04x src 0x%04x", tx->sub->net_idx, - tx->ctx->addr, tx->src); + BT_DBG("net_idx 0x%04x dst 0x%04x src 0x%04x", tx->sub->net_idx, + tx->ctx->addr, tx->src); - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - if (!friend_lpn_matches(frnd, tx->sub->net_idx, - tx->ctx->addr)) { - continue; - } + if (!friend_lpn_matches(frnd, tx->sub->net_idx, + tx->ctx->addr)) { + continue; + } - if (!friend_queue_prepare_space(frnd, tx->src, seq_auth, - seg_count)) { - continue; - } + if (!friend_queue_prepare_space(frnd, tx->src, seq_auth, + seg_count)) { + continue; + } - friend_lpn_enqueue_tx(frnd, tx, type, seq_auth, seg_count, - sbuf); - matched = true; - } + friend_lpn_enqueue_tx(frnd, tx, type, seq_auth, seg_count, + sbuf); + matched = true; + } - return matched; + return matched; } void bt_mesh_friend_clear_incomplete(struct bt_mesh_subnet *sub, u16_t src, - u16_t dst, u64_t *seq_auth) + u16_t dst, u64_t *seq_auth) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { - struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; - int j; + for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) { + struct bt_mesh_friend *frnd = &bt_mesh.frnd[i]; + int j; - if (!friend_lpn_matches(frnd, sub->net_idx, dst)) { - continue; - } + if (!friend_lpn_matches(frnd, sub->net_idx, dst)) { + continue; + } - for (j = 0; j < ARRAY_SIZE(frnd->seg); j++) { - struct bt_mesh_friend_seg *seg = &frnd->seg[j]; - struct net_buf *buf; + for (j = 0; j < ARRAY_SIZE(frnd->seg); j++) { + struct bt_mesh_friend_seg *seg = &frnd->seg[j]; + struct net_buf *buf; - buf = (void *)sys_slist_peek_head(&seg->queue); - if (!buf) { - continue; - } + buf = (void *)sys_slist_peek_head(&seg->queue); + if (!buf) { + continue; + } - if (BT_MESH_ADV(buf)->addr != src) { - continue; - } + if (BT_MESH_ADV(buf)->addr != src) { + continue; + } - if (FRIEND_ADV(buf)->seq_auth != *seq_auth) { - continue; - } + if (FRIEND_ADV(buf)->seq_auth != *seq_auth) { + continue; + } - BT_WARN("Clearing incomplete segments for 0x%04x", src); + BT_WARN("Clearing incomplete segments for 0x%04x", src); - purge_buffers(&seg->queue); - seg->seg_count = 0U; - } - } + purge_buffers(&seg->queue); + seg->seg_count = 0U; + } + } } diff --git a/components/network/ble/blemesh/src/friend.h b/components/network/ble/blemesh/src/friend.h index be3133b4..4796f2a0 100644 --- a/components/network/ble/blemesh/src/friend.h +++ b/components/network/ble/blemesh/src/friend.h @@ -9,30 +9,30 @@ #define __FRIEND_H__ enum bt_mesh_friend_pdu_type { - BT_MESH_FRIEND_PDU_SINGLE, - BT_MESH_FRIEND_PDU_PARTIAL, - BT_MESH_FRIEND_PDU_COMPLETE, + BT_MESH_FRIEND_PDU_SINGLE, + BT_MESH_FRIEND_PDU_PARTIAL, + BT_MESH_FRIEND_PDU_COMPLETE, }; bool bt_mesh_friend_match(u16_t net_idx, u16_t addr); struct bt_mesh_friend *bt_mesh_friend_find(u16_t net_idx, u16_t lpn_addr, - bool valid, bool established); + bool valid, bool established); bool bt_mesh_friend_queue_has_space(u16_t net_idx, u16_t src, u16_t dst, - u64_t *seq_auth, u8_t seg_count); + u64_t *seq_auth, u8_t seg_count); void bt_mesh_friend_enqueue_rx(struct bt_mesh_net_rx *rx, - enum bt_mesh_friend_pdu_type type, - u64_t *seq_auth, u8_t seg_count, - struct net_buf_simple *sbuf); + enum bt_mesh_friend_pdu_type type, + u64_t *seq_auth, u8_t seg_count, + struct net_buf_simple *sbuf); bool bt_mesh_friend_enqueue_tx(struct bt_mesh_net_tx *tx, - enum bt_mesh_friend_pdu_type type, - u64_t *seq_auth, u8_t seg_count, - struct net_buf_simple *sbuf); + enum bt_mesh_friend_pdu_type type, + u64_t *seq_auth, u8_t seg_count, + struct net_buf_simple *sbuf); void bt_mesh_friend_clear_incomplete(struct bt_mesh_subnet *sub, u16_t src, - u16_t dst, u64_t *seq_auth); + u16_t dst, u64_t *seq_auth); void bt_mesh_friend_sec_update(u16_t net_idx); @@ -42,11 +42,11 @@ int bt_mesh_friend_poll(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf); int bt_mesh_friend_req(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf); int bt_mesh_friend_clear(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf); int bt_mesh_friend_clear_cfm(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf); + struct net_buf_simple *buf); int bt_mesh_friend_sub_add(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf); + struct net_buf_simple *buf); int bt_mesh_friend_sub_rem(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf); + struct net_buf_simple *buf); int bt_mesh_friend_init(void); diff --git a/components/network/ble/blemesh/src/health_cli.c b/components/network/ble/blemesh/src/health_cli.c index 4a399223..3541546d 100644 --- a/components/network/ble/blemesh/src/health_cli.c +++ b/components/network/ble/blemesh/src/health_cli.c @@ -31,506 +31,506 @@ static s32_t msg_timeout = K_SECONDS(2); static struct bt_mesh_health_cli *health_cli; struct health_fault_param { - u16_t cid; - u8_t *expect_test_id; - u8_t *test_id; - u8_t *faults; - size_t *fault_count; + u16_t cid; + u8_t *expect_test_id; + u8_t *test_id; + u8_t *faults; + size_t *fault_count; }; static void health_fault_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct health_fault_param *param; - u8_t test_id; - u16_t cid; + struct health_fault_param *param; + u8_t test_id; + u16_t cid; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (health_cli->op_pending != OP_HEALTH_FAULT_STATUS) { - BT_WARN("Unexpected Health Fault Status message"); - return; - } + if (health_cli->op_pending != OP_HEALTH_FAULT_STATUS) { + BT_WARN("Unexpected Health Fault Status message"); + return; + } - param = health_cli->op_param; + param = health_cli->op_param; - test_id = net_buf_simple_pull_u8(buf); - if (param->expect_test_id && test_id != *param->expect_test_id) { - BT_WARN("Health fault with unexpected Test ID"); - return; - } + test_id = net_buf_simple_pull_u8(buf); + if (param->expect_test_id && test_id != *param->expect_test_id) { + BT_WARN("Health fault with unexpected Test ID"); + return; + } - cid = net_buf_simple_pull_le16(buf); - if (cid != param->cid) { - BT_WARN("Health fault with unexpected Company ID"); - return; - } + cid = net_buf_simple_pull_le16(buf); + if (cid != param->cid) { + BT_WARN("Health fault with unexpected Company ID"); + return; + } - if (param->test_id) { - *param->test_id = test_id; - } + if (param->test_id) { + *param->test_id = test_id; + } - if (buf->len > *param->fault_count) { - BT_WARN("Got more faults than there's space for"); - } else { - *param->fault_count = buf->len; - } + if (buf->len > *param->fault_count) { + BT_WARN("Got more faults than there's space for"); + } else { + *param->fault_count = buf->len; + } - memcpy(param->faults, buf->data, *param->fault_count); + memcpy(param->faults, buf->data, *param->fault_count); - k_sem_give(&health_cli->op_sync); + k_sem_give(&health_cli->op_sync); } static void health_current_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_health_cli *cli = model->user_data; - u8_t test_id; - u16_t cid; + struct bt_mesh_health_cli *cli = model->user_data; + u8_t test_id; + u16_t cid; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - test_id = net_buf_simple_pull_u8(buf); - cid = net_buf_simple_pull_le16(buf); + test_id = net_buf_simple_pull_u8(buf); + cid = net_buf_simple_pull_le16(buf); - BT_DBG("Test ID 0x%02x Company ID 0x%04x Fault Count %u", - test_id, cid, buf->len); + BT_DBG("Test ID 0x%02x Company ID 0x%04x Fault Count %u", + test_id, cid, buf->len); - if (!cli->current_status) { - BT_WARN("No Current Status callback available"); - return; - } + if (!cli->current_status) { + BT_WARN("No Current Status callback available"); + return; + } - cli->current_status(cli, ctx->addr, test_id, cid, buf->data, buf->len); + cli->current_status(cli, ctx->addr, test_id, cid, buf->data, buf->len); } struct health_period_param { - u8_t *divisor; + u8_t *divisor; }; static void health_period_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct health_period_param *param; + struct health_period_param *param; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (health_cli->op_pending != OP_HEALTH_PERIOD_STATUS) { - BT_WARN("Unexpected Health Period Status message"); - return; - } + if (health_cli->op_pending != OP_HEALTH_PERIOD_STATUS) { + BT_WARN("Unexpected Health Period Status message"); + return; + } - param = health_cli->op_param; + param = health_cli->op_param; - *param->divisor = net_buf_simple_pull_u8(buf); + *param->divisor = net_buf_simple_pull_u8(buf); - k_sem_give(&health_cli->op_sync); + k_sem_give(&health_cli->op_sync); } struct health_attention_param { - u8_t *attention; + u8_t *attention; }; static void health_attention_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct health_attention_param *param; + struct health_attention_param *param; - BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", - ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, - bt_hex(buf->data, buf->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", + ctx->net_idx, ctx->app_idx, ctx->addr, buf->len, + bt_hex(buf->data, buf->len)); - if (health_cli->op_pending != OP_ATTENTION_STATUS) { - BT_WARN("Unexpected Health Attention Status message"); - return; - } + if (health_cli->op_pending != OP_ATTENTION_STATUS) { + BT_WARN("Unexpected Health Attention Status message"); + return; + } - param = health_cli->op_param; + param = health_cli->op_param; - if (param->attention) { - *param->attention = net_buf_simple_pull_u8(buf); - } + if (param->attention) { + *param->attention = net_buf_simple_pull_u8(buf); + } - k_sem_give(&health_cli->op_sync); + k_sem_give(&health_cli->op_sync); } const struct bt_mesh_model_op bt_mesh_health_cli_op[] = { - { OP_HEALTH_FAULT_STATUS, 3, health_fault_status }, - { OP_HEALTH_CURRENT_STATUS, 3, health_current_status }, - { OP_HEALTH_PERIOD_STATUS, 1, health_period_status }, - { OP_ATTENTION_STATUS, 1, health_attention_status }, - BT_MESH_MODEL_OP_END, + { OP_HEALTH_FAULT_STATUS, 3, health_fault_status }, + { OP_HEALTH_CURRENT_STATUS, 3, health_current_status }, + { OP_HEALTH_PERIOD_STATUS, 1, health_period_status }, + { OP_ATTENTION_STATUS, 1, health_attention_status }, + BT_MESH_MODEL_OP_END, }; static int cli_prepare(void *param, u32_t op) { - if (!health_cli) { - BT_ERR("No available Health Client context!"); - return -EINVAL; - } + if (!health_cli) { + BT_ERR("No available Health Client context!"); + return -EINVAL; + } - if (health_cli->op_pending) { - BT_WARN("Another synchronous operation pending"); - return -EBUSY; - } + if (health_cli->op_pending) { + BT_WARN("Another synchronous operation pending"); + return -EBUSY; + } - health_cli->op_param = param; - health_cli->op_pending = op; + health_cli->op_param = param; + health_cli->op_pending = op; - return 0; + return 0; } static void cli_reset(void) { - health_cli->op_pending = 0U; - health_cli->op_param = NULL; + health_cli->op_pending = 0U; + health_cli->op_param = NULL; } static int cli_wait(void) { - int err; + int err; - err = k_sem_take(&health_cli->op_sync, msg_timeout); + err = k_sem_take(&health_cli->op_sync, msg_timeout); - cli_reset(); + cli_reset(); - return err; + return err; } int bt_mesh_health_attention_get(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t *attention) + u8_t *attention) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = app_idx, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct health_attention_param param = { - .attention = attention, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = app_idx, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct health_attention_param param = { + .attention = attention, + }; + int err; - err = cli_prepare(¶m, OP_ATTENTION_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_ATTENTION_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_ATTENTION_GET); + bt_mesh_model_msg_init(&msg, OP_ATTENTION_GET); - err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_health_attention_set(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t attention, u8_t *updated_attention) + u8_t attention, u8_t *updated_attention) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = app_idx, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct health_attention_param param = { - .attention = updated_attention, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = app_idx, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct health_attention_param param = { + .attention = updated_attention, + }; + int err; - err = cli_prepare(¶m, OP_ATTENTION_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_ATTENTION_STATUS); + if (err) { + return err; + } - if (updated_attention) { - bt_mesh_model_msg_init(&msg, OP_ATTENTION_SET); - } else { - bt_mesh_model_msg_init(&msg, OP_ATTENTION_SET_UNREL); - } + if (updated_attention) { + bt_mesh_model_msg_init(&msg, OP_ATTENTION_SET); + } else { + bt_mesh_model_msg_init(&msg, OP_ATTENTION_SET_UNREL); + } - net_buf_simple_add_u8(&msg, attention); + net_buf_simple_add_u8(&msg, attention); - err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!updated_attention) { - cli_reset(); - return 0; - } + if (!updated_attention) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_health_period_get(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t *divisor) + u8_t *divisor) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = app_idx, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct health_period_param param = { - .divisor = divisor, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = app_idx, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct health_period_param param = { + .divisor = divisor, + }; + int err; - err = cli_prepare(¶m, OP_HEALTH_PERIOD_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEALTH_PERIOD_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_GET); + bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_GET); - err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_health_period_set(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t divisor, u8_t *updated_divisor) + u8_t divisor, u8_t *updated_divisor) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = app_idx, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct health_period_param param = { - .divisor = updated_divisor, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = app_idx, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct health_period_param param = { + .divisor = updated_divisor, + }; + int err; - err = cli_prepare(¶m, OP_HEALTH_PERIOD_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEALTH_PERIOD_STATUS); + if (err) { + return err; + } - if (updated_divisor) { - bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_SET); - } else { - bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_SET_UNREL); - } + if (updated_divisor) { + bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_SET); + } else { + bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_SET_UNREL); + } - net_buf_simple_add_u8(&msg, divisor); + net_buf_simple_add_u8(&msg, divisor); - err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!updated_divisor) { - cli_reset(); - return 0; - } + if (!updated_divisor) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_health_fault_test(u16_t net_idx, u16_t addr, u16_t app_idx, - u16_t cid, u8_t test_id, u8_t *faults, - size_t *fault_count) + u16_t cid, u8_t test_id, u8_t *faults, + size_t *fault_count) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = app_idx, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct health_fault_param param = { - .cid = cid, - .expect_test_id = &test_id, - .faults = faults, - .fault_count = fault_count, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = app_idx, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct health_fault_param param = { + .cid = cid, + .expect_test_id = &test_id, + .faults = faults, + .fault_count = fault_count, + }; + int err; - err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS); + if (err) { + return err; + } - if (faults) { - bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_TEST); - } else { - bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_TEST_UNREL); - } + if (faults) { + bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_TEST); + } else { + bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_TEST_UNREL); + } - net_buf_simple_add_u8(&msg, test_id); - net_buf_simple_add_le16(&msg, cid); + net_buf_simple_add_u8(&msg, test_id); + net_buf_simple_add_le16(&msg, cid); - err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!faults) { - cli_reset(); - return 0; - } + if (!faults) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_health_fault_clear(u16_t net_idx, u16_t addr, u16_t app_idx, - u16_t cid, u8_t *test_id, u8_t *faults, - size_t *fault_count) + u16_t cid, u8_t *test_id, u8_t *faults, + size_t *fault_count) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = app_idx, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct health_fault_param param = { - .cid = cid, - .test_id = test_id, - .faults = faults, - .fault_count = fault_count, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = app_idx, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct health_fault_param param = { + .cid = cid, + .test_id = test_id, + .faults = faults, + .fault_count = fault_count, + }; + int err; - err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS); + if (err) { + return err; + } - if (test_id) { - bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_CLEAR); - } else { - bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_CLEAR_UNREL); - } + if (test_id) { + bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_CLEAR); + } else { + bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_CLEAR_UNREL); + } - net_buf_simple_add_le16(&msg, cid); + net_buf_simple_add_le16(&msg, cid); - err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - if (!test_id) { - cli_reset(); - return 0; - } + if (!test_id) { + cli_reset(); + return 0; + } - return cli_wait(); + return cli_wait(); } int bt_mesh_health_fault_get(u16_t net_idx, u16_t addr, u16_t app_idx, - u16_t cid, u8_t *test_id, u8_t *faults, - size_t *fault_count) + u16_t cid, u8_t *test_id, u8_t *faults, + size_t *fault_count) { - NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); - struct bt_mesh_msg_ctx ctx = { - .net_idx = net_idx, - .app_idx = app_idx, - .addr = addr, - .send_ttl = BT_MESH_TTL_DEFAULT, - }; - struct health_fault_param param = { - .cid = cid, - .test_id = test_id, - .faults = faults, - .fault_count = fault_count, - }; - int err; + NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4); + struct bt_mesh_msg_ctx ctx = { + .net_idx = net_idx, + .app_idx = app_idx, + .addr = addr, + .send_ttl = BT_MESH_TTL_DEFAULT, + }; + struct health_fault_param param = { + .cid = cid, + .test_id = test_id, + .faults = faults, + .fault_count = fault_count, + }; + int err; - err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS); - if (err) { - return err; - } + err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS); + if (err) { + return err; + } - bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_GET); - net_buf_simple_add_le16(&msg, cid); + bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_GET); + net_buf_simple_add_le16(&msg, cid); - err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); - if (err) { - BT_ERR("model_send() failed (err %d)", err); - cli_reset(); - return err; - } + err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL); + if (err) { + BT_ERR("model_send() failed (err %d)", err); + cli_reset(); + return err; + } - return cli_wait(); + return cli_wait(); } s32_t bt_mesh_health_cli_timeout_get(void) { - return msg_timeout; + return msg_timeout; } void bt_mesh_health_cli_timeout_set(s32_t timeout) { - msg_timeout = timeout; + msg_timeout = timeout; } int bt_mesh_health_cli_set(struct bt_mesh_model *model) { - if (!model->user_data) { - BT_ERR("No Health Client context for given model"); - return -EINVAL; - } + if (!model->user_data) { + BT_ERR("No Health Client context for given model"); + return -EINVAL; + } - health_cli = model->user_data; + health_cli = model->user_data; - return 0; + return 0; } int bt_mesh_health_cli_init(struct bt_mesh_model *model, bool primary) { - struct bt_mesh_health_cli *cli = model->user_data; + struct bt_mesh_health_cli *cli = model->user_data; - BT_DBG("primary %u", primary); + BT_DBG("primary %u", primary); - if (!cli) { - BT_ERR("No Health Client context provided"); - return -EINVAL; - } + if (!cli) { + BT_ERR("No Health Client context provided"); + return -EINVAL; + } - cli = model->user_data; - cli->model = model; + cli = model->user_data; + cli->model = model; - k_sem_init(&cli->op_sync, 0, 1); + k_sem_init(&cli->op_sync, 0, 1); - /* Set the default health client pointer */ - if (!health_cli) { - health_cli = cli; - } + /* Set the default health client pointer */ + if (!health_cli) { + health_cli = cli; + } - return 0; + return 0; } diff --git a/components/network/ble/blemesh/src/health_srv.c b/components/network/ble/blemesh/src/health_srv.c index 621a8536..d4224132 100644 --- a/components/network/ble/blemesh/src/health_srv.c +++ b/components/network/ble/blemesh/src/health_srv.c @@ -34,414 +34,414 @@ struct bt_mesh_health_srv *health_srv; static void health_get_registered(struct bt_mesh_model *mod, - u16_t company_id, - struct net_buf_simple *msg) + u16_t company_id, + struct net_buf_simple *msg) { - struct bt_mesh_health_srv *srv = mod->user_data; - u8_t *test_id; + struct bt_mesh_health_srv *srv = mod->user_data; + u8_t *test_id; - BT_DBG("Company ID 0x%04x", company_id); + BT_DBG("Company ID 0x%04x", company_id); - bt_mesh_model_msg_init(msg, OP_HEALTH_FAULT_STATUS); + bt_mesh_model_msg_init(msg, OP_HEALTH_FAULT_STATUS); - test_id = net_buf_simple_add(msg, 1); - net_buf_simple_add_le16(msg, company_id); + test_id = net_buf_simple_add(msg, 1); + net_buf_simple_add_le16(msg, company_id); - if (srv->cb && srv->cb->fault_get_reg) { - u8_t fault_count = net_buf_simple_tailroom(msg) - 4; - int err; + if (srv->cb && srv->cb->fault_get_reg) { + u8_t fault_count = net_buf_simple_tailroom(msg) - 4; + int err; - err = srv->cb->fault_get_reg(mod, company_id, test_id, - net_buf_simple_tail(msg), - &fault_count); - if (err) { - BT_ERR("Failed to get faults (err %d)", err); - *test_id = HEALTH_TEST_STANDARD; - } else { - net_buf_simple_add(msg, fault_count); - } - } else { - BT_WARN("No callback for getting faults"); - *test_id = HEALTH_TEST_STANDARD; - } + err = srv->cb->fault_get_reg(mod, company_id, test_id, + net_buf_simple_tail(msg), + &fault_count); + if (err) { + BT_ERR("Failed to get faults (err %d)", err); + *test_id = HEALTH_TEST_STANDARD; + } else { + net_buf_simple_add(msg, fault_count); + } + } else { + BT_WARN("No callback for getting faults"); + *test_id = HEALTH_TEST_STANDARD; + } } static size_t health_get_current(struct bt_mesh_model *mod, - struct net_buf_simple *msg) + struct net_buf_simple *msg) { - struct bt_mesh_health_srv *srv = mod->user_data; - const struct bt_mesh_comp *comp; - u8_t *test_id, *company_ptr; - u16_t company_id; - u8_t fault_count; - int err; + struct bt_mesh_health_srv *srv = mod->user_data; + const struct bt_mesh_comp *comp; + u8_t *test_id, *company_ptr; + u16_t company_id; + u8_t fault_count; + int err; - bt_mesh_model_msg_init(msg, OP_HEALTH_CURRENT_STATUS); + bt_mesh_model_msg_init(msg, OP_HEALTH_CURRENT_STATUS); - test_id = net_buf_simple_add(msg, 1); - company_ptr = net_buf_simple_add(msg, sizeof(company_id)); - comp = bt_mesh_comp_get(); + test_id = net_buf_simple_add(msg, 1); + company_ptr = net_buf_simple_add(msg, sizeof(company_id)); + comp = bt_mesh_comp_get(); - if (srv->cb && srv->cb->fault_get_cur) { - fault_count = net_buf_simple_tailroom(msg); - err = srv->cb->fault_get_cur(mod, test_id, &company_id, - net_buf_simple_tail(msg), - &fault_count); - if (err) { - BT_ERR("Failed to get faults (err %d)", err); - sys_put_le16(comp->cid, company_ptr); - *test_id = HEALTH_TEST_STANDARD; - fault_count = 0U; - } else { - sys_put_le16(company_id, company_ptr); - net_buf_simple_add(msg, fault_count); - } - } else { - BT_WARN("No callback for getting faults"); - sys_put_le16(comp->cid, company_ptr); - *test_id = HEALTH_TEST_STANDARD; - fault_count = 0U; - } + if (srv->cb && srv->cb->fault_get_cur) { + fault_count = net_buf_simple_tailroom(msg); + err = srv->cb->fault_get_cur(mod, test_id, &company_id, + net_buf_simple_tail(msg), + &fault_count); + if (err) { + BT_ERR("Failed to get faults (err %d)", err); + sys_put_le16(comp->cid, company_ptr); + *test_id = HEALTH_TEST_STANDARD; + fault_count = 0U; + } else { + sys_put_le16(company_id, company_ptr); + net_buf_simple_add(msg, fault_count); + } + } else { + BT_WARN("No callback for getting faults"); + sys_put_le16(comp->cid, company_ptr); + *test_id = HEALTH_TEST_STANDARD; + fault_count = 0U; + } - return fault_count; + return fault_count; } static void health_fault_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); - u16_t company_id; + NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); + u16_t company_id; - company_id = net_buf_simple_pull_le16(buf); + company_id = net_buf_simple_pull_le16(buf); - BT_DBG("company_id 0x%04x", company_id); + BT_DBG("company_id 0x%04x", company_id); - health_get_registered(model, company_id, &sdu); + health_get_registered(model, company_id, &sdu); - if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { - BT_ERR("Unable to send Health Current Status response"); - } + if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { + BT_ERR("Unable to send Health Current Status response"); + } } static void health_fault_clear_unrel(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_health_srv *srv = model->user_data; - u16_t company_id; + struct bt_mesh_health_srv *srv = model->user_data; + u16_t company_id; - company_id = net_buf_simple_pull_le16(buf); + company_id = net_buf_simple_pull_le16(buf); - BT_DBG("company_id 0x%04x", company_id); + BT_DBG("company_id 0x%04x", company_id); - if (srv->cb && srv->cb->fault_clear) { - srv->cb->fault_clear(model, company_id); - } + if (srv->cb && srv->cb->fault_clear) { + srv->cb->fault_clear(model, company_id); + } } static void health_fault_clear(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); - struct bt_mesh_health_srv *srv = model->user_data; - u16_t company_id; + NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); + struct bt_mesh_health_srv *srv = model->user_data; + u16_t company_id; - company_id = net_buf_simple_pull_le16(buf); + company_id = net_buf_simple_pull_le16(buf); - BT_DBG("company_id 0x%04x", company_id); + BT_DBG("company_id 0x%04x", company_id); - if (srv->cb && srv->cb->fault_clear) { - srv->cb->fault_clear(model, company_id); - } + if (srv->cb && srv->cb->fault_clear) { + srv->cb->fault_clear(model, company_id); + } - health_get_registered(model, company_id, &sdu); + health_get_registered(model, company_id, &sdu); - if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { - BT_ERR("Unable to send Health Current Status response"); - } + if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { + BT_ERR("Unable to send Health Current Status response"); + } } static void health_fault_test_unrel(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - struct bt_mesh_health_srv *srv = model->user_data; - u16_t company_id; - u8_t test_id; + struct bt_mesh_health_srv *srv = model->user_data; + u16_t company_id; + u8_t test_id; - test_id = net_buf_simple_pull_u8(buf); - company_id = net_buf_simple_pull_le16(buf); + test_id = net_buf_simple_pull_u8(buf); + company_id = net_buf_simple_pull_le16(buf); - BT_DBG("test 0x%02x company 0x%04x", test_id, company_id); + BT_DBG("test 0x%02x company 0x%04x", test_id, company_id); - if (srv->cb && srv->cb->fault_test) { - srv->cb->fault_test(model, test_id, company_id); - } + if (srv->cb && srv->cb->fault_test) { + srv->cb->fault_test(model, test_id, company_id); + } } static void health_fault_test(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); - struct bt_mesh_health_srv *srv = model->user_data; - u16_t company_id; - u8_t test_id; + NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX); + struct bt_mesh_health_srv *srv = model->user_data; + u16_t company_id; + u8_t test_id; - BT_DBG(""); + BT_DBG(""); - test_id = net_buf_simple_pull_u8(buf); - company_id = net_buf_simple_pull_le16(buf); + test_id = net_buf_simple_pull_u8(buf); + company_id = net_buf_simple_pull_le16(buf); - BT_DBG("test 0x%02x company 0x%04x", test_id, company_id); + BT_DBG("test 0x%02x company 0x%04x", test_id, company_id); - if (srv->cb && srv->cb->fault_test) { - int err; + if (srv->cb && srv->cb->fault_test) { + int err; - err = srv->cb->fault_test(model, test_id, company_id); - if (err) { - BT_WARN("Running fault test failed with err %d", err); - return; - } - } + err = srv->cb->fault_test(model, test_id, company_id); + if (err) { + BT_WARN("Running fault test failed with err %d", err); + return; + } + } - health_get_registered(model, company_id, &sdu); + health_get_registered(model, company_id, &sdu); - if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { - BT_ERR("Unable to send Health Current Status response"); - } + if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) { + BT_ERR("Unable to send Health Current Status response"); + } } static void send_attention_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx) + struct bt_mesh_msg_ctx *ctx) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - struct bt_mesh_health_srv *srv = model->user_data; - u8_t time; + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + struct bt_mesh_health_srv *srv = model->user_data; + u8_t time; - time = k_delayed_work_remaining_get(&srv->attn_timer) / 1000; - BT_DBG("%u second%s", time, (time == 1U) ? "" : "s"); + time = k_delayed_work_remaining_get(&srv->attn_timer) / 1000; + BT_DBG("%u second%s", time, (time == 1U) ? "" : "s"); - bt_mesh_model_msg_init(&msg, OP_ATTENTION_STATUS); + bt_mesh_model_msg_init(&msg, OP_ATTENTION_STATUS); - net_buf_simple_add_u8(&msg, time); + net_buf_simple_add_u8(&msg, time); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Attention Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Attention Status"); + } } static void attention_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG(""); + BT_DBG(""); - send_attention_status(model, ctx); + send_attention_status(model, ctx); } static void attention_set_unrel(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u8_t time; + u8_t time; - time = net_buf_simple_pull_u8(buf); + time = net_buf_simple_pull_u8(buf); - BT_DBG("%u second%s", time, (time == 1U) ? "" : "s"); + BT_DBG("%u second%s", time, (time == 1U) ? "" : "s"); - bt_mesh_attention(model, time); + bt_mesh_attention(model, time); } static void attention_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG(""); + BT_DBG(""); - attention_set_unrel(model, ctx, buf); + attention_set_unrel(model, ctx, buf); - send_attention_status(model, ctx); + send_attention_status(model, ctx); } static void send_health_period_status(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx) + struct bt_mesh_msg_ctx *ctx) { - /* Needed size: opcode (2 bytes) + msg + MIC */ - NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); + /* Needed size: opcode (2 bytes) + msg + MIC */ + NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4); - bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_STATUS); + bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_STATUS); - net_buf_simple_add_u8(&msg, model->pub->period_div); + net_buf_simple_add_u8(&msg, model->pub->period_div); - if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("Unable to send Health Period Status"); - } + if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { + BT_ERR("Unable to send Health Period Status"); + } } static void health_period_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG(""); + BT_DBG(""); - send_health_period_status(model, ctx); + send_health_period_status(model, ctx); } static void health_period_set_unrel(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - u8_t period; + u8_t period; - period = net_buf_simple_pull_u8(buf); - if (period > 15) { - BT_WARN("Prohibited period value %u", period); - return; - } + period = net_buf_simple_pull_u8(buf); + if (period > 15) { + BT_WARN("Prohibited period value %u", period); + return; + } - BT_DBG("period %u", period); + BT_DBG("period %u", period); - model->pub->period_div = period; + model->pub->period_div = period; } static void health_period_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { - BT_DBG(""); + BT_DBG(""); - health_period_set_unrel(model, ctx, buf); + health_period_set_unrel(model, ctx, buf); - send_health_period_status(model, ctx); + send_health_period_status(model, ctx); } const struct bt_mesh_model_op bt_mesh_health_srv_op[] = { - { OP_HEALTH_FAULT_GET, 2, health_fault_get }, - { OP_HEALTH_FAULT_CLEAR, 2, health_fault_clear }, - { OP_HEALTH_FAULT_CLEAR_UNREL, 2, health_fault_clear_unrel }, - { OP_HEALTH_FAULT_TEST, 3, health_fault_test }, - { OP_HEALTH_FAULT_TEST_UNREL, 3, health_fault_test_unrel }, - { OP_HEALTH_PERIOD_GET, 0, health_period_get }, - { OP_HEALTH_PERIOD_SET, 1, health_period_set }, - { OP_HEALTH_PERIOD_SET_UNREL, 1, health_period_set_unrel }, - { OP_ATTENTION_GET, 0, attention_get }, - { OP_ATTENTION_SET, 1, attention_set }, - { OP_ATTENTION_SET_UNREL, 1, attention_set_unrel }, - BT_MESH_MODEL_OP_END, + { OP_HEALTH_FAULT_GET, 2, health_fault_get }, + { OP_HEALTH_FAULT_CLEAR, 2, health_fault_clear }, + { OP_HEALTH_FAULT_CLEAR_UNREL, 2, health_fault_clear_unrel }, + { OP_HEALTH_FAULT_TEST, 3, health_fault_test }, + { OP_HEALTH_FAULT_TEST_UNREL, 3, health_fault_test_unrel }, + { OP_HEALTH_PERIOD_GET, 0, health_period_get }, + { OP_HEALTH_PERIOD_SET, 1, health_period_set }, + { OP_HEALTH_PERIOD_SET_UNREL, 1, health_period_set_unrel }, + { OP_ATTENTION_GET, 0, attention_get }, + { OP_ATTENTION_SET, 1, attention_set }, + { OP_ATTENTION_SET_UNREL, 1, attention_set_unrel }, + BT_MESH_MODEL_OP_END, }; static int health_pub_update(struct bt_mesh_model *mod) { - struct bt_mesh_model_pub *pub = mod->pub; - size_t count; + struct bt_mesh_model_pub *pub = mod->pub; + size_t count; - BT_DBG(""); + BT_DBG(""); - count = health_get_current(mod, pub->msg); - if (count) { - pub->fast_period = 1U; - } else { - pub->fast_period = 0U; - } + count = health_get_current(mod, pub->msg); + if (count) { + pub->fast_period = 1U; + } else { + pub->fast_period = 0U; + } - return 0; + return 0; } int bt_mesh_fault_update(struct bt_mesh_elem *elem) { - struct bt_mesh_model *mod; + struct bt_mesh_model *mod; - mod = bt_mesh_model_find(elem, BT_MESH_MODEL_ID_HEALTH_SRV); - if (!mod) { - return -EINVAL; - } + mod = bt_mesh_model_find(elem, BT_MESH_MODEL_ID_HEALTH_SRV); + if (!mod) { + return -EINVAL; + } - /* Let periodic publishing, if enabled, take care of sending the - * Health Current Status. - */ - if (bt_mesh_model_pub_period_get(mod)) { - return 0; - } + /* Let periodic publishing, if enabled, take care of sending the + * Health Current Status. + */ + if (bt_mesh_model_pub_period_get(mod)) { + return 0; + } - health_pub_update(mod); + health_pub_update(mod); - return bt_mesh_model_publish(mod); + return bt_mesh_model_publish(mod); } static void attention_off(struct k_work *work) { - struct bt_mesh_health_srv *srv = CONTAINER_OF(work, - struct bt_mesh_health_srv, - attn_timer.work); - BT_DBG(""); + struct bt_mesh_health_srv *srv = CONTAINER_OF(work, + struct bt_mesh_health_srv, + attn_timer.work); + BT_DBG(""); - if (srv->cb && srv->cb->attn_off) { - srv->cb->attn_off(srv->model); - } + if (srv->cb && srv->cb->attn_off) { + srv->cb->attn_off(srv->model); + } } int bt_mesh_health_srv_init(struct bt_mesh_model *model, bool primary) { - struct bt_mesh_health_srv *srv = model->user_data; + struct bt_mesh_health_srv *srv = model->user_data; - if (!srv) { - if (!primary) { - return 0; - } + if (!srv) { + if (!primary) { + return 0; + } - BT_ERR("No Health Server context provided"); - return -EINVAL; - } + BT_ERR("No Health Server context provided"); + return -EINVAL; + } - if (!model->pub) { - BT_ERR("Health Server has no publication support"); - return -EINVAL; - } + if (!model->pub) { + BT_ERR("Health Server has no publication support"); + return -EINVAL; + } - model->pub->update = health_pub_update; + model->pub->update = health_pub_update; - k_delayed_work_init(&srv->attn_timer, attention_off); + k_delayed_work_init(&srv->attn_timer, attention_off); - srv->model = model; + srv->model = model; - if (primary) { - health_srv = srv; - } + if (primary) { + health_srv = srv; + } - return 0; + return 0; } void bt_mesh_attention(struct bt_mesh_model *model, u8_t time) { - struct bt_mesh_health_srv *srv; + struct bt_mesh_health_srv *srv; - if (!model) { - srv = health_srv; - if (!srv) { - BT_WARN("No Health Server available"); - return; - } + if (!model) { + srv = health_srv; + if (!srv) { + BT_WARN("No Health Server available"); + return; + } - model = srv->model; - } else { - srv = model->user_data; - } + model = srv->model; + } else { + srv = model->user_data; + } - if (time) { - if (srv->cb && srv->cb->attn_on) { - srv->cb->attn_on(model); - } + if (time) { + if (srv->cb && srv->cb->attn_on) { + srv->cb->attn_on(model); + } - k_delayed_work_submit(&srv->attn_timer, time * 1000U); - } else { - k_delayed_work_cancel(&srv->attn_timer); + k_delayed_work_submit(&srv->attn_timer, time * 1000U); + } else { + k_delayed_work_cancel(&srv->attn_timer); - if (srv->cb && srv->cb->attn_off) { - srv->cb->attn_off(model); - } - } + if (srv->cb && srv->cb->attn_off) { + srv->cb->attn_off(model); + } + } } diff --git a/components/network/ble/blemesh/src/include/access.h b/components/network/ble/blemesh/src/include/access.h index a89dc5a8..b6947822 100644 --- a/components/network/ble/blemesh/src/include/access.h +++ b/components/network/ble/blemesh/src/include/access.h @@ -47,26 +47,26 @@ extern "C" { */ #define BT_MESH_ELEM(_loc, _mods, _vnd_mods) \ { \ - .loc = (_loc), \ - .model_count = ARRAY_SIZE(_mods), \ - .models = (_mods), \ - .vnd_model_count = ARRAY_SIZE(_vnd_mods), \ - .vnd_models = (_vnd_mods), \ + .loc = (_loc), \ + .model_count = ARRAY_SIZE(_mods), \ + .models = (_mods), \ + .vnd_model_count = ARRAY_SIZE(_vnd_mods), \ + .vnd_models = (_vnd_mods), \ } /** Abstraction that describes a Mesh Element */ struct bt_mesh_elem { - /* Unicast Address. Set at runtime during provisioning. */ - u16_t addr; + /* Unicast Address. Set at runtime during provisioning. */ + u16_t addr; - /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ - const u16_t loc; + /* Location Descriptor (GATT Bluetooth Namespace Descriptors) */ + const u16_t loc; - const u8_t model_count; - const u8_t vnd_model_count; + const u8_t model_count; + const u8_t vnd_model_count; - struct bt_mesh_model * const models; - struct bt_mesh_model * const vnd_models; + struct bt_mesh_model * const models; + struct bt_mesh_model * const vnd_models; }; /* Foundation Models */ @@ -131,31 +131,31 @@ struct bt_mesh_elem { /** Message sending context. */ struct bt_mesh_msg_ctx { - /** NetKey Index of the subnet to send the message on. */ - u16_t net_idx; + /** NetKey Index of the subnet to send the message on. */ + u16_t net_idx; - /** AppKey Index to encrypt the message with. */ - u16_t app_idx; + /** AppKey Index to encrypt the message with. */ + u16_t app_idx; - /** Remote address. */ - u16_t addr; + /** Remote address. */ + u16_t addr; - /** Destination address of a received message. Not used for sending. */ - u16_t recv_dst; + /** Destination address of a received message. Not used for sending. */ + u16_t recv_dst; - /** RSSI of received packet. Not used for sending. */ - s8_t recv_rssi; + /** RSSI of received packet. Not used for sending. */ + s8_t recv_rssi; - /** Received TTL value. Not used for sending. */ - u8_t recv_ttl; + /** Received TTL value. Not used for sending. */ + u8_t recv_ttl; - /** Force sending reliably by using segment acknowledgement */ - bool send_rel; + /** Force sending reliably by using segment acknowledgement */ + bool send_rel; - /** TTL, or BT_MESH_TTL_DEFAULT for default TTL. */ - u8_t send_ttl; + /** TTL, or BT_MESH_TTL_DEFAULT for default TTL. */ + u8_t send_ttl; - /** opcode of a received message. + /** opcode of a received message. * Not used for sending message. */ u32_t recv_op; @@ -168,16 +168,16 @@ struct bt_mesh_msg_ctx { }; struct bt_mesh_model_op { - /* OpCode encoded using the BT_MESH_MODEL_OP_* macros */ - const u32_t opcode; + /* OpCode encoded using the BT_MESH_MODEL_OP_* macros */ + const u32_t opcode; - /* Minimum required message length */ - const size_t min_len; + /* Minimum required message length */ + const size_t min_len; - /* Message handler for the opcode */ - void (*func)(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf); + /* Message handler for the opcode */ + void (*func)(struct bt_mesh_model *model, + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf); }; #define BT_MESH_MODEL_OP_1(b0) (b0) @@ -186,34 +186,34 @@ struct bt_mesh_model_op { #define BT_MESH_MODEL_OP_END { 0, 0, NULL } #define BT_MESH_MODEL_NO_OPS ((struct bt_mesh_model_op []) \ - { BT_MESH_MODEL_OP_END }) + { BT_MESH_MODEL_OP_END }) /** Helper to define an empty model array */ #define BT_MESH_MODEL_NONE ((struct bt_mesh_model []){}) #define BT_MESH_MODEL(_id, _op, _pub, _user_data) \ { \ - .id = (_id), \ - .op = _op, \ - .keys = { [0 ... (CONFIG_BT_MESH_MODEL_KEY_COUNT - 1)] = \ - BT_MESH_KEY_UNUSED }, \ - .pub = _pub, \ - .groups = { [0 ... (CONFIG_BT_MESH_MODEL_GROUP_COUNT - 1)] = \ - BT_MESH_ADDR_UNASSIGNED }, \ - .user_data = _user_data, \ + .id = (_id), \ + .op = _op, \ + .keys = { [0 ... (CONFIG_BT_MESH_MODEL_KEY_COUNT - 1)] = \ + BT_MESH_KEY_UNUSED }, \ + .pub = _pub, \ + .groups = { [0 ... (CONFIG_BT_MESH_MODEL_GROUP_COUNT - 1)] = \ + BT_MESH_ADDR_UNASSIGNED }, \ + .user_data = _user_data, \ } #define BT_MESH_MODEL_VND(_company, _id, _op, _pub, _user_data) \ { \ - .vnd.company = (_company), \ - .vnd.id = (_id), \ - .op = _op, \ - .pub = _pub, \ - .keys = { [0 ... (CONFIG_BT_MESH_MODEL_KEY_COUNT - 1)] = \ - BT_MESH_KEY_UNUSED }, \ - .groups = { [0 ... (CONFIG_BT_MESH_MODEL_GROUP_COUNT - 1)] = \ - BT_MESH_ADDR_UNASSIGNED }, \ - .user_data = _user_data, \ + .vnd.company = (_company), \ + .vnd.id = (_id), \ + .op = _op, \ + .pub = _pub, \ + .keys = { [0 ... (CONFIG_BT_MESH_MODEL_KEY_COUNT - 1)] = \ + BT_MESH_KEY_UNUSED }, \ + .groups = { [0 ... (CONFIG_BT_MESH_MODEL_GROUP_COUNT - 1)] = \ + BT_MESH_ADDR_UNASSIGNED }, \ + .user_data = _user_data, \ } /** @def BT_MESH_TRANSMIT @@ -261,7 +261,7 @@ struct bt_mesh_model_op { * values of the configuration model data. */ #define BT_MESH_PUB_TRANSMIT(count, int_ms) BT_MESH_TRANSMIT(count, \ - (int_ms) / 5) + (int_ms) / 5) /** @def BT_MESH_PUB_TRANSMIT_COUNT * @@ -289,49 +289,49 @@ struct bt_mesh_model_op { * BT_MESH_MODEL_PUB_DEFINE macro. */ struct bt_mesh_model_pub { - /** The model the context belongs to. Initialized by the stack. */ - struct bt_mesh_model *mod; + /** The model the context belongs to. Initialized by the stack. */ + struct bt_mesh_model *mod; - u16_t addr; /**< Publish Address. */ - u16_t key; /**< Publish AppKey Index. */ + u16_t addr; /**< Publish Address. */ + u16_t key; /**< Publish AppKey Index. */ - u8_t ttl; /**< Publish Time to Live. */ - u8_t retransmit; /**< Retransmit Count & Interval Steps. */ - u8_t period; /**< Publish Period. */ - u8_t period_div:4, /**< Divisor for the Period. */ - cred:1, /**< Friendship Credentials Flag. */ - fast_period:1,/**< Use FastPeriodDivisor */ - count:3; /**< Retransmissions left. */ + u8_t ttl; /**< Publish Time to Live. */ + u8_t retransmit; /**< Retransmit Count & Interval Steps. */ + u8_t period; /**< Publish Period. */ + u8_t period_div:4, /**< Divisor for the Period. */ + cred:1, /**< Friendship Credentials Flag. */ + fast_period:1,/**< Use FastPeriodDivisor */ + count:3; /**< Retransmissions left. */ - u32_t period_start; /**< Start of the current period. */ + u32_t period_start; /**< Start of the current period. */ - /** @brief Publication buffer, containing the publication message. - * - * This will get correctly created when the publication context - * has been defined using the BT_MESH_MODEL_PUB_DEFINE macro. - * - * BT_MESH_MODEL_PUB_DEFINE(name, update, size); - */ - struct net_buf_simple *msg; + /** @brief Publication buffer, containing the publication message. + * + * This will get correctly created when the publication context + * has been defined using the BT_MESH_MODEL_PUB_DEFINE macro. + * + * BT_MESH_MODEL_PUB_DEFINE(name, update, size); + */ + struct net_buf_simple *msg; - /** @brief Callback for updating the publication buffer. - * - * When set to NULL, the model is assumed not to support - * periodic publishing. When set to non-NULL the callback - * will be called periodically and is expected to update - * @ref bt_mesh_model_pub.msg with a valid publication - * message. - * - * @param mod The Model the Publication Context belogs to. - * - * @return Zero on success or (negative) error code otherwise. - */ - int (*update)(struct bt_mesh_model *mod); + /** @brief Callback for updating the publication buffer. + * + * When set to NULL, the model is assumed not to support + * periodic publishing. When set to non-NULL the callback + * will be called periodically and is expected to update + * @ref bt_mesh_model_pub.msg with a valid publication + * message. + * + * @param mod The Model the Publication Context belogs to. + * + * @return Zero on success or (negative) error code otherwise. + */ + int (*update)(struct bt_mesh_model *mod); - /** Publish Period Timer. Only for stack-internal use. */ - struct k_delayed_work timer; + /** Publish Period Timer. Only for stack-internal use. */ + struct k_delayed_work timer; - /** Role of the device that is going to publish messages */ + /** Role of the device that is going to publish messages */ uint8_t dev_role; }; @@ -344,46 +344,46 @@ struct bt_mesh_model_pub { * @param _msg_len Length of the publication message. */ #define BT_MESH_MODEL_PUB_DEFINE(_name, _update, _msg_len) \ - NET_BUF_SIMPLE_DEFINE_STATIC(bt_mesh_pub_msg_##_name, _msg_len); \ - static struct bt_mesh_model_pub _name = { \ - .update = _update, \ - .msg = &bt_mesh_pub_msg_##_name, \ - } + NET_BUF_SIMPLE_DEFINE_STATIC(bt_mesh_pub_msg_##_name, _msg_len); \ + static struct bt_mesh_model_pub _name = { \ + .update = _update, \ + .msg = &bt_mesh_pub_msg_##_name, \ + } /** Abstraction that describes a Mesh Model instance */ struct bt_mesh_model { - union { - const u16_t id; - struct { - u16_t company; - u16_t id; - } vnd; - }; + union { + const u16_t id; + struct { + u16_t company; + u16_t id; + } vnd; + }; - /* Internal information, mainly for persistent storage */ - u8_t elem_idx; /* Belongs to Nth element */ - u8_t mod_idx; /* Is the Nth model in the element */ - u16_t flags; /* Information about what has changed */ + /* Internal information, mainly for persistent storage */ + u8_t elem_idx; /* Belongs to Nth element */ + u8_t mod_idx; /* Is the Nth model in the element */ + u16_t flags; /* Information about what has changed */ - /* Model Publication */ - struct bt_mesh_model_pub * const pub; + /* Model Publication */ + struct bt_mesh_model_pub * const pub; - /* AppKey List */ - u16_t keys[CONFIG_BT_MESH_MODEL_KEY_COUNT]; + /* AppKey List */ + u16_t keys[CONFIG_BT_MESH_MODEL_KEY_COUNT]; - /* Subscription List (group or virtual addresses) */ - u16_t groups[CONFIG_BT_MESH_MODEL_GROUP_COUNT]; + /* Subscription List (group or virtual addresses) */ + u16_t groups[CONFIG_BT_MESH_MODEL_GROUP_COUNT]; - //const struct bt_mesh_model_op * const op; - const struct bt_mesh_model_op *op; + //const struct bt_mesh_model_op * const op; + const struct bt_mesh_model_op *op; - /* Model-specific user data */ - void *user_data; + /* Model-specific user data */ + void *user_data; }; struct bt_mesh_send_cb { - void (*start)(u16_t duration, int err, void *cb_data); - void (*end)(int err, void *cb_data); + void (*start)(u16_t duration, int err, void *cb_data); + void (*end)(int err, void *cb_data); }; void bt_mesh_model_msg_init(struct net_buf_simple *msg, u32_t opcode); @@ -406,10 +406,10 @@ void bt_mesh_model_msg_init(struct net_buf_simple *msg, u32_t opcode); * @return 0 on success, or (negative) error code on failure. */ int bt_mesh_model_send(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *msg, - const struct bt_mesh_send_cb *cb, - void *cb_data); + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *msg, + const struct bt_mesh_send_cb *cb, + void *cb_data); /** * @brief Send a model publication message. @@ -438,12 +438,12 @@ struct bt_mesh_elem *bt_mesh_model_elem(struct bt_mesh_model *mod); /** Node Composition */ struct bt_mesh_comp { - u16_t cid; - u16_t pid; - u16_t vid; + u16_t cid; + u16_t pid; + u16_t vid; - size_t elem_count; - struct bt_mesh_elem *elem; + size_t elem_count; + struct bt_mesh_elem *elem; }; #ifdef __cplusplus diff --git a/components/network/ble/blemesh/src/include/cfg_cli.h b/components/network/ble/blemesh/src/include/cfg_cli.h index 3c673704..a3aa9c58 100644 --- a/components/network/ble/blemesh/src/include/cfg_cli.h +++ b/components/network/ble/blemesh/src/include/cfg_cli.h @@ -25,21 +25,21 @@ extern "C" { /** Mesh Configuration Client Model Context */ struct bt_mesh_cfg_cli { - struct bt_mesh_model *model; + struct bt_mesh_model *model; - struct k_sem op_sync; - u32_t op_pending; - void *op_param; + struct k_sem op_sync; + u32_t op_pending; + void *op_param; }; extern const struct bt_mesh_model_op bt_mesh_cfg_cli_op[]; #define BT_MESH_MODEL_CFG_CLI(cli_data) \ - BT_MESH_MODEL(BT_MESH_MODEL_ID_CFG_CLI, \ - bt_mesh_cfg_cli_op, NULL, cli_data) + BT_MESH_MODEL(BT_MESH_MODEL_ID_CFG_CLI, \ + bt_mesh_cfg_cli_op, NULL, cli_data) int bt_mesh_cfg_comp_data_get(u16_t net_idx, u16_t addr, u8_t page, - u8_t *status, struct net_buf_simple *comp); + u8_t *status, struct net_buf_simple *comp); int bt_mesh_cfg_beacon_get(u16_t net_idx, u16_t addr, u8_t *status); @@ -56,27 +56,27 @@ int bt_mesh_cfg_friend_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status); int bt_mesh_cfg_gatt_proxy_get(u16_t net_idx, u16_t addr, u8_t *status); int bt_mesh_cfg_gatt_proxy_set(u16_t net_idx, u16_t addr, u8_t val, - u8_t *status); + u8_t *status); int bt_mesh_cfg_relay_get(u16_t net_idx, u16_t addr, u8_t *status, - u8_t *transmit); + u8_t *transmit); int bt_mesh_cfg_relay_set(u16_t net_idx, u16_t addr, u8_t new_relay, - u8_t new_transmit, u8_t *status, u8_t *transmit); + u8_t new_transmit, u8_t *status, u8_t *transmit); int bt_mesh_cfg_net_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, - const u8_t net_key[16], u8_t *status); + const u8_t net_key[16], u8_t *status); int bt_mesh_cfg_app_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, - u16_t key_app_idx, const u8_t app_key[16], - u8_t *status); + u16_t key_app_idx, const u8_t app_key[16], + u8_t *status); int bt_mesh_cfg_mod_app_bind(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_app_idx, u16_t mod_id, u8_t *status); + u16_t mod_app_idx, u16_t mod_id, u8_t *status); int bt_mesh_cfg_mod_app_bind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_app_idx, u16_t mod_id, u16_t cid, - u8_t *status); + u16_t mod_app_idx, u16_t mod_id, u16_t cid, + u8_t *status); /** @def BT_MESH_PUB_PERIOD_100MS * @@ -121,106 +121,106 @@ int bt_mesh_cfg_mod_app_bind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, #define BT_MESH_PUB_PERIOD_10MIN(steps) (((steps) & BIT_MASK(6)) | (3 << 6)) struct bt_mesh_cfg_mod_pub { - u16_t addr; - u16_t app_idx; - bool cred_flag; - u8_t ttl; - u8_t period; - u8_t transmit; + u16_t addr; + u16_t app_idx; + bool cred_flag; + u8_t ttl; + u8_t period; + u8_t transmit; }; int bt_mesh_cfg_mod_pub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, - u8_t *status); + u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, + u8_t *status); int bt_mesh_cfg_mod_pub_get_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, u16_t cid, - struct bt_mesh_cfg_mod_pub *pub, u8_t *status); + u16_t mod_id, u16_t cid, + struct bt_mesh_cfg_mod_pub *pub, u8_t *status); int bt_mesh_cfg_mod_pub_set(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, - u8_t *status); + u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub, + u8_t *status); int bt_mesh_cfg_mod_pub_set_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t mod_id, u16_t cid, - struct bt_mesh_cfg_mod_pub *pub, u8_t *status); + u16_t mod_id, u16_t cid, + struct bt_mesh_cfg_mod_pub *pub, u8_t *status); int bt_mesh_cfg_mod_sub_add(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u8_t *status); + u16_t sub_addr, u16_t mod_id, u8_t *status); int bt_mesh_cfg_mod_sub_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u16_t cid, - u8_t *status); + u16_t sub_addr, u16_t mod_id, u16_t cid, + u8_t *status); int bt_mesh_cfg_mod_sub_del(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u8_t *status); + u16_t sub_addr, u16_t mod_id, u8_t *status); int bt_mesh_cfg_mod_sub_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u16_t cid, - u8_t *status); + u16_t sub_addr, u16_t mod_id, u16_t cid, + u8_t *status); int bt_mesh_cfg_mod_sub_overwrite(u16_t net_idx, u16_t addr, u16_t elem_addr, - u16_t sub_addr, u16_t mod_id, u8_t *status); + u16_t sub_addr, u16_t mod_id, u8_t *status); int bt_mesh_cfg_mod_sub_overwrite_vnd(u16_t net_idx, u16_t addr, - u16_t elem_addr, u16_t sub_addr, - u16_t mod_id, u16_t cid, u8_t *status); + u16_t elem_addr, u16_t sub_addr, + u16_t mod_id, u16_t cid, u8_t *status); int bt_mesh_cfg_mod_sub_va_add(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t *virt_addr, u8_t *status); + const u8_t label[16], u16_t mod_id, + u16_t *virt_addr, u8_t *status); int bt_mesh_cfg_mod_sub_va_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t cid, u16_t *virt_addr, u8_t *status); + const u8_t label[16], u16_t mod_id, + u16_t cid, u16_t *virt_addr, u8_t *status); int bt_mesh_cfg_mod_sub_va_del(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t *virt_addr, u8_t *status); + const u8_t label[16], u16_t mod_id, + u16_t *virt_addr, u8_t *status); int bt_mesh_cfg_mod_sub_va_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, - const u8_t label[16], u16_t mod_id, - u16_t cid, u16_t *virt_addr, u8_t *status); + const u8_t label[16], u16_t mod_id, + u16_t cid, u16_t *virt_addr, u8_t *status); int bt_mesh_cfg_mod_sub_va_overwrite(u16_t net_idx, u16_t addr, - u16_t elem_addr, const u8_t label[16], - u16_t mod_id, u16_t *virt_addr, - u8_t *status); + u16_t elem_addr, const u8_t label[16], + u16_t mod_id, u16_t *virt_addr, + u8_t *status); int bt_mesh_cfg_mod_sub_va_overwrite_vnd(u16_t net_idx, u16_t addr, - u16_t elem_addr, const u8_t label[16], - u16_t mod_id, u16_t cid, - u16_t *virt_addr, u8_t *status); + u16_t elem_addr, const u8_t label[16], + u16_t mod_id, u16_t cid, + u16_t *virt_addr, u8_t *status); struct bt_mesh_cfg_hb_sub { - u16_t src; - u16_t dst; - u8_t period; - u8_t count; - u8_t min; - u8_t max; + u16_t src; + u16_t dst; + u8_t period; + u8_t count; + u8_t min; + u8_t max; }; int bt_mesh_cfg_hb_sub_set(u16_t net_idx, u16_t addr, - struct bt_mesh_cfg_hb_sub *sub, u8_t *status); + struct bt_mesh_cfg_hb_sub *sub, u8_t *status); int bt_mesh_cfg_hb_sub_get(u16_t net_idx, u16_t addr, - struct bt_mesh_cfg_hb_sub *sub, u8_t *status); + struct bt_mesh_cfg_hb_sub *sub, u8_t *status); struct bt_mesh_cfg_hb_pub { - u16_t dst; - u8_t count; - u8_t period; - u8_t ttl; - u16_t feat; - u16_t net_idx; + u16_t dst; + u8_t count; + u8_t period; + u8_t ttl; + u16_t feat; + u16_t net_idx; }; int bt_mesh_cfg_hb_pub_set(u16_t net_idx, u16_t addr, - const struct bt_mesh_cfg_hb_pub *pub, u8_t *status); + const struct bt_mesh_cfg_hb_pub *pub, u8_t *status); int bt_mesh_cfg_hb_pub_get(u16_t net_idx, u16_t addr, - struct bt_mesh_cfg_hb_pub *pub, u8_t *status); + struct bt_mesh_cfg_hb_pub *pub, u8_t *status); s32_t bt_mesh_cfg_cli_timeout_get(void); void bt_mesh_cfg_cli_timeout_set(s32_t timeout); diff --git a/components/network/ble/blemesh/src/include/cfg_srv.h b/components/network/ble/blemesh/src/include/cfg_srv.h index 630ce91a..d50c864a 100644 --- a/components/network/ble/blemesh/src/include/cfg_srv.h +++ b/components/network/ble/blemesh/src/include/cfg_srv.h @@ -25,48 +25,48 @@ extern "C" { /** Mesh Configuration Server Model Context */ struct bt_mesh_cfg_srv { - struct bt_mesh_model *model; + struct bt_mesh_model *model; - u8_t net_transmit; /* Network Transmit state */ - u8_t relay; /* Relay Mode state */ - u8_t relay_retransmit; /* Relay Retransmit state */ - u8_t beacon; /* Secure Network Beacon state */ - u8_t gatt_proxy; /* GATT Proxy state */ - u8_t frnd; /* Friend state */ - u8_t default_ttl; /* Default TTL */ + u8_t net_transmit; /* Network Transmit state */ + u8_t relay; /* Relay Mode state */ + u8_t relay_retransmit; /* Relay Retransmit state */ + u8_t beacon; /* Secure Network Beacon state */ + u8_t gatt_proxy; /* GATT Proxy state */ + u8_t frnd; /* Friend state */ + u8_t default_ttl; /* Default TTL */ - /* Heartbeat Publication */ - struct bt_mesh_hb_pub { - struct k_delayed_work timer; + /* Heartbeat Publication */ + struct bt_mesh_hb_pub { + struct k_delayed_work timer; - u16_t dst; - u16_t count; - u8_t period; - u8_t ttl; - u16_t feat; - u16_t net_idx; - } hb_pub; + u16_t dst; + u16_t count; + u8_t period; + u8_t ttl; + u16_t feat; + u16_t net_idx; + } hb_pub; - /* Heartbeat Subscription */ - struct bt_mesh_hb_sub { - s64_t expiry; + /* Heartbeat Subscription */ + struct bt_mesh_hb_sub { + s64_t expiry; - u16_t src; - u16_t dst; - u16_t count; - u8_t min_hops; - u8_t max_hops; + u16_t src; + u16_t dst; + u16_t count; + u8_t min_hops; + u8_t max_hops; - /* Optional subscription tracking function, Add src and dst addr*/ - void (*func)(u16_t src, u16_t dst, u8_t hops, u16_t feat); - } hb_sub; + /* Optional subscription tracking function, Add src and dst addr*/ + void (*func)(u16_t src, u16_t dst, u8_t hops, u16_t feat); + } hb_sub; }; extern const struct bt_mesh_model_op bt_mesh_cfg_srv_op[]; #define BT_MESH_MODEL_CFG_SRV(srv_data) \ - BT_MESH_MODEL(BT_MESH_MODEL_ID_CFG_SRV, \ - bt_mesh_cfg_srv_op, NULL, srv_data) + BT_MESH_MODEL(BT_MESH_MODEL_ID_CFG_SRV, \ + bt_mesh_cfg_srv_op, NULL, srv_data) #ifdef __cplusplus } diff --git a/components/network/ble/blemesh/src/include/health_cli.h b/components/network/ble/blemesh/src/include/health_cli.h index dd24175a..4670908b 100644 --- a/components/network/ble/blemesh/src/include/health_cli.h +++ b/components/network/ble/blemesh/src/include/health_cli.h @@ -25,48 +25,48 @@ extern "C" { /** Mesh Health Client Model Context */ struct bt_mesh_health_cli { - struct bt_mesh_model *model; + struct bt_mesh_model *model; - void (*current_status)(struct bt_mesh_health_cli *cli, u16_t addr, - u8_t test_id, u16_t cid, u8_t *faults, - size_t fault_count); + void (*current_status)(struct bt_mesh_health_cli *cli, u16_t addr, + u8_t test_id, u16_t cid, u8_t *faults, + size_t fault_count); - struct k_sem op_sync; - u32_t op_pending; - void *op_param; + struct k_sem op_sync; + u32_t op_pending; + void *op_param; }; extern const struct bt_mesh_model_op bt_mesh_health_cli_op[]; #define BT_MESH_MODEL_HEALTH_CLI(cli_data) \ - BT_MESH_MODEL(BT_MESH_MODEL_ID_HEALTH_CLI, \ - bt_mesh_health_cli_op, NULL, cli_data) + BT_MESH_MODEL(BT_MESH_MODEL_ID_HEALTH_CLI, \ + bt_mesh_health_cli_op, NULL, cli_data) int bt_mesh_health_cli_set(struct bt_mesh_model *model); int bt_mesh_health_fault_get(u16_t net_idx, u16_t addr, u16_t app_idx, - u16_t cid, u8_t *test_id, u8_t *faults, - size_t *fault_count); + u16_t cid, u8_t *test_id, u8_t *faults, + size_t *fault_count); int bt_mesh_health_fault_clear(u16_t net_idx, u16_t addr, u16_t app_idx, - u16_t cid, u8_t *test_id, u8_t *faults, - size_t *fault_count); + u16_t cid, u8_t *test_id, u8_t *faults, + size_t *fault_count); int bt_mesh_health_fault_test(u16_t net_idx, u16_t addr, u16_t app_idx, - u16_t cid, u8_t test_id, u8_t *faults, - size_t *fault_count); + u16_t cid, u8_t test_id, u8_t *faults, + size_t *fault_count); int bt_mesh_health_period_get(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t *divisor); + u8_t *divisor); int bt_mesh_health_period_set(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t divisor, u8_t *updated_divisor); + u8_t divisor, u8_t *updated_divisor); int bt_mesh_health_attention_get(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t *attention); + u8_t *attention); int bt_mesh_health_attention_set(u16_t net_idx, u16_t addr, u16_t app_idx, - u8_t attention, u8_t *updated_attention); + u8_t attention, u8_t *updated_attention); s32_t bt_mesh_health_cli_timeout_get(void); void bt_mesh_health_cli_timeout_set(s32_t timeout); diff --git a/components/network/ble/blemesh/src/include/health_srv.h b/components/network/ble/blemesh/src/include/health_srv.h index 1292c592..5cf9140c 100644 --- a/components/network/ble/blemesh/src/include/health_srv.h +++ b/components/network/ble/blemesh/src/include/health_srv.h @@ -24,28 +24,28 @@ extern "C" { #include "access.h" struct bt_mesh_health_srv_cb { - /* Fetch current faults */ - int (*fault_get_cur)(struct bt_mesh_model *model, u8_t *test_id, - u16_t *company_id, u8_t *faults, - u8_t *fault_count); + /* Fetch current faults */ + int (*fault_get_cur)(struct bt_mesh_model *model, u8_t *test_id, + u16_t *company_id, u8_t *faults, + u8_t *fault_count); - /* Fetch registered faults */ - int (*fault_get_reg)(struct bt_mesh_model *model, u16_t company_id, - u8_t *test_id, u8_t *faults, - u8_t *fault_count); + /* Fetch registered faults */ + int (*fault_get_reg)(struct bt_mesh_model *model, u16_t company_id, + u8_t *test_id, u8_t *faults, + u8_t *fault_count); - /* Clear registered faults */ - int (*fault_clear)(struct bt_mesh_model *model, u16_t company_id); + /* Clear registered faults */ + int (*fault_clear)(struct bt_mesh_model *model, u16_t company_id); - /* Run a specific test */ - int (*fault_test)(struct bt_mesh_model *model, u8_t test_id, - u16_t company_id); + /* Run a specific test */ + int (*fault_test)(struct bt_mesh_model *model, u8_t test_id, + u16_t company_id); - /* Attention on */ - void (*attn_on)(struct bt_mesh_model *model); + /* Attention on */ + void (*attn_on)(struct bt_mesh_model *model); - /* Attention off */ - void (*attn_off)(struct bt_mesh_model *model); + /* Attention off */ + void (*attn_off)(struct bt_mesh_model *model); }; /** @def BT_MESH_HEALTH_PUB_DEFINE @@ -56,17 +56,17 @@ struct bt_mesh_health_srv_cb { * @param _max_faults Maximum number of faults the element can have. */ #define BT_MESH_HEALTH_PUB_DEFINE(_name, _max_faults) \ - BT_MESH_MODEL_PUB_DEFINE(_name, NULL, (1 + 3 + (_max_faults))) + BT_MESH_MODEL_PUB_DEFINE(_name, NULL, (1 + 3 + (_max_faults))) /** Mesh Health Server Model Context */ struct bt_mesh_health_srv { - struct bt_mesh_model *model; + struct bt_mesh_model *model; - /* Optional callback struct */ - const struct bt_mesh_health_srv_cb *cb; + /* Optional callback struct */ + const struct bt_mesh_health_srv_cb *cb; - /* Attention Timer state */ - struct k_delayed_work attn_timer; + /* Attention Timer state */ + struct k_delayed_work attn_timer; }; int bt_mesh_fault_update(struct bt_mesh_elem *elem); @@ -86,8 +86,8 @@ extern const struct bt_mesh_model_op bt_mesh_health_srv_op[]; * @return New mesh model instance. */ #define BT_MESH_MODEL_HEALTH_SRV(srv, pub) \ - BT_MESH_MODEL(BT_MESH_MODEL_ID_HEALTH_SRV, \ - bt_mesh_health_srv_op, pub, srv) + BT_MESH_MODEL(BT_MESH_MODEL_ID_HEALTH_SRV, \ + bt_mesh_health_srv_op, pub, srv) #ifdef __cplusplus } diff --git a/components/network/ble/blemesh/src/include/main.h b/components/network/ble/blemesh/src/include/main.h index 9617b77e..9f8aebfe 100644 --- a/components/network/ble/blemesh/src/include/main.h +++ b/components/network/ble/blemesh/src/include/main.h @@ -25,158 +25,158 @@ extern "C" { typedef enum { - BT_MESH_NO_OUTPUT = 0, - BT_MESH_BLINK = BIT(0), - BT_MESH_BEEP = BIT(1), - BT_MESH_VIBRATE = BIT(2), - BT_MESH_DISPLAY_NUMBER = BIT(3), - BT_MESH_DISPLAY_STRING = BIT(4), + BT_MESH_NO_OUTPUT = 0, + BT_MESH_BLINK = BIT(0), + BT_MESH_BEEP = BIT(1), + BT_MESH_VIBRATE = BIT(2), + BT_MESH_DISPLAY_NUMBER = BIT(3), + BT_MESH_DISPLAY_STRING = BIT(4), } bt_mesh_output_action_t; typedef enum { - BT_MESH_NO_INPUT = 0, - BT_MESH_PUSH = BIT(0), - BT_MESH_TWIST = BIT(1), - BT_MESH_ENTER_NUMBER = BIT(2), - BT_MESH_ENTER_STRING = BIT(3), + BT_MESH_NO_INPUT = 0, + BT_MESH_PUSH = BIT(0), + BT_MESH_TWIST = BIT(1), + BT_MESH_ENTER_NUMBER = BIT(2), + BT_MESH_ENTER_STRING = BIT(3), } bt_mesh_input_action_t; typedef enum { - BT_MESH_PROV_ADV = BIT(0), - BT_MESH_PROV_GATT = BIT(1), + BT_MESH_PROV_ADV = BIT(0), + BT_MESH_PROV_GATT = BIT(1), } bt_mesh_prov_bearer_t; typedef enum { - BT_MESH_PROV_OOB_OTHER = BIT(0), - BT_MESH_PROV_OOB_URI = BIT(1), - BT_MESH_PROV_OOB_2D_CODE = BIT(2), - BT_MESH_PROV_OOB_BAR_CODE = BIT(3), - BT_MESH_PROV_OOB_NFC = BIT(4), - BT_MESH_PROV_OOB_NUMBER = BIT(5), - BT_MESH_PROV_OOB_STRING = BIT(6), - /* 7 - 10 are reserved */ - BT_MESH_PROV_OOB_ON_BOX = BIT(11), - BT_MESH_PROV_OOB_IN_BOX = BIT(12), - BT_MESH_PROV_OOB_ON_PAPER = BIT(13), - BT_MESH_PROV_OOB_IN_MANUAL = BIT(14), - BT_MESH_PROV_OOB_ON_DEV = BIT(15), + BT_MESH_PROV_OOB_OTHER = BIT(0), + BT_MESH_PROV_OOB_URI = BIT(1), + BT_MESH_PROV_OOB_2D_CODE = BIT(2), + BT_MESH_PROV_OOB_BAR_CODE = BIT(3), + BT_MESH_PROV_OOB_NFC = BIT(4), + BT_MESH_PROV_OOB_NUMBER = BIT(5), + BT_MESH_PROV_OOB_STRING = BIT(6), + /* 7 - 10 are reserved */ + BT_MESH_PROV_OOB_ON_BOX = BIT(11), + BT_MESH_PROV_OOB_IN_BOX = BIT(12), + BT_MESH_PROV_OOB_ON_PAPER = BIT(13), + BT_MESH_PROV_OOB_IN_MANUAL = BIT(14), + BT_MESH_PROV_OOB_ON_DEV = BIT(15), } bt_mesh_prov_oob_info_t; /** Provisioning properties & capabilities. */ struct bt_mesh_prov { - /** The UUID that's used when advertising as unprovisioned */ - const u8_t *uuid; + /** The UUID that's used when advertising as unprovisioned */ + const u8_t *uuid; - /** Optional URI. This will be advertised separately from the - * unprovisioned beacon, however the unprovisioned beacon will - * contain a hash of it so the two can be associated by the - * provisioner. - */ - const char *uri; + /** Optional URI. This will be advertised separately from the + * unprovisioned beacon, however the unprovisioned beacon will + * contain a hash of it so the two can be associated by the + * provisioner. + */ + const char *uri; - /** Out of Band information field. */ - bt_mesh_prov_oob_info_t oob_info; + /** Out of Band information field. */ + bt_mesh_prov_oob_info_t oob_info; - /** Static OOB value */ - const u8_t *static_val; - /** Static OOB value length */ - u8_t static_val_len; + /** Static OOB value */ + const u8_t *static_val; + /** Static OOB value length */ + u8_t static_val_len; - /** Maximum size of Output OOB supported */ - u8_t output_size; - /** Supported Output OOB Actions */ - u16_t output_actions; + /** Maximum size of Output OOB supported */ + u8_t output_size; + /** Supported Output OOB Actions */ + u16_t output_actions; - /* Maximum size of Input OOB supported */ - u8_t input_size; - /** Supported Input OOB Actions */ - u16_t input_actions; + /* Maximum size of Input OOB supported */ + u8_t input_size; + /** Supported Input OOB Actions */ + u16_t input_actions; - /** @brief Output of a number is requested. - * - * This callback notifies the application that it should - * output the given number using the given action. - * - * @param act Action for outputting the number. - * @param num Number to be outputted. - * - * @return Zero on success or negative error code otherwise - */ - int (*output_number)(bt_mesh_output_action_t act, u32_t num); + /** @brief Output of a number is requested. + * + * This callback notifies the application that it should + * output the given number using the given action. + * + * @param act Action for outputting the number. + * @param num Number to be outputted. + * + * @return Zero on success or negative error code otherwise + */ + int (*output_number)(bt_mesh_output_action_t act, u32_t num); - /** @brief Output of a string is requested. - * - * This callback notifies the application that it should - * display the given string to the user. - * - * @param str String to be displayed. - * - * @return Zero on success or negative error code otherwise - */ - int (*output_string)(const char *str); + /** @brief Output of a string is requested. + * + * This callback notifies the application that it should + * display the given string to the user. + * + * @param str String to be displayed. + * + * @return Zero on success or negative error code otherwise + */ + int (*output_string)(const char *str); - /** @brief Input is requested. - * - * This callback notifies the application that it should - * request input from the user using the given action. The - * requested input will either be a string or a number, and - * the application needs to consequently call the - * bt_mesh_input_string() or bt_mesh_input_number() functions - * once the data has been acquired from the user. - * - * @param act Action for inputting data. - * @param num Maximum size of the inputted data. - * - * @return Zero on success or negative error code otherwise - */ - int (*input)(bt_mesh_input_action_t act, u8_t size); + /** @brief Input is requested. + * + * This callback notifies the application that it should + * request input from the user using the given action. The + * requested input will either be a string or a number, and + * the application needs to consequently call the + * bt_mesh_input_string() or bt_mesh_input_number() functions + * once the data has been acquired from the user. + * + * @param act Action for inputting data. + * @param num Maximum size of the inputted data. + * + * @return Zero on success or negative error code otherwise + */ + int (*input)(bt_mesh_input_action_t act, u8_t size); /** @brief The other device finished their OOB input. - * - * This callback notifies the application that it should stop - * displaying its output OOB value, as the other party finished their - * OOB input. - */ - void (*input_complete)(void); + * + * This callback notifies the application that it should stop + * displaying its output OOB value, as the other party finished their + * OOB input. + */ + void (*input_complete)(void); /** @brief Provisioning link has been opened. - * - * This callback notifies the application that a provisioning - * link has been opened on the given provisioning bearer. - * - * @param bearer Provisioning bearer. - */ - void (*link_open)(bt_mesh_prov_bearer_t bearer); + * + * This callback notifies the application that a provisioning + * link has been opened on the given provisioning bearer. + * + * @param bearer Provisioning bearer. + */ + void (*link_open)(bt_mesh_prov_bearer_t bearer); - /** @brief Provisioning link has been closed. - * - * This callback notifies the application that a provisioning - * link has been closed on the given provisioning bearer. - * - * @param bearer Provisioning bearer. - */ - void (*link_close)(bt_mesh_prov_bearer_t bearer); + /** @brief Provisioning link has been closed. + * + * This callback notifies the application that a provisioning + * link has been closed on the given provisioning bearer. + * + * @param bearer Provisioning bearer. + */ + void (*link_close)(bt_mesh_prov_bearer_t bearer); - /** @brief Provisioning is complete. - * - * This callback notifies the application that provisioning has - * been successfully completed, and that the local node has been - * assigned the specified NetKeyIndex and primary element address. - * - * @param net_idx NetKeyIndex given during provisioning. - * @param addr Primary element address. - */ - void (*complete)(u16_t net_idx, u16_t addr); + /** @brief Provisioning is complete. + * + * This callback notifies the application that provisioning has + * been successfully completed, and that the local node has been + * assigned the specified NetKeyIndex and primary element address. + * + * @param net_idx NetKeyIndex given during provisioning. + * @param addr Primary element address. + */ + void (*complete)(u16_t net_idx, u16_t addr); - /** @brief Node has been reset. - * - * This callback notifies the application that the local node - * has been reset and needs to be reprovisioned. The node will - * not automatically advertise as unprovisioned, rather the - * bt_mesh_prov_enable() API needs to be called to enable - * unprovisioned advertising on one or more provisioning bearers. - */ - void (*reset)(void); + /** @brief Node has been reset. + * + * This callback notifies the application that the local node + * has been reset and needs to be reprovisioned. The node will + * not automatically advertise as unprovisioned, rather the + * bt_mesh_prov_enable() API needs to be called to enable + * unprovisioned advertising on one or more provisioning bearers. + */ + void (*reset)(void); }; enum ble_mesh_role { @@ -267,9 +267,9 @@ int bt_mesh_prov_disable(bt_mesh_prov_bearer_t bearers); #define BT_MESH_FEAT_FRIEND BIT(2) #define BT_MESH_FEAT_LOW_POWER BIT(3) #define BT_MESH_FEAT_SUPPORTED (BT_MESH_FEAT_RELAY | \ - BT_MESH_FEAT_PROXY | \ - BT_MESH_FEAT_FRIEND | \ - BT_MESH_FEAT_LOW_POWER) + BT_MESH_FEAT_PROXY | \ + BT_MESH_FEAT_FRIEND | \ + BT_MESH_FEAT_LOW_POWER) /** @brief Initialize Mesh support * @@ -283,7 +283,7 @@ int bt_mesh_prov_disable(bt_mesh_prov_bearer_t bearers); * @return Zero on success or (negative) error code otherwise. */ int bt_mesh_init(const struct bt_mesh_prov *prov, - const struct bt_mesh_comp *comp); + const struct bt_mesh_comp *comp); /** @brief Reset the state of the local Mesh node. * @@ -334,8 +334,8 @@ int bt_mesh_resume(void); * @return Zero on success or (negative) error code otherwise. */ int bt_mesh_provision(const u8_t net_key[16], u16_t net_idx, - u8_t flags, u32_t iv_index, u16_t addr, - const u8_t dev_key[16]); + u8_t flags, u32_t iv_index, u16_t addr, + const u8_t dev_key[16]); /** @brief Check if the local node has been provisioned. * diff --git a/components/network/ble/blemesh/src/local_operation.c b/components/network/ble/blemesh/src/local_operation.c index e1b0b4a5..607ea72d 100644 --- a/components/network/ble/blemesh/src/local_operation.c +++ b/components/network/ble/blemesh/src/local_operation.c @@ -16,11 +16,11 @@ int bt_mesh_model_subscribe_group_addr(u16_t elem_addr, u16_t cid, u16_t mod_id, u16_t group_addr) { - return -ENOMEM; + return -ENOMEM; } int bt_mesh_model_unsubscribe_group_addr(u16_t elem_addr, u16_t cid, u16_t mod_id, u16_t group_addr) { - return -ENODEV; + return -ENODEV; } diff --git a/components/network/ble/blemesh/src/lpn.c b/components/network/ble/blemesh/src/lpn.c index 13782a49..7a1f4e67 100644 --- a/components/network/ble/blemesh/src/lpn.c +++ b/components/network/ble/blemesh/src/lpn.c @@ -37,7 +37,7 @@ #define LPN_RECV_DELAY CONFIG_BT_MESH_LPN_RECV_DELAY #define SCAN_LATENCY MIN(CONFIG_BT_MESH_LPN_SCAN_LATENCY, \ - LPN_RECV_DELAY) + LPN_RECV_DELAY) #define FRIEND_REQ_RETRY_TIMEOUT K_SECONDS(CONFIG_BT_MESH_LPN_RETRY_TIMEOUT) @@ -48,19 +48,19 @@ #define POLL_RETRY_TIMEOUT K_MSEC(100) #define REQ_RETRY_DURATION(lpn) (4 * (LPN_RECV_DELAY + (lpn)->adv_duration + \ - (lpn)->recv_win + POLL_RETRY_TIMEOUT)) + (lpn)->recv_win + POLL_RETRY_TIMEOUT)) #define POLL_TIMEOUT_INIT (CONFIG_BT_MESH_LPN_INIT_POLL_TIMEOUT * 100) #define POLL_TIMEOUT_MAX(lpn) ((CONFIG_BT_MESH_LPN_POLL_TIMEOUT * 100) - \ - REQ_RETRY_DURATION(lpn)) + REQ_RETRY_DURATION(lpn)) #define REQ_ATTEMPTS(lpn) (POLL_TIMEOUT_MAX(lpn) < K_SECONDS(3) ? 2 : 4) #define CLEAR_ATTEMPTS 2 #define LPN_CRITERIA ((CONFIG_BT_MESH_LPN_MIN_QUEUE_SIZE) | \ - (CONFIG_BT_MESH_LPN_RSSI_FACTOR << 3) | \ - (CONFIG_BT_MESH_LPN_RECV_WIN_FACTOR << 5)) + (CONFIG_BT_MESH_LPN_RSSI_FACTOR << 3) | \ + (CONFIG_BT_MESH_LPN_RECV_WIN_FACTOR << 5)) #define POLL_TO(to) { (u8_t)((to) >> 16), (u8_t)((to) >> 8), (u8_t)(to) } #define LPN_POLL_TO POLL_TO(CONFIG_BT_MESH_LPN_POLL_TIMEOUT) @@ -73,75 +73,75 @@ static void (*lpn_cb)(u16_t friend_addr, bool established); #if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER) static const char *state2str(int state) { - switch (state) { - case BT_MESH_LPN_DISABLED: - return "disabled"; - case BT_MESH_LPN_CLEAR: - return "clear"; - case BT_MESH_LPN_TIMER: - return "timer"; - case BT_MESH_LPN_ENABLED: - return "enabled"; - case BT_MESH_LPN_REQ_WAIT: - return "req wait"; - case BT_MESH_LPN_WAIT_OFFER: - return "wait offer"; - case BT_MESH_LPN_ESTABLISHED: - return "established"; - case BT_MESH_LPN_RECV_DELAY: - return "recv delay"; - case BT_MESH_LPN_WAIT_UPDATE: - return "wait update"; - default: - return "(unknown)"; - } + switch (state) { + case BT_MESH_LPN_DISABLED: + return "disabled"; + case BT_MESH_LPN_CLEAR: + return "clear"; + case BT_MESH_LPN_TIMER: + return "timer"; + case BT_MESH_LPN_ENABLED: + return "enabled"; + case BT_MESH_LPN_REQ_WAIT: + return "req wait"; + case BT_MESH_LPN_WAIT_OFFER: + return "wait offer"; + case BT_MESH_LPN_ESTABLISHED: + return "established"; + case BT_MESH_LPN_RECV_DELAY: + return "recv delay"; + case BT_MESH_LPN_WAIT_UPDATE: + return "wait update"; + default: + return "(unknown)"; + } } #endif /* CONFIG_BT_MESH_DEBUG_LOW_POWER */ static inline void lpn_set_state(int state) { #if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER) - BT_DBG("%s -> %s", state2str(bt_mesh.lpn.state), state2str(state)); + BT_DBG("%s -> %s", state2str(bt_mesh.lpn.state), state2str(state)); #endif - bt_mesh.lpn.state = state; + bt_mesh.lpn.state = state; } static inline void group_zero(atomic_t *target) { #if CONFIG_BT_MESH_LPN_GROUPS > 32 - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { - atomic_set(&target[i], 0); - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { + atomic_set(&target[i], 0); + } #else - atomic_set(target, 0); + atomic_set(target, 0); #endif } static inline void group_set(atomic_t *target, atomic_t *source) { #if CONFIG_BT_MESH_LPN_GROUPS > 32 - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { - (void)atomic_or(&target[i], atomic_get(&source[i])); - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { + (void)atomic_or(&target[i], atomic_get(&source[i])); + } #else - (void)atomic_or(target, atomic_get(source)); + (void)atomic_or(target, atomic_get(source)); #endif } static inline void group_clear(atomic_t *target, atomic_t *source) { #if CONFIG_BT_MESH_LPN_GROUPS > 32 - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { - (void)atomic_and(&target[i], ~atomic_get(&source[i])); - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { + (void)atomic_and(&target[i], ~atomic_get(&source[i])); + } #else - (void)atomic_and(target, ~atomic_get(source)); + (void)atomic_and(target, ~atomic_get(source)); #endif } @@ -149,913 +149,913 @@ static void clear_friendship(bool force, bool disable); static void friend_clear_sent(int err, void *user_data) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - /* We're switching away from Low Power behavior, so permanently - * enable scanning. - */ - bt_mesh_scan_enable(); + /* We're switching away from Low Power behavior, so permanently + * enable scanning. + */ + bt_mesh_scan_enable(); - lpn->req_attempts++; + lpn->req_attempts++; - if (err) { - BT_ERR("Sending Friend Request failed (err %d)", err); - lpn_set_state(BT_MESH_LPN_ENABLED); - clear_friendship(false, lpn->disable); - return; - } + if (err) { + BT_ERR("Sending Friend Request failed (err %d)", err); + lpn_set_state(BT_MESH_LPN_ENABLED); + clear_friendship(false, lpn->disable); + return; + } - lpn_set_state(BT_MESH_LPN_CLEAR); - k_delayed_work_submit(&lpn->timer, FRIEND_REQ_TIMEOUT); + lpn_set_state(BT_MESH_LPN_CLEAR); + k_delayed_work_submit(&lpn->timer, FRIEND_REQ_TIMEOUT); } static const struct bt_mesh_send_cb clear_sent_cb = { - .end = friend_clear_sent, + .end = friend_clear_sent, }; static int send_friend_clear(void) { - struct bt_mesh_msg_ctx ctx = { - .net_idx = bt_mesh.sub[0].net_idx, - .app_idx = BT_MESH_KEY_UNUSED, - .addr = bt_mesh.lpn.frnd, - .send_ttl = 0, - }; - struct bt_mesh_net_tx tx = { - .sub = &bt_mesh.sub[0], - .ctx = &ctx, - .src = bt_mesh_primary_addr(), - .xmit = bt_mesh_net_transmit_get(), - }; - struct bt_mesh_ctl_friend_clear req = { - .lpn_addr = sys_cpu_to_be16(tx.src), - .lpn_counter = sys_cpu_to_be16(bt_mesh.lpn.counter), - }; + struct bt_mesh_msg_ctx ctx = { + .net_idx = bt_mesh.sub[0].net_idx, + .app_idx = BT_MESH_KEY_UNUSED, + .addr = bt_mesh.lpn.frnd, + .send_ttl = 0, + }; + struct bt_mesh_net_tx tx = { + .sub = &bt_mesh.sub[0], + .ctx = &ctx, + .src = bt_mesh_primary_addr(), + .xmit = bt_mesh_net_transmit_get(), + }; + struct bt_mesh_ctl_friend_clear req = { + .lpn_addr = sys_cpu_to_be16(tx.src), + .lpn_counter = sys_cpu_to_be16(bt_mesh.lpn.counter), + }; - BT_DBG(""); + BT_DBG(""); - return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR, &req, - sizeof(req), NULL, &clear_sent_cb, NULL); + return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR, &req, + sizeof(req), NULL, &clear_sent_cb, NULL); } static void clear_friendship(bool force, bool disable) { - struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - BT_DBG("force %u disable %u", force, disable); + BT_DBG("force %u disable %u", force, disable); - if (!force && lpn->established && !lpn->clear_success && - lpn->req_attempts < CLEAR_ATTEMPTS) { - send_friend_clear(); - lpn->disable = disable; - return; - } + if (!force && lpn->established && !lpn->clear_success && + lpn->req_attempts < CLEAR_ATTEMPTS) { + send_friend_clear(); + lpn->disable = disable; + return; + } - bt_mesh_rx_reset(); + bt_mesh_rx_reset(); - k_delayed_work_cancel(&lpn->timer); + k_delayed_work_cancel(&lpn->timer); - friend_cred_del(bt_mesh.sub[0].net_idx, lpn->frnd); + friend_cred_del(bt_mesh.sub[0].net_idx, lpn->frnd); - if (lpn->clear_success) { - lpn->old_friend = BT_MESH_ADDR_UNASSIGNED; - } else { - lpn->old_friend = lpn->frnd; - } + if (lpn->clear_success) { + lpn->old_friend = BT_MESH_ADDR_UNASSIGNED; + } else { + lpn->old_friend = lpn->frnd; + } - if (lpn_cb && lpn->frnd != BT_MESH_ADDR_UNASSIGNED) { - lpn_cb(lpn->frnd, false); - } + if (lpn_cb && lpn->frnd != BT_MESH_ADDR_UNASSIGNED) { + lpn_cb(lpn->frnd, false); + } - lpn->frnd = BT_MESH_ADDR_UNASSIGNED; - lpn->fsn = 0U; - lpn->req_attempts = 0U; - lpn->recv_win = 0U; - lpn->queue_size = 0U; - lpn->disable = 0U; - lpn->sent_req = 0U; - lpn->established = 0U; - lpn->clear_success = 0U; + lpn->frnd = BT_MESH_ADDR_UNASSIGNED; + lpn->fsn = 0U; + lpn->req_attempts = 0U; + lpn->recv_win = 0U; + lpn->queue_size = 0U; + lpn->disable = 0U; + lpn->sent_req = 0U; + lpn->established = 0U; + lpn->clear_success = 0U; - group_zero(lpn->added); - group_zero(lpn->pending); - group_zero(lpn->to_remove); + group_zero(lpn->added); + group_zero(lpn->pending); + group_zero(lpn->to_remove); - /* Set this to 1 to force group subscription when the next - * Friendship is created, in case lpn->groups doesn't get - * modified meanwhile. - */ - lpn->groups_changed = 1U; + /* Set this to 1 to force group subscription when the next + * Friendship is created, in case lpn->groups doesn't get + * modified meanwhile. + */ + lpn->groups_changed = 1U; - if (cfg->hb_pub.feat & BT_MESH_FEAT_LOW_POWER) { - bt_mesh_heartbeat_send(); - } + if (cfg->hb_pub.feat & BT_MESH_FEAT_LOW_POWER) { + bt_mesh_heartbeat_send(); + } - if (disable) { - lpn_set_state(BT_MESH_LPN_DISABLED); - return; - } + if (disable) { + lpn_set_state(BT_MESH_LPN_DISABLED); + return; + } - lpn_set_state(BT_MESH_LPN_ENABLED); - k_delayed_work_submit(&lpn->timer, FRIEND_REQ_RETRY_TIMEOUT); + lpn_set_state(BT_MESH_LPN_ENABLED); + k_delayed_work_submit(&lpn->timer, FRIEND_REQ_RETRY_TIMEOUT); } static void friend_req_sent(u16_t duration, int err, void *user_data) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - if (err) { - BT_ERR("Sending Friend Request failed (err %d)", err); - return; - } + if (err) { + BT_ERR("Sending Friend Request failed (err %d)", err); + return; + } - lpn->adv_duration = duration; + lpn->adv_duration = duration; - if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { - k_delayed_work_submit(&lpn->timer, FRIEND_REQ_WAIT); - lpn_set_state(BT_MESH_LPN_REQ_WAIT); - } else { - k_delayed_work_submit(&lpn->timer, - duration + FRIEND_REQ_TIMEOUT); - lpn_set_state(BT_MESH_LPN_WAIT_OFFER); - } + if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { + k_delayed_work_submit(&lpn->timer, FRIEND_REQ_WAIT); + lpn_set_state(BT_MESH_LPN_REQ_WAIT); + } else { + k_delayed_work_submit(&lpn->timer, + duration + FRIEND_REQ_TIMEOUT); + lpn_set_state(BT_MESH_LPN_WAIT_OFFER); + } } static const struct bt_mesh_send_cb friend_req_sent_cb = { - .start = friend_req_sent, + .start = friend_req_sent, }; static int send_friend_req(struct bt_mesh_lpn *lpn) { - const struct bt_mesh_comp *comp = bt_mesh_comp_get(); - struct bt_mesh_msg_ctx ctx = { - .net_idx = bt_mesh.sub[0].net_idx, - .app_idx = BT_MESH_KEY_UNUSED, - .addr = BT_MESH_ADDR_FRIENDS, - .send_ttl = 0, - }; - struct bt_mesh_net_tx tx = { - .sub = &bt_mesh.sub[0], - .ctx = &ctx, - .src = bt_mesh_primary_addr(), - .xmit = POLL_XMIT, - }; - struct bt_mesh_ctl_friend_req req = { - .criteria = LPN_CRITERIA, - .recv_delay = LPN_RECV_DELAY, - .poll_to = LPN_POLL_TO, - .prev_addr = lpn->old_friend, - .num_elem = comp->elem_count, - .lpn_counter = sys_cpu_to_be16(lpn->counter), - }; + const struct bt_mesh_comp *comp = bt_mesh_comp_get(); + struct bt_mesh_msg_ctx ctx = { + .net_idx = bt_mesh.sub[0].net_idx, + .app_idx = BT_MESH_KEY_UNUSED, + .addr = BT_MESH_ADDR_FRIENDS, + .send_ttl = 0, + }; + struct bt_mesh_net_tx tx = { + .sub = &bt_mesh.sub[0], + .ctx = &ctx, + .src = bt_mesh_primary_addr(), + .xmit = POLL_XMIT, + }; + struct bt_mesh_ctl_friend_req req = { + .criteria = LPN_CRITERIA, + .recv_delay = LPN_RECV_DELAY, + .poll_to = LPN_POLL_TO, + .prev_addr = lpn->old_friend, + .num_elem = comp->elem_count, + .lpn_counter = sys_cpu_to_be16(lpn->counter), + }; - BT_DBG(""); + BT_DBG(""); - return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_REQ, &req, - sizeof(req), NULL, &friend_req_sent_cb, NULL); + return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_REQ, &req, + sizeof(req), NULL, &friend_req_sent_cb, NULL); } static void req_sent(u16_t duration, int err, void *user_data) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; #if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER) - BT_DBG("req 0x%02x duration %u err %d state %s", - lpn->sent_req, duration, err, state2str(lpn->state)); + BT_DBG("req 0x%02x duration %u err %d state %s", + lpn->sent_req, duration, err, state2str(lpn->state)); #endif - if (err) { - BT_ERR("Sending request failed (err %d)", err); - lpn->sent_req = 0U; - group_zero(lpn->pending); - return; - } + if (err) { + BT_ERR("Sending request failed (err %d)", err); + lpn->sent_req = 0U; + group_zero(lpn->pending); + return; + } - lpn->req_attempts++; - lpn->adv_duration = duration; + lpn->req_attempts++; + lpn->adv_duration = duration; - if (lpn->established || IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { - lpn_set_state(BT_MESH_LPN_RECV_DELAY); - /* We start scanning a bit early to elimitate risk of missing - * response data due to HCI and other latencies. - */ - k_delayed_work_submit(&lpn->timer, - LPN_RECV_DELAY - SCAN_LATENCY); - } else { - k_delayed_work_submit(&lpn->timer, - LPN_RECV_DELAY + duration + - lpn->recv_win); - } + if (lpn->established || IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { + lpn_set_state(BT_MESH_LPN_RECV_DELAY); + /* We start scanning a bit early to elimitate risk of missing + * response data due to HCI and other latencies. + */ + k_delayed_work_submit(&lpn->timer, + LPN_RECV_DELAY - SCAN_LATENCY); + } else { + k_delayed_work_submit(&lpn->timer, + LPN_RECV_DELAY + duration + + lpn->recv_win); + } } static const struct bt_mesh_send_cb req_sent_cb = { - .start = req_sent, + .start = req_sent, }; static int send_friend_poll(void) { - struct bt_mesh_msg_ctx ctx = { - .net_idx = bt_mesh.sub[0].net_idx, - .app_idx = BT_MESH_KEY_UNUSED, - .addr = bt_mesh.lpn.frnd, - .send_ttl = 0, - }; - struct bt_mesh_net_tx tx = { - .sub = &bt_mesh.sub[0], - .ctx = &ctx, - .src = bt_mesh_primary_addr(), - .xmit = POLL_XMIT, - .friend_cred = true, - }; - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - u8_t fsn = lpn->fsn; - int err; + struct bt_mesh_msg_ctx ctx = { + .net_idx = bt_mesh.sub[0].net_idx, + .app_idx = BT_MESH_KEY_UNUSED, + .addr = bt_mesh.lpn.frnd, + .send_ttl = 0, + }; + struct bt_mesh_net_tx tx = { + .sub = &bt_mesh.sub[0], + .ctx = &ctx, + .src = bt_mesh_primary_addr(), + .xmit = POLL_XMIT, + .friend_cred = true, + }; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + u8_t fsn = lpn->fsn; + int err; - BT_DBG("lpn->sent_req 0x%02x", lpn->sent_req); + BT_DBG("lpn->sent_req 0x%02x", lpn->sent_req); - if (lpn->sent_req) { - if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) { - lpn->pending_poll = 1U; - } + if (lpn->sent_req) { + if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) { + lpn->pending_poll = 1U; + } - return 0; - } + return 0; + } - err = bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_POLL, &fsn, 1, - NULL, &req_sent_cb, NULL); - if (err == 0) { - lpn->pending_poll = 0U; - lpn->sent_req = TRANS_CTL_OP_FRIEND_POLL; - } + err = bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_POLL, &fsn, 1, + NULL, &req_sent_cb, NULL); + if (err == 0) { + lpn->pending_poll = 0U; + lpn->sent_req = TRANS_CTL_OP_FRIEND_POLL; + } - return err; + return err; } void bt_mesh_lpn_disable(bool force) { - if (bt_mesh.lpn.state == BT_MESH_LPN_DISABLED) { - return; - } + if (bt_mesh.lpn.state == BT_MESH_LPN_DISABLED) { + return; + } - clear_friendship(force, true); + clear_friendship(force, true); } int bt_mesh_lpn_set(bool enable) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - if (enable) { - if (lpn->state != BT_MESH_LPN_DISABLED) { - return 0; - } - } else { - if (lpn->state == BT_MESH_LPN_DISABLED) { - return 0; - } - } + if (enable) { + if (lpn->state != BT_MESH_LPN_DISABLED) { + return 0; + } + } else { + if (lpn->state == BT_MESH_LPN_DISABLED) { + return 0; + } + } - if (!bt_mesh_is_provisioned()) { - if (enable) { - lpn_set_state(BT_MESH_LPN_ENABLED); - } else { - lpn_set_state(BT_MESH_LPN_DISABLED); - } + if (!bt_mesh_is_provisioned()) { + if (enable) { + lpn_set_state(BT_MESH_LPN_ENABLED); + } else { + lpn_set_state(BT_MESH_LPN_DISABLED); + } - return 0; - } + return 0; + } - if (enable) { - lpn_set_state(BT_MESH_LPN_ENABLED); + if (enable) { + lpn_set_state(BT_MESH_LPN_ENABLED); - if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { - bt_mesh_scan_disable(); - } + if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { + bt_mesh_scan_disable(); + } - send_friend_req(lpn); - } else { - if (IS_ENABLED(CONFIG_BT_MESH_LPN_AUTO) && - lpn->state == BT_MESH_LPN_TIMER) { - k_delayed_work_cancel(&lpn->timer); - lpn_set_state(BT_MESH_LPN_DISABLED); - } else { - bt_mesh_lpn_disable(false); - } - } + send_friend_req(lpn); + } else { + if (IS_ENABLED(CONFIG_BT_MESH_LPN_AUTO) && + lpn->state == BT_MESH_LPN_TIMER) { + k_delayed_work_cancel(&lpn->timer); + lpn_set_state(BT_MESH_LPN_DISABLED); + } else { + bt_mesh_lpn_disable(false); + } + } - return 0; + return 0; } static void friend_response_received(struct bt_mesh_lpn *lpn) { - BT_DBG("lpn->sent_req 0x%02x", lpn->sent_req); + BT_DBG("lpn->sent_req 0x%02x", lpn->sent_req); - if (lpn->sent_req == TRANS_CTL_OP_FRIEND_POLL) { - lpn->fsn++; - } + if (lpn->sent_req == TRANS_CTL_OP_FRIEND_POLL) { + lpn->fsn++; + } - k_delayed_work_cancel(&lpn->timer); - bt_mesh_scan_disable(); - lpn_set_state(BT_MESH_LPN_ESTABLISHED); - lpn->req_attempts = 0U; - lpn->sent_req = 0U; + k_delayed_work_cancel(&lpn->timer); + bt_mesh_scan_disable(); + lpn_set_state(BT_MESH_LPN_ESTABLISHED); + lpn->req_attempts = 0U; + lpn->sent_req = 0U; } void bt_mesh_lpn_msg_received(struct bt_mesh_net_rx *rx) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - if (lpn->state == BT_MESH_LPN_TIMER) { - BT_DBG("Restarting establishment timer"); - k_delayed_work_submit(&lpn->timer, LPN_AUTO_TIMEOUT); - return; - } + if (lpn->state == BT_MESH_LPN_TIMER) { + BT_DBG("Restarting establishment timer"); + k_delayed_work_submit(&lpn->timer, LPN_AUTO_TIMEOUT); + return; + } - if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) { - BT_WARN("Unexpected message withouth a preceding Poll"); - return; - } + if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) { + BT_WARN("Unexpected message withouth a preceding Poll"); + return; + } - friend_response_received(lpn); + friend_response_received(lpn); - BT_DBG("Requesting more messages from Friend"); + BT_DBG("Requesting more messages from Friend"); - send_friend_poll(); + send_friend_poll(); } int bt_mesh_lpn_friend_offer(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_offer *msg = (void *)buf->data; - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - struct bt_mesh_subnet *sub = rx->sub; - struct friend_cred *cred; - u16_t frnd_counter; - int err; + struct bt_mesh_ctl_friend_offer *msg = (void *)buf->data; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_subnet *sub = rx->sub; + struct friend_cred *cred; + u16_t frnd_counter; + int err; - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Offer"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Offer"); + return -EINVAL; + } - if (lpn->state != BT_MESH_LPN_WAIT_OFFER) { - BT_WARN("Ignoring unexpected Friend Offer"); - return 0; - } + if (lpn->state != BT_MESH_LPN_WAIT_OFFER) { + BT_WARN("Ignoring unexpected Friend Offer"); + return 0; + } - if (!msg->recv_win) { - BT_WARN("Prohibited ReceiveWindow value"); - return -EINVAL; - } + if (!msg->recv_win) { + BT_WARN("Prohibited ReceiveWindow value"); + return -EINVAL; + } - frnd_counter = sys_be16_to_cpu(msg->frnd_counter); + frnd_counter = sys_be16_to_cpu(msg->frnd_counter); - BT_DBG("recv_win %u queue_size %u sub_list_size %u rssi %d counter %u", - msg->recv_win, msg->queue_size, msg->sub_list_size, msg->rssi, - frnd_counter); + BT_DBG("recv_win %u queue_size %u sub_list_size %u rssi %d counter %u", + msg->recv_win, msg->queue_size, msg->sub_list_size, msg->rssi, + frnd_counter); - lpn->frnd = rx->ctx.addr; + lpn->frnd = rx->ctx.addr; - cred = friend_cred_create(sub, lpn->frnd, lpn->counter, frnd_counter); - if (!cred) { - lpn->frnd = BT_MESH_ADDR_UNASSIGNED; - return -ENOMEM; - } + cred = friend_cred_create(sub, lpn->frnd, lpn->counter, frnd_counter); + if (!cred) { + lpn->frnd = BT_MESH_ADDR_UNASSIGNED; + return -ENOMEM; + } - /* TODO: Add offer acceptance criteria check */ + /* TODO: Add offer acceptance criteria check */ - k_delayed_work_cancel(&lpn->timer); + k_delayed_work_cancel(&lpn->timer); - lpn->recv_win = msg->recv_win; - lpn->queue_size = msg->queue_size; + lpn->recv_win = msg->recv_win; + lpn->queue_size = msg->queue_size; - err = send_friend_poll(); - if (err) { - friend_cred_clear(cred); - lpn->frnd = BT_MESH_ADDR_UNASSIGNED; - lpn->recv_win = 0U; - lpn->queue_size = 0U; - return err; - } + err = send_friend_poll(); + if (err) { + friend_cred_clear(cred); + lpn->frnd = BT_MESH_ADDR_UNASSIGNED; + lpn->recv_win = 0U; + lpn->queue_size = 0U; + return err; + } - lpn->counter++; + lpn->counter++; - return 0; + return 0; } int bt_mesh_lpn_friend_clear_cfm(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_clear_confirm *msg = (void *)buf->data; - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - u16_t addr, counter; + struct bt_mesh_ctl_friend_clear_confirm *msg = (void *)buf->data; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + u16_t addr, counter; - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Clear Confirm"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Clear Confirm"); + return -EINVAL; + } - if (lpn->state != BT_MESH_LPN_CLEAR) { - BT_WARN("Ignoring unexpected Friend Clear Confirm"); - return 0; - } + if (lpn->state != BT_MESH_LPN_CLEAR) { + BT_WARN("Ignoring unexpected Friend Clear Confirm"); + return 0; + } - addr = sys_be16_to_cpu(msg->lpn_addr); - counter = sys_be16_to_cpu(msg->lpn_counter); + addr = sys_be16_to_cpu(msg->lpn_addr); + counter = sys_be16_to_cpu(msg->lpn_counter); - BT_DBG("LPNAddress 0x%04x LPNCounter 0x%04x", addr, counter); + BT_DBG("LPNAddress 0x%04x LPNCounter 0x%04x", addr, counter); - if (addr != bt_mesh_primary_addr() || counter != lpn->counter) { - BT_WARN("Invalid parameters in Friend Clear Confirm"); - return 0; - } + if (addr != bt_mesh_primary_addr() || counter != lpn->counter) { + BT_WARN("Invalid parameters in Friend Clear Confirm"); + return 0; + } - lpn->clear_success = 1U; - clear_friendship(false, lpn->disable); + lpn->clear_success = 1U; + clear_friendship(false, lpn->disable); - return 0; + return 0; } static void lpn_group_add(u16_t group) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - u16_t *free_slot = NULL; - int i; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + u16_t *free_slot = NULL; + int i; - for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) { - if (lpn->groups[i] == group) { - atomic_clear_bit(lpn->to_remove, i); - return; - } + for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) { + if (lpn->groups[i] == group) { + atomic_clear_bit(lpn->to_remove, i); + return; + } - if (!free_slot && lpn->groups[i] == BT_MESH_ADDR_UNASSIGNED) { - free_slot = &lpn->groups[i]; - } - } + if (!free_slot && lpn->groups[i] == BT_MESH_ADDR_UNASSIGNED) { + free_slot = &lpn->groups[i]; + } + } - if (!free_slot) { - BT_WARN("Friend Subscription List exceeded!"); - return; - } + if (!free_slot) { + BT_WARN("Friend Subscription List exceeded!"); + return; + } - *free_slot = group; - lpn->groups_changed = 1U; + *free_slot = group; + lpn->groups_changed = 1U; } static void lpn_group_del(u16_t group) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - int i; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + int i; - for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) { - if (lpn->groups[i] == group) { - if (atomic_test_bit(lpn->added, i) || - atomic_test_bit(lpn->pending, i)) { - atomic_set_bit(lpn->to_remove, i); - lpn->groups_changed = 1U; - } else { - lpn->groups[i] = BT_MESH_ADDR_UNASSIGNED; - } - } - } + for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) { + if (lpn->groups[i] == group) { + if (atomic_test_bit(lpn->added, i) || + atomic_test_bit(lpn->pending, i)) { + atomic_set_bit(lpn->to_remove, i); + lpn->groups_changed = 1U; + } else { + lpn->groups[i] = BT_MESH_ADDR_UNASSIGNED; + } + } + } } static inline int group_popcount(atomic_t *target) { #if CONFIG_BT_MESH_LPN_GROUPS > 32 - int i, count = 0; + int i, count = 0; - for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { - count += popcount(atomic_get(&target[i])); - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) { + count += popcount(atomic_get(&target[i])); + } #else - return popcount(atomic_get(target)); + return popcount(atomic_get(target)); #endif } static bool sub_update(u8_t op) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - int added_count = group_popcount(lpn->added); - struct bt_mesh_msg_ctx ctx = { - .net_idx = bt_mesh.sub[0].net_idx, - .app_idx = BT_MESH_KEY_UNUSED, - .addr = lpn->frnd, - .send_ttl = 0, - }; - struct bt_mesh_net_tx tx = { - .sub = &bt_mesh.sub[0], - .ctx = &ctx, - .src = bt_mesh_primary_addr(), - .xmit = POLL_XMIT, - .friend_cred = true, - }; - struct bt_mesh_ctl_friend_sub req; - size_t i, g; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + int added_count = group_popcount(lpn->added); + struct bt_mesh_msg_ctx ctx = { + .net_idx = bt_mesh.sub[0].net_idx, + .app_idx = BT_MESH_KEY_UNUSED, + .addr = lpn->frnd, + .send_ttl = 0, + }; + struct bt_mesh_net_tx tx = { + .sub = &bt_mesh.sub[0], + .ctx = &ctx, + .src = bt_mesh_primary_addr(), + .xmit = POLL_XMIT, + .friend_cred = true, + }; + struct bt_mesh_ctl_friend_sub req; + size_t i, g; - BT_DBG("op 0x%02x sent_req 0x%02x", op, lpn->sent_req); + BT_DBG("op 0x%02x sent_req 0x%02x", op, lpn->sent_req); - if (lpn->sent_req) { - return false; - } + if (lpn->sent_req) { + return false; + } - for (i = 0, g = 0; i < ARRAY_SIZE(lpn->groups); i++) { - if (lpn->groups[i] == BT_MESH_ADDR_UNASSIGNED) { - continue; - } + for (i = 0, g = 0; i < ARRAY_SIZE(lpn->groups); i++) { + if (lpn->groups[i] == BT_MESH_ADDR_UNASSIGNED) { + continue; + } - if (op == TRANS_CTL_OP_FRIEND_SUB_ADD) { - if (atomic_test_bit(lpn->added, i)) { - continue; - } - } else { - if (!atomic_test_bit(lpn->to_remove, i)) { - continue; - } - } + if (op == TRANS_CTL_OP_FRIEND_SUB_ADD) { + if (atomic_test_bit(lpn->added, i)) { + continue; + } + } else { + if (!atomic_test_bit(lpn->to_remove, i)) { + continue; + } + } - if (added_count + g >= lpn->queue_size) { - BT_WARN("Friend Queue Size exceeded"); - break; - } + if (added_count + g >= lpn->queue_size) { + BT_WARN("Friend Queue Size exceeded"); + break; + } - req.addr_list[g++] = sys_cpu_to_be16(lpn->groups[i]); - atomic_set_bit(lpn->pending, i); + req.addr_list[g++] = sys_cpu_to_be16(lpn->groups[i]); + atomic_set_bit(lpn->pending, i); - if (g == ARRAY_SIZE(req.addr_list)) { - break; - } - } + if (g == ARRAY_SIZE(req.addr_list)) { + break; + } + } - if (g == 0) { - group_zero(lpn->pending); - return false; - } + if (g == 0) { + group_zero(lpn->pending); + return false; + } - req.xact = lpn->xact_next++; + req.xact = lpn->xact_next++; - if (bt_mesh_ctl_send(&tx, op, &req, 1 + g * 2, NULL, - &req_sent_cb, NULL) < 0) { - group_zero(lpn->pending); - return false; - } + if (bt_mesh_ctl_send(&tx, op, &req, 1 + g * 2, NULL, + &req_sent_cb, NULL) < 0) { + group_zero(lpn->pending); + return false; + } - lpn->xact_pending = req.xact; - lpn->sent_req = op; - return true; + lpn->xact_pending = req.xact; + lpn->sent_req = op; + return true; } static void update_timeout(struct bt_mesh_lpn *lpn) { - if (lpn->established) { - BT_WARN("No response from Friend during ReceiveWindow"); - bt_mesh_scan_disable(); - lpn_set_state(BT_MESH_LPN_ESTABLISHED); - k_delayed_work_submit(&lpn->timer, POLL_RETRY_TIMEOUT); - } else { - if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { - bt_mesh_scan_disable(); - } + if (lpn->established) { + BT_WARN("No response from Friend during ReceiveWindow"); + bt_mesh_scan_disable(); + lpn_set_state(BT_MESH_LPN_ESTABLISHED); + k_delayed_work_submit(&lpn->timer, POLL_RETRY_TIMEOUT); + } else { + if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { + bt_mesh_scan_disable(); + } - if (lpn->req_attempts < 6) { - BT_WARN("Retrying first Friend Poll"); - lpn->sent_req = 0U; - if (send_friend_poll() == 0) { - return; - } - } + if (lpn->req_attempts < 6) { + BT_WARN("Retrying first Friend Poll"); + lpn->sent_req = 0U; + if (send_friend_poll() == 0) { + return; + } + } - BT_ERR("Timed out waiting for first Friend Update"); - clear_friendship(false, false); - } + BT_ERR("Timed out waiting for first Friend Update"); + clear_friendship(false, false); + } } static void lpn_timeout(struct k_work *work) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; #if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER) - BT_DBG("state: %s", state2str(lpn->state)); + BT_DBG("state: %s", state2str(lpn->state)); #endif - switch (lpn->state) { - case BT_MESH_LPN_DISABLED: - break; - case BT_MESH_LPN_CLEAR: - clear_friendship(false, bt_mesh.lpn.disable); - break; - case BT_MESH_LPN_TIMER: - BT_DBG("Starting to look for Friend nodes"); - lpn_set_state(BT_MESH_LPN_ENABLED); - if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { - bt_mesh_scan_disable(); - } - /* fall through */ + switch (lpn->state) { + case BT_MESH_LPN_DISABLED: + break; + case BT_MESH_LPN_CLEAR: + clear_friendship(false, bt_mesh.lpn.disable); + break; + case BT_MESH_LPN_TIMER: + BT_DBG("Starting to look for Friend nodes"); + lpn_set_state(BT_MESH_LPN_ENABLED); + if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { + bt_mesh_scan_disable(); + } + /* fall through */ __attribute__ ((fallthrough)); - case BT_MESH_LPN_ENABLED: - send_friend_req(lpn); - break; - case BT_MESH_LPN_REQ_WAIT: - bt_mesh_scan_enable(); - k_delayed_work_submit(&lpn->timer, - lpn->adv_duration + FRIEND_REQ_SCAN); - lpn_set_state(BT_MESH_LPN_WAIT_OFFER); - break; - case BT_MESH_LPN_WAIT_OFFER: - BT_WARN("No acceptable Friend Offers received"); - if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { - bt_mesh_scan_disable(); - } - lpn->counter++; - lpn_set_state(BT_MESH_LPN_ENABLED); - lpn->sent_req = 0U; - k_delayed_work_submit(&lpn->timer, FRIEND_REQ_RETRY_TIMEOUT); - break; - case BT_MESH_LPN_ESTABLISHED: - if (lpn->req_attempts < REQ_ATTEMPTS(lpn)) { - u8_t req = lpn->sent_req; + case BT_MESH_LPN_ENABLED: + send_friend_req(lpn); + break; + case BT_MESH_LPN_REQ_WAIT: + bt_mesh_scan_enable(); + k_delayed_work_submit(&lpn->timer, + lpn->adv_duration + FRIEND_REQ_SCAN); + lpn_set_state(BT_MESH_LPN_WAIT_OFFER); + break; + case BT_MESH_LPN_WAIT_OFFER: + BT_WARN("No acceptable Friend Offers received"); + if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { + bt_mesh_scan_disable(); + } + lpn->counter++; + lpn_set_state(BT_MESH_LPN_ENABLED); + lpn->sent_req = 0U; + k_delayed_work_submit(&lpn->timer, FRIEND_REQ_RETRY_TIMEOUT); + break; + case BT_MESH_LPN_ESTABLISHED: + if (lpn->req_attempts < REQ_ATTEMPTS(lpn)) { + u8_t req = lpn->sent_req; - lpn->sent_req = 0U; + lpn->sent_req = 0U; - if (!req || req == TRANS_CTL_OP_FRIEND_POLL) { - send_friend_poll(); - } else { - sub_update(req); - } + if (!req || req == TRANS_CTL_OP_FRIEND_POLL) { + send_friend_poll(); + } else { + sub_update(req); + } - break; - } + break; + } - BT_ERR("No response from Friend after %u retries", - lpn->req_attempts); - lpn->req_attempts = 0U; - clear_friendship(false, false); - break; - case BT_MESH_LPN_RECV_DELAY: - k_delayed_work_submit(&lpn->timer, - lpn->adv_duration + SCAN_LATENCY + - lpn->recv_win); - bt_mesh_scan_enable(); - lpn_set_state(BT_MESH_LPN_WAIT_UPDATE); - break; - case BT_MESH_LPN_WAIT_UPDATE: - update_timeout(lpn); - break; - default: - __ASSERT(0, "Unhandled LPN state"); - break; - } + BT_ERR("No response from Friend after %u retries", + lpn->req_attempts); + lpn->req_attempts = 0U; + clear_friendship(false, false); + break; + case BT_MESH_LPN_RECV_DELAY: + k_delayed_work_submit(&lpn->timer, + lpn->adv_duration + SCAN_LATENCY + + lpn->recv_win); + bt_mesh_scan_enable(); + lpn_set_state(BT_MESH_LPN_WAIT_UPDATE); + break; + case BT_MESH_LPN_WAIT_UPDATE: + update_timeout(lpn); + break; + default: + __ASSERT(0, "Unhandled LPN state"); + break; + } } void bt_mesh_lpn_group_add(u16_t group) { - BT_DBG("group 0x%04x", group); + BT_DBG("group 0x%04x", group); - lpn_group_add(group); + lpn_group_add(group); - if (!bt_mesh_lpn_established() || bt_mesh.lpn.sent_req) { - return; - } + if (!bt_mesh_lpn_established() || bt_mesh.lpn.sent_req) { + return; + } - sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD); + sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD); } void bt_mesh_lpn_group_del(u16_t *groups, size_t group_count) { - int i; + int i; - for (i = 0; i < group_count; i++) { - if (groups[i] != BT_MESH_ADDR_UNASSIGNED) { - BT_DBG("group 0x%04x", groups[i]); - lpn_group_del(groups[i]); - } - } + for (i = 0; i < group_count; i++) { + if (groups[i] != BT_MESH_ADDR_UNASSIGNED) { + BT_DBG("group 0x%04x", groups[i]); + lpn_group_del(groups[i]); + } + } - if (!bt_mesh_lpn_established() || bt_mesh.lpn.sent_req) { - return; - } + if (!bt_mesh_lpn_established() || bt_mesh.lpn.sent_req) { + return; + } - sub_update(TRANS_CTL_OP_FRIEND_SUB_REM); + sub_update(TRANS_CTL_OP_FRIEND_SUB_REM); } static s32_t poll_timeout(struct bt_mesh_lpn *lpn) { - /* If we're waiting for segment acks keep polling at high freq */ - if (bt_mesh_tx_in_progress()) { - return MIN(POLL_TIMEOUT_MAX(lpn), K_SECONDS(1)); - } + /* If we're waiting for segment acks keep polling at high freq */ + if (bt_mesh_tx_in_progress()) { + return MIN(POLL_TIMEOUT_MAX(lpn), K_SECONDS(1)); + } - if (lpn->poll_timeout < POLL_TIMEOUT_MAX(lpn)) { - lpn->poll_timeout *= 2; - lpn->poll_timeout = MIN(lpn->poll_timeout, - POLL_TIMEOUT_MAX(lpn)); - } + if (lpn->poll_timeout < POLL_TIMEOUT_MAX(lpn)) { + lpn->poll_timeout *= 2; + lpn->poll_timeout = MIN(lpn->poll_timeout, + POLL_TIMEOUT_MAX(lpn)); + } - BT_DBG("Poll Timeout is %ums", lpn->poll_timeout); + BT_DBG("Poll Timeout is %ums", lpn->poll_timeout); - return lpn->poll_timeout; + return lpn->poll_timeout; } int bt_mesh_lpn_friend_sub_cfm(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_sub_confirm *msg = (void *)buf->data; - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_ctl_friend_sub_confirm *msg = (void *)buf->data; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Subscription Confirm"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Subscription Confirm"); + return -EINVAL; + } - BT_DBG("xact 0x%02x", msg->xact); + BT_DBG("xact 0x%02x", msg->xact); - if (!lpn->sent_req) { - BT_WARN("No pending subscription list message"); - return 0; - } + if (!lpn->sent_req) { + BT_WARN("No pending subscription list message"); + return 0; + } - if (msg->xact != lpn->xact_pending) { - BT_WARN("Transaction mismatch (0x%02x != 0x%02x)", - msg->xact, lpn->xact_pending); - return 0; - } + if (msg->xact != lpn->xact_pending) { + BT_WARN("Transaction mismatch (0x%02x != 0x%02x)", + msg->xact, lpn->xact_pending); + return 0; + } - if (lpn->sent_req == TRANS_CTL_OP_FRIEND_SUB_ADD) { - group_set(lpn->added, lpn->pending); - group_zero(lpn->pending); - } else if (lpn->sent_req == TRANS_CTL_OP_FRIEND_SUB_REM) { - int i; + if (lpn->sent_req == TRANS_CTL_OP_FRIEND_SUB_ADD) { + group_set(lpn->added, lpn->pending); + group_zero(lpn->pending); + } else if (lpn->sent_req == TRANS_CTL_OP_FRIEND_SUB_REM) { + int i; - group_clear(lpn->added, lpn->pending); + group_clear(lpn->added, lpn->pending); - for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) { - if (atomic_test_and_clear_bit(lpn->pending, i) && - atomic_test_and_clear_bit(lpn->to_remove, i)) { - lpn->groups[i] = BT_MESH_ADDR_UNASSIGNED; - } - } - } else { - BT_WARN("Unexpected Friend Subscription Confirm"); - return 0; - } + for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) { + if (atomic_test_and_clear_bit(lpn->pending, i) && + atomic_test_and_clear_bit(lpn->to_remove, i)) { + lpn->groups[i] = BT_MESH_ADDR_UNASSIGNED; + } + } + } else { + BT_WARN("Unexpected Friend Subscription Confirm"); + return 0; + } - friend_response_received(lpn); + friend_response_received(lpn); - if (lpn->groups_changed) { - sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD); - sub_update(TRANS_CTL_OP_FRIEND_SUB_REM); + if (lpn->groups_changed) { + sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD); + sub_update(TRANS_CTL_OP_FRIEND_SUB_REM); - if (!lpn->sent_req) { - lpn->groups_changed = 0U; - } - } + if (!lpn->sent_req) { + lpn->groups_changed = 0U; + } + } - if (lpn->pending_poll) { - send_friend_poll(); - } + if (lpn->pending_poll) { + send_friend_poll(); + } - if (!lpn->sent_req) { - k_delayed_work_submit(&lpn->timer, poll_timeout(lpn)); - } + if (!lpn->sent_req) { + k_delayed_work_submit(&lpn->timer, poll_timeout(lpn)); + } - return 0; + return 0; } int bt_mesh_lpn_friend_update(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - struct bt_mesh_ctl_friend_update *msg = (void *)buf->data; - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - struct bt_mesh_subnet *sub = rx->sub; - u32_t iv_index; + struct bt_mesh_ctl_friend_update *msg = (void *)buf->data; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_subnet *sub = rx->sub; + u32_t iv_index; - if (buf->len < sizeof(*msg)) { - BT_WARN("Too short Friend Update"); - return -EINVAL; - } + if (buf->len < sizeof(*msg)) { + BT_WARN("Too short Friend Update"); + return -EINVAL; + } - if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) { - BT_WARN("Unexpected friend update"); - return 0; - } + if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) { + BT_WARN("Unexpected friend update"); + return 0; + } - if (sub->kr_phase == BT_MESH_KR_PHASE_2 && !rx->new_key) { - BT_WARN("Ignoring Phase 2 KR Update secured using old key"); - return 0; - } + if (sub->kr_phase == BT_MESH_KR_PHASE_2 && !rx->new_key) { + BT_WARN("Ignoring Phase 2 KR Update secured using old key"); + return 0; + } - if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR) && - (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) == - BT_MESH_IV_UPDATE(msg->flags))) { - bt_mesh_beacon_ivu_initiator(false); - } + if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR) && + (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) == + BT_MESH_IV_UPDATE(msg->flags))) { + bt_mesh_beacon_ivu_initiator(false); + } - if (!lpn->established) { - struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); + if (!lpn->established) { + struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); - /* This is normally checked on the transport layer, however - * in this state we're also still accepting master - * credentials so we need to ensure the right ones (Friend - * Credentials) were used for this message. - */ - if (!rx->friend_cred) { - BT_WARN("Friend Update with wrong credentials"); - return -EINVAL; - } + /* This is normally checked on the transport layer, however + * in this state we're also still accepting master + * credentials so we need to ensure the right ones (Friend + * Credentials) were used for this message. + */ + if (!rx->friend_cred) { + BT_WARN("Friend Update with wrong credentials"); + return -EINVAL; + } - lpn->established = 1U; + lpn->established = 1U; - BT_INFO("Friendship established with 0x%04x", lpn->frnd); + BT_INFO("Friendship established with 0x%04x", lpn->frnd); - if (cfg->hb_pub.feat & BT_MESH_FEAT_LOW_POWER) { - bt_mesh_heartbeat_send(); - } + if (cfg->hb_pub.feat & BT_MESH_FEAT_LOW_POWER) { + bt_mesh_heartbeat_send(); + } - if (lpn_cb) { - lpn_cb(lpn->frnd, true); - } + if (lpn_cb) { + lpn_cb(lpn->frnd, true); + } - /* Set initial poll timeout */ - lpn->poll_timeout = MIN(POLL_TIMEOUT_MAX(lpn), - POLL_TIMEOUT_INIT); - } + /* Set initial poll timeout */ + lpn->poll_timeout = MIN(POLL_TIMEOUT_MAX(lpn), + POLL_TIMEOUT_INIT); + } - friend_response_received(lpn); + friend_response_received(lpn); - iv_index = sys_be32_to_cpu(msg->iv_index); + iv_index = sys_be32_to_cpu(msg->iv_index); - BT_DBG("flags 0x%02x iv_index 0x%08x md %u", msg->flags, iv_index, - msg->md); + BT_DBG("flags 0x%02x iv_index 0x%08x md %u", msg->flags, iv_index, + msg->md); - if (bt_mesh_kr_update(sub, BT_MESH_KEY_REFRESH(msg->flags), - rx->new_key)) { - bt_mesh_net_beacon_update(sub); - } + if (bt_mesh_kr_update(sub, BT_MESH_KEY_REFRESH(msg->flags), + rx->new_key)) { + bt_mesh_net_beacon_update(sub); + } - bt_mesh_net_iv_update(iv_index, BT_MESH_IV_UPDATE(msg->flags)); + bt_mesh_net_iv_update(iv_index, BT_MESH_IV_UPDATE(msg->flags)); - if (lpn->groups_changed) { - sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD); - sub_update(TRANS_CTL_OP_FRIEND_SUB_REM); + if (lpn->groups_changed) { + sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD); + sub_update(TRANS_CTL_OP_FRIEND_SUB_REM); - if (!lpn->sent_req) { - lpn->groups_changed = 0U; - } - } + if (!lpn->sent_req) { + lpn->groups_changed = 0U; + } + } - if (msg->md) { - BT_DBG("Requesting for more messages"); - send_friend_poll(); - } + if (msg->md) { + BT_DBG("Requesting for more messages"); + send_friend_poll(); + } - if (!lpn->sent_req) { - k_delayed_work_submit(&lpn->timer, poll_timeout(lpn)); - } + if (!lpn->sent_req) { + k_delayed_work_submit(&lpn->timer, poll_timeout(lpn)); + } - return 0; + return 0; } int bt_mesh_lpn_poll(void) { - if (!bt_mesh.lpn.established) { - return -EAGAIN; - } + if (!bt_mesh.lpn.established) { + return -EAGAIN; + } - BT_DBG("Requesting more messages"); + BT_DBG("Requesting more messages"); - return send_friend_poll(); + return send_friend_poll(); } void bt_mesh_lpn_set_cb(void (*cb)(u16_t friend_addr, bool established)) { - lpn_cb = cb; + lpn_cb = cb; } int bt_mesh_lpn_init(void) { - struct bt_mesh_lpn *lpn = &bt_mesh.lpn; + struct bt_mesh_lpn *lpn = &bt_mesh.lpn; - BT_DBG(""); + BT_DBG(""); - k_delayed_work_init(&lpn->timer, lpn_timeout); + k_delayed_work_init(&lpn->timer, lpn_timeout); - if (lpn->state == BT_MESH_LPN_ENABLED) { - if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { - bt_mesh_scan_disable(); - } else { - bt_mesh_scan_enable(); - } + if (lpn->state == BT_MESH_LPN_ENABLED) { + if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) { + bt_mesh_scan_disable(); + } else { + bt_mesh_scan_enable(); + } - send_friend_req(lpn); - } else { - bt_mesh_scan_enable(); + send_friend_req(lpn); + } else { + bt_mesh_scan_enable(); - if (IS_ENABLED(CONFIG_BT_MESH_LPN_AUTO)) { - BT_DBG("Waiting %u ms for messages", LPN_AUTO_TIMEOUT); - lpn_set_state(BT_MESH_LPN_TIMER); - k_delayed_work_submit(&lpn->timer, LPN_AUTO_TIMEOUT); - } - } + if (IS_ENABLED(CONFIG_BT_MESH_LPN_AUTO)) { + BT_DBG("Waiting %u ms for messages", LPN_AUTO_TIMEOUT); + lpn_set_state(BT_MESH_LPN_TIMER); + k_delayed_work_submit(&lpn->timer, LPN_AUTO_TIMEOUT); + } + } - return 0; + return 0; } diff --git a/components/network/ble/blemesh/src/lpn.h b/components/network/ble/blemesh/src/lpn.h index 3a07285e..cf4ce713 100644 --- a/components/network/ble/blemesh/src/lpn.h +++ b/components/network/ble/blemesh/src/lpn.h @@ -13,48 +13,48 @@ int bt_mesh_lpn_friend_update(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf); + struct net_buf_simple *buf); int bt_mesh_lpn_friend_offer(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf); + struct net_buf_simple *buf); int bt_mesh_lpn_friend_clear_cfm(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf); + struct net_buf_simple *buf); int bt_mesh_lpn_friend_sub_cfm(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf); + struct net_buf_simple *buf); static inline bool bt_mesh_lpn_established(void) { #if defined(CONFIG_BT_MESH_LOW_POWER) - return bt_mesh.lpn.established; + return bt_mesh.lpn.established; #else - return false; + return false; #endif } static inline bool bt_mesh_lpn_match(u16_t addr) { #if defined(CONFIG_BT_MESH_LOW_POWER) - if (bt_mesh_lpn_established()) { - return (addr == bt_mesh.lpn.frnd); - } + if (bt_mesh_lpn_established()) { + return (addr == bt_mesh.lpn.frnd); + } #endif - return false; + return false; } static inline bool bt_mesh_lpn_waiting_update(void) { #if defined(CONFIG_BT_MESH_LOW_POWER) - return (bt_mesh.lpn.state == BT_MESH_LPN_WAIT_UPDATE); + return (bt_mesh.lpn.state == BT_MESH_LPN_WAIT_UPDATE); #else - return false; + return false; #endif } static inline bool bt_mesh_lpn_timer(void) { #if defined(CONFIG_BT_MESH_LPN_AUTO) - return (bt_mesh.lpn.state == BT_MESH_LPN_TIMER); + return (bt_mesh.lpn.state == BT_MESH_LPN_TIMER); #else - return false; + return false; #endif } diff --git a/components/network/ble/blemesh/src/main.c b/components/network/ble/blemesh/src/main.c index 30bcad7a..8d8c3e7e 100644 --- a/components/network/ble/blemesh/src/main.c +++ b/components/network/ble/blemesh/src/main.c @@ -35,11 +35,11 @@ #include "mesh.h" int bt_mesh_provision(const u8_t net_key[16], u16_t net_idx, - u8_t flags, u32_t iv_index, u16_t addr, - const u8_t dev_key[16]) + u8_t flags, u32_t iv_index, u16_t addr, + const u8_t dev_key[16]) { - bool pb_gatt_enabled; - int err; + bool pb_gatt_enabled; + int err; printf("\nmesh provision, network key :"); for(int i = 0; i < 16; i++) @@ -53,269 +53,269 @@ for(int i = 0; i < 16; i++) } printf("\nmesh provison, network key index :0x%04x flags :0x%02x iv index :0x%04x\n", net_idx, flags, iv_index); - BT_INFO("Primary Element: 0x%04x", addr); - BT_DBG("net_idx 0x%04x flags 0x%02x iv_index 0x%04x", - net_idx, flags, iv_index); + BT_INFO("Primary Element: 0x%04x", addr); + BT_DBG("net_idx 0x%04x flags 0x%02x iv_index 0x%04x", + net_idx, flags, iv_index); - if (atomic_test_and_set_bit(bt_mesh.flags, BT_MESH_VALID)) { - return -EALREADY; - } + if (atomic_test_and_set_bit(bt_mesh.flags, BT_MESH_VALID)) { + return -EALREADY; + } - if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT)) { - if (bt_mesh_proxy_prov_disable(false) == 0) { - pb_gatt_enabled = true; - } else { - pb_gatt_enabled = false; - } - } else { - pb_gatt_enabled = false; - } + if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT)) { + if (bt_mesh_proxy_prov_disable(false) == 0) { + pb_gatt_enabled = true; + } else { + pb_gatt_enabled = false; + } + } else { + pb_gatt_enabled = false; + } - err = bt_mesh_net_create(net_idx, flags, net_key, iv_index); - if (err) { - atomic_clear_bit(bt_mesh.flags, BT_MESH_VALID); + err = bt_mesh_net_create(net_idx, flags, net_key, iv_index); + if (err) { + atomic_clear_bit(bt_mesh.flags, BT_MESH_VALID); - if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && pb_gatt_enabled) { - bt_mesh_proxy_prov_enable(); - } + if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && pb_gatt_enabled) { + bt_mesh_proxy_prov_enable(); + } - return err; - } + return err; + } - bt_mesh.seq = 0U; + bt_mesh.seq = 0U; - bt_mesh_comp_provision(addr); + bt_mesh_comp_provision(addr); - memcpy(bt_mesh.dev_key, dev_key, 16); + memcpy(bt_mesh.dev_key, dev_key, 16); - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - BT_DBG("Storing network information persistently"); - bt_mesh_store_net(); - bt_mesh_store_subnet(&bt_mesh.sub[0]); - bt_mesh_store_iv(false); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + BT_DBG("Storing network information persistently"); + bt_mesh_store_net(); + bt_mesh_store_subnet(&bt_mesh.sub[0]); + bt_mesh_store_iv(false); + } - bt_mesh_net_start(); + bt_mesh_net_start(); - return 0; + return 0; } void bt_mesh_reset(void) { - if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { - return; - } + if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { + return; + } - bt_mesh.iv_index = 0U; - bt_mesh.seq = 0U; + bt_mesh.iv_index = 0U; + bt_mesh.seq = 0U; - memset(bt_mesh.flags, 0, sizeof(bt_mesh.flags)); + memset(bt_mesh.flags, 0, sizeof(bt_mesh.flags)); - k_delayed_work_cancel(&bt_mesh.ivu_timer); + k_delayed_work_cancel(&bt_mesh.ivu_timer); - bt_mesh_cfg_reset(); + bt_mesh_cfg_reset(); - bt_mesh_rx_reset(); - bt_mesh_tx_reset(); + bt_mesh_rx_reset(); + bt_mesh_tx_reset(); - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_disable(true); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_disable(true); + } - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - bt_mesh_friend_clear_net_idx(BT_MESH_KEY_ANY); - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + bt_mesh_friend_clear_net_idx(BT_MESH_KEY_ANY); + } - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { - bt_mesh_proxy_gatt_disable(); - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { + bt_mesh_proxy_gatt_disable(); + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_clear_net(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_clear_net(); + } - (void)memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key)); + (void)memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key)); - bt_mesh_scan_disable(); + bt_mesh_scan_disable(); - bt_mesh_beacon_disable(); + bt_mesh_beacon_disable(); - bt_mesh_comp_unprovision(); + bt_mesh_comp_unprovision(); - if (IS_ENABLED(CONFIG_BT_MESH_PROV)) { - bt_mesh_prov_reset(); - } + if (IS_ENABLED(CONFIG_BT_MESH_PROV)) { + bt_mesh_prov_reset(); + } } bool bt_mesh_is_provisioned(void) { - return atomic_test_bit(bt_mesh.flags, BT_MESH_VALID); + return atomic_test_bit(bt_mesh.flags, BT_MESH_VALID); } int bt_mesh_prov_enable(bt_mesh_prov_bearer_t bearers) { - if (bt_mesh_is_provisioned()) { - return -EALREADY; - } + if (bt_mesh_is_provisioned()) { + return -EALREADY; + } - if (IS_ENABLED(CONFIG_BT_DEBUG)) { - const struct bt_mesh_prov *prov = bt_mesh_prov_get(); - struct bt_uuid_128 uuid = { .uuid.type = BT_UUID_TYPE_128 }; + if (IS_ENABLED(CONFIG_BT_DEBUG)) { + const struct bt_mesh_prov *prov = bt_mesh_prov_get(); + struct bt_uuid_128 uuid = { .uuid.type = BT_UUID_TYPE_128 }; - memcpy(uuid.val, prov->uuid, 16); - BT_INFO("Device UUID: %s", bt_uuid_str(&uuid.uuid)); - } + memcpy(uuid.val, prov->uuid, 16); + BT_INFO("Device UUID: %s", bt_uuid_str(&uuid.uuid)); + } - if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && - (bearers & BT_MESH_PROV_ADV)) { - /* Make sure we're scanning for provisioning inviations */ - bt_mesh_scan_enable(); - /* Enable unprovisioned beacon sending */ - bt_mesh_beacon_enable(); - } + if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && + (bearers & BT_MESH_PROV_ADV)) { + /* Make sure we're scanning for provisioning inviations */ + bt_mesh_scan_enable(); + /* Enable unprovisioned beacon sending */ + bt_mesh_beacon_enable(); + } - if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && - (bearers & BT_MESH_PROV_GATT)) { - bt_mesh_proxy_prov_enable(); - bt_mesh_adv_update(); - } + if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && + (bearers & BT_MESH_PROV_GATT)) { + bt_mesh_proxy_prov_enable(); + bt_mesh_adv_update(); + } - return 0; + return 0; } int bt_mesh_prov_disable(bt_mesh_prov_bearer_t bearers) { - if (bt_mesh_is_provisioned()) { - return -EALREADY; - } + if (bt_mesh_is_provisioned()) { + return -EALREADY; + } - if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && - (bearers & BT_MESH_PROV_ADV)) { - bt_mesh_beacon_disable(); - bt_mesh_scan_disable(); - } + if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && + (bearers & BT_MESH_PROV_ADV)) { + bt_mesh_beacon_disable(); + bt_mesh_scan_disable(); + } - if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && - (bearers & BT_MESH_PROV_GATT)) { - bt_mesh_proxy_prov_disable(true); - } + if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && + (bearers & BT_MESH_PROV_GATT)) { + bt_mesh_proxy_prov_disable(true); + } - return 0; + return 0; } static void model_suspend(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, - bool vnd, bool primary, void *user_data) + bool vnd, bool primary, void *user_data) { - if (mod->pub && mod->pub->update) { - mod->pub->count = 0U; - k_delayed_work_cancel(&mod->pub->timer); - } + if (mod->pub && mod->pub->update) { + mod->pub->count = 0U; + k_delayed_work_cancel(&mod->pub->timer); + } } int bt_mesh_suspend(void) { - int err; + int err; - if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { - return -EINVAL; - } + if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { + return -EINVAL; + } - if (atomic_test_and_set_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) { - return -EALREADY; - } + if (atomic_test_and_set_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) { + return -EALREADY; + } - err = bt_mesh_scan_disable(); - if (err) { - atomic_clear_bit(bt_mesh.flags, BT_MESH_SUSPENDED); - BT_WARN("Disabling scanning failed (err %d)", err); - return err; - } + err = bt_mesh_scan_disable(); + if (err) { + atomic_clear_bit(bt_mesh.flags, BT_MESH_SUSPENDED); + BT_WARN("Disabling scanning failed (err %d)", err); + return err; + } - bt_mesh_hb_pub_disable(); + bt_mesh_hb_pub_disable(); - if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) { - bt_mesh_beacon_disable(); - } + if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) { + bt_mesh_beacon_disable(); + } - bt_mesh_model_foreach(model_suspend, NULL); + bt_mesh_model_foreach(model_suspend, NULL); - return 0; + return 0; } static void model_resume(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, - bool vnd, bool primary, void *user_data) + bool vnd, bool primary, void *user_data) { - if (mod->pub && mod->pub->update) { - s32_t period_ms = bt_mesh_model_pub_period_get(mod); + if (mod->pub && mod->pub->update) { + s32_t period_ms = bt_mesh_model_pub_period_get(mod); - if (period_ms) { - k_delayed_work_submit(&mod->pub->timer, period_ms); - } - } + if (period_ms) { + k_delayed_work_submit(&mod->pub->timer, period_ms); + } + } } int bt_mesh_resume(void) { - int err; + int err; - if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { - return -EINVAL; - } + if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { + return -EINVAL; + } - if (!atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) { - return -EALREADY; - } + if (!atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) { + return -EALREADY; + } - err = bt_mesh_scan_enable(); - if (err) { - BT_WARN("Re-enabling scanning failed (err %d)", err); - atomic_set_bit(bt_mesh.flags, BT_MESH_SUSPENDED); - return err; - } + err = bt_mesh_scan_enable(); + if (err) { + BT_WARN("Re-enabling scanning failed (err %d)", err); + atomic_set_bit(bt_mesh.flags, BT_MESH_SUSPENDED); + return err; + } - if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) { - bt_mesh_beacon_enable(); - } + if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) { + bt_mesh_beacon_enable(); + } - bt_mesh_model_foreach(model_resume, NULL); + bt_mesh_model_foreach(model_resume, NULL); - return err; + return err; } int bt_mesh_init(const struct bt_mesh_prov *prov, - const struct bt_mesh_comp *comp) + const struct bt_mesh_comp *comp) { - int err; + int err; - err = bt_mesh_test(); - if (err) { - return err; - } + err = bt_mesh_test(); + if (err) { + return err; + } - err = bt_mesh_comp_register(comp); - if (err) { - return err; - } + err = bt_mesh_comp_register(comp); + if (err) { + return err; + } - if (IS_ENABLED(CONFIG_BT_MESH_PROV)) { - err = bt_mesh_prov_init(prov); - if (err) { - return err; - } - } + if (IS_ENABLED(CONFIG_BT_MESH_PROV)) { + err = bt_mesh_prov_init(prov); + if (err) { + return err; + } + } - bt_mesh_net_init(); - bt_mesh_trans_init(); - bt_mesh_beacon_init(); - bt_mesh_adv_init(); + bt_mesh_net_init(); + bt_mesh_trans_init(); + bt_mesh_beacon_init(); + bt_mesh_adv_init(); - if (IS_ENABLED(CONFIG_BT_MESH_PROXY)) { - bt_mesh_proxy_init(); - } + if (IS_ENABLED(CONFIG_BT_MESH_PROXY)) { + bt_mesh_proxy_init(); + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_settings_init(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_settings_init(); + } - return 0; + return 0; } diff --git a/components/network/ble/blemesh/src/mesh_cli_cmds/mesh_cli_cmds.c b/components/network/ble/blemesh/src/mesh_cli_cmds/mesh_cli_cmds.c index b07edb21..ab2ec8ef 100644 --- a/components/network/ble/blemesh/src/mesh_cli_cmds/mesh_cli_cmds.c +++ b/components/network/ble/blemesh/src/mesh_cli_cmds/mesh_cli_cmds.c @@ -55,13 +55,13 @@ static u8_t cur_faults[CUR_FAULTS_MAX]; static u8_t reg_faults[CUR_FAULTS_MAX * 2]; static struct { - u16_t local; - u16_t dst; - u16_t net_idx; - u16_t app_idx; + u16_t local; + u16_t dst; + u16_t net_idx; + u16_t app_idx; } net = { - .local = BT_MESH_ADDR_UNASSIGNED, - .dst = BT_MESH_ADDR_UNASSIGNED, + .local = BT_MESH_ADDR_UNASSIGNED, + .dst = BT_MESH_ADDR_UNASSIGNED, }; #if defined(BL602) || defined(BL702) @@ -82,11 +82,11 @@ static void prov_reset(void); static int input(bt_mesh_input_action_t act, u8_t size); static void get_faults(u8_t *faults, u8_t faults_size, u8_t *dst, u8_t *count); static void health_current_status(struct bt_mesh_health_cli *cli, u16_t addr, - u8_t test_id, u16_t cid, u8_t *faults, size_t fault_count); + u8_t test_id, u16_t cid, u8_t *faults, size_t fault_count); static int fault_get_cur(struct bt_mesh_model *model, u8_t *test_id, - u16_t *company_id, u8_t *faults, u8_t *fault_count); + u16_t *company_id, u8_t *faults, u8_t *fault_count); static int fault_get_reg(struct bt_mesh_model *model, u16_t cid, - u8_t *test_id, u8_t *faults, u8_t *fault_count); + u8_t *test_id, u8_t *faults, u8_t *fault_count); static int fault_clear(struct bt_mesh_model *model, uint16_t cid); static int fault_test(struct bt_mesh_model *model, uint8_t test_id, uint16_t cid); static void attn_on(struct bt_mesh_model *model); @@ -120,39 +120,39 @@ static void blemesh_lpn_set(char *pcWriteBuffer, int xWriteBufferLen, int argc, #endif static struct bt_mesh_prov prov = { - .uuid = dev_uuid, + .uuid = dev_uuid, .oob_info = 0, - .link_open = link_open, - .link_close = link_close, - .complete = prov_complete, - .reset = prov_reset, - .static_val = auth_value, - .static_val_len = 16, - .output_size = 6, - .output_actions = (BT_MESH_DISPLAY_NUMBER | BT_MESH_DISPLAY_STRING), - .output_number = output_number, - .output_string = output_string, - .input_size = 6, - .input_actions = (BT_MESH_ENTER_NUMBER | BT_MESH_ENTER_STRING), - .input = input, - .input_complete = prov_input_complete, + .link_open = link_open, + .link_close = link_close, + .complete = prov_complete, + .reset = prov_reset, + .static_val = auth_value, + .static_val_len = 16, + .output_size = 6, + .output_actions = (BT_MESH_DISPLAY_NUMBER | BT_MESH_DISPLAY_STRING), + .output_number = output_number, + .output_string = output_string, + .input_size = 6, + .input_actions = (BT_MESH_ENTER_NUMBER | BT_MESH_ENTER_STRING), + .input = input, + .input_complete = prov_input_complete, }; static const struct bt_mesh_health_srv_cb health_srv_cb = { - .fault_get_cur = fault_get_cur, - .fault_get_reg = fault_get_reg, - .fault_clear = fault_clear, - .fault_test = fault_test, - .attn_on = attn_on, - .attn_off = attn_off, + .fault_get_cur = fault_get_cur, + .fault_get_reg = fault_get_reg, + .fault_clear = fault_clear, + .fault_test = fault_test, + .attn_on = attn_on, + .attn_off = attn_off, }; static struct bt_mesh_health_srv health_srv = { - .cb = &health_srv_cb, + .cb = &health_srv_cb, }; static struct bt_mesh_health_cli health_cli = { - .current_status = health_current_status, + .current_status = health_current_status, }; BT_MESH_HEALTH_PUB_DEFINE(health_pub, CUR_FAULTS_MAX); @@ -161,25 +161,25 @@ static struct bt_mesh_cfg_cli cfg_cli = { }; static struct bt_mesh_cfg_srv cfg_srv = { - .relay = BT_MESH_RELAY_ENABLED, - .beacon = BT_MESH_BEACON_ENABLED,//BT_MESH_BEACON_DISABLED, + .relay = BT_MESH_RELAY_ENABLED, + .beacon = BT_MESH_BEACON_ENABLED,//BT_MESH_BEACON_DISABLED, #if defined(CONFIG_BT_MESH_FRIEND) - .frnd = BT_MESH_FRIEND_DISABLED, + .frnd = BT_MESH_FRIEND_DISABLED, #else - .frnd = BT_MESH_FRIEND_NOT_SUPPORTED, + .frnd = BT_MESH_FRIEND_NOT_SUPPORTED, #endif #if defined(CONFIG_BT_MESH_GATT_PROXY) - .gatt_proxy = BT_MESH_GATT_PROXY_ENABLED, + .gatt_proxy = BT_MESH_GATT_PROXY_ENABLED, #else - .gatt_proxy = BT_MESH_GATT_PROXY_NOT_SUPPORTED, + .gatt_proxy = BT_MESH_GATT_PROXY_NOT_SUPPORTED, #endif - .default_ttl = 7, + .default_ttl = 7, - /* 6 transmissions with 20ms interval */ - .net_transmit = BT_MESH_TRANSMIT(5, 20), - /* 3 transmissions with 20ms interval */ - .relay_retransmit = BT_MESH_TRANSMIT(2, 20), + /* 6 transmissions with 20ms interval */ + .net_transmit = BT_MESH_TRANSMIT(5, 20), + /* 3 transmissions with 20ms interval */ + .relay_retransmit = BT_MESH_TRANSMIT(2, 20), }; #if defined(CONFIG_BT_MESH_MODEL) @@ -211,14 +211,14 @@ static bfl_ble_mesh_light_lightness_srv_t lightness_server = { BFL_BLE_MESH_MODEL_PUB_DEFINE(lightness_cli_pub, 2 + 1, ROLE_NODE); static bfl_ble_mesh_client_t lightness_client; #endif - + #if defined(CONFIG_BT_MESH_MODEL_LIGHT_SRV) BFL_BLE_MESH_MODEL_PUB_DEFINE(ctl_pub, 2 + 3, ROLE_NODE); static bfl_ble_mesh_light_ctl_state_t ctl_state; static bfl_ble_mesh_light_ctl_srv_t ctl_server = { - .rsp_ctrl.get_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, - .rsp_ctrl.set_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, - .state = &ctl_state, + .rsp_ctrl.get_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, + .rsp_ctrl.set_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, + .state = &ctl_state, }; #endif @@ -231,9 +231,9 @@ static bfl_ble_mesh_client_t ctl_client; BFL_BLE_MESH_MODEL_PUB_DEFINE(hsl_pub, 2 + 3, ROLE_NODE); static bfl_ble_mesh_light_hsl_state_t hsl_state; static bfl_ble_mesh_light_hsl_srv_t hsl_server = { - .rsp_ctrl.get_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, - .rsp_ctrl.set_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, - .state = &hsl_state, + .rsp_ctrl.get_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, + .rsp_ctrl.set_auto_rsp = BFL_BLE_MESH_SERVER_AUTO_RSP, + .state = &hsl_state, }; #endif @@ -250,45 +250,45 @@ struct bt_mesh_gen_onoff_srv onoff_srv = { #endif /* CONFIG_BT_MESH_MODEL */ static struct bt_mesh_model sig_models[] = { - BT_MESH_MODEL_CFG_SRV(&cfg_srv), - BT_MESH_MODEL_CFG_CLI(&cfg_cli), - BT_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), - BT_MESH_MODEL_HEALTH_CLI(&health_cli), + BT_MESH_MODEL_CFG_SRV(&cfg_srv), + BT_MESH_MODEL_CFG_CLI(&cfg_cli), + BT_MESH_MODEL_HEALTH_SRV(&health_srv, &health_pub), + BT_MESH_MODEL_HEALTH_CLI(&health_cli), #if !defined(CONFIG_BT_MESH_MODEL) - #if defined(CONFIG_BT_MESH_MODEL_GEN_SRV) - BT_MESH_MODEL_GEN_ONOFF(&onoff_srv), - #endif + #if defined(CONFIG_BT_MESH_MODEL_GEN_SRV) + BT_MESH_MODEL_GEN_ONOFF(&onoff_srv), + #endif #else - #if defined(CONFIG_BT_MESH_MODEL_GEN_SRV) - BFL_BLE_MESH_MODEL_GEN_ONOFF_SRV(&onoff_pub, &onoff_server), - #endif - #if defined(CONFIG_BT_MESH_MODEL_GEN_CLI) - BFL_BLE_MESH_MODEL_GEN_ONOFF_CLI(&onoff_cli_pub, &onoff_client), - #endif - #if defined(CONFIG_BT_MESH_MODEL_LIGHT_SRV) - BFL_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SRV(&lightness_pub, &lightness_server), + #if defined(CONFIG_BT_MESH_MODEL_GEN_SRV) + BFL_BLE_MESH_MODEL_GEN_ONOFF_SRV(&onoff_pub, &onoff_server), #endif - #if defined(CONFIG_BT_MESH_MODEL_LIGHT_CLI) - BFL_BLE_MESH_MODEL_LIGHT_LIGHTNESS_CLI(&lightness_cli_pub, &lightness_client), + #if defined(CONFIG_BT_MESH_MODEL_GEN_CLI) + BFL_BLE_MESH_MODEL_GEN_ONOFF_CLI(&onoff_cli_pub, &onoff_client), #endif #if defined(CONFIG_BT_MESH_MODEL_LIGHT_SRV) - BFL_BLE_MESH_MODEL_LIGHT_CTL_SRV(&ctl_pub, &ctl_server), + BFL_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SRV(&lightness_pub, &lightness_server), #endif #if defined(CONFIG_BT_MESH_MODEL_LIGHT_CLI) - BFL_BLE_MESH_MODEL_LIGHT_CTL_CLI(&ctl_cli_pub, &ctl_client), + BFL_BLE_MESH_MODEL_LIGHT_LIGHTNESS_CLI(&lightness_cli_pub, &lightness_client), #endif #if defined(CONFIG_BT_MESH_MODEL_LIGHT_SRV) - BFL_BLE_MESH_MODEL_LIGHT_HSL_SRV(&hsl_pub, &hsl_server), + BFL_BLE_MESH_MODEL_LIGHT_CTL_SRV(&ctl_pub, &ctl_server), #endif #if defined(CONFIG_BT_MESH_MODEL_LIGHT_CLI) - BFL_BLE_MESH_MODEL_LIGHT_HSL_CLI(&hsl_cli_pub, &hsl_client), + BFL_BLE_MESH_MODEL_LIGHT_CTL_CLI(&ctl_cli_pub, &ctl_client), + #endif + #if defined(CONFIG_BT_MESH_MODEL_LIGHT_SRV) + BFL_BLE_MESH_MODEL_LIGHT_HSL_SRV(&hsl_pub, &hsl_server), + #endif + #if defined(CONFIG_BT_MESH_MODEL_LIGHT_CLI) + BFL_BLE_MESH_MODEL_LIGHT_HSL_CLI(&hsl_cli_pub, &hsl_client), #endif #endif /* CONFIG_BT_MESH_MODEL */ }; #define VENDOR_DATA_LEN (BT_MESH_TX_SDU_MAX-4-3) struct vendor_data_t{ - uint8_t data[VENDOR_DATA_LEN]; + uint8_t data[VENDOR_DATA_LEN]; }vendor_data; static void vendor_data_set(struct bt_mesh_model *model, @@ -304,7 +304,7 @@ static void vendor_data_set(struct bt_mesh_model *model, return; } bt_mesh_model_msg_init(&msg, 0xC2003F); - net_buf_simple_add_mem(&msg, buf->data, buf->len); + net_buf_simple_add_mem(&msg, buf->data, buf->len); bt_mesh_model_send(model, ctx, &msg, NULL, NULL); } @@ -316,17 +316,17 @@ const struct bt_mesh_model_op vendor_data_op[] = { }; static struct bt_mesh_model vendor_models[] = { - BT_MESH_MODEL_VND(0x003F, 0x002A, vendor_data_op, NULL, &vendor_data), + BT_MESH_MODEL_VND(0x003F, 0x002A, vendor_data_op, NULL, &vendor_data), }; static struct bt_mesh_elem elements[] = { - BT_MESH_ELEM(0, sig_models, vendor_models), + BT_MESH_ELEM(0, sig_models, vendor_models), }; static const struct bt_mesh_comp comp = { - .cid = BL_COMP_ID, - .elem = elements, - .elem_count = ARRAY_SIZE(elements), + .cid = BL_COMP_ID, + .elem = elements, + .elem_count = ARRAY_SIZE(elements), }; #if defined(BL602) || defined(BL702) @@ -340,7 +340,7 @@ const struct cli_command btMeshCmdSet[] = { {"blemesh_pb", "\r\nblemesh_pb:[Enable or disable provisioning]\r\n\ [bear, 1:adv bear, 2:gatt bear]\r\n\ [enable, 0:disable provisioning, 1:enable provisioning]\r\n", blemesh_pb}, - + {"blemesh_reset", "\r\nblemesh_reset:[Reset the state of the local mesh node]\r\n Parameter[Null]\r\n", blemesh_reset}, {"blemesh_net_send", "\r\nblemesh_net_send:[Send a network packet]\r\n Parameter[TTL CTL SRC DST]\r\n", blemesh_net_send}, {"blemesh_seg_send", "\r\nblemesh_seg_send:[Send a segmented message]\r\n Parameter[SRC DST]\r\n", blemesh_seg_send}, @@ -358,12 +358,12 @@ const struct cli_command btMeshCmdSet[] = { #endif {"blemesh_input_num", "\r\nblemesh_input_num:[input number in provisionging procedure]\r\n\ [Max Size:16 Octets, e.g.112233445566778899AA]\r\n", blemesh_input_num}, - + {"blemesh_input_str", "\r\nblemesh_input_str:[input Alphanumeric in provisionging procedure]\r\n\ [Max Size:16 Characters, e.g.123ABC]\r\n", blemesh_input_str}, #if defined(CONFIG_BT_MESH_MODEL) #if defined(CONFIG_BT_MESH_MODEL_GEN_CLI) - {"blemesh_gen_oo_cli", "\r\blemesh_gen_oo_cli:[cmd op app_idx opcode msg_role addr net_idx op_en_t onoff tid trans_time delay]\r\n\ + {"blemesh_gen_oo_cli", "\r\blemesh_gen_oo_cli:[cmd op app_idx opcode msg_role addr net_idx op_en_t onoff tid trans_time delay]\r\n\ []\r\n", blemesh_gen_oo_cli}, #endif #if defined(CONFIG_BT_MESH_MODEL_LIGHT_CLI) @@ -390,20 +390,20 @@ static void blemesh_lpn_set(char *pcWriteBuffer, int xWriteBufferLen, int argc, get_uint8_from_string(&argv[1], &enable); - + if(enable){ if(lpn_enabled){ vOutputString("LPN already enabled\r\n"); return; } - + err = bt_mesh_lpn_set(true); if(err){ vOutputString("Failed to enable LPN\r\n"); }else{ lpn_enabled = true; vOutputString("Enable LPN successfully\r\n"); - } + } }else{ if(!lpn_enabled){ vOutputString("LPN already disabled\r\n"); @@ -422,11 +422,11 @@ static void blemesh_lpn_set(char *pcWriteBuffer, int xWriteBufferLen, int argc, static void lpn_cb(u16_t friend_addr, bool established) { - if (established) { - vOutputString("Friendship (as LPN) established to Friend 0x%04x\r\n", friend_addr); - } else { - vOutputString("Friendship (as LPN) lost with Friend 0x%04x\r\n", friend_addr); - } + if (established) { + vOutputString("Friendship (as LPN) established to Friend 0x%04x\r\n", friend_addr); + } else { + vOutputString("Friendship (as LPN) lost with Friend 0x%04x\r\n", friend_addr); + } } #endif @@ -446,7 +446,7 @@ static void blemesh_init(char *pcWriteBuffer, int xWriteBufferLen, int argc, cha vOutputString("Failed to init \r\n"); return; } - + blemesh_inited = true; vOutputString("Init successfully \r\n"); @@ -456,53 +456,53 @@ static void blemesh_init(char *pcWriteBuffer, int xWriteBufferLen, int argc, cha } if (bt_mesh_is_provisioned()) { - vOutputString("Mesh network restored from flash\r\n"); - } else { - vOutputString("Use pb-adv or pb-gatt to enable advertising\r\n"); - } + vOutputString("Mesh network restored from flash\r\n"); + } else { + vOutputString("Use pb-adv or pb-gatt to enable advertising\r\n"); + } #ifdef CONFIG_BT_MESH_PTS int i; - + // used for almost all test cases vOutputString("[PTS] TSPX_bd_addr_iut: "); for(i=0; i<6; i++) { vOutputString("%02X", bt_dev.id_addr[0].a.val[i]); } vOutputString("\r\n"); - + // used for almost all test cases vOutputString("[PTS] TSPX_device_uuid: "); for(i=0; i<16; i++) { vOutputString("%02X", dev_uuid[i]); } vOutputString("\r\n"); - + // used for test case MESH/NODE/RLY/BV-02-C vOutputString("[PTS] TSPX_maximum_network_message_cache_entries: %d\r\n", CONFIG_BT_MESH_MSG_CACHE_SIZE); - + // used for test case MESH/NODE/CFG/CFGR/BV-01-C vOutputString("[PTS] TSPX_iut_supports_relay: %s\r\n", cfg_srv.relay == BT_MESH_RELAY_ENABLED ? "TRUE" : "FALSE"); - + // used for test case MESH/NODE/CFG/SL/BV-03-C vOutputString("[PTS] TSPX_vendor_model_id: %04X%04X\r\n", vendor_models[0].vnd.company, vendor_models[0].vnd.id); #endif #if IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) - bt_mesh_lpn_set_cb(lpn_cb); + bt_mesh_lpn_set_cb(lpn_cb); #endif } static const char *bearer2str(bt_mesh_prov_bearer_t bearer) { - switch (bearer) { - case BT_MESH_PROV_ADV: - return "PB-ADV"; - case BT_MESH_PROV_GATT: - return "PB-GATT"; - default: - return "unknown"; - } + switch (bearer) { + case BT_MESH_PROV_ADV: + return "PB-ADV"; + case BT_MESH_PROV_GATT: + return "PB-GATT"; + default: + return "unknown"; + } } #if defined(CONFIG_BT_MESH_PROV) @@ -516,83 +516,83 @@ static void blemesh_pb(char *pcWriteBuffer, int xWriteBufferLen, int argc, char vOutputString("Number of Parameters is not correct\r\n"); return; } - + get_uint8_from_string(&argv[1], &bearer); get_uint8_from_string(&argv[2], &enable); - - if (enable) { - err = bt_mesh_prov_enable(bearer); - if (err) { - vOutputString("Failed to enable %s (err %d)\r\n", bearer2str(bearer), err); - } else { - vOutputString("%s enabled\r\n", bearer2str(bearer)); - } - } else { - err = bt_mesh_prov_disable(bearer); - if (err) { - vOutputString("Failed to disable %s (err %d)\r\n", - bearer2str(bearer), err); - } else { - vOutputString("%s disabled\r\n", bearer2str(bearer)); - } - } + + if (enable) { + err = bt_mesh_prov_enable(bearer); + if (err) { + vOutputString("Failed to enable %s (err %d)\r\n", bearer2str(bearer), err); + } else { + vOutputString("%s enabled\r\n", bearer2str(bearer)); + } + } else { + err = bt_mesh_prov_disable(bearer); + if (err) { + vOutputString("Failed to disable %s (err %d)\r\n", + bearer2str(bearer), err); + } else { + vOutputString("%s disabled\r\n", bearer2str(bearer)); + } + } } #endif static void link_open(bt_mesh_prov_bearer_t bearer) { - vOutputString("Provisioning link opened on %s\r\n", bearer2str(bearer)); + vOutputString("Provisioning link opened on %s\r\n", bearer2str(bearer)); } static void link_close(bt_mesh_prov_bearer_t bearer) { - vOutputString("Provisioning link closed on %s\r\n", bearer2str(bearer)); + vOutputString("Provisioning link closed on %s\r\n", bearer2str(bearer)); } static int output_number(bt_mesh_output_action_t action, u32_t number) { - vOutputString("OOB Number: %u\r\n", number); - return 0; + vOutputString("OOB Number: %u\r\n", number); + return 0; } static int output_string(const char *str) { - vOutputString("OOB String: %s\r\n", str); - return 0; + vOutputString("OOB String: %s\r\n", str); + return 0; } static void prov_input_complete(void) { - vOutputString("Input complete\r\n"); + vOutputString("Input complete\r\n"); } static void prov_complete(u16_t net_idx, u16_t addr) { - vOutputString("Local node provisioned, net_idx 0x%04x address 0x%04x\r\n", net_idx, addr); - net.net_idx = net_idx, - net.local = addr; - net.dst = addr; + vOutputString("Local node provisioned, net_idx 0x%04x address 0x%04x\r\n", net_idx, addr); + net.net_idx = net_idx, + net.local = addr; + net.dst = addr; } static void prov_reset(void) { - vOutputString("The local node has been reset and needs reprovisioning\r\n"); + vOutputString("The local node has been reset and needs reprovisioning\r\n"); } static void gen_dev_uuid(void) { //device uuid: 07af0000-1111-2222-3333-mac address(6 bytes) - bt_addr_le_t adv_addr; - bt_get_local_public_address(&adv_addr); - u8_t uuid[16] = {0x07,0xaf,0x00,0x00,0x11,0x11,0x22,0x22,0x33,0x33, - adv_addr.a.val[5], - adv_addr.a.val[4], - adv_addr.a.val[3], - adv_addr.a.val[2], - adv_addr.a.val[1], - adv_addr.a.val[0]}; - memcpy(dev_uuid, uuid, 16); + bt_addr_le_t adv_addr; + bt_get_local_public_address(&adv_addr); + u8_t uuid[16] = {0x07,0xaf,0x00,0x00,0x11,0x11,0x22,0x22,0x33,0x33, + adv_addr.a.val[5], + adv_addr.a.val[4], + adv_addr.a.val[3], + adv_addr.a.val[2], + adv_addr.a.val[1], + adv_addr.a.val[0]}; + memcpy(dev_uuid, uuid, 16); } @@ -609,61 +609,61 @@ static void blemesh_set_dev_uuid(char *pcWriteBuffer, int xWriteBufferLen, int a static void blemesh_input_num(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; + int err; uint32_t num; if(argc != 2){ vOutputString("Number of Parameters is not correct\r\n"); return; } - + num = strtoul(argv[1], NULL, 10); - if (input_act != BT_MESH_ENTER_NUMBER) { - vOutputString("A number hasn't been requested!\r\n"); - return; - } + if (input_act != BT_MESH_ENTER_NUMBER) { + vOutputString("A number hasn't been requested!\r\n"); + return; + } - if (strlen(argv[1]) < input_size) { - vOutputString("Too short input (%u digits required)\r\n", input_size); - return; - } + if (strlen(argv[1]) < input_size) { + vOutputString("Too short input (%u digits required)\r\n", input_size); + return; + } - err = bt_mesh_input_number(num); - if (err) { - vOutputString("Numeric input failed (err %d)\r\n", err); - return; - } + err = bt_mesh_input_number(num); + if (err) { + vOutputString("Numeric input failed (err %d)\r\n", err); + return; + } - input_act = BT_MESH_NO_INPUT; + input_act = BT_MESH_NO_INPUT; } static void blemesh_input_str(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; + int err; if(argc != 2){ vOutputString("Number of Parameters is not correct\r\n"); return; } - if (input_act != BT_MESH_ENTER_STRING) { - vOutputString("A string hasn't been requested!\r\n"); - return; - } + if (input_act != BT_MESH_ENTER_STRING) { + vOutputString("A string hasn't been requested!\r\n"); + return; + } - if (strlen(argv[1]) < input_size) { - vOutputString("Too short input (%u characters required)\r\n", input_size); - return; - } + if (strlen(argv[1]) < input_size) { + vOutputString("Too short input (%u characters required)\r\n", input_size); + return; + } - err = bt_mesh_input_string(argv[1]); - if (err) { - vOutputString("String input failed (err %d)\r\n", err); - return; - } + err = bt_mesh_input_string(argv[1]); + if (err) { + vOutputString("String input failed (err %d)\r\n", err); + return; + } - input_act = BT_MESH_NO_INPUT; + input_act = BT_MESH_NO_INPUT; } #if defined(CONFIG_BT_MESH_MODEL) @@ -735,7 +735,7 @@ void ble_mesh_generic_onoff_client_model_cb(bfl_ble_mesh_generic_client_cb_event static void blemesh_gen_oo_cli(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err = BFL_OK; + int err = BFL_OK; if(argc < 1){ vOutputString("Number of Parameters is not correct\r\n"); @@ -752,44 +752,44 @@ static void blemesh_gen_oo_cli(char *pcWriteBuffer, int xWriteBufferLen, int arg vOutputString("enter %s\n", __func__); - /*Get client model*/ - for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ - if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_GEN_ONOFF_CLI){ - onoff_common.model = &sig_models[i]; - } - } - if(onoff_common.model == NULL){ - vOutputString("Can't find gen onoff cli %s\n", __func__); - return; - } + /*Get client model*/ + for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ + if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_GEN_ONOFF_CLI){ + onoff_common.model = &sig_models[i]; + } + } + if(onoff_common.model == NULL){ + vOutputString("Can't find gen onoff cli %s\n", __func__); + return; + } - if(argc > 6){ - /* appkey_index */ - get_uint16_from_string(&argv[2], &onoff_common.ctx.app_idx); - /* opcode */ - get_uint32_from_string(&argv[3], &onoff_common.opcode); - /* role */ - get_uint8_from_string(&argv[4], &onoff_common.msg_role); - /* address */ - get_uint16_from_string(&argv[5], &onoff_common.ctx.addr); - /* network key index */ - get_uint16_from_string(&argv[6], &onoff_common.ctx.net_idx); - } - if(argc > 11){ - /* op_en */ - uint8_t op_en_t; - get_uint8_from_string(&argv[7], &op_en_t); - gen_client_set.onoff_set.op_en = op_en_t?true:false; + if(argc > 6){ + /* appkey_index */ + get_uint16_from_string(&argv[2], &onoff_common.ctx.app_idx); + /* opcode */ + get_uint32_from_string(&argv[3], &onoff_common.opcode); + /* role */ + get_uint8_from_string(&argv[4], &onoff_common.msg_role); + /* address */ + get_uint16_from_string(&argv[5], &onoff_common.ctx.addr); + /* network key index */ + get_uint16_from_string(&argv[6], &onoff_common.ctx.net_idx); + } + if(argc > 11){ + /* op_en */ + uint8_t op_en_t; + get_uint8_from_string(&argv[7], &op_en_t); + gen_client_set.onoff_set.op_en = op_en_t?true:false; - /* onoff */ - get_uint8_from_string(&argv[8], &gen_client_set.onoff_set.onoff); - /* tid */ - get_uint8_from_string(&argv[9], &gen_client_set.onoff_set.tid); - /* trans_time */ - get_uint8_from_string(&argv[10], &gen_client_set.onoff_set.trans_time); - /* delay */ - get_uint8_from_string(&argv[11], &gen_client_set.onoff_set.delay); - } + /* onoff */ + get_uint8_from_string(&argv[8], &gen_client_set.onoff_set.onoff); + /* tid */ + get_uint8_from_string(&argv[9], &gen_client_set.onoff_set.tid); + /* trans_time */ + get_uint8_from_string(&argv[10], &gen_client_set.onoff_set.trans_time); + /* delay */ + get_uint8_from_string(&argv[11], &gen_client_set.onoff_set.delay); + } if (strcmp(argv[1], "get") == 0) { err = bfl_ble_mesh_generic_client_get_state(&onoff_common, &gen_client_get); @@ -809,7 +809,7 @@ static void blemesh_gen_oo_cli(char *pcWriteBuffer, int xWriteBufferLen, int arg void ble_mesh_light_client_model_cb(bfl_ble_mesh_light_client_cb_event_t event, bfl_ble_mesh_light_client_cb_param_t *param) { - uint32_t opcode = param->params->opcode; + uint32_t opcode = param->params->opcode; vOutputString("enter %s: event is %d, error code is %d, opcode is 0x%x\n", __func__, event, param->error_code, opcode); @@ -820,29 +820,29 @@ void ble_mesh_light_client_model_cb(bfl_ble_mesh_light_client_cb_event_t event, case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET: if (param->error_code == BFL_OK) { vOutputString("Light lightness Client:GetStatus,OK, ln[%x]ln_t[%x]\n" - , param->status_cb.lightness_status.present_lightness - , param->status_cb.lightness_status.target_lightness); + , param->status_cb.lightness_status.present_lightness + , param->status_cb.lightness_status.target_lightness); } else { vOutputString("Light lightness Client:GetStatus,Fail[%x]\n", param->error_code); } break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_GET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_GET: if (param->error_code == BFL_OK) { vOutputString("Light ctl Client:GetStatus,OK,ln[%x]ln_t[%x] tp[%x]tp_t[%x]\n", - param->status_cb.ctl_status.present_ctl_lightness, - param->status_cb.ctl_status.target_ctl_lightness, - param->status_cb.ctl_status.present_ctl_temperature, - param->status_cb.ctl_status.target_ctl_temperature); + param->status_cb.ctl_status.present_ctl_lightness, + param->status_cb.ctl_status.target_ctl_lightness, + param->status_cb.ctl_status.present_ctl_temperature, + param->status_cb.ctl_status.target_ctl_temperature); } else { vOutputString("Light ctl Client:GetStatus,Fail[%x]\n", param->error_code); } break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_GET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_GET: if (param->error_code == BFL_OK) { vOutputString("Light hsl Client:GetStatus,OK,l[%x] h[%x] s[%x]\n", - param->status_cb.hsl_status.hsl_lightness, - param->status_cb.hsl_status.hsl_hue, - param->status_cb.hsl_status.hsl_saturation); + param->status_cb.hsl_status.hsl_lightness, + param->status_cb.hsl_status.hsl_hue, + param->status_cb.hsl_status.hsl_saturation); } else { vOutputString("Light hsl Client:GetStatus,Fail[%x]\n", param->error_code); } @@ -857,8 +857,8 @@ void ble_mesh_light_client_model_cb(bfl_ble_mesh_light_client_cb_event_t event, case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET: if (param->error_code == BFL_OK) { vOutputString("Light lightness Client:SetStatus,OK, ln[%x]ln_t[%x]\n" - , param->status_cb.lightness_status.present_lightness - , param->status_cb.lightness_status.target_lightness); + , param->status_cb.lightness_status.present_lightness + , param->status_cb.lightness_status.target_lightness); } else { vOutputString("Light lightness Client:SetStatus,Fail[%x]\n", param->error_code); } @@ -870,13 +870,13 @@ void ble_mesh_light_client_model_cb(bfl_ble_mesh_light_client_cb_event_t event, vOutputString("Light lightness Client:SetUNACK,Fail[%x]\n", param->error_code); } break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_SET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_SET: if (param->error_code == BFL_OK) { - vOutputString("Light ctl Client:SetStatus,OK, ln[%x]ln_t[%x] tp[%x]tp_t[%x]\n", - param->status_cb.ctl_status.present_ctl_lightness, - param->status_cb.ctl_status.target_ctl_lightness, - param->status_cb.ctl_status.present_ctl_temperature, - param->status_cb.ctl_status.target_ctl_temperature); + vOutputString("Light ctl Client:SetStatus,OK, ln[%x]ln_t[%x] tp[%x]tp_t[%x]\n", + param->status_cb.ctl_status.present_ctl_lightness, + param->status_cb.ctl_status.target_ctl_lightness, + param->status_cb.ctl_status.present_ctl_temperature, + param->status_cb.ctl_status.target_ctl_temperature); } else { vOutputString("Light ctl Client:SetStatus,Fail[%x]\n", param->error_code); } @@ -888,12 +888,12 @@ void ble_mesh_light_client_model_cb(bfl_ble_mesh_light_client_cb_event_t event, vOutputString("Light ctl Client:SetUNACK,Fail[%x]\n", param->error_code); } break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_SET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_SET: if (param->error_code == BFL_OK) { - vOutputString("Light hsl Client:SetStatus,OK, l[%x] h[%x] s[%x]\n", - param->status_cb.hsl_status.hsl_lightness, - param->status_cb.hsl_status.hsl_hue, - param->status_cb.hsl_status.hsl_saturation); + vOutputString("Light hsl Client:SetStatus,OK, l[%x] h[%x] s[%x]\n", + param->status_cb.hsl_status.hsl_lightness, + param->status_cb.hsl_status.hsl_hue, + param->status_cb.hsl_status.hsl_saturation); } else { vOutputString("Light ctl Client:SetStatus,Fail[%x]\n", param->error_code); } @@ -911,53 +911,53 @@ void ble_mesh_light_client_model_cb(bfl_ble_mesh_light_client_cb_event_t event, break; } case BFL_BLE_MESH_LIGHT_CLIENT_PUBLISH_EVT: { - switch (opcode) { + switch (opcode) { case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET: - if (param->error_code == BFL_OK) { - vOutputString("Light lightness Client:Publish,OK\n"); - } else { - vOutputString("Light lightness Client:Publish,Fail[%x]\n", param->error_code); - } - break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_GET: - if (param->error_code == BFL_OK) { - vOutputString("Light ctl Client:Publish,OK\n"); - } else { - vOutputString("Light ctl Client:Publish,Fail[%x]\n", param->error_code); - } - break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_GET: - if (param->error_code == BFL_OK) { - vOutputString("Light hsl Client:Publish,OK\n"); - } else { - vOutputString("Light hsl Client:Publish,Fail[%x]\n", param->error_code); - } - break; - default: - break; - } - break; + if (param->error_code == BFL_OK) { + vOutputString("Light lightness Client:Publish,OK\n"); + } else { + vOutputString("Light lightness Client:Publish,Fail[%x]\n", param->error_code); + } + break; + case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_GET: + if (param->error_code == BFL_OK) { + vOutputString("Light ctl Client:Publish,OK\n"); + } else { + vOutputString("Light ctl Client:Publish,Fail[%x]\n", param->error_code); + } + break; + case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_GET: + if (param->error_code == BFL_OK) { + vOutputString("Light hsl Client:Publish,OK\n"); + } else { + vOutputString("Light hsl Client:Publish,Fail[%x]\n", param->error_code); + } + break; + default: + break; + } + break; } case BFL_BLE_MESH_LIGHT_CLIENT_TIMEOUT_EVT:{ - switch (opcode) { + switch (opcode) { case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET: - case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET: - case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK: - vOutputString("Light lightness Client:TimeOut[%x]\n", param->error_code); - break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_GET: - case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_SET: - case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK: - vOutputString("Light ctl Client:TimeOut[%x]\n", param->error_code); - break; - case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_GET: - case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_SET: - case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK: - vOutputString("Light hsl Client:TimeOut[%x]\n", param->error_code); - break; - default: - break; - } + case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK: + vOutputString("Light lightness Client:TimeOut[%x]\n", param->error_code); + break; + case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_GET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_SET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK: + vOutputString("Light ctl Client:TimeOut[%x]\n", param->error_code); + break; + case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_GET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_SET: + case BFL_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK: + vOutputString("Light hsl Client:TimeOut[%x]\n", param->error_code); + break; + default: + break; + } break; } case BFL_BLE_MESH_LIGHT_CLIENT_EVT_MAX:{ @@ -972,7 +972,7 @@ void ble_mesh_light_client_model_cb(bfl_ble_mesh_light_client_cb_event_t event, static void blemesh_light_lgn_cli(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err = BFL_OK; + int err = BFL_OK; if(argc < 1){ vOutputString("Number of Parameters is not correct\r\n"); @@ -989,44 +989,44 @@ static void blemesh_light_lgn_cli(char *pcWriteBuffer, int xWriteBufferLen, int vOutputString("enter %s\n", __func__); - /*Get client model*/ - for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ - if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI){ - lgn_common.model = &sig_models[i]; - } - } - if(lgn_common.model == NULL){ - vOutputString("Can't find light ligntness cli %s\n", __func__); - return; - } + /*Get client model*/ + for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ + if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI){ + lgn_common.model = &sig_models[i]; + } + } + if(lgn_common.model == NULL){ + vOutputString("Can't find light ligntness cli %s\n", __func__); + return; + } - if(argc > 6){ - /* appkey_index */ - get_uint16_from_string(&argv[2], &lgn_common.ctx.app_idx); - /* opcode */ - get_uint32_from_string(&argv[3], &lgn_common.opcode); - /* role */ - get_uint8_from_string(&argv[4], &lgn_common.msg_role); - /* address */ - get_uint16_from_string(&argv[5], &lgn_common.ctx.addr); - /* network key index */ - get_uint16_from_string(&argv[6], &lgn_common.ctx.net_idx); - } - if(argc > 11){ - /* op_en */ - uint8_t op_en_t; - get_uint8_from_string(&argv[7], &op_en_t); - light_client_set.lightness_set.op_en = op_en_t?true:false; + if(argc > 6){ + /* appkey_index */ + get_uint16_from_string(&argv[2], &lgn_common.ctx.app_idx); + /* opcode */ + get_uint32_from_string(&argv[3], &lgn_common.opcode); + /* role */ + get_uint8_from_string(&argv[4], &lgn_common.msg_role); + /* address */ + get_uint16_from_string(&argv[5], &lgn_common.ctx.addr); + /* network key index */ + get_uint16_from_string(&argv[6], &lgn_common.ctx.net_idx); + } + if(argc > 11){ + /* op_en */ + uint8_t op_en_t; + get_uint8_from_string(&argv[7], &op_en_t); + light_client_set.lightness_set.op_en = op_en_t?true:false; - /* lightness */ - get_uint16_from_string(&argv[8], &light_client_set.lightness_set.lightness); - /* tid */ - get_uint8_from_string(&argv[9], &light_client_set.lightness_set.tid); - /* trans_time */ - get_uint8_from_string(&argv[10], &light_client_set.lightness_set.trans_time); - /* delay */ - get_uint8_from_string(&argv[11], &light_client_set.lightness_set.delay); - } + /* lightness */ + get_uint16_from_string(&argv[8], &light_client_set.lightness_set.lightness); + /* tid */ + get_uint8_from_string(&argv[9], &light_client_set.lightness_set.tid); + /* trans_time */ + get_uint8_from_string(&argv[10], &light_client_set.lightness_set.trans_time); + /* delay */ + get_uint8_from_string(&argv[11], &light_client_set.lightness_set.delay); + } if (strcmp(argv[1], "get") == 0) { err = bfl_ble_mesh_light_client_get_state(&lgn_common, &light_client_get); @@ -1043,177 +1043,177 @@ static void blemesh_light_lgn_cli(char *pcWriteBuffer, int xWriteBufferLen, int static void blemesh_light_ctl_cli(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err = BFL_OK; + int err = BFL_OK; - if(argc < 1){ - vOutputString("Number of Parameters is not correct\r\n"); - return; - } + if(argc < 1){ + vOutputString("Number of Parameters is not correct\r\n"); + return; + } - bfl_ble_mesh_light_client_set_state_t light_client_set; - bfl_ble_mesh_light_client_get_state_t light_client_get; - bfl_ble_mesh_client_common_param_t ctl_common = { - .msg_timeout = 0, - .ctx.send_ttl = 7, - .model = NULL, - }; + bfl_ble_mesh_light_client_set_state_t light_client_set; + bfl_ble_mesh_light_client_get_state_t light_client_get; + bfl_ble_mesh_client_common_param_t ctl_common = { + .msg_timeout = 0, + .ctx.send_ttl = 7, + .model = NULL, + }; - vOutputString("enter %s\n", __func__); + vOutputString("enter %s\n", __func__); - /*Get client model*/ - for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ - if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_LIGHT_CTL_CLI){ - ctl_common.model = &sig_models[i]; - } - } - if(ctl_common.model == NULL){ - vOutputString("Can't find light ctl cli %s\n", __func__); - return; - } + /*Get client model*/ + for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ + if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_LIGHT_CTL_CLI){ + ctl_common.model = &sig_models[i]; + } + } + if(ctl_common.model == NULL){ + vOutputString("Can't find light ctl cli %s\n", __func__); + return; + } - if(argc > 6){ - /* appkey_index */ - get_uint16_from_string(&argv[2], &ctl_common.ctx.app_idx); - /* opcode */ - get_uint32_from_string(&argv[3], &ctl_common.opcode); - /* role */ - get_uint8_from_string(&argv[4], &ctl_common.msg_role); - /* address */ - get_uint16_from_string(&argv[5], &ctl_common.ctx.addr); - /* network key index */ - get_uint16_from_string(&argv[6], &ctl_common.ctx.net_idx); - } - if(argc > 13){ - /* op_en */ - uint8_t op_en_t; - get_uint8_from_string(&argv[7], &op_en_t); - light_client_set.ctl_set.op_en = op_en_t?true:false; + if(argc > 6){ + /* appkey_index */ + get_uint16_from_string(&argv[2], &ctl_common.ctx.app_idx); + /* opcode */ + get_uint32_from_string(&argv[3], &ctl_common.opcode); + /* role */ + get_uint8_from_string(&argv[4], &ctl_common.msg_role); + /* address */ + get_uint16_from_string(&argv[5], &ctl_common.ctx.addr); + /* network key index */ + get_uint16_from_string(&argv[6], &ctl_common.ctx.net_idx); + } + if(argc > 13){ + /* op_en */ + uint8_t op_en_t; + get_uint8_from_string(&argv[7], &op_en_t); + light_client_set.ctl_set.op_en = op_en_t?true:false; - /* onoff */ - get_uint16_from_string(&argv[8], &light_client_set.ctl_set.ctl_lightness); + /* onoff */ + get_uint16_from_string(&argv[8], &light_client_set.ctl_set.ctl_lightness); - get_uint16_from_string(&argv[9], &light_client_set.ctl_set.ctl_temperatrue); + get_uint16_from_string(&argv[9], &light_client_set.ctl_set.ctl_temperatrue); - get_uint16_from_string(&argv[10], (uint16_t*)&light_client_set.ctl_set.ctl_delta_uv); - /* tid */ - get_uint8_from_string(&argv[11], &light_client_set.ctl_set.tid); - /* trans_time */ - get_uint8_from_string(&argv[12], &light_client_set.ctl_set.trans_time); - /* delay */ - get_uint8_from_string(&argv[13], &light_client_set.ctl_set.delay); - } + get_uint16_from_string(&argv[10], (uint16_t*)&light_client_set.ctl_set.ctl_delta_uv); + /* tid */ + get_uint8_from_string(&argv[11], &light_client_set.ctl_set.tid); + /* trans_time */ + get_uint8_from_string(&argv[12], &light_client_set.ctl_set.trans_time); + /* delay */ + get_uint8_from_string(&argv[13], &light_client_set.ctl_set.delay); + } - if (strcmp(argv[1], "get") == 0) { - err = bfl_ble_mesh_light_client_get_state(&ctl_common, &light_client_get); - } else if (strcmp(argv[1], "set") == 0) { - err = bfl_ble_mesh_light_client_set_state(&ctl_common, &light_client_set); - } else if (strcmp(argv[1], "reg") == 0) { - err = bfl_ble_mesh_register_light_client_callback(ble_mesh_light_client_model_cb); - if (err == BFL_OK) { - vOutputString("Light lightness client:Reg,OK\n"); - } - } - vOutputString("exit %s\n", __func__); + if (strcmp(argv[1], "get") == 0) { + err = bfl_ble_mesh_light_client_get_state(&ctl_common, &light_client_get); + } else if (strcmp(argv[1], "set") == 0) { + err = bfl_ble_mesh_light_client_set_state(&ctl_common, &light_client_set); + } else if (strcmp(argv[1], "reg") == 0) { + err = bfl_ble_mesh_register_light_client_callback(ble_mesh_light_client_model_cb); + if (err == BFL_OK) { + vOutputString("Light lightness client:Reg,OK\n"); + } + } + vOutputString("exit %s\n", __func__); } static void blemesh_light_hsl_cli(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err = BFL_OK; + int err = BFL_OK; - if(argc < 1){ - vOutputString("Number of Parameters is not correct\n"); - return; - } + if(argc < 1){ + vOutputString("Number of Parameters is not correct\n"); + return; + } - bfl_ble_mesh_light_client_set_state_t light_client_set; - bfl_ble_mesh_light_client_get_state_t light_client_get; - bfl_ble_mesh_client_common_param_t hsl_common = { - .msg_timeout = 0, - .ctx.send_ttl = 7, - .model = NULL, - }; + bfl_ble_mesh_light_client_set_state_t light_client_set; + bfl_ble_mesh_light_client_get_state_t light_client_get; + bfl_ble_mesh_client_common_param_t hsl_common = { + .msg_timeout = 0, + .ctx.send_ttl = 7, + .model = NULL, + }; - vOutputString("enter %s\n", __func__); + vOutputString("enter %s\n", __func__); - /*Get client model*/ - for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ - if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_LIGHT_HSL_CLI){ - hsl_common.model = &sig_models[i]; - } - } - if(hsl_common.model == NULL){ - vOutputString("Can't find light ligntness cli %s\n", __func__); - return; - } + /*Get client model*/ + for(int i = 0; i < sizeof(sig_models)/sizeof(struct bt_mesh_model); ++i){ + if(sig_models[i].id == BFL_BLE_MESH_MODEL_ID_LIGHT_HSL_CLI){ + hsl_common.model = &sig_models[i]; + } + } + if(hsl_common.model == NULL){ + vOutputString("Can't find light ligntness cli %s\n", __func__); + return; + } - if(argc > 6){ - /* appkey_index */ - get_uint16_from_string(&argv[2], &hsl_common.ctx.app_idx); - /* opcode */ - get_uint32_from_string(&argv[3], &hsl_common.opcode); - /* role */ - get_uint8_from_string(&argv[4], &hsl_common.msg_role); - /* address */ - get_uint16_from_string(&argv[5], &hsl_common.ctx.addr); - /* network key index */ - get_uint16_from_string(&argv[6], &hsl_common.ctx.net_idx); - } - if(argc > 13){ - /* op_en */ - uint8_t op_en_t; - get_uint8_from_string(&argv[7], &op_en_t); - light_client_set.hsl_set.op_en = op_en_t?true:false; + if(argc > 6){ + /* appkey_index */ + get_uint16_from_string(&argv[2], &hsl_common.ctx.app_idx); + /* opcode */ + get_uint32_from_string(&argv[3], &hsl_common.opcode); + /* role */ + get_uint8_from_string(&argv[4], &hsl_common.msg_role); + /* address */ + get_uint16_from_string(&argv[5], &hsl_common.ctx.addr); + /* network key index */ + get_uint16_from_string(&argv[6], &hsl_common.ctx.net_idx); + } + if(argc > 13){ + /* op_en */ + uint8_t op_en_t; + get_uint8_from_string(&argv[7], &op_en_t); + light_client_set.hsl_set.op_en = op_en_t?true:false; - /* onoff */ - get_uint16_from_string(&argv[8], &light_client_set.hsl_set.hsl_lightness); - get_uint16_from_string(&argv[9], &light_client_set.hsl_set.hsl_hue); - get_uint16_from_string(&argv[10], &light_client_set.hsl_set.hsl_saturation); - /* tid */ - get_uint8_from_string(&argv[11], &light_client_set.hsl_set.tid); - /* trans_time */ - get_uint8_from_string(&argv[12], &light_client_set.hsl_set.trans_time); - /* delay */ - get_uint8_from_string(&argv[13], &light_client_set.hsl_set.delay); - } + /* onoff */ + get_uint16_from_string(&argv[8], &light_client_set.hsl_set.hsl_lightness); + get_uint16_from_string(&argv[9], &light_client_set.hsl_set.hsl_hue); + get_uint16_from_string(&argv[10], &light_client_set.hsl_set.hsl_saturation); + /* tid */ + get_uint8_from_string(&argv[11], &light_client_set.hsl_set.tid); + /* trans_time */ + get_uint8_from_string(&argv[12], &light_client_set.hsl_set.trans_time); + /* delay */ + get_uint8_from_string(&argv[13], &light_client_set.hsl_set.delay); + } - if (strcmp(argv[1], "get") == 0) { - err = bfl_ble_mesh_light_client_get_state(&hsl_common, &light_client_get); - } else if (strcmp(argv[1], "set") == 0) { - err = bfl_ble_mesh_light_client_set_state(&hsl_common, &light_client_set); - } else if (strcmp(argv[1], "reg") == 0) { - err = bfl_ble_mesh_register_light_client_callback(ble_mesh_light_client_model_cb); - if (err == BFL_OK) { - vOutputString("Light lightness client:Reg,OK\n"); - } - } - vOutputString("exit %s\n", __func__); + if (strcmp(argv[1], "get") == 0) { + err = bfl_ble_mesh_light_client_get_state(&hsl_common, &light_client_get); + } else if (strcmp(argv[1], "set") == 0) { + err = bfl_ble_mesh_light_client_set_state(&hsl_common, &light_client_set); + } else if (strcmp(argv[1], "reg") == 0) { + err = bfl_ble_mesh_register_light_client_callback(ble_mesh_light_client_model_cb); + if (err == BFL_OK) { + vOutputString("Light lightness client:Reg,OK\n"); + } + } + vOutputString("exit %s\n", __func__); } #endif #endif /* CONFIG_BT_MESH_MODEL */ static int input(bt_mesh_input_action_t act, u8_t size) { - switch (act) { - case BT_MESH_ENTER_NUMBER: - vOutputString("Enter a number (max %u digits) with: input-num \r\n", size); - break; - case BT_MESH_ENTER_STRING: - vOutputString("Enter a string (max %u chars) with: input-str \r\n", size); - break; - default: - vOutputString("Unknown input action %u (size %u) requested!\r\n", act, size); - return -EINVAL; - } + switch (act) { + case BT_MESH_ENTER_NUMBER: + vOutputString("Enter a number (max %u digits) with: input-num \r\n", size); + break; + case BT_MESH_ENTER_STRING: + vOutputString("Enter a string (max %u chars) with: input-str \r\n", size); + break; + default: + vOutputString("Unknown input action %u (size %u) requested!\r\n", act, size); + return -EINVAL; + } - input_act = act; - input_size = size; - return 0; + input_act = act; + input_size = size; + return 0; } static void blemesh_reset(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - bt_mesh_reset(); - vOutputString("Local node reset complete\r\n"); + bt_mesh_reset(); + vOutputString("Local node reset complete\r\n"); } static void blemesh_net_send(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) @@ -1223,22 +1223,22 @@ static void blemesh_net_send(char *pcWriteBuffer, int xWriteBufferLen, int argc, uint16_t src; uint16_t dst; uint8_t payload[16] = {0x00}; - + if(argc != 5){ vOutputString("Number of Parameters is not correct\r\n"); return; } - + if (!bt_mesh_is_provisioned()) { vOutputString("Local node is not yet provisioned\r\n"); return; } - + get_uint8_from_string(&argv[1], &ttl); get_uint8_from_string(&argv[2], &ctl); get_uint16_from_string(&argv[3], &src); get_uint16_from_string(&argv[4], &dst); - + struct bt_mesh_msg_ctx ctx = { .net_idx = net.net_idx, .app_idx = ctl ? BT_MESH_KEY_UNUSED : BT_MESH_KEY_DEV, @@ -1246,7 +1246,7 @@ static void blemesh_net_send(char *pcWriteBuffer, int xWriteBufferLen, int argc, .send_rel = 0, .send_ttl = ttl, }; - + struct bt_mesh_net_tx tx = { .sub = bt_mesh_subnet_get(ctx.net_idx), .ctx = &ctx, @@ -1254,33 +1254,33 @@ static void blemesh_net_send(char *pcWriteBuffer, int xWriteBufferLen, int argc, .xmit = bt_mesh_net_transmit_get(), .friend_cred = 0, }; - + struct net_buf *buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx.xmit, K_NO_WAIT); if (!buf) { vOutputString("Out of network buffers\r\n"); return; } - + vOutputString("Sending network packet\r\n"); - + net_buf_reserve(buf, BT_MESH_NET_HDR_LEN); net_buf_add_mem(buf, payload, sizeof(payload)); - + bt_mesh_net_send(&tx, buf, NULL, NULL); } static uint16_t get_app_idx(void) { int i; - + for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - + if (key->net_idx != BT_MESH_KEY_UNUSED) { return key->app_idx; } } - + return BT_MESH_KEY_UNUSED; } @@ -1290,20 +1290,20 @@ static void blemesh_seg_send(char *pcWriteBuffer, int xWriteBufferLen, int argc, uint16_t src; uint16_t dst; uint8_t payload[12] = {0xFF}; - + if(argc != 3){ vOutputString("Number of Parameters is not correct\r\n"); return; } - + if (!bt_mesh_is_provisioned()) { vOutputString("Local node is not yet provisioned\r\n"); return; } - + get_uint16_from_string(&argv[1], &src); get_uint16_from_string(&argv[2], &dst); - + struct bt_mesh_msg_ctx ctx = { .net_idx = net.net_idx, .app_idx = get_app_idx(), @@ -1311,7 +1311,7 @@ static void blemesh_seg_send(char *pcWriteBuffer, int xWriteBufferLen, int argc, .send_rel = 1, .send_ttl = 0, }; - + struct bt_mesh_net_tx tx = { .sub = bt_mesh_subnet_get(ctx.net_idx), .ctx = &ctx, @@ -1319,11 +1319,11 @@ static void blemesh_seg_send(char *pcWriteBuffer, int xWriteBufferLen, int argc, .xmit = bt_mesh_net_transmit_get(), .friend_cred = 0, }; - + vOutputString("Sending segmented message\r\n"); - + net_buf_simple_add_mem(&sdu, payload, sizeof(payload)); - + bt_mesh_trans_send(&tx, &sdu, NULL, NULL); } @@ -1338,25 +1338,25 @@ static void blemesh_rpl_clr(char *pcWriteBuffer, int xWriteBufferLen, int argc, vOutputString("Replay protection list (size: %d) cleared\r\n", CONFIG_BT_MESH_CRPL); } #endif - + memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); } static void blemesh_ivu_test(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { uint8_t enable; - + if(argc != 2){ vOutputString("Number of Parameters is not correct\r\n"); return; } - + get_uint8_from_string(&argv[1], &enable); - + #if defined(CONFIG_BT_MESH_IV_UPDATE_TEST) bt_mesh_iv_update_test(enable); #endif - + if (enable) { vOutputString("IV Update test mode enabled\r\n"); } else { @@ -1367,32 +1367,32 @@ static void blemesh_ivu_test(char *pcWriteBuffer, int xWriteBufferLen, int argc, static void blemesh_iv_update(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { uint8_t enable; - + if(argc != 2){ vOutputString("Number of Parameters is not correct\r\n"); return; } - + if (!bt_mesh_is_provisioned()) { vOutputString("Local node is not yet provisioned\r\n"); return; } - + get_uint8_from_string(&argv[1], &enable); - + if (enable) { vOutputString("IV Update procedure started\r\n"); - + #if defined(CONFIG_BT_MESH_IV_UPDATE_TEST) bt_mesh_iv_update(); #endif - + if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) { bt_mesh_beacon_ivu_initiator(1); } } else { vOutputString("IV Update procedure stopped\r\n"); - + if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) { bt_mesh_beacon_ivu_initiator(0); } @@ -1403,14 +1403,14 @@ static void blemesh_fault_set(char *pcWriteBuffer, int xWriteBufferLen, int argc { uint8_t type; int i; - + if(argc != 3){ vOutputString("Number of Parameters is not correct\r\n"); return; } - + get_uint8_from_string(&argv[1], &type); - + if (type == 0) { if(strlen(argv[2])/2 >= sizeof(cur_faults)) { get_bytearray_from_string(&argv[2], cur_faults,sizeof(cur_faults)); @@ -1418,7 +1418,7 @@ static void blemesh_fault_set(char *pcWriteBuffer, int xWriteBufferLen, int argc memset(cur_faults, 0x00, sizeof(cur_faults)); get_bytearray_from_string(&argv[2], cur_faults,strlen(argv[2])/2); } - + vOutputString("Current Fault: "); for(i=0; itid && src_addr == last_msg->src_addr && + if(tid == last_msg->tid && src_addr == last_msg->src_addr && dst_addr == last_msg->dst_addr && *rcvd_time - last_msg->rcvd_time <= K_SECONDS(6)) { diff --git a/components/network/ble/blemesh/src/mesh_models/server/gen_srv.c b/components/network/ble/blemesh/src/mesh_models/server/gen_srv.c index 5f95cdc6..973c05c6 100644 --- a/components/network/ble/blemesh/src/mesh_models/server/gen_srv.c +++ b/components/network/ble/blemesh/src/mesh_models/server/gen_srv.c @@ -11,7 +11,7 @@ static void send_onoff_status(struct bt_mesh_model *model, struct bt_mesh_msg_ct struct bt_mesh_gen_onoff_srv *srv = model->user_data; NET_BUF_SIMPLE_DEFINE(msg, MESH_GEN_OPCODE_SIZE_2 + GEN_ONOFF_STATUS_PAYLOAD_SIZE + MESH_TRANS_MIC_SIZE_4); - + bt_mesh_model_msg_init(&msg, BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS); net_buf_simple_add_u8(&msg, srv->onoff_state.prest_onoff); /*Ignore transition delay currently, will do this later*/ @@ -19,13 +19,13 @@ static void send_onoff_status(struct bt_mesh_model *model, struct bt_mesh_msg_ct //net_buf_simple_add_u8(&msg, srv->transition.trans_time); if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) { - BT_ERR("%s, Unable to send onoff status", __func__); - } + BT_ERR("%s, Unable to send onoff status", __func__); + } } static void gen_onoff_get(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { struct bt_mesh_gen_onoff_srv *srv = model->user_data; @@ -38,8 +38,8 @@ static void gen_onoff_get(struct bt_mesh_model *model, } static void gen_onoff_set(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { struct bt_mesh_gen_onoff_srv *srv = model->user_data; u8_t onoff, tid;// trans_time, delay; @@ -51,12 +51,12 @@ static void gen_onoff_set(struct bt_mesh_model *model, } onoff = net_buf_simple_pull_u8(buf); - + if(onoff > MESH_STATE_ON){ BT_ERR("%s, Invalid OnOff value 0x%02x", __func__, onoff); return; } - + tid = net_buf_simple_pull_u8(buf); if(bt_mesh_srv_check_rcvd_msg_with_last(tid, ctx->addr, ctx->recv_dst, &recv_time, &srv->last_msg)){ @@ -75,29 +75,29 @@ static void gen_onoff_set(struct bt_mesh_model *model, } static void gen_onoff_set_with_ack(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { gen_onoff_set(model, ctx, buf); send_onoff_status(model, ctx); } static void gen_onoff_set_unack(struct bt_mesh_model *model, - struct bt_mesh_msg_ctx *ctx, - struct net_buf_simple *buf) + struct bt_mesh_msg_ctx *ctx, + struct net_buf_simple *buf) { gen_onoff_set(model, ctx, buf); } void mesh_gen_srv_callback_register(bt_mesh_model_gen_cb cb) { - gen_cb = cb; + gen_cb = cb; } const struct bt_mesh_model_op bt_mesh_onoff_srv_op[] = { - {BLE_MESH_MODEL_OP_GEN_ONOFF_GET, 0, gen_onoff_get}, - {BLE_MESH_MODEL_OP_GEN_ONOFF_SET, 2, gen_onoff_set_with_ack}, - {BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK, 2, gen_onoff_set_unack }, - BT_MESH_MODEL_OP_END, + {BLE_MESH_MODEL_OP_GEN_ONOFF_GET, 0, gen_onoff_get}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET, 2, gen_onoff_set_with_ack}, + {BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK, 2, gen_onoff_set_unack }, + BT_MESH_MODEL_OP_END, }; diff --git a/components/network/ble/blemesh/src/mesh_models/server/include/common_srv.h b/components/network/ble/blemesh/src/mesh_models/server/include/common_srv.h index 9f2e5a1b..5b8caf08 100644 --- a/components/network/ble/blemesh/src/mesh_models/server/include/common_srv.h +++ b/components/network/ble/blemesh/src/mesh_models/server/include/common_srv.h @@ -3,7 +3,7 @@ #include #include -#include +#include #define MESH_TRANS_MIC_SIZE_4 4 #define MESH_TRANS_MIC_SIZE_8 8 diff --git a/components/network/ble/blemesh/src/mesh_models/server/include/gen_srv.h b/components/network/ble/blemesh/src/mesh_models/server/include/gen_srv.h index 5191fb6e..c66d6a71 100644 --- a/components/network/ble/blemesh/src/mesh_models/server/include/gen_srv.h +++ b/components/network/ble/blemesh/src/mesh_models/server/include/gen_srv.h @@ -22,8 +22,8 @@ struct bt_mesh_gen_onoff_srv { extern const struct bt_mesh_model_op bt_mesh_onoff_srv_op[]; #define BT_MESH_MODEL_GEN_ONOFF(srv_data) \ - BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_ONOFF_SRV, \ - bt_mesh_onoff_srv_op, NULL, srv_data) + BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_ONOFF_SRV, \ + bt_mesh_onoff_srv_op, NULL, srv_data) typedef void (*bt_mesh_model_gen_cb)(uint8_t value); void mesh_gen_srv_callback_register(bt_mesh_model_gen_cb cb); diff --git a/components/network/ble/blemesh/src/net.c b/components/network/ble/blemesh/src/net.c index 6626b9c9..fffa1e20 100644 --- a/components/network/ble/blemesh/src/net.c +++ b/components/network/ble/blemesh/src/net.c @@ -54,7 +54,7 @@ #define CTL(pdu) ((pdu)[1] >> 7) #define TTL(pdu) ((pdu)[1] & 0x7f) #define SEQ(pdu) (((u32_t)(pdu)[2] << 16) | \ - ((u32_t)(pdu)[3] << 8) | (u32_t)(pdu)[4]); + ((u32_t)(pdu)[3] << 8) | (u32_t)(pdu)[4]); #define SRC(pdu) (sys_get_be16(&(pdu)[5])) #define DST(pdu) (sys_get_be16(&(pdu)[7])) @@ -76,17 +76,17 @@ static u16_t msg_cache_next; /* Singleton network context (the implementation only supports one) */ struct bt_mesh_net bt_mesh = { - .local_queue = SYS_SLIST_STATIC_INIT(&bt_mesh.local_queue), - .sub = { - [0 ... (CONFIG_BT_MESH_SUBNET_COUNT - 1)] = { - .net_idx = BT_MESH_KEY_UNUSED, - } - }, - .app_keys = { - [0 ... (CONFIG_BT_MESH_APP_KEY_COUNT - 1)] = { - .net_idx = BT_MESH_KEY_UNUSED, - } - }, + .local_queue = SYS_SLIST_STATIC_INIT(&bt_mesh.local_queue), + .sub = { + [0 ... (CONFIG_BT_MESH_SUBNET_COUNT - 1)] = { + .net_idx = BT_MESH_KEY_UNUSED, + } + }, + .app_keys = { + [0 ... (CONFIG_BT_MESH_APP_KEY_COUNT - 1)] = { + .net_idx = BT_MESH_KEY_UNUSED, + } + }, }; #if !defined(BFLB_BLE_MESH_PATCH_NET_DECODE) @@ -95,1062 +95,1062 @@ static int dup_cache_next; static bool check_dup(struct net_buf_simple *data) { - const u8_t *tail = net_buf_simple_tail(data); - u32_t val; - int i; + const u8_t *tail = net_buf_simple_tail(data); + u32_t val; + int i; - val = sys_get_be32(tail - 4) ^ sys_get_be32(tail - 8); + val = sys_get_be32(tail - 4) ^ sys_get_be32(tail - 8); - for (i = 0; i < ARRAY_SIZE(dup_cache); i++) { - if (dup_cache[i] == val) { - return true; - } - } + for (i = 0; i < ARRAY_SIZE(dup_cache); i++) { + if (dup_cache[i] == val) { + return true; + } + } - dup_cache[dup_cache_next++] = val; - dup_cache_next %= ARRAY_SIZE(dup_cache); + dup_cache[dup_cache_next++] = val; + dup_cache_next %= ARRAY_SIZE(dup_cache); - return false; + return false; } #endif static u64_t msg_hash(struct bt_mesh_net_rx *rx, struct net_buf_simple *pdu) { - u32_t hash1, hash2; + u32_t hash1, hash2; - /* Three least significant bytes of IVI + first byte of SEQ */ - hash1 = (BT_MESH_NET_IVI_RX(rx) << 8) | pdu->data[2]; + /* Three least significant bytes of IVI + first byte of SEQ */ + hash1 = (BT_MESH_NET_IVI_RX(rx) << 8) | pdu->data[2]; - /* Two last bytes of SEQ + SRC */ - memcpy(&hash2, &pdu->data[3], 4); + /* Two last bytes of SEQ + SRC */ + memcpy(&hash2, &pdu->data[3], 4); - return (u64_t)hash1 << 32 | (u64_t)hash2; + return (u64_t)hash1 << 32 | (u64_t)hash2; } static bool msg_cache_match(struct bt_mesh_net_rx *rx, - struct net_buf_simple *pdu) + struct net_buf_simple *pdu) { - u64_t hash = msg_hash(rx, pdu); - u16_t i; + u64_t hash = msg_hash(rx, pdu); + u16_t i; - for (i = 0U; i < ARRAY_SIZE(msg_cache); i++) { - if (msg_cache[i] == hash) { - return true; - } - } + for (i = 0U; i < ARRAY_SIZE(msg_cache); i++) { + if (msg_cache[i] == hash) { + return true; + } + } - /* Add to the cache */ - rx->msg_cache_idx = msg_cache_next++; - msg_cache[rx->msg_cache_idx] = hash; - msg_cache_next %= ARRAY_SIZE(msg_cache); + /* Add to the cache */ + rx->msg_cache_idx = msg_cache_next++; + msg_cache[rx->msg_cache_idx] = hash; + msg_cache_next %= ARRAY_SIZE(msg_cache); - return false; + return false; } struct bt_mesh_subnet *bt_mesh_subnet_get(u16_t net_idx) { - int i; + int i; - if (net_idx == BT_MESH_KEY_ANY) { - return &bt_mesh.sub[0]; - } + if (net_idx == BT_MESH_KEY_ANY) { + return &bt_mesh.sub[0]; + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - if (bt_mesh.sub[i].net_idx == net_idx) { - return &bt_mesh.sub[i]; - } - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + if (bt_mesh.sub[i].net_idx == net_idx) { + return &bt_mesh.sub[i]; + } + } - return NULL; + return NULL; } int bt_mesh_net_keys_create(struct bt_mesh_subnet_keys *keys, - const u8_t key[16]) + const u8_t key[16]) { - u8_t p[] = { 0 }; - u8_t nid; - int err; + u8_t p[] = { 0 }; + u8_t nid; + int err; - err = bt_mesh_k2(key, p, sizeof(p), &nid, keys->enc, keys->privacy); - if (err) { - BT_ERR("Unable to generate NID, EncKey & PrivacyKey"); - return err; - } + err = bt_mesh_k2(key, p, sizeof(p), &nid, keys->enc, keys->privacy); + if (err) { + BT_ERR("Unable to generate NID, EncKey & PrivacyKey"); + return err; + } - memcpy(keys->net, key, 16); + memcpy(keys->net, key, 16); - keys->nid = nid; + keys->nid = nid; - BT_DBG("NID 0x%02x EncKey %s", keys->nid, bt_hex(keys->enc, 16)); - BT_DBG("PrivacyKey %s", bt_hex(keys->privacy, 16)); + BT_DBG("NID 0x%02x EncKey %s", keys->nid, bt_hex(keys->enc, 16)); + BT_DBG("PrivacyKey %s", bt_hex(keys->privacy, 16)); - err = bt_mesh_k3(key, keys->net_id); - if (err) { - BT_ERR("Unable to generate Net ID"); - return err; - } + err = bt_mesh_k3(key, keys->net_id); + if (err) { + BT_ERR("Unable to generate Net ID"); + return err; + } - BT_DBG("NetID %s", bt_hex(keys->net_id, 8)); + BT_DBG("NetID %s", bt_hex(keys->net_id, 8)); #if defined(CONFIG_BT_MESH_GATT_PROXY) - err = bt_mesh_identity_key(key, keys->identity); - if (err) { - BT_ERR("Unable to generate IdentityKey"); - return err; - } + err = bt_mesh_identity_key(key, keys->identity); + if (err) { + BT_ERR("Unable to generate IdentityKey"); + return err; + } - BT_DBG("IdentityKey %s", bt_hex(keys->identity, 16)); + BT_DBG("IdentityKey %s", bt_hex(keys->identity, 16)); #endif /* GATT_PROXY */ - err = bt_mesh_beacon_key(key, keys->beacon); - if (err) { - BT_ERR("Unable to generate beacon key"); - return err; - } + err = bt_mesh_beacon_key(key, keys->beacon); + if (err) { + BT_ERR("Unable to generate beacon key"); + return err; + } - BT_DBG("BeaconKey %s", bt_hex(keys->beacon, 16)); + BT_DBG("BeaconKey %s", bt_hex(keys->beacon, 16)); - return 0; + return 0; } #if (defined(CONFIG_BT_MESH_LOW_POWER) || \ defined(CONFIG_BT_MESH_FRIEND)) int friend_cred_set(struct friend_cred *cred, u8_t idx, const u8_t net_key[16]) { - u16_t lpn_addr, frnd_addr; - int err; - u8_t p[9]; + u16_t lpn_addr, frnd_addr; + int err; + u8_t p[9]; #if defined(CONFIG_BT_MESH_LOW_POWER) - if (cred->addr == bt_mesh.lpn.frnd) { - lpn_addr = bt_mesh_primary_addr(); - frnd_addr = cred->addr; - } else { - lpn_addr = cred->addr; - frnd_addr = bt_mesh_primary_addr(); - } + if (cred->addr == bt_mesh.lpn.frnd) { + lpn_addr = bt_mesh_primary_addr(); + frnd_addr = cred->addr; + } else { + lpn_addr = cred->addr; + frnd_addr = bt_mesh_primary_addr(); + } #else - lpn_addr = cred->addr; - frnd_addr = bt_mesh_primary_addr(); + lpn_addr = cred->addr; + frnd_addr = bt_mesh_primary_addr(); #endif - BT_DBG("LPNAddress 0x%04x FriendAddress 0x%04x", lpn_addr, frnd_addr); - BT_DBG("LPNCounter 0x%04x FriendCounter 0x%04x", cred->lpn_counter, - cred->frnd_counter); + BT_DBG("LPNAddress 0x%04x FriendAddress 0x%04x", lpn_addr, frnd_addr); + BT_DBG("LPNCounter 0x%04x FriendCounter 0x%04x", cred->lpn_counter, + cred->frnd_counter); - p[0] = 0x01; - sys_put_be16(lpn_addr, p + 1); - sys_put_be16(frnd_addr, p + 3); - sys_put_be16(cred->lpn_counter, p + 5); - sys_put_be16(cred->frnd_counter, p + 7); + p[0] = 0x01; + sys_put_be16(lpn_addr, p + 1); + sys_put_be16(frnd_addr, p + 3); + sys_put_be16(cred->lpn_counter, p + 5); + sys_put_be16(cred->frnd_counter, p + 7); - err = bt_mesh_k2(net_key, p, sizeof(p), &cred->cred[idx].nid, - cred->cred[idx].enc, cred->cred[idx].privacy); - if (err) { - BT_ERR("Unable to generate NID, EncKey & PrivacyKey"); - return err; - } + err = bt_mesh_k2(net_key, p, sizeof(p), &cred->cred[idx].nid, + cred->cred[idx].enc, cred->cred[idx].privacy); + if (err) { + BT_ERR("Unable to generate NID, EncKey & PrivacyKey"); + return err; + } - BT_DBG("Friend NID 0x%02x EncKey %s", cred->cred[idx].nid, - bt_hex(cred->cred[idx].enc, 16)); - BT_DBG("Friend PrivacyKey %s", bt_hex(cred->cred[idx].privacy, 16)); + BT_DBG("Friend NID 0x%02x EncKey %s", cred->cred[idx].nid, + bt_hex(cred->cred[idx].enc, 16)); + BT_DBG("Friend PrivacyKey %s", bt_hex(cred->cred[idx].privacy, 16)); - return 0; + return 0; } void friend_cred_refresh(u16_t net_idx) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { - struct friend_cred *cred = &friend_cred[i]; + for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { + struct friend_cred *cred = &friend_cred[i]; - if (cred->addr != BT_MESH_ADDR_UNASSIGNED && - cred->net_idx == net_idx) { - memcpy(&cred->cred[0], &cred->cred[1], - sizeof(cred->cred[0])); - } - } + if (cred->addr != BT_MESH_ADDR_UNASSIGNED && + cred->net_idx == net_idx) { + memcpy(&cred->cred[0], &cred->cred[1], + sizeof(cred->cred[0])); + } + } } int friend_cred_update(struct bt_mesh_subnet *sub) { - int err, i; + int err, i; - BT_DBG("net_idx 0x%04x", sub->net_idx); + BT_DBG("net_idx 0x%04x", sub->net_idx); - for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { - struct friend_cred *cred = &friend_cred[i]; + for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { + struct friend_cred *cred = &friend_cred[i]; - if (cred->addr == BT_MESH_ADDR_UNASSIGNED || - cred->net_idx != sub->net_idx) { - continue; - } + if (cred->addr == BT_MESH_ADDR_UNASSIGNED || + cred->net_idx != sub->net_idx) { + continue; + } - err = friend_cred_set(cred, 1, sub->keys[1].net); - if (err) { - return err; - } - } + err = friend_cred_set(cred, 1, sub->keys[1].net); + if (err) { + return err; + } + } - return 0; + return 0; } struct friend_cred *friend_cred_create(struct bt_mesh_subnet *sub, u16_t addr, - u16_t lpn_counter, u16_t frnd_counter) + u16_t lpn_counter, u16_t frnd_counter) { - struct friend_cred *cred; - int i, err; + struct friend_cred *cred; + int i, err; - BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr); + BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr); - for (cred = NULL, i = 0; i < ARRAY_SIZE(friend_cred); i++) { - if ((friend_cred[i].addr == BT_MESH_ADDR_UNASSIGNED) || - (friend_cred[i].addr == addr && - friend_cred[i].net_idx == sub->net_idx)) { - cred = &friend_cred[i]; - break; - } - } + for (cred = NULL, i = 0; i < ARRAY_SIZE(friend_cred); i++) { + if ((friend_cred[i].addr == BT_MESH_ADDR_UNASSIGNED) || + (friend_cred[i].addr == addr && + friend_cred[i].net_idx == sub->net_idx)) { + cred = &friend_cred[i]; + break; + } + } - if (!cred) { - BT_WARN("No free friend credential slots"); - return NULL; - } + if (!cred) { + BT_WARN("No free friend credential slots"); + return NULL; + } - cred->net_idx = sub->net_idx; - cred->addr = addr; - cred->lpn_counter = lpn_counter; - cred->frnd_counter = frnd_counter; + cred->net_idx = sub->net_idx; + cred->addr = addr; + cred->lpn_counter = lpn_counter; + cred->frnd_counter = frnd_counter; - err = friend_cred_set(cred, 0, sub->keys[0].net); - if (err) { - friend_cred_clear(cred); - return NULL; - } + err = friend_cred_set(cred, 0, sub->keys[0].net); + if (err) { + friend_cred_clear(cred); + return NULL; + } - if (sub->kr_flag) { - err = friend_cred_set(cred, 1, sub->keys[1].net); - if (err) { - friend_cred_clear(cred); - return NULL; - } - } + if (sub->kr_flag) { + err = friend_cred_set(cred, 1, sub->keys[1].net); + if (err) { + friend_cred_clear(cred); + return NULL; + } + } - return cred; + return cred; } void friend_cred_clear(struct friend_cred *cred) { - cred->net_idx = BT_MESH_KEY_UNUSED; - cred->addr = BT_MESH_ADDR_UNASSIGNED; - cred->lpn_counter = 0U; - cred->frnd_counter = 0U; - (void)memset(cred->cred, 0, sizeof(cred->cred)); + cred->net_idx = BT_MESH_KEY_UNUSED; + cred->addr = BT_MESH_ADDR_UNASSIGNED; + cred->lpn_counter = 0U; + cred->frnd_counter = 0U; + (void)memset(cred->cred, 0, sizeof(cred->cred)); } int friend_cred_del(u16_t net_idx, u16_t addr) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { - struct friend_cred *cred = &friend_cred[i]; + for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { + struct friend_cred *cred = &friend_cred[i]; - if (cred->addr == addr && cred->net_idx == net_idx) { - friend_cred_clear(cred); - return 0; - } - } + if (cred->addr == addr && cred->net_idx == net_idx) { + friend_cred_clear(cred); + return 0; + } + } - return -ENOENT; + return -ENOENT; } int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, - const u8_t **enc, const u8_t **priv) + const u8_t **enc, const u8_t **priv) { - int i; + int i; - BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr); + BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr); - for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { - struct friend_cred *cred = &friend_cred[i]; + for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { + struct friend_cred *cred = &friend_cred[i]; - if (cred->net_idx != sub->net_idx) { - continue; - } + if (cred->net_idx != sub->net_idx) { + continue; + } - if (addr != BT_MESH_ADDR_UNASSIGNED && cred->addr != addr) { - continue; - } + if (addr != BT_MESH_ADDR_UNASSIGNED && cred->addr != addr) { + continue; + } - if (nid) { - *nid = cred->cred[sub->kr_flag].nid; - } + if (nid) { + *nid = cred->cred[sub->kr_flag].nid; + } - if (enc) { - *enc = cred->cred[sub->kr_flag].enc; - } + if (enc) { + *enc = cred->cred[sub->kr_flag].enc; + } - if (priv) { - *priv = cred->cred[sub->kr_flag].privacy; - } + if (priv) { + *priv = cred->cred[sub->kr_flag].privacy; + } - return 0; - } + return 0; + } - return -ENOENT; + return -ENOENT; } #else int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, - const u8_t **enc, const u8_t **priv) + const u8_t **enc, const u8_t **priv) { - return -ENOENT; + return -ENOENT; } #endif /* FRIEND || LOW_POWER */ u8_t bt_mesh_net_flags(struct bt_mesh_subnet *sub) { - u8_t flags = 0x00; + u8_t flags = 0x00; - if (sub && sub->kr_flag) { - flags |= BT_MESH_NET_FLAG_KR; - } + if (sub && sub->kr_flag) { + flags |= BT_MESH_NET_FLAG_KR; + } - if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { - flags |= BT_MESH_NET_FLAG_IVU; - } + if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { + flags |= BT_MESH_NET_FLAG_IVU; + } - return flags; + return flags; } int bt_mesh_net_beacon_update(struct bt_mesh_subnet *sub) { - u8_t flags = bt_mesh_net_flags(sub); - struct bt_mesh_subnet_keys *keys; + u8_t flags = bt_mesh_net_flags(sub); + struct bt_mesh_subnet_keys *keys; - if (sub->kr_flag) { - BT_DBG("NetIndex %u Using new key", sub->net_idx); - keys = &sub->keys[1]; - } else { - BT_DBG("NetIndex %u Using current key", sub->net_idx); - keys = &sub->keys[0]; - } + if (sub->kr_flag) { + BT_DBG("NetIndex %u Using new key", sub->net_idx); + keys = &sub->keys[1]; + } else { + BT_DBG("NetIndex %u Using current key", sub->net_idx); + keys = &sub->keys[0]; + } - BT_DBG("flags 0x%02x, IVI 0x%08x", flags, bt_mesh.iv_index); + BT_DBG("flags 0x%02x, IVI 0x%08x", flags, bt_mesh.iv_index); - return bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, - bt_mesh.iv_index, sub->auth); + return bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, + bt_mesh.iv_index, sub->auth); } int bt_mesh_net_create(u16_t idx, u8_t flags, const u8_t key[16], - u32_t iv_index) + u32_t iv_index) { - struct bt_mesh_subnet *sub; - int err; + struct bt_mesh_subnet *sub; + int err; - BT_DBG("idx %u flags 0x%02x iv_index %u", idx, flags, iv_index); + BT_DBG("idx %u flags 0x%02x iv_index %u", idx, flags, iv_index); - BT_DBG("NetKey %s", bt_hex(key, 16)); + BT_DBG("NetKey %s", bt_hex(key, 16)); - (void)memset(msg_cache, 0, sizeof(msg_cache)); - msg_cache_next = 0U; + (void)memset(msg_cache, 0, sizeof(msg_cache)); + msg_cache_next = 0U; - sub = &bt_mesh.sub[0]; + sub = &bt_mesh.sub[0]; - sub->kr_flag = BT_MESH_KEY_REFRESH(flags); - if (sub->kr_flag) { - err = bt_mesh_net_keys_create(&sub->keys[1], key); - if (err) { - return -EIO; - } + sub->kr_flag = BT_MESH_KEY_REFRESH(flags); + if (sub->kr_flag) { + err = bt_mesh_net_keys_create(&sub->keys[1], key); + if (err) { + return -EIO; + } - sub->kr_phase = BT_MESH_KR_PHASE_2; - } else { - err = bt_mesh_net_keys_create(&sub->keys[0], key); - if (err) { - return -EIO; - } - } + sub->kr_phase = BT_MESH_KR_PHASE_2; + } else { + err = bt_mesh_net_keys_create(&sub->keys[0], key); + if (err) { + return -EIO; + } + } - sub->net_idx = idx; + sub->net_idx = idx; - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { - sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; - } else { - sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED; - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { + sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; + } else { + sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED; + } - bt_mesh.iv_index = iv_index; - atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, - BT_MESH_IV_UPDATE(flags)); + bt_mesh.iv_index = iv_index; + atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, + BT_MESH_IV_UPDATE(flags)); - /* Set minimum required hours, since the 96-hour minimum requirement - * doesn't apply straight after provisioning (since we can't know how - * long has actually passed since the network changed its state). - */ - bt_mesh.ivu_duration = BT_MESH_IVU_MIN_HOURS; + /* Set minimum required hours, since the 96-hour minimum requirement + * doesn't apply straight after provisioning (since we can't know how + * long has actually passed since the network changed its state). + */ + bt_mesh.ivu_duration = BT_MESH_IVU_MIN_HOURS; - /* Make sure we have valid beacon data to be sent */ - bt_mesh_net_beacon_update(sub); + /* Make sure we have valid beacon data to be sent */ + bt_mesh_net_beacon_update(sub); - return 0; + return 0; } void bt_mesh_net_revoke_keys(struct bt_mesh_subnet *sub) { - int i; + int i; - BT_DBG("idx 0x%04x", sub->net_idx); + BT_DBG("idx 0x%04x", sub->net_idx); - memcpy(&sub->keys[0], &sub->keys[1], sizeof(sub->keys[0])); + memcpy(&sub->keys[0], &sub->keys[1], sizeof(sub->keys[0])); #if defined(BFLB_BLE_MESH_PATCH_NET_REVOKE_KEYS) - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - BT_DBG("Storing NetKey persistently"); - bt_mesh_store_subnet(sub); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + BT_DBG("Storing NetKey persistently"); + bt_mesh_store_subnet(sub); + } #endif - for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { - struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { + struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - if (key->net_idx != sub->net_idx || !key->updated) { - continue; - } + if (key->net_idx != sub->net_idx || !key->updated) { + continue; + } - memcpy(&key->keys[0], &key->keys[1], sizeof(key->keys[0])); - key->updated = false; + memcpy(&key->keys[0], &key->keys[1], sizeof(key->keys[0])); + key->updated = false; #if defined(BFLB_BLE_MESH_PATCH_NET_REVOKE_KEYS) - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - BT_DBG("Storing AppKey persistently"); - bt_mesh_store_app_key(key); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + BT_DBG("Storing AppKey persistently"); + bt_mesh_store_app_key(key); + } #endif - } + } } bool bt_mesh_kr_update(struct bt_mesh_subnet *sub, u8_t new_kr, bool new_key) { - if (new_kr != sub->kr_flag && sub->kr_phase == BT_MESH_KR_NORMAL) { - BT_WARN("KR change in normal operation. Are we blacklisted?"); - return false; - } + if (new_kr != sub->kr_flag && sub->kr_phase == BT_MESH_KR_NORMAL) { + BT_WARN("KR change in normal operation. Are we blacklisted?"); + return false; + } - sub->kr_flag = new_kr; + sub->kr_flag = new_kr; - if (sub->kr_flag) { - if (sub->kr_phase == BT_MESH_KR_PHASE_1) { + if (sub->kr_flag) { + if (sub->kr_phase == BT_MESH_KR_PHASE_1) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Key Refresh: Phase 1 -> Phase 2"); + BT_PTS("[PTS] Key Refresh: Phase 1 -> Phase 2"); #endif - BT_DBG("Phase 1 -> Phase 2"); - sub->kr_phase = BT_MESH_KR_PHASE_2; - return true; - } - } else { - switch (sub->kr_phase) { - case BT_MESH_KR_PHASE_1: - if (!new_key) { - /* Ignore */ - break; - } + BT_DBG("Phase 1 -> Phase 2"); + sub->kr_phase = BT_MESH_KR_PHASE_2; + return true; + } + } else { + switch (sub->kr_phase) { + case BT_MESH_KR_PHASE_1: + if (!new_key) { + /* Ignore */ + break; + } __attribute__((fallthrough)); - /* Upon receiving a Secure Network beacon with the KR flag set - * to 0 using the new NetKey in Phase 1, the node shall - * immediately transition to Phase 3, which effectively skips - * Phase 2. - * - * Intentional fall-through. - */ - case BT_MESH_KR_PHASE_2: + /* Upon receiving a Secure Network beacon with the KR flag set + * to 0 using the new NetKey in Phase 1, the node shall + * immediately transition to Phase 3, which effectively skips + * Phase 2. + * + * Intentional fall-through. + */ + case BT_MESH_KR_PHASE_2: #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Key Refresh: Phase %d -> Normal", sub->kr_phase); + BT_PTS("[PTS] Key Refresh: Phase %d -> Normal", sub->kr_phase); #endif - BT_DBG("KR Phase 0x%02x -> Normal", sub->kr_phase); - bt_mesh_net_revoke_keys(sub); - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || - IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - friend_cred_refresh(sub->net_idx); - } - sub->kr_phase = BT_MESH_KR_NORMAL; - return true; - } - } + BT_DBG("KR Phase 0x%02x -> Normal", sub->kr_phase); + bt_mesh_net_revoke_keys(sub); + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || + IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + friend_cred_refresh(sub->net_idx); + } + sub->kr_phase = BT_MESH_KR_NORMAL; + return true; + } + } - return false; + return false; } void bt_mesh_rpl_reset(void) { - int i; + int i; - /* Discard "old old" IV Index entries from RPL and flag - * any other ones (which are valid) as old. - */ - for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { - struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; + /* Discard "old old" IV Index entries from RPL and flag + * any other ones (which are valid) as old. + */ + for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { + struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; - if (rpl->src) { - if (rpl->old_iv) { - (void)memset(rpl, 0, sizeof(*rpl)); - } else { - rpl->old_iv = true; - } - } - } + if (rpl->src) { + if (rpl->old_iv) { + (void)memset(rpl, 0, sizeof(*rpl)); + } else { + rpl->old_iv = true; + } + } + } } #if defined(CONFIG_BT_MESH_IV_UPDATE_TEST) void bt_mesh_iv_update_test(bool enable) { - atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_TEST, enable); - /* Reset the duration variable - needed for some PTS tests */ - bt_mesh.ivu_duration = 0U; + atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_TEST, enable); + /* Reset the duration variable - needed for some PTS tests */ + bt_mesh.ivu_duration = 0U; } bool bt_mesh_iv_update(void) { - if (!bt_mesh_is_provisioned()) { - BT_ERR("Not yet provisioned"); - return false; - } + if (!bt_mesh_is_provisioned()) { + BT_ERR("Not yet provisioned"); + return false; + } - if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { - bt_mesh_net_iv_update(bt_mesh.iv_index, false); - } else { - bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true); - } + if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { + bt_mesh_net_iv_update(bt_mesh.iv_index, false); + } else { + bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true); + } - bt_mesh_net_sec_update(NULL); + bt_mesh_net_sec_update(NULL); - return atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); + return atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); } #endif /* CONFIG_BT_MESH_IV_UPDATE_TEST */ /* Used for sending immediate beacons to Friend queues and GATT clients */ void bt_mesh_net_sec_update(struct bt_mesh_subnet *sub) { - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - bt_mesh_friend_sec_update(sub ? sub->net_idx : BT_MESH_KEY_ANY); - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + bt_mesh_friend_sec_update(sub ? sub->net_idx : BT_MESH_KEY_ANY); + } - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && - bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { - bt_mesh_proxy_beacon_send(sub); - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && + bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { + bt_mesh_proxy_beacon_send(sub); + } } bool bt_mesh_net_iv_update(u32_t iv_index, bool iv_update) { - int i; + int i; - if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { - /* We're currently in IV Update mode */ + if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { + /* We're currently in IV Update mode */ - if (iv_index != bt_mesh.iv_index) { - BT_WARN("IV Index mismatch: 0x%08x != 0x%08x", - iv_index, bt_mesh.iv_index); - return false; - } + if (iv_index != bt_mesh.iv_index) { + BT_WARN("IV Index mismatch: 0x%08x != 0x%08x", + iv_index, bt_mesh.iv_index); + return false; + } - if (iv_update) { - /* Nothing to do */ - BT_DBG("Already in IV Update in Progress state"); - return false; - } - } else { - /* We're currently in Normal mode */ + if (iv_update) { + /* Nothing to do */ + BT_DBG("Already in IV Update in Progress state"); + return false; + } + } else { + /* We're currently in Normal mode */ - if (iv_index == bt_mesh.iv_index) { - BT_DBG("Same IV Index in normal mode"); - return false; - } + if (iv_index == bt_mesh.iv_index) { + BT_DBG("Same IV Index in normal mode"); + return false; + } - if (iv_index < bt_mesh.iv_index || - iv_index > bt_mesh.iv_index + 42) { - BT_ERR("IV Index out of sync: 0x%08x != 0x%08x", - iv_index, bt_mesh.iv_index); - return false; - } + if (iv_index < bt_mesh.iv_index || + iv_index > bt_mesh.iv_index + 42) { + BT_ERR("IV Index out of sync: 0x%08x != 0x%08x", + iv_index, bt_mesh.iv_index); + return false; + } - if (iv_index > bt_mesh.iv_index + 1) { - BT_WARN("Performing IV Index Recovery"); - (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); - bt_mesh.iv_index = iv_index; - bt_mesh.seq = 0U; - goto do_update; - } + if (iv_index > bt_mesh.iv_index + 1) { + BT_WARN("Performing IV Index Recovery"); + (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); + bt_mesh.iv_index = iv_index; + bt_mesh.seq = 0U; + goto do_update; + } - if (iv_index == bt_mesh.iv_index + 1 && !iv_update) { - BT_WARN("Ignoring new index in normal mode"); - return false; - } + if (iv_index == bt_mesh.iv_index + 1 && !iv_update) { + BT_WARN("Ignoring new index in normal mode"); + return false; + } - if (!iv_update) { - /* Nothing to do */ - BT_DBG("Already in Normal state"); - return false; - } - } + if (!iv_update) { + /* Nothing to do */ + BT_DBG("Already in Normal state"); + return false; + } + } - if (!(IS_ENABLED(CONFIG_BT_MESH_IV_UPDATE_TEST) && - atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_TEST))) { - if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) { - BT_WARN("IV Update before minimum duration"); - return false; - } - } + if (!(IS_ENABLED(CONFIG_BT_MESH_IV_UPDATE_TEST) && + atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_TEST))) { + if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) { + BT_WARN("IV Update before minimum duration"); + return false; + } + } - /* Defer change to Normal Operation if there are pending acks */ - if (!iv_update && bt_mesh_tx_in_progress()) { - BT_WARN("IV Update deferred because of pending transfer"); - atomic_set_bit(bt_mesh.flags, BT_MESH_IVU_PENDING); - return false; - } + /* Defer change to Normal Operation if there are pending acks */ + if (!iv_update && bt_mesh_tx_in_progress()) { + BT_WARN("IV Update deferred because of pending transfer"); + atomic_set_bit(bt_mesh.flags, BT_MESH_IVU_PENDING); + return false; + } do_update: - atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv_update); - bt_mesh.ivu_duration = 0U; + atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv_update); + bt_mesh.ivu_duration = 0U; #ifdef CONFIG_BT_MESH_PTS - if (iv_update) { - BT_PTS("[PTS] IV Update: transitioning to IV Update in Progress state"); - } else { - BT_PTS("[PTS] IV Update: transitioning to Normal Operation state"); - } + if (iv_update) { + BT_PTS("[PTS] IV Update: transitioning to IV Update in Progress state"); + } else { + BT_PTS("[PTS] IV Update: transitioning to Normal Operation state"); + } #endif - if (iv_update) { - bt_mesh.iv_index = iv_index; - BT_DBG("IV Update state entered. New index 0x%08x", - bt_mesh.iv_index); + if (iv_update) { + bt_mesh.iv_index = iv_index; + BT_DBG("IV Update state entered. New index 0x%08x", + bt_mesh.iv_index); - bt_mesh_rpl_reset(); - } else { - BT_DBG("Normal mode entered"); - bt_mesh.seq = 0U; - } + bt_mesh_rpl_reset(); + } else { + BT_DBG("Normal mode entered"); + bt_mesh.seq = 0U; + } - k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT); + k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT); - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - if (bt_mesh.sub[i].net_idx != BT_MESH_KEY_UNUSED) { - bt_mesh_net_beacon_update(&bt_mesh.sub[i]); - } - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + if (bt_mesh.sub[i].net_idx != BT_MESH_KEY_UNUSED) { + bt_mesh_net_beacon_update(&bt_mesh.sub[i]); + } + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_iv(false); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_iv(false); + } - return true; + return true; } u32_t bt_mesh_next_seq(void) { - u32_t seq = bt_mesh.seq++; + u32_t seq = bt_mesh.seq++; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_seq(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_seq(); + } - if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) && - bt_mesh.seq > IV_UPDATE_SEQ_LIMIT && - bt_mesh_subnet_get(BT_MESH_KEY_PRIMARY)) { - bt_mesh_beacon_ivu_initiator(true); - bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true); - bt_mesh_net_sec_update(NULL); - } + if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) && + bt_mesh.seq > IV_UPDATE_SEQ_LIMIT && + bt_mesh_subnet_get(BT_MESH_KEY_PRIMARY)) { + bt_mesh_beacon_ivu_initiator(true); + bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true); + bt_mesh_net_sec_update(NULL); + } - return seq; + return seq; } int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf, - bool new_key, const struct bt_mesh_send_cb *cb, - void *cb_data) + bool new_key, const struct bt_mesh_send_cb *cb, + void *cb_data) { - const u8_t *enc, *priv; - u32_t seq; - u16_t dst; - int err; + const u8_t *enc, *priv; + u32_t seq; + u16_t dst; + int err; - BT_DBG("net_idx 0x%04x new_key %u len %u", sub->net_idx, new_key, - buf->len); + BT_DBG("net_idx 0x%04x new_key %u len %u", sub->net_idx, new_key, + buf->len); - enc = sub->keys[new_key].enc; - priv = sub->keys[new_key].privacy; + enc = sub->keys[new_key].enc; + priv = sub->keys[new_key].privacy; - err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv); - if (err) { - BT_ERR("deobfuscate failed (err %d)", err); - return err; - } + err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv); + if (err) { + BT_ERR("deobfuscate failed (err %d)", err); + return err; + } - err = bt_mesh_net_decrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false); - if (err) { - BT_ERR("decrypt failed (err %d)", err); - return err; - } + err = bt_mesh_net_decrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false); + if (err) { + BT_ERR("decrypt failed (err %d)", err); + return err; + } - /* Update with a new sequence number */ - seq = bt_mesh_next_seq(); - buf->data[2] = seq >> 16; - buf->data[3] = seq >> 8; - buf->data[4] = seq; + /* Update with a new sequence number */ + seq = bt_mesh_next_seq(); + buf->data[2] = seq >> 16; + buf->data[3] = seq >> 8; + buf->data[4] = seq; - /* Get destination, in case it's a proxy client */ - dst = DST(buf->data); + /* Get destination, in case it's a proxy client */ + dst = DST(buf->data); - err = bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false); - if (err) { - BT_ERR("encrypt failed (err %d)", err); - return err; - } + err = bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false); + if (err) { + BT_ERR("encrypt failed (err %d)", err); + return err; + } - err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv); - if (err) { - BT_ERR("obfuscate failed (err %d)", err); - return err; - } + err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv); + if (err) { + BT_ERR("obfuscate failed (err %d)", err); + return err; + } - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && - bt_mesh_proxy_relay(&buf->b, dst)) { - send_cb_finalize(cb, cb_data); - } else { - bt_mesh_adv_send(buf, cb, cb_data); - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && + bt_mesh_proxy_relay(&buf->b, dst)) { + send_cb_finalize(cb, cb_data); + } else { + bt_mesh_adv_send(buf, cb, cb_data); + } - return 0; + return 0; } static void bt_mesh_net_local(struct k_work *work) { - struct net_buf *buf; + struct net_buf *buf; - while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) { - BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); - bt_mesh_net_recv(&buf->b, 0, BT_MESH_NET_IF_LOCAL); - net_buf_unref(buf); - } + while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) { + BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); + bt_mesh_net_recv(&buf->b, 0, BT_MESH_NET_IF_LOCAL); + net_buf_unref(buf); + } } int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf, - bool proxy) + bool proxy) { - const bool ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED); - u32_t seq_val; - u8_t nid; - const u8_t *enc, *priv; - u8_t *seq; - int err; + const bool ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED); + u32_t seq_val; + u8_t nid; + const u8_t *enc, *priv; + u8_t *seq; + int err; - if (ctl && net_buf_simple_tailroom(buf) < 8) { - BT_ERR("Insufficient MIC space for CTL PDU"); - return -EINVAL; - } else if (net_buf_simple_tailroom(buf) < 4) { - BT_ERR("Insufficient MIC space for PDU"); - return -EINVAL; - } + if (ctl && net_buf_simple_tailroom(buf) < 8) { + BT_ERR("Insufficient MIC space for CTL PDU"); + return -EINVAL; + } else if (net_buf_simple_tailroom(buf) < 4) { + BT_ERR("Insufficient MIC space for PDU"); + return -EINVAL; + } - BT_DBG("src 0x%04x dst 0x%04x ctl %u seq 0x%06x", - tx->src, tx->ctx->addr, ctl, bt_mesh.seq); + BT_DBG("src 0x%04x dst 0x%04x ctl %u seq 0x%06x", + tx->src, tx->ctx->addr, ctl, bt_mesh.seq); - net_buf_simple_push_be16(buf, tx->ctx->addr); - net_buf_simple_push_be16(buf, tx->src); + net_buf_simple_push_be16(buf, tx->ctx->addr); + net_buf_simple_push_be16(buf, tx->src); - seq = net_buf_simple_push(buf, 3); - seq_val = bt_mesh_next_seq(); - seq[0] = seq_val >> 16; - seq[1] = seq_val >> 8; - seq[2] = seq_val; + seq = net_buf_simple_push(buf, 3); + seq_val = bt_mesh_next_seq(); + seq[0] = seq_val >> 16; + seq[1] = seq_val >> 8; + seq[2] = seq_val; - if (ctl) { - net_buf_simple_push_u8(buf, tx->ctx->send_ttl | 0x80); - } else { - net_buf_simple_push_u8(buf, tx->ctx->send_ttl); - } + if (ctl) { + net_buf_simple_push_u8(buf, tx->ctx->send_ttl | 0x80); + } else { + net_buf_simple_push_u8(buf, tx->ctx->send_ttl); + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && tx->friend_cred) { - if (friend_cred_get(tx->sub, BT_MESH_ADDR_UNASSIGNED, - &nid, &enc, &priv)) { - BT_WARN("Falling back to master credentials"); + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && tx->friend_cred) { + if (friend_cred_get(tx->sub, BT_MESH_ADDR_UNASSIGNED, + &nid, &enc, &priv)) { + BT_WARN("Falling back to master credentials"); - tx->friend_cred = 0U; + tx->friend_cred = 0U; - nid = tx->sub->keys[tx->sub->kr_flag].nid; - enc = tx->sub->keys[tx->sub->kr_flag].enc; - priv = tx->sub->keys[tx->sub->kr_flag].privacy; - } - } else { - tx->friend_cred = 0U; - nid = tx->sub->keys[tx->sub->kr_flag].nid; - enc = tx->sub->keys[tx->sub->kr_flag].enc; - priv = tx->sub->keys[tx->sub->kr_flag].privacy; - } + nid = tx->sub->keys[tx->sub->kr_flag].nid; + enc = tx->sub->keys[tx->sub->kr_flag].enc; + priv = tx->sub->keys[tx->sub->kr_flag].privacy; + } + } else { + tx->friend_cred = 0U; + nid = tx->sub->keys[tx->sub->kr_flag].nid; + enc = tx->sub->keys[tx->sub->kr_flag].enc; + priv = tx->sub->keys[tx->sub->kr_flag].privacy; + } - net_buf_simple_push_u8(buf, (nid | (BT_MESH_NET_IVI_TX & 1) << 7)); + net_buf_simple_push_u8(buf, (nid | (BT_MESH_NET_IVI_TX & 1) << 7)); - err = bt_mesh_net_encrypt(enc, buf, BT_MESH_NET_IVI_TX, proxy); - if (err) { - return err; - } + err = bt_mesh_net_encrypt(enc, buf, BT_MESH_NET_IVI_TX, proxy); + if (err) { + return err; + } - return bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv); + return bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv); } int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf, - const struct bt_mesh_send_cb *cb, void *cb_data) + const struct bt_mesh_send_cb *cb, void *cb_data) { - int err; + int err; - BT_DBG("src 0x%04x dst 0x%04x len %u headroom %zu tailroom %zu", - tx->src, tx->ctx->addr, buf->len, net_buf_headroom(buf), - net_buf_tailroom(buf)); - BT_DBG("Payload len %u: %s", buf->len, bt_hex(buf->data, buf->len)); - BT_DBG("Seq 0x%06x", bt_mesh.seq); + BT_DBG("src 0x%04x dst 0x%04x len %u headroom %zu tailroom %zu", + tx->src, tx->ctx->addr, buf->len, net_buf_headroom(buf), + net_buf_tailroom(buf)); + BT_DBG("Payload len %u: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("Seq 0x%06x", bt_mesh.seq); - if (tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) { - tx->ctx->send_ttl = bt_mesh_default_ttl_get(); - } + if (tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) { + tx->ctx->send_ttl = bt_mesh_default_ttl_get(); + } - err = bt_mesh_net_encode(tx, &buf->b, false); - if (err) { - goto done; - } + err = bt_mesh_net_encode(tx, &buf->b, false); + if (err) { + goto done; + } - /* Deliver to GATT Proxy Clients if necessary. Mesh spec 3.4.5.2: - * "The output filter of the interface connected to advertising or - * GATT bearers shall drop all messages with TTL value set to 1." - */ - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && - tx->ctx->send_ttl != 1U) { - if (bt_mesh_proxy_relay(&buf->b, tx->ctx->addr) && - BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { - /* Notify completion if this only went - * through the Mesh Proxy. - */ - send_cb_finalize(cb, cb_data); + /* Deliver to GATT Proxy Clients if necessary. Mesh spec 3.4.5.2: + * "The output filter of the interface connected to advertising or + * GATT bearers shall drop all messages with TTL value set to 1." + */ + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && + tx->ctx->send_ttl != 1U) { + if (bt_mesh_proxy_relay(&buf->b, tx->ctx->addr) && + BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { + /* Notify completion if this only went + * through the Mesh Proxy. + */ + send_cb_finalize(cb, cb_data); - err = 0; - goto done; - } - } + err = 0; + goto done; + } + } - /* Deliver to local network interface if necessary */ - if (bt_mesh_fixed_group_match(tx->ctx->addr) || - bt_mesh_elem_find(tx->ctx->addr)) { - if (cb && cb->start) { - cb->start(0, 0, cb_data); - } - net_buf_slist_put(&bt_mesh.local_queue, net_buf_ref(buf)); - if (cb && cb->end) { - cb->end(0, cb_data); - } - k_work_submit(&bt_mesh.local_work); - } else if (tx->ctx->send_ttl != 1U) { - /* Deliver to to the advertising network interface. Mesh spec - * 3.4.5.2: "The output filter of the interface connected to - * advertising or GATT bearers shall drop all messages with - * TTL value set to 1." - */ - bt_mesh_adv_send(buf, cb, cb_data); - } + /* Deliver to local network interface if necessary */ + if (bt_mesh_fixed_group_match(tx->ctx->addr) || + bt_mesh_elem_find(tx->ctx->addr)) { + if (cb && cb->start) { + cb->start(0, 0, cb_data); + } + net_buf_slist_put(&bt_mesh.local_queue, net_buf_ref(buf)); + if (cb && cb->end) { + cb->end(0, cb_data); + } + k_work_submit(&bt_mesh.local_work); + } else if (tx->ctx->send_ttl != 1U) { + /* Deliver to to the advertising network interface. Mesh spec + * 3.4.5.2: "The output filter of the interface connected to + * advertising or GATT bearers shall drop all messages with + * TTL value set to 1." + */ + bt_mesh_adv_send(buf, cb, cb_data); + } done: - net_buf_unref(buf); - return err; + net_buf_unref(buf); + return err; } static bool auth_match(struct bt_mesh_subnet_keys *keys, - const u8_t net_id[8], u8_t flags, - u32_t iv_index, const u8_t auth[8]) + const u8_t net_id[8], u8_t flags, + u32_t iv_index, const u8_t auth[8]) { - u8_t net_auth[8]; + u8_t net_auth[8]; - if (memcmp(net_id, keys->net_id, 8)) { - return false; - } + if (memcmp(net_id, keys->net_id, 8)) { + return false; + } - bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, iv_index, - net_auth); + bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, iv_index, + net_auth); - if (memcmp(auth, net_auth, 8)) { - BT_WARN("Authentication Value %s != %s", - bt_hex(auth, 8), bt_hex(net_auth, 8)); - return false; - } + if (memcmp(auth, net_auth, 8)) { + BT_WARN("Authentication Value %s != %s", + bt_hex(auth, 8), bt_hex(net_auth, 8)); + return false; + } - return true; + return true; } struct bt_mesh_subnet *bt_mesh_subnet_find(const u8_t net_id[8], u8_t flags, - u32_t iv_index, const u8_t auth[8], - bool *new_key) + u32_t iv_index, const u8_t auth[8], + bool *new_key) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - if (auth_match(&sub->keys[0], net_id, flags, iv_index, auth)) { - *new_key = false; - return sub; - } + if (auth_match(&sub->keys[0], net_id, flags, iv_index, auth)) { + *new_key = false; + return sub; + } - if (sub->kr_phase == BT_MESH_KR_NORMAL) { - continue; - } + if (sub->kr_phase == BT_MESH_KR_NORMAL) { + continue; + } - if (auth_match(&sub->keys[1], net_id, flags, iv_index, auth)) { - *new_key = true; - return sub; - } - } + if (auth_match(&sub->keys[1], net_id, flags, iv_index, auth)) { + *new_key = true; + return sub; + } + } - return NULL; + return NULL; } static int net_decrypt(struct bt_mesh_subnet *sub, const u8_t *enc, - const u8_t *priv, const u8_t *data, - size_t data_len, struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + const u8_t *priv, const u8_t *data, + size_t data_len, struct bt_mesh_net_rx *rx, + struct net_buf_simple *buf) { - BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx); - BT_DBG("IVI %u net->iv_index 0x%08x", IVI(data), bt_mesh.iv_index); + BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx); + BT_DBG("IVI %u net->iv_index 0x%08x", IVI(data), bt_mesh.iv_index); - rx->old_iv = (IVI(data) != (bt_mesh.iv_index & 0x01)); + rx->old_iv = (IVI(data) != (bt_mesh.iv_index & 0x01)); - net_buf_simple_reset(buf); - memcpy(net_buf_simple_add(buf, data_len), data, data_len); + net_buf_simple_reset(buf); + memcpy(net_buf_simple_add(buf, data_len), data, data_len); - if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) { - return -ENOENT; - } + if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) { + return -ENOENT; + } - if (rx->net_if == BT_MESH_NET_IF_ADV && msg_cache_match(rx, buf)) { + if (rx->net_if == BT_MESH_NET_IF_ADV && msg_cache_match(rx, buf)) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Message found in network message cache"); + BT_PTS("[PTS] Message found in network message cache"); #endif - BT_WARN("Duplicate found in Network Message Cache"); - return -EALREADY; - } + BT_WARN("Duplicate found in Network Message Cache"); + return -EALREADY; + } - rx->ctx.addr = SRC(buf->data); - if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr)) { + rx->ctx.addr = SRC(buf->data); + if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr)) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Invalid address (SRC = 0x%04X)", rx->ctx.addr); + BT_PTS("[PTS] Invalid address (SRC = 0x%04X)", rx->ctx.addr); #endif - BT_WARN("Ignoring non-unicast src addr 0x%04x", rx->ctx.addr); - return -EINVAL; - } + BT_WARN("Ignoring non-unicast src addr 0x%04x", rx->ctx.addr); + return -EINVAL; + } - BT_DBG("src 0x%04x", rx->ctx.addr); + BT_DBG("src 0x%04x", rx->ctx.addr); - if (IS_ENABLED(CONFIG_BT_MESH_PROXY) && - rx->net_if == BT_MESH_NET_IF_PROXY_CFG) { - return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), - true); - } + if (IS_ENABLED(CONFIG_BT_MESH_PROXY) && + rx->net_if == BT_MESH_NET_IF_PROXY_CFG) { + return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), + true); + } - return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), false); + return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), false); } #if (defined(CONFIG_BT_MESH_LOW_POWER) || \ defined(CONFIG_BT_MESH_FRIEND)) static int friend_decrypt(struct bt_mesh_subnet *sub, const u8_t *data, - size_t data_len, struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + size_t data_len, struct bt_mesh_net_rx *rx, + struct net_buf_simple *buf) { - int i; + int i; - BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx); + BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx); - for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { - struct friend_cred *cred = &friend_cred[i]; + for (i = 0; i < ARRAY_SIZE(friend_cred); i++) { + struct friend_cred *cred = &friend_cred[i]; - if (cred->net_idx != sub->net_idx) { - continue; - } + if (cred->net_idx != sub->net_idx) { + continue; + } - if (NID(data) == cred->cred[0].nid && - !net_decrypt(sub, cred->cred[0].enc, cred->cred[0].privacy, - data, data_len, rx, buf)) { - return 0; - } + if (NID(data) == cred->cred[0].nid && + !net_decrypt(sub, cred->cred[0].enc, cred->cred[0].privacy, + data, data_len, rx, buf)) { + return 0; + } - if (sub->kr_phase == BT_MESH_KR_NORMAL) { - continue; - } + if (sub->kr_phase == BT_MESH_KR_NORMAL) { + continue; + } - if (NID(data) == cred->cred[1].nid && - !net_decrypt(sub, cred->cred[1].enc, cred->cred[1].privacy, - data, data_len, rx, buf)) { - rx->new_key = 1U; - return 0; - } - } + if (NID(data) == cred->cred[1].nid && + !net_decrypt(sub, cred->cred[1].enc, cred->cred[1].privacy, + data, data_len, rx, buf)) { + rx->new_key = 1U; + return 0; + } + } - return -ENOENT; + return -ENOENT; } #endif static bool net_find_and_decrypt(const u8_t *data, size_t data_len, - struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct bt_mesh_net_rx *rx, + struct net_buf_simple *buf) { - struct bt_mesh_subnet *sub; - int i; + struct bt_mesh_subnet *sub; + int i; - BT_DBG(""); + BT_DBG(""); - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - sub = &bt_mesh.sub[i]; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + sub = &bt_mesh.sub[i]; + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } #if (defined(CONFIG_BT_MESH_LOW_POWER) || \ defined(CONFIG_BT_MESH_FRIEND)) - if (!friend_decrypt(sub, data, data_len, rx, buf)) { - rx->friend_cred = 1U; - rx->ctx.net_idx = sub->net_idx; - rx->sub = sub; - return true; - } + if (!friend_decrypt(sub, data, data_len, rx, buf)) { + rx->friend_cred = 1U; + rx->ctx.net_idx = sub->net_idx; + rx->sub = sub; + return true; + } #endif - if (NID(data) == sub->keys[0].nid && - !net_decrypt(sub, sub->keys[0].enc, sub->keys[0].privacy, - data, data_len, rx, buf)) { - rx->ctx.net_idx = sub->net_idx; - rx->sub = sub; - return true; - } + if (NID(data) == sub->keys[0].nid && + !net_decrypt(sub, sub->keys[0].enc, sub->keys[0].privacy, + data, data_len, rx, buf)) { + rx->ctx.net_idx = sub->net_idx; + rx->sub = sub; + return true; + } - if (sub->kr_phase == BT_MESH_KR_NORMAL) { - continue; - } + if (sub->kr_phase == BT_MESH_KR_NORMAL) { + continue; + } - if (NID(data) == sub->keys[1].nid && - !net_decrypt(sub, sub->keys[1].enc, sub->keys[1].privacy, - data, data_len, rx, buf)) { - rx->new_key = 1U; - rx->ctx.net_idx = sub->net_idx; - rx->sub = sub; - return true; - } - } + if (NID(data) == sub->keys[1].nid && + !net_decrypt(sub, sub->keys[1].enc, sub->keys[1].privacy, + data, data_len, rx, buf)) { + rx->new_key = 1U; + rx->ctx.net_idx = sub->net_idx; + rx->sub = sub; + return true; + } + } - return false; + return false; } /* Relaying from advertising to the advertising bearer should only happen @@ -1160,332 +1160,332 @@ static bool net_find_and_decrypt(const u8_t *data, size_t data_len, */ static bool relay_to_adv(enum bt_mesh_net_if net_if) { - switch (net_if) { - case BT_MESH_NET_IF_LOCAL: - return true; - case BT_MESH_NET_IF_ADV: - return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED); - case BT_MESH_NET_IF_PROXY: - return (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED); - default: - return false; - } + switch (net_if) { + case BT_MESH_NET_IF_LOCAL: + return true; + case BT_MESH_NET_IF_ADV: + return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED); + case BT_MESH_NET_IF_PROXY: + return (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED); + default: + return false; + } } static void bt_mesh_net_relay(struct net_buf_simple *sbuf, - struct bt_mesh_net_rx *rx) + struct bt_mesh_net_rx *rx) { - const u8_t *enc, *priv; - struct net_buf *buf; - u8_t nid, transmit; + const u8_t *enc, *priv; + struct net_buf *buf; + u8_t nid, transmit; - if (rx->net_if == BT_MESH_NET_IF_LOCAL) { - /* Locally originated PDUs with TTL=1 will only be delivered - * to local elements as per Mesh Profile 1.0 section 3.4.5.2: - * "The output filter of the interface connected to - * advertising or GATT bearers shall drop all messages with - * TTL value set to 1." - */ - if (rx->ctx.recv_ttl == 1U) { - return; - } - } else { - if (rx->ctx.recv_ttl <= 1U) { - return; - } - } + if (rx->net_if == BT_MESH_NET_IF_LOCAL) { + /* Locally originated PDUs with TTL=1 will only be delivered + * to local elements as per Mesh Profile 1.0 section 3.4.5.2: + * "The output filter of the interface connected to + * advertising or GATT bearers shall drop all messages with + * TTL value set to 1." + */ + if (rx->ctx.recv_ttl == 1U) { + return; + } + } else { + if (rx->ctx.recv_ttl <= 1U) { + return; + } + } - if (rx->net_if == BT_MESH_NET_IF_ADV && - bt_mesh_relay_get() != BT_MESH_RELAY_ENABLED && - bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_ENABLED) { - return; - } + if (rx->net_if == BT_MESH_NET_IF_ADV && + bt_mesh_relay_get() != BT_MESH_RELAY_ENABLED && + bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_ENABLED) { + return; + } - BT_DBG("TTL %u CTL %u dst 0x%04x", rx->ctx.recv_ttl, rx->ctl, - rx->ctx.recv_dst); + BT_DBG("TTL %u CTL %u dst 0x%04x", rx->ctx.recv_ttl, rx->ctl, + rx->ctx.recv_dst); - /* The Relay Retransmit state is only applied to adv-adv relaying. - * Anything else (like GATT to adv, or locally originated packets) - * use the Network Transmit state. - */ - if (rx->net_if == BT_MESH_NET_IF_ADV) { - transmit = bt_mesh_relay_retransmit_get(); - } else { - transmit = bt_mesh_net_transmit_get(); - } + /* The Relay Retransmit state is only applied to adv-adv relaying. + * Anything else (like GATT to adv, or locally originated packets) + * use the Network Transmit state. + */ + if (rx->net_if == BT_MESH_NET_IF_ADV) { + transmit = bt_mesh_relay_retransmit_get(); + } else { + transmit = bt_mesh_net_transmit_get(); + } - buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, transmit, K_NO_WAIT); - if (!buf) { - BT_ERR("Out of relay buffers"); - return; - } + buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, transmit, K_NO_WAIT); + if (!buf) { + BT_ERR("Out of relay buffers"); + return; + } - /* Only decrement TTL for non-locally originated packets */ - if (rx->net_if != BT_MESH_NET_IF_LOCAL) { - /* Leave CTL bit intact */ - sbuf->data[1] &= 0x80; - sbuf->data[1] |= rx->ctx.recv_ttl - 1U; - } + /* Only decrement TTL for non-locally originated packets */ + if (rx->net_if != BT_MESH_NET_IF_LOCAL) { + /* Leave CTL bit intact */ + sbuf->data[1] &= 0x80; + sbuf->data[1] |= rx->ctx.recv_ttl - 1U; + } - net_buf_add_mem(buf, sbuf->data, sbuf->len); + net_buf_add_mem(buf, sbuf->data, sbuf->len); - enc = rx->sub->keys[rx->sub->kr_flag].enc; - priv = rx->sub->keys[rx->sub->kr_flag].privacy; - nid = rx->sub->keys[rx->sub->kr_flag].nid; + enc = rx->sub->keys[rx->sub->kr_flag].enc; + priv = rx->sub->keys[rx->sub->kr_flag].privacy; + nid = rx->sub->keys[rx->sub->kr_flag].nid; #ifdef CONFIG_BT_MESH_PTS - if (rx->net_if != BT_MESH_NET_IF_LOCAL) { - BT_PTS("[PTS] Relaying packet (TTL = 0x%02X)", TTL(buf->data)); - } + if (rx->net_if != BT_MESH_NET_IF_LOCAL) { + BT_PTS("[PTS] Relaying packet (TTL = 0x%02X)", TTL(buf->data)); + } #endif - BT_DBG("Relaying packet. TTL is now %u", TTL(buf->data)); + BT_DBG("Relaying packet. TTL is now %u", TTL(buf->data)); - /* Update NID if RX or RX was with friend credentials */ - if (rx->friend_cred) { - buf->data[0] &= 0x80; /* Clear everything except IVI */ - buf->data[0] |= nid; - } + /* Update NID if RX or RX was with friend credentials */ + if (rx->friend_cred) { + buf->data[0] &= 0x80; /* Clear everything except IVI */ + buf->data[0] |= nid; + } - /* We re-encrypt and obfuscate using the received IVI rather than - * the normal TX IVI (which may be different) since the transport - * layer nonce includes the IVI. - */ - if (bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_RX(rx), false)) { - BT_ERR("Re-encrypting failed"); - goto done; - } + /* We re-encrypt and obfuscate using the received IVI rather than + * the normal TX IVI (which may be different) since the transport + * layer nonce includes the IVI. + */ + if (bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_RX(rx), false)) { + BT_ERR("Re-encrypting failed"); + goto done; + } - if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) { - BT_ERR("Re-obfuscating failed"); - goto done; - } + if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) { + BT_ERR("Re-obfuscating failed"); + goto done; + } - /* Sending to the GATT bearer should only happen if GATT Proxy - * is enabled or the message originates from the local node. - */ - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && - (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED || - rx->net_if == BT_MESH_NET_IF_LOCAL)) { - if (bt_mesh_proxy_relay(&buf->b, rx->ctx.recv_dst) && - BT_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) { - goto done; - } - } + /* Sending to the GATT bearer should only happen if GATT Proxy + * is enabled or the message originates from the local node. + */ + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && + (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED || + rx->net_if == BT_MESH_NET_IF_LOCAL)) { + if (bt_mesh_proxy_relay(&buf->b, rx->ctx.recv_dst) && + BT_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) { + goto done; + } + } - if (relay_to_adv(rx->net_if)) { - bt_mesh_adv_send(buf, NULL, NULL); - } + if (relay_to_adv(rx->net_if)) { + bt_mesh_adv_send(buf, NULL, NULL); + } done: - net_buf_unref(buf); + net_buf_unref(buf); } int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if, - struct bt_mesh_net_rx *rx, struct net_buf_simple *buf) + struct bt_mesh_net_rx *rx, struct net_buf_simple *buf) { - if (data->len < BT_MESH_NET_MIN_PDU_LEN) { - BT_WARN("Dropping too short mesh packet (len %u)", data->len); - BT_WARN("%s", bt_hex(data->data, data->len)); - return -EINVAL; - } + if (data->len < BT_MESH_NET_MIN_PDU_LEN) { + BT_WARN("Dropping too short mesh packet (len %u)", data->len); + BT_WARN("%s", bt_hex(data->data, data->len)); + return -EINVAL; + } #if !defined(BFLB_BLE_MESH_PATCH_NET_DECODE) - if (net_if == BT_MESH_NET_IF_ADV && check_dup(data)) { - return -EINVAL; - } + if (net_if == BT_MESH_NET_IF_ADV && check_dup(data)) { + return -EINVAL; + } #endif - BT_DBG("%u bytes: %s", data->len, bt_hex(data->data, data->len)); + BT_DBG("%u bytes: %s", data->len, bt_hex(data->data, data->len)); - rx->net_if = net_if; + rx->net_if = net_if; - if (!net_find_and_decrypt(data->data, data->len, rx, buf)) { + if (!net_find_and_decrypt(data->data, data->len, rx, buf)) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Fail to decrypt packet"); + BT_PTS("[PTS] Fail to decrypt packet"); #endif - BT_DBG("Unable to find matching net for packet"); - return -ENOENT; - } + BT_DBG("Unable to find matching net for packet"); + return -ENOENT; + } - /* Initialize AppIdx to a sane value */ - rx->ctx.app_idx = BT_MESH_KEY_UNUSED; + /* Initialize AppIdx to a sane value */ + rx->ctx.app_idx = BT_MESH_KEY_UNUSED; - rx->ctx.recv_ttl = TTL(buf->data); + rx->ctx.recv_ttl = TTL(buf->data); - /* Default to responding with TTL 0 for non-routed messages */ - if (rx->ctx.recv_ttl == 0U) { - rx->ctx.send_ttl = 0U; - } else { - rx->ctx.send_ttl = BT_MESH_TTL_DEFAULT; - } + /* Default to responding with TTL 0 for non-routed messages */ + if (rx->ctx.recv_ttl == 0U) { + rx->ctx.send_ttl = 0U; + } else { + rx->ctx.send_ttl = BT_MESH_TTL_DEFAULT; + } - rx->ctl = CTL(buf->data); - rx->seq = SEQ(buf->data); - rx->ctx.recv_dst = DST(buf->data); + rx->ctl = CTL(buf->data); + rx->seq = SEQ(buf->data); + rx->ctx.recv_dst = DST(buf->data); - BT_DBG("Decryption successful. Payload len %u", buf->len); + BT_DBG("Decryption successful. Payload len %u", buf->len); - if (net_if != BT_MESH_NET_IF_PROXY_CFG && - rx->ctx.recv_dst == BT_MESH_ADDR_UNASSIGNED) { + if (net_if != BT_MESH_NET_IF_PROXY_CFG && + rx->ctx.recv_dst == BT_MESH_ADDR_UNASSIGNED) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Invalid address (DST = 0x%04X)", rx->ctx.recv_dst); + BT_PTS("[PTS] Invalid address (DST = 0x%04X)", rx->ctx.recv_dst); #endif - BT_ERR("Destination address is unassigned; dropping packet"); - return -EBADMSG; - } + BT_ERR("Destination address is unassigned; dropping packet"); + return -EBADMSG; + } - if (BT_MESH_ADDR_IS_RFU(rx->ctx.recv_dst)) { + if (BT_MESH_ADDR_IS_RFU(rx->ctx.recv_dst)) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] RFU address (DST = 0x%04X)", rx->ctx.recv_dst); + BT_PTS("[PTS] RFU address (DST = 0x%04X)", rx->ctx.recv_dst); #endif - BT_ERR("Destination address is RFU; dropping packet"); - return -EBADMSG; - } + BT_ERR("Destination address is RFU; dropping packet"); + return -EBADMSG; + } - if (net_if != BT_MESH_NET_IF_LOCAL && bt_mesh_elem_find(rx->ctx.addr)) { + if (net_if != BT_MESH_NET_IF_LOCAL && bt_mesh_elem_find(rx->ctx.addr)) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Invalid address (SRC = 0x%04X)", rx->ctx.addr); + BT_PTS("[PTS] Invalid address (SRC = 0x%04X)", rx->ctx.addr); #endif - BT_DBG("Dropping locally originated packet"); - return -EBADMSG; - } + BT_DBG("Dropping locally originated packet"); + return -EBADMSG; + } - BT_DBG("src 0x%04x dst 0x%04x ttl %u", rx->ctx.addr, rx->ctx.recv_dst, - rx->ctx.recv_ttl); - BT_DBG("PDU: %s", bt_hex(buf->data, buf->len)); + BT_DBG("src 0x%04x dst 0x%04x ttl %u", rx->ctx.addr, rx->ctx.recv_dst, + rx->ctx.recv_ttl); + BT_DBG("PDU: %s", bt_hex(buf->data, buf->len)); #ifdef CONFIG_BT_MESH_PTS - if (net_if != BT_MESH_NET_IF_LOCAL) { - BT_PTS("[PTS] Network packet received"); - BT_PTS("[PTS] - TTL: [0x%02X]", rx->ctx.recv_ttl); - BT_PTS("[PTS] - CTL: [0x%02X]", rx->ctl); - BT_PTS("[PTS] - SRC: [0x%04X]", rx->ctx.addr); - BT_PTS("[PTS] - DST: [0x%04X]", rx->ctx.recv_dst); - BT_PTS("[PTS] - TransportPDU: [%s]", bt_hex(buf->data + BT_MESH_NET_HDR_LEN, buf->len - BT_MESH_NET_HDR_LEN)); - } + if (net_if != BT_MESH_NET_IF_LOCAL) { + BT_PTS("[PTS] Network packet received"); + BT_PTS("[PTS] - TTL: [0x%02X]", rx->ctx.recv_ttl); + BT_PTS("[PTS] - CTL: [0x%02X]", rx->ctl); + BT_PTS("[PTS] - SRC: [0x%04X]", rx->ctx.addr); + BT_PTS("[PTS] - DST: [0x%04X]", rx->ctx.recv_dst); + BT_PTS("[PTS] - TransportPDU: [%s]", bt_hex(buf->data + BT_MESH_NET_HDR_LEN, buf->len - BT_MESH_NET_HDR_LEN)); + } #endif - return 0; + return 0; } void bt_mesh_net_recv(struct net_buf_simple *data, s8_t rssi, - enum bt_mesh_net_if net_if) + enum bt_mesh_net_if net_if) { - NET_BUF_SIMPLE_DEFINE(buf, 29); - struct bt_mesh_net_rx rx = { .ctx.recv_rssi = rssi }; - struct net_buf_simple_state state; + NET_BUF_SIMPLE_DEFINE(buf, 29); + struct bt_mesh_net_rx rx = { .ctx.recv_rssi = rssi }; + struct net_buf_simple_state state; - BT_DBG("rssi %d net_if %u", rssi, net_if); + BT_DBG("rssi %d net_if %u", rssi, net_if); - if (!bt_mesh_is_provisioned()) { - return; - } + if (!bt_mesh_is_provisioned()) { + return; + } - if (bt_mesh_net_decode(data, net_if, &rx, &buf)) { - return; - } + if (bt_mesh_net_decode(data, net_if, &rx, &buf)) { + return; + } - /* Save the state so the buffer can later be relayed */ - net_buf_simple_save(&buf, &state); + /* Save the state so the buffer can later be relayed */ + net_buf_simple_save(&buf, &state); - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && - net_if == BT_MESH_NET_IF_PROXY) { - bt_mesh_proxy_addr_add(data, rx.ctx.addr); - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && + net_if == BT_MESH_NET_IF_PROXY) { + bt_mesh_proxy_addr_add(data, rx.ctx.addr); + } - rx.local_match = (bt_mesh_fixed_group_match(rx.ctx.recv_dst) || - bt_mesh_elem_find(rx.ctx.recv_dst)); + rx.local_match = (bt_mesh_fixed_group_match(rx.ctx.recv_dst) || + bt_mesh_elem_find(rx.ctx.recv_dst)); - /* The transport layer has indicated that it has rejected the message, - * but would like to see it again if it is received in the future. - * This can happen if a message is received when the device is in - * Low Power mode, but the message was not encrypted with the friend - * credentials. Remove it from the message cache so that we accept - * it again in the future. - */ - if (bt_mesh_trans_recv(&buf, &rx) == -EAGAIN) { - BT_WARN("Removing rejected message from Network Message Cache"); - msg_cache[rx.msg_cache_idx] = 0ULL; - /* Rewind the next index now that we're not using this entry */ - msg_cache_next = rx.msg_cache_idx; - } + /* The transport layer has indicated that it has rejected the message, + * but would like to see it again if it is received in the future. + * This can happen if a message is received when the device is in + * Low Power mode, but the message was not encrypted with the friend + * credentials. Remove it from the message cache so that we accept + * it again in the future. + */ + if (bt_mesh_trans_recv(&buf, &rx) == -EAGAIN) { + BT_WARN("Removing rejected message from Network Message Cache"); + msg_cache[rx.msg_cache_idx] = 0ULL; + /* Rewind the next index now that we're not using this entry */ + msg_cache_next = rx.msg_cache_idx; + } - /* Relay if this was a group/virtual address, or if the destination - * was neither a local element nor an LPN we're Friends for. - */ - if (!BT_MESH_ADDR_IS_UNICAST(rx.ctx.recv_dst) || - (!rx.local_match && !rx.friend_match)) { - net_buf_simple_restore(&buf, &state); - bt_mesh_net_relay(&buf, &rx); - } + /* Relay if this was a group/virtual address, or if the destination + * was neither a local element nor an LPN we're Friends for. + */ + if (!BT_MESH_ADDR_IS_UNICAST(rx.ctx.recv_dst) || + (!rx.local_match && !rx.friend_match)) { + net_buf_simple_restore(&buf, &state); + bt_mesh_net_relay(&buf, &rx); + } } static void ivu_refresh(struct k_work *work) { - bt_mesh.ivu_duration += BT_MESH_IVU_HOURS; + bt_mesh.ivu_duration += BT_MESH_IVU_HOURS; - BT_DBG("%s for %u hour%s", - atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) ? - "IVU in Progress" : "IVU Normal mode", - bt_mesh.ivu_duration, bt_mesh.ivu_duration == 1U ? "" : "s"); + BT_DBG("%s for %u hour%s", + atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) ? + "IVU in Progress" : "IVU Normal mode", + bt_mesh.ivu_duration, bt_mesh.ivu_duration == 1U ? "" : "s"); - if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) { - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_iv(true); - } + if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) { + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_iv(true); + } - k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT); - return; - } + k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT); + return; + } - if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { - bt_mesh_beacon_ivu_initiator(true); - bt_mesh_net_iv_update(bt_mesh.iv_index, false); - } else if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_iv(true); - } + if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) { + bt_mesh_beacon_ivu_initiator(true); + bt_mesh_net_iv_update(bt_mesh.iv_index, false); + } else if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_iv(true); + } } void bt_mesh_net_start(void) { - if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) { - bt_mesh_beacon_enable(); - } else { - bt_mesh_beacon_disable(); - } + if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) { + bt_mesh_beacon_enable(); + } else { + bt_mesh_beacon_disable(); + } - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && - bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_NOT_SUPPORTED) { - bt_mesh_proxy_gatt_enable(); - bt_mesh_adv_update(); - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && + bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_NOT_SUPPORTED) { + bt_mesh_proxy_gatt_enable(); + bt_mesh_adv_update(); + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { - bt_mesh_lpn_init(); - } else { - bt_mesh_scan_enable(); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) { + bt_mesh_lpn_init(); + } else { + bt_mesh_scan_enable(); + } - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - bt_mesh_friend_init(); - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + bt_mesh_friend_init(); + } - if (IS_ENABLED(CONFIG_BT_MESH_PROV)) { - u16_t net_idx = bt_mesh.sub[0].net_idx; - u16_t addr = bt_mesh_primary_addr(); + if (IS_ENABLED(CONFIG_BT_MESH_PROV)) { + u16_t net_idx = bt_mesh.sub[0].net_idx; + u16_t addr = bt_mesh_primary_addr(); - bt_mesh_prov_complete(net_idx, addr); - } + bt_mesh_prov_complete(net_idx, addr); + } } void bt_mesh_net_init(void) { - k_delayed_work_init(&bt_mesh.ivu_timer, ivu_refresh); + k_delayed_work_init(&bt_mesh.ivu_timer, ivu_refresh); - k_work_init(&bt_mesh.local_work, bt_mesh_net_local); + k_work_init(&bt_mesh.local_work, bt_mesh_net_local); } diff --git a/components/network/ble/blemesh/src/net.h b/components/network/ble/blemesh/src/net.h index 387621ba..9c90cb9d 100644 --- a/components/network/ble/blemesh/src/net.h +++ b/components/network/ble/blemesh/src/net.h @@ -26,60 +26,60 @@ /* How many hours in between updating IVU duration */ #define BT_MESH_IVU_MIN_HOURS 96 #define BT_MESH_IVU_HOURS (BT_MESH_IVU_MIN_HOURS / \ - CONFIG_BT_MESH_IVU_DIVIDER) + CONFIG_BT_MESH_IVU_DIVIDER) #define BT_MESH_IVU_TIMEOUT K_HOURS(BT_MESH_IVU_HOURS) struct bt_mesh_app_key { - u16_t net_idx; - u16_t app_idx; - bool updated; - struct bt_mesh_app_keys { - u8_t id; - u8_t val[16]; - } keys[2]; + u16_t net_idx; + u16_t app_idx; + bool updated; + struct bt_mesh_app_keys { + u8_t id; + u8_t val[16]; + } keys[2]; }; struct bt_mesh_subnet { - u32_t beacon_sent; /* Timestamp of last sent beacon */ - u8_t beacons_last; /* Number of beacons during last - * observation window - */ - u8_t beacons_cur; /* Number of beaconds observed during - * currently ongoing window. - */ + u32_t beacon_sent; /* Timestamp of last sent beacon */ + u8_t beacons_last; /* Number of beacons during last + * observation window + */ + u8_t beacons_cur; /* Number of beaconds observed during + * currently ongoing window. + */ - u8_t beacon_cache[21]; /* Cached last authenticated beacon */ + u8_t beacon_cache[21]; /* Cached last authenticated beacon */ - u16_t net_idx; /* NetKeyIndex */ + u16_t net_idx; /* NetKeyIndex */ - bool kr_flag; /* Key Refresh Flag */ - u8_t kr_phase; /* Key Refresh Phase */ + bool kr_flag; /* Key Refresh Flag */ + u8_t kr_phase; /* Key Refresh Phase */ - u8_t node_id; /* Node Identity State */ - u32_t node_id_start; /* Node Identity started timestamp */ + u8_t node_id; /* Node Identity State */ + u32_t node_id_start; /* Node Identity started timestamp */ - u8_t auth[8]; /* Beacon Authentication Value */ + u8_t auth[8]; /* Beacon Authentication Value */ - struct bt_mesh_subnet_keys { - u8_t net[16]; /* NetKey */ - u8_t nid; /* NID */ - u8_t enc[16]; /* EncKey */ - u8_t net_id[8]; /* Network ID */ + struct bt_mesh_subnet_keys { + u8_t net[16]; /* NetKey */ + u8_t nid; /* NID */ + u8_t enc[16]; /* EncKey */ + u8_t net_id[8]; /* Network ID */ #if defined(CONFIG_BT_MESH_GATT_PROXY) - u8_t identity[16]; /* IdentityKey */ + u8_t identity[16]; /* IdentityKey */ #endif - u8_t privacy[16]; /* PrivacyKey */ - u8_t beacon[16]; /* BeaconKey */ - } keys[2]; + u8_t privacy[16]; /* PrivacyKey */ + u8_t beacon[16]; /* BeaconKey */ + } keys[2]; }; struct bt_mesh_rpl { - u16_t src; - bool old_iv; + u16_t src; + bool old_iv; #if defined(CONFIG_BT_SETTINGS) - bool store; + bool store; #endif - u32_t seq; + u32_t seq; }; #if defined(CONFIG_BT_MESH_FRIEND) @@ -91,48 +91,48 @@ struct bt_mesh_rpl { #endif struct bt_mesh_friend { - u16_t lpn; - u8_t recv_delay; - u8_t fsn:1, - send_last:1, - pending_req:1, - sec_update:1, - pending_buf:1, - valid:1, - established:1; - s32_t poll_to; - u8_t num_elem; - u16_t lpn_counter; - u16_t counter; + u16_t lpn; + u8_t recv_delay; + u8_t fsn:1, + send_last:1, + pending_req:1, + sec_update:1, + pending_buf:1, + valid:1, + established:1; + s32_t poll_to; + u8_t num_elem; + u16_t lpn_counter; + u16_t counter; - u16_t net_idx; + u16_t net_idx; - u16_t sub_list[FRIEND_SUB_LIST_SIZE]; + u16_t sub_list[FRIEND_SUB_LIST_SIZE]; - struct k_delayed_work timer; + struct k_delayed_work timer; - struct bt_mesh_friend_seg { - sys_slist_t queue; + struct bt_mesh_friend_seg { + sys_slist_t queue; - /* The target number of segments, i.e. not necessarily - * the current number of segments, in the queue. This is - * used for Friend Queue free space calculations. - */ - u8_t seg_count; - } seg[FRIEND_SEG_RX]; + /* The target number of segments, i.e. not necessarily + * the current number of segments, in the queue. This is + * used for Friend Queue free space calculations. + */ + u8_t seg_count; + } seg[FRIEND_SEG_RX]; - struct net_buf *last; + struct net_buf *last; - sys_slist_t queue; - u32_t queue_size; + sys_slist_t queue; + u32_t queue_size; - /* Friend Clear Procedure */ - struct { - u32_t start; /* Clear Procedure start */ - u16_t frnd; /* Previous Friend's address */ - u16_t repeat_sec; /* Repeat timeout in seconds */ - struct k_delayed_work timer; /* Repeat timer */ - } clear; + /* Friend Clear Procedure */ + struct { + u32_t start; /* Clear Procedure start */ + u16_t frnd; /* Previous Friend's address */ + u16_t repeat_sec; /* Repeat timeout in seconds */ + struct k_delayed_work timer; /* Repeat timer */ + } clear; }; #if defined(CONFIG_BT_MESH_LOW_POWER) @@ -143,171 +143,171 @@ struct bt_mesh_friend { /* Low Power Node state */ struct bt_mesh_lpn { - enum __packed { - BT_MESH_LPN_DISABLED, /* LPN feature is disabled */ - BT_MESH_LPN_CLEAR, /* Clear in progress */ - BT_MESH_LPN_TIMER, /* Waiting for auto timer expiry */ - BT_MESH_LPN_ENABLED, /* LPN enabled, but no Friend */ - BT_MESH_LPN_REQ_WAIT, /* Wait before scanning for offers */ - BT_MESH_LPN_WAIT_OFFER, /* Friend Req sent */ - BT_MESH_LPN_ESTABLISHED, /* Friendship established */ - BT_MESH_LPN_RECV_DELAY, /* Poll sent, waiting ReceiveDelay */ - BT_MESH_LPN_WAIT_UPDATE, /* Waiting for Update or message */ - } state; + enum __packed { + BT_MESH_LPN_DISABLED, /* LPN feature is disabled */ + BT_MESH_LPN_CLEAR, /* Clear in progress */ + BT_MESH_LPN_TIMER, /* Waiting for auto timer expiry */ + BT_MESH_LPN_ENABLED, /* LPN enabled, but no Friend */ + BT_MESH_LPN_REQ_WAIT, /* Wait before scanning for offers */ + BT_MESH_LPN_WAIT_OFFER, /* Friend Req sent */ + BT_MESH_LPN_ESTABLISHED, /* Friendship established */ + BT_MESH_LPN_RECV_DELAY, /* Poll sent, waiting ReceiveDelay */ + BT_MESH_LPN_WAIT_UPDATE, /* Waiting for Update or message */ + } state; - /* Transaction Number (used for subscription list) */ - u8_t xact_next; - u8_t xact_pending; - u8_t sent_req; + /* Transaction Number (used for subscription list) */ + u8_t xact_next; + u8_t xact_pending; + u8_t sent_req; - /* Address of our Friend when we're a LPN. Unassigned if we don't - * have a friend yet. - */ - u16_t frnd; + /* Address of our Friend when we're a LPN. Unassigned if we don't + * have a friend yet. + */ + u16_t frnd; - /* Value from the friend offer */ - u8_t recv_win; + /* Value from the friend offer */ + u8_t recv_win; - u8_t req_attempts; /* Number of Request attempts */ + u8_t req_attempts; /* Number of Request attempts */ - s32_t poll_timeout; + s32_t poll_timeout; - u8_t groups_changed:1, /* Friend Subscription List needs updating */ - pending_poll:1, /* Poll to be sent after subscription */ - disable:1, /* Disable LPN after clearing */ - fsn:1, /* Friend Sequence Number */ - established:1, /* Friendship established */ - clear_success:1; /* Friend Clear Confirm received */ + u8_t groups_changed:1, /* Friend Subscription List needs updating */ + pending_poll:1, /* Poll to be sent after subscription */ + disable:1, /* Disable LPN after clearing */ + fsn:1, /* Friend Sequence Number */ + established:1, /* Friendship established */ + clear_success:1; /* Friend Clear Confirm received */ - /* Friend Queue Size */ - u8_t queue_size; + /* Friend Queue Size */ + u8_t queue_size; - /* LPNCounter */ - u16_t counter; + /* LPNCounter */ + u16_t counter; - /* Previous Friend of this LPN */ - u16_t old_friend; + /* Previous Friend of this LPN */ + u16_t old_friend; - /* Duration reported for last advertising packet */ - u16_t adv_duration; + /* Duration reported for last advertising packet */ + u16_t adv_duration; - /* Next LPN related action timer */ - struct k_delayed_work timer; + /* Next LPN related action timer */ + struct k_delayed_work timer; - /* Subscribed groups */ - u16_t groups[LPN_GROUPS]; + /* Subscribed groups */ + u16_t groups[LPN_GROUPS]; - /* Bit fields for tracking which groups the Friend knows about */ - ATOMIC_DEFINE(added, LPN_GROUPS); - ATOMIC_DEFINE(pending, LPN_GROUPS); - ATOMIC_DEFINE(to_remove, LPN_GROUPS); + /* Bit fields for tracking which groups the Friend knows about */ + ATOMIC_DEFINE(added, LPN_GROUPS); + ATOMIC_DEFINE(pending, LPN_GROUPS); + ATOMIC_DEFINE(to_remove, LPN_GROUPS); }; /* bt_mesh_net.flags */ enum { - BT_MESH_VALID, /* We have been provisioned */ - BT_MESH_SUSPENDED, /* Network is temporarily suspended */ - BT_MESH_IVU_IN_PROGRESS, /* IV Update in Progress */ - BT_MESH_IVU_INITIATOR, /* IV Update initiated by us */ - BT_MESH_IVU_TEST, /* IV Update test mode */ - BT_MESH_IVU_PENDING, /* Update blocked by SDU in progress */ + BT_MESH_VALID, /* We have been provisioned */ + BT_MESH_SUSPENDED, /* Network is temporarily suspended */ + BT_MESH_IVU_IN_PROGRESS, /* IV Update in Progress */ + BT_MESH_IVU_INITIATOR, /* IV Update initiated by us */ + BT_MESH_IVU_TEST, /* IV Update test mode */ + BT_MESH_IVU_PENDING, /* Update blocked by SDU in progress */ - /* pending storage actions, must reside within first 32 flags */ - BT_MESH_RPL_PENDING, - BT_MESH_KEYS_PENDING, - BT_MESH_NET_PENDING, - BT_MESH_IV_PENDING, - BT_MESH_SEQ_PENDING, - BT_MESH_HB_PUB_PENDING, - BT_MESH_CFG_PENDING, - BT_MESH_MOD_PENDING, + /* pending storage actions, must reside within first 32 flags */ + BT_MESH_RPL_PENDING, + BT_MESH_KEYS_PENDING, + BT_MESH_NET_PENDING, + BT_MESH_IV_PENDING, + BT_MESH_SEQ_PENDING, + BT_MESH_HB_PUB_PENDING, + BT_MESH_CFG_PENDING, + BT_MESH_MOD_PENDING, - /* Don't touch - intentionally last */ - BT_MESH_FLAG_COUNT, + /* Don't touch - intentionally last */ + BT_MESH_FLAG_COUNT, }; struct bt_mesh_net { - u32_t iv_index; /* Current IV Index */ - u32_t seq; /* Next outgoing sequence number (24 bits) */ + u32_t iv_index; /* Current IV Index */ + u32_t seq; /* Next outgoing sequence number (24 bits) */ - ATOMIC_DEFINE(flags, BT_MESH_FLAG_COUNT); + ATOMIC_DEFINE(flags, BT_MESH_FLAG_COUNT); - /* Local network interface */ - struct k_work local_work; - sys_slist_t local_queue; + /* Local network interface */ + struct k_work local_work; + sys_slist_t local_queue; #if defined(CONFIG_BT_MESH_FRIEND) - /* Friend state, unique for each LPN that we're Friends for */ - struct bt_mesh_friend frnd[CONFIG_BT_MESH_FRIEND_LPN_COUNT]; + /* Friend state, unique for each LPN that we're Friends for */ + struct bt_mesh_friend frnd[CONFIG_BT_MESH_FRIEND_LPN_COUNT]; #endif #if defined(CONFIG_BT_MESH_LOW_POWER) - struct bt_mesh_lpn lpn; /* Low Power Node state */ + struct bt_mesh_lpn lpn; /* Low Power Node state */ #endif - /* Number of hours in current IV Update state */ - u8_t ivu_duration; + /* Number of hours in current IV Update state */ + u8_t ivu_duration; - /* Timer to track duration in current IV Update state */ - struct k_delayed_work ivu_timer; + /* Timer to track duration in current IV Update state */ + struct k_delayed_work ivu_timer; - u8_t dev_key[16]; + u8_t dev_key[16]; - struct bt_mesh_app_key app_keys[CONFIG_BT_MESH_APP_KEY_COUNT]; + struct bt_mesh_app_key app_keys[CONFIG_BT_MESH_APP_KEY_COUNT]; - struct bt_mesh_subnet sub[CONFIG_BT_MESH_SUBNET_COUNT]; + struct bt_mesh_subnet sub[CONFIG_BT_MESH_SUBNET_COUNT]; - struct bt_mesh_rpl rpl[CONFIG_BT_MESH_CRPL]; + struct bt_mesh_rpl rpl[CONFIG_BT_MESH_CRPL]; }; /* Network interface */ enum bt_mesh_net_if { - BT_MESH_NET_IF_ADV, - BT_MESH_NET_IF_LOCAL, - BT_MESH_NET_IF_PROXY, - BT_MESH_NET_IF_PROXY_CFG, + BT_MESH_NET_IF_ADV, + BT_MESH_NET_IF_LOCAL, + BT_MESH_NET_IF_PROXY, + BT_MESH_NET_IF_PROXY_CFG, }; /* Decoding context for Network/Transport data */ struct bt_mesh_net_rx { - struct bt_mesh_subnet *sub; - struct bt_mesh_msg_ctx ctx; - u32_t seq; /* Sequence Number */ - u8_t old_iv:1, /* iv_index - 1 was used */ - new_key:1, /* Data was encrypted with updated key */ - friend_cred:1, /* Data was encrypted with friend cred */ - ctl:1, /* Network Control */ - net_if:2, /* Network interface */ - local_match:1, /* Matched a local element */ - friend_match:1; /* Matched an LPN we're friends for */ - u16_t msg_cache_idx; /* Index of entry in message cache */ + struct bt_mesh_subnet *sub; + struct bt_mesh_msg_ctx ctx; + u32_t seq; /* Sequence Number */ + u8_t old_iv:1, /* iv_index - 1 was used */ + new_key:1, /* Data was encrypted with updated key */ + friend_cred:1, /* Data was encrypted with friend cred */ + ctl:1, /* Network Control */ + net_if:2, /* Network interface */ + local_match:1, /* Matched a local element */ + friend_match:1; /* Matched an LPN we're friends for */ + u16_t msg_cache_idx; /* Index of entry in message cache */ }; /* Encoding context for Network/Transport data */ struct bt_mesh_net_tx { - struct bt_mesh_subnet *sub; - struct bt_mesh_msg_ctx *ctx; - u16_t src; - u8_t xmit; - u8_t friend_cred:1, - aszmic:1, - aid:6; + struct bt_mesh_subnet *sub; + struct bt_mesh_msg_ctx *ctx; + u16_t src; + u8_t xmit; + u8_t friend_cred:1, + aszmic:1, + aid:6; }; extern struct bt_mesh_net bt_mesh; #define BT_MESH_NET_IVI_TX (bt_mesh.iv_index - \ - atomic_test_bit(bt_mesh.flags, \ - BT_MESH_IVU_IN_PROGRESS)) + atomic_test_bit(bt_mesh.flags, \ + BT_MESH_IVU_IN_PROGRESS)) #define BT_MESH_NET_IVI_RX(rx) (bt_mesh.iv_index - (rx)->old_iv) #define BT_MESH_NET_HDR_LEN 9 int bt_mesh_net_keys_create(struct bt_mesh_subnet_keys *keys, - const u8_t key[16]); + const u8_t key[16]); int bt_mesh_net_create(u16_t idx, u8_t flags, const u8_t key[16], - u32_t iv_index); + u32_t iv_index); u8_t bt_mesh_net_flags(struct bt_mesh_subnet *sub); @@ -326,24 +326,24 @@ void bt_mesh_net_sec_update(struct bt_mesh_subnet *sub); struct bt_mesh_subnet *bt_mesh_subnet_get(u16_t net_idx); struct bt_mesh_subnet *bt_mesh_subnet_find(const u8_t net_id[8], u8_t flags, - u32_t iv_index, const u8_t auth[8], - bool *new_key); + u32_t iv_index, const u8_t auth[8], + bool *new_key); int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf, - bool proxy); + bool proxy); int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf, - const struct bt_mesh_send_cb *cb, void *cb_data); + const struct bt_mesh_send_cb *cb, void *cb_data); int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf, - bool new_key, const struct bt_mesh_send_cb *cb, - void *cb_data); + bool new_key, const struct bt_mesh_send_cb *cb, + void *cb_data); int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if, - struct bt_mesh_net_rx *rx, struct net_buf_simple *buf); + struct bt_mesh_net_rx *rx, struct net_buf_simple *buf); void bt_mesh_net_recv(struct net_buf_simple *data, s8_t rssi, - enum bt_mesh_net_if net_if); + enum bt_mesh_net_if net_if); u32_t bt_mesh_next_seq(void); @@ -353,43 +353,43 @@ void bt_mesh_net_init(void); /* Friendship Credential Management */ struct friend_cred { - u16_t net_idx; - u16_t addr; + u16_t net_idx; + u16_t addr; - u16_t lpn_counter; - u16_t frnd_counter; + u16_t lpn_counter; + u16_t frnd_counter; - struct { - u8_t nid; /* NID */ - u8_t enc[16]; /* EncKey */ - u8_t privacy[16]; /* PrivacyKey */ - } cred[2]; + struct { + u8_t nid; /* NID */ + u8_t enc[16]; /* EncKey */ + u8_t privacy[16]; /* PrivacyKey */ + } cred[2]; }; int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, - const u8_t **enc, const u8_t **priv); + const u8_t **enc, const u8_t **priv); int friend_cred_set(struct friend_cred *cred, u8_t idx, const u8_t net_key[16]); void friend_cred_refresh(u16_t net_idx); int friend_cred_update(struct bt_mesh_subnet *sub); struct friend_cred *friend_cred_create(struct bt_mesh_subnet *sub, u16_t addr, - u16_t lpn_counter, u16_t frnd_counter); + u16_t lpn_counter, u16_t frnd_counter); void friend_cred_clear(struct friend_cred *cred); int friend_cred_del(u16_t net_idx, u16_t addr); static inline void send_cb_finalize(const struct bt_mesh_send_cb *cb, - void *cb_data) + void *cb_data) { - if (!cb) { - return; - } + if (!cb) { + return; + } - if (cb->start) { - cb->start(0, 0, cb_data); - } + if (cb->start) { + cb->start(0, 0, cb_data); + } - if (cb->end) { - cb->end(0, cb_data); - } + if (cb->end) { + cb->end(0, cb_data); + } } #endif /*__NET_H__*/ diff --git a/components/network/ble/blemesh/src/prov.c b/components/network/ble/blemesh/src/prov.c index fcda637e..a2dcc0f4 100644 --- a/components/network/ble/blemesh/src/prov.c +++ b/components/network/ble/blemesh/src/prov.c @@ -108,71 +108,71 @@ #define XACT_NVAL 0xff enum { - REMOTE_PUB_KEY, /* Remote key has been received */ - LINK_ACTIVE, /* Link has been opened */ - WAIT_NUMBER, /* Waiting for number input from user */ - WAIT_STRING, /* Waiting for string input from user */ - NOTIFY_INPUT_COMPLETE, /* Notify that input has been completed. */ - LINK_INVALID, /* Error occurred during provisioning */ + REMOTE_PUB_KEY, /* Remote key has been received */ + LINK_ACTIVE, /* Link has been opened */ + WAIT_NUMBER, /* Waiting for number input from user */ + WAIT_STRING, /* Waiting for string input from user */ + NOTIFY_INPUT_COMPLETE, /* Notify that input has been completed. */ + LINK_INVALID, /* Error occurred during provisioning */ - NUM_FLAGS, + NUM_FLAGS, }; struct prov_link { - ATOMIC_DEFINE(flags, NUM_FLAGS); + ATOMIC_DEFINE(flags, NUM_FLAGS); #if defined(CONFIG_BT_MESH_PB_GATT) - struct bt_conn *conn; /* GATT connection */ + struct bt_conn *conn; /* GATT connection */ #endif - u8_t dhkey[32]; /* Calculated DHKey */ - u8_t expect; /* Next expected PDU */ + u8_t dhkey[32]; /* Calculated DHKey */ + u8_t expect; /* Next expected PDU */ - u8_t oob_method; - u8_t oob_action; - u8_t oob_size; + u8_t oob_method; + u8_t oob_action; + u8_t oob_size; - u8_t conf[16]; /* Remote Confirmation */ - u8_t rand[16]; /* Local Random */ - u8_t auth[16]; /* Authentication Value */ + u8_t conf[16]; /* Remote Confirmation */ + u8_t rand[16]; /* Local Random */ + u8_t auth[16]; /* Authentication Value */ - u8_t conf_salt[16]; /* ConfirmationSalt */ - u8_t conf_key[16]; /* ConfirmationKey */ - u8_t conf_inputs[145]; /* ConfirmationInputs */ - u8_t prov_salt[16]; /* Provisioning Salt */ + u8_t conf_salt[16]; /* ConfirmationSalt */ + u8_t conf_key[16]; /* ConfirmationKey */ + u8_t conf_inputs[145]; /* ConfirmationInputs */ + u8_t prov_salt[16]; /* Provisioning Salt */ #if defined(CONFIG_BT_MESH_PB_ADV) - u32_t id; /* Link ID */ + u32_t id; /* Link ID */ - struct { - u8_t id; /* Transaction ID */ - u8_t prev_id; /* Previous Transaction ID */ - u8_t seg; /* Bit-field of unreceived segments */ - u8_t last_seg; /* Last segment (to check length) */ - u8_t fcs; /* Expected FCS value */ - struct net_buf_simple *buf; - } rx; + struct { + u8_t id; /* Transaction ID */ + u8_t prev_id; /* Previous Transaction ID */ + u8_t seg; /* Bit-field of unreceived segments */ + u8_t last_seg; /* Last segment (to check length) */ + u8_t fcs; /* Expected FCS value */ + struct net_buf_simple *buf; + } rx; - struct { - /* Start timestamp of the transaction */ - s64_t start; + struct { + /* Start timestamp of the transaction */ + s64_t start; - /* Transaction id*/ - u8_t id; + /* Transaction id*/ + u8_t id; - /* Pending outgoing buffer(s) */ - struct net_buf *buf[3]; + /* Pending outgoing buffer(s) */ + struct net_buf *buf[3]; - /* Retransmit timer */ - struct k_delayed_work retransmit; - } tx; + /* Retransmit timer */ + struct k_delayed_work retransmit; + } tx; #endif - struct k_delayed_work prot_timer; + struct k_delayed_work prot_timer; }; struct prov_rx { - u32_t link_id; - u8_t xact_id; - u8_t gpc; + u32_t link_id; + u8_t xact_id; + u8_t gpc; }; #define RETRANSMIT_TIMEOUT K_MSEC(500) @@ -188,7 +188,7 @@ NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65); #endif #define PROV_BUF(name, len) \ - NET_BUF_SIMPLE_DEFINE(name, PROV_BUF_HEADROOM + len) + NET_BUF_SIMPLE_DEFINE(name, PROV_BUF_HEADROOM + len) static struct prov_link link; @@ -198,288 +198,288 @@ static void pub_key_ready(const u8_t *pkey); static int reset_state(void) { - static struct bt_pub_key_cb pub_key_cb = { - .func = pub_key_ready, - }; - int err; + static struct bt_pub_key_cb pub_key_cb = { + .func = pub_key_ready, + }; + int err; - k_delayed_work_cancel(&link.prot_timer); + k_delayed_work_cancel(&link.prot_timer); - /* Disable Attention Timer if it was set */ - if (link.conf_inputs[0]) { - bt_mesh_attention(NULL, 0); - } + /* Disable Attention Timer if it was set */ + if (link.conf_inputs[0]) { + bt_mesh_attention(NULL, 0); + } #if defined(CONFIG_BT_MESH_PB_GATT) - if (link.conn) { - bt_conn_unref(link.conn); - } + if (link.conn) { + bt_conn_unref(link.conn); + } #endif #if defined(CONFIG_BT_MESH_PB_ADV) - /* Clear everything except the retransmit and protocol timer - * delayed work objects. - */ - (void)memset(&link, 0, offsetof(struct prov_link, tx.retransmit)); - link.rx.prev_id = XACT_NVAL; + /* Clear everything except the retransmit and protocol timer + * delayed work objects. + */ + (void)memset(&link, 0, offsetof(struct prov_link, tx.retransmit)); + link.rx.prev_id = XACT_NVAL; #if defined(CONFIG_BT_MESH_PB_GATT) - link.rx.buf = bt_mesh_proxy_get_buf(); + link.rx.buf = bt_mesh_proxy_get_buf(); #else - net_buf_simple_reset(&rx_buf); - link.rx.buf = &rx_buf; + net_buf_simple_reset(&rx_buf); + link.rx.buf = &rx_buf; #endif /* PB_GATT */ #else /* !PB_ADV */ - /* Clear everything except the protocol timer (k_delayed_work) */ - (void)memset(&link, 0, offsetof(struct prov_link, prot_timer)); + /* Clear everything except the protocol timer (k_delayed_work) */ + (void)memset(&link, 0, offsetof(struct prov_link, prot_timer)); #endif /* PB_ADV */ - err = bt_pub_key_gen(&pub_key_cb); - if (err) { - BT_ERR("Failed to generate public key (%d)", err); - return err; - } + err = bt_pub_key_gen(&pub_key_cb); + if (err) { + BT_ERR("Failed to generate public key (%d)", err); + return err; + } - return 0; + return 0; } #if defined(CONFIG_BT_MESH_PB_ADV) static void buf_sent(int err, void *user_data) { - if (!link.tx.buf[0]) { - return; - } + if (!link.tx.buf[0]) { + return; + } - k_delayed_work_submit(&link.tx.retransmit, RETRANSMIT_TIMEOUT); + k_delayed_work_submit(&link.tx.retransmit, RETRANSMIT_TIMEOUT); } static struct bt_mesh_send_cb buf_sent_cb = { - .end = buf_sent, + .end = buf_sent, }; static void free_segments(void) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(link.tx.buf); i++) { - struct net_buf *buf = link.tx.buf[i]; + for (i = 0; i < ARRAY_SIZE(link.tx.buf); i++) { + struct net_buf *buf = link.tx.buf[i]; - if (!buf) { - break; - } + if (!buf) { + break; + } - link.tx.buf[i] = NULL; - /* Mark as canceled */ - BT_MESH_ADV(buf)->busy = 0U; - net_buf_unref(buf); - } + link.tx.buf[i] = NULL; + /* Mark as canceled */ + BT_MESH_ADV(buf)->busy = 0U; + net_buf_unref(buf); + } } static void prov_clear_tx(void) { - BT_DBG(""); + BT_DBG(""); - k_delayed_work_cancel(&link.tx.retransmit); + k_delayed_work_cancel(&link.tx.retransmit); - free_segments(); + free_segments(); } static void reset_adv_link(void) { - prov_clear_tx(); + prov_clear_tx(); - if (prov->link_close) { - prov->link_close(BT_MESH_PROV_ADV); - } + if (prov->link_close) { + prov->link_close(BT_MESH_PROV_ADV); + } - reset_state(); + reset_state(); } static struct net_buf *adv_buf_create(void) { - struct net_buf *buf; + struct net_buf *buf; - buf = bt_mesh_adv_create(BT_MESH_ADV_PROV, PROV_XMIT, BUF_TIMEOUT); - if (!buf) { - BT_ERR("Out of provisioning buffers"); - return NULL; - } + buf = bt_mesh_adv_create(BT_MESH_ADV_PROV, PROV_XMIT, BUF_TIMEOUT); + if (!buf) { + BT_ERR("Out of provisioning buffers"); + return NULL; + } - return buf; + return buf; } static u8_t pending_ack = XACT_NVAL; static void ack_complete(u16_t duration, int err, void *user_data) { - BT_DBG("xact %u complete", (u8_t)pending_ack); - pending_ack = XACT_NVAL; + BT_DBG("xact %u complete", (u8_t)pending_ack); + pending_ack = XACT_NVAL; } static void gen_prov_ack_send(u8_t xact_id) { - static const struct bt_mesh_send_cb cb = { - .start = ack_complete, - }; - const struct bt_mesh_send_cb *complete; - struct net_buf *buf; + static const struct bt_mesh_send_cb cb = { + .start = ack_complete, + }; + const struct bt_mesh_send_cb *complete; + struct net_buf *buf; - BT_DBG("xact_id %u", xact_id); + BT_DBG("xact_id %u", xact_id); - if (pending_ack == xact_id) { - BT_DBG("Not sending duplicate ack"); - return; - } + if (pending_ack == xact_id) { + BT_DBG("Not sending duplicate ack"); + return; + } - buf = adv_buf_create(); - if (!buf) { - return; - } + buf = adv_buf_create(); + if (!buf) { + return; + } - if (pending_ack == XACT_NVAL) { - pending_ack = xact_id; - complete = &cb; - } else { - complete = NULL; - } + if (pending_ack == XACT_NVAL) { + pending_ack = xact_id; + complete = &cb; + } else { + complete = NULL; + } - net_buf_add_be32(buf, link.id); - net_buf_add_u8(buf, xact_id); - net_buf_add_u8(buf, GPC_ACK); + net_buf_add_be32(buf, link.id); + net_buf_add_u8(buf, xact_id); + net_buf_add_u8(buf, GPC_ACK); - bt_mesh_adv_send(buf, complete, NULL); - net_buf_unref(buf); + bt_mesh_adv_send(buf, complete, NULL); + net_buf_unref(buf); } static void send_reliable(void) { - int i; + int i; - link.tx.start = k_uptime_get(); + link.tx.start = k_uptime_get(); - for (i = 0; i < ARRAY_SIZE(link.tx.buf); i++) { - struct net_buf *buf = link.tx.buf[i]; + for (i = 0; i < ARRAY_SIZE(link.tx.buf); i++) { + struct net_buf *buf = link.tx.buf[i]; - if (!buf) { - break; - } + if (!buf) { + break; + } - if (i + 1 < ARRAY_SIZE(link.tx.buf) && link.tx.buf[i + 1]) { - bt_mesh_adv_send(buf, NULL, NULL); - } else { - bt_mesh_adv_send(buf, &buf_sent_cb, NULL); - } - } + if (i + 1 < ARRAY_SIZE(link.tx.buf) && link.tx.buf[i + 1]) { + bt_mesh_adv_send(buf, NULL, NULL); + } else { + bt_mesh_adv_send(buf, &buf_sent_cb, NULL); + } + } } static int bearer_ctl_send(u8_t op, void *data, u8_t data_len) { - struct net_buf *buf; + struct net_buf *buf; - BT_DBG("op 0x%02x data_len %u", op, data_len); + BT_DBG("op 0x%02x data_len %u", op, data_len); - prov_clear_tx(); + prov_clear_tx(); - buf = adv_buf_create(); - if (!buf) { - return -ENOBUFS; - } + buf = adv_buf_create(); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_be32(buf, link.id); - /* Transaction ID, always 0 for Bearer messages */ - net_buf_add_u8(buf, 0x00); - net_buf_add_u8(buf, GPC_CTL(op)); - net_buf_add_mem(buf, data, data_len); + net_buf_add_be32(buf, link.id); + /* Transaction ID, always 0 for Bearer messages */ + net_buf_add_u8(buf, 0x00); + net_buf_add_u8(buf, GPC_CTL(op)); + net_buf_add_mem(buf, data, data_len); - link.tx.buf[0] = buf; - send_reliable(); + link.tx.buf[0] = buf; + send_reliable(); - return 0; + return 0; } static u8_t last_seg(u8_t len) { - if (len <= START_PAYLOAD_MAX) { - return 0; - } + if (len <= START_PAYLOAD_MAX) { + return 0; + } - len -= START_PAYLOAD_MAX; + len -= START_PAYLOAD_MAX; - return 1 + (len / CONT_PAYLOAD_MAX); + return 1 + (len / CONT_PAYLOAD_MAX); } static inline u8_t next_transaction_id(void) { - if (link.tx.id != 0U && link.tx.id != 0xFF) { - return ++link.tx.id; - } + if (link.tx.id != 0U && link.tx.id != 0xFF) { + return ++link.tx.id; + } - link.tx.id = 0x80; - return link.tx.id; + link.tx.id = 0x80; + return link.tx.id; } static int prov_send_adv(struct net_buf_simple *msg) { - struct net_buf *start, *buf; - u8_t seg_len, seg_id; - u8_t xact_id; + struct net_buf *start, *buf; + u8_t seg_len, seg_id; + u8_t xact_id; - BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len)); + BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len)); - prov_clear_tx(); + prov_clear_tx(); - start = adv_buf_create(); - if (!start) { - return -ENOBUFS; - } + start = adv_buf_create(); + if (!start) { + return -ENOBUFS; + } - xact_id = next_transaction_id(); - net_buf_add_be32(start, link.id); - net_buf_add_u8(start, xact_id); + xact_id = next_transaction_id(); + net_buf_add_be32(start, link.id); + net_buf_add_u8(start, xact_id); - net_buf_add_u8(start, GPC_START(last_seg(msg->len))); - net_buf_add_be16(start, msg->len); - net_buf_add_u8(start, bt_mesh_fcs_calc(msg->data, msg->len)); + net_buf_add_u8(start, GPC_START(last_seg(msg->len))); + net_buf_add_be16(start, msg->len); + net_buf_add_u8(start, bt_mesh_fcs_calc(msg->data, msg->len)); - link.tx.buf[0] = start; + link.tx.buf[0] = start; - seg_len = MIN(msg->len, START_PAYLOAD_MAX); - BT_DBG("seg 0 len %u: %s", seg_len, bt_hex(msg->data, seg_len)); - net_buf_add_mem(start, msg->data, seg_len); - net_buf_simple_pull(msg, seg_len); + seg_len = MIN(msg->len, START_PAYLOAD_MAX); + BT_DBG("seg 0 len %u: %s", seg_len, bt_hex(msg->data, seg_len)); + net_buf_add_mem(start, msg->data, seg_len); + net_buf_simple_pull(msg, seg_len); - buf = start; - for (seg_id = 1U; msg->len > 0; seg_id++) { - if (seg_id >= ARRAY_SIZE(link.tx.buf)) { - BT_ERR("Too big message"); - free_segments(); - return -E2BIG; - } + buf = start; + for (seg_id = 1U; msg->len > 0; seg_id++) { + if (seg_id >= ARRAY_SIZE(link.tx.buf)) { + BT_ERR("Too big message"); + free_segments(); + return -E2BIG; + } - buf = adv_buf_create(); - if (!buf) { - free_segments(); - return -ENOBUFS; - } + buf = adv_buf_create(); + if (!buf) { + free_segments(); + return -ENOBUFS; + } - link.tx.buf[seg_id] = buf; + link.tx.buf[seg_id] = buf; - seg_len = MIN(msg->len, CONT_PAYLOAD_MAX); + seg_len = MIN(msg->len, CONT_PAYLOAD_MAX); - BT_DBG("seg_id %u len %u: %s", seg_id, seg_len, - bt_hex(msg->data, seg_len)); + BT_DBG("seg_id %u len %u: %s", seg_id, seg_len, + bt_hex(msg->data, seg_len)); - net_buf_add_be32(buf, link.id); - net_buf_add_u8(buf, xact_id); - net_buf_add_u8(buf, GPC_CONT(seg_id)); - net_buf_add_mem(buf, msg->data, seg_len); - net_buf_simple_pull(msg, seg_len); - } + net_buf_add_be32(buf, link.id); + net_buf_add_u8(buf, xact_id); + net_buf_add_u8(buf, GPC_CONT(seg_id)); + net_buf_add_mem(buf, msg->data, seg_len); + net_buf_simple_pull(msg, seg_len); + } - send_reliable(); + send_reliable(); - return 0; + return 0; } #endif /* CONFIG_BT_MESH_PB_ADV */ @@ -487,1165 +487,1165 @@ static int prov_send_adv(struct net_buf_simple *msg) #if defined(CONFIG_BT_MESH_PB_GATT) static int prov_send_gatt(struct net_buf_simple *msg) { - if (!link.conn) { - return -ENOTCONN; - } + if (!link.conn) { + return -ENOTCONN; + } - return bt_mesh_proxy_send(link.conn, BT_MESH_PROXY_PROV, msg); + return bt_mesh_proxy_send(link.conn, BT_MESH_PROXY_PROV, msg); } #endif /* CONFIG_BT_MESH_PB_GATT */ static inline int prov_send(struct net_buf_simple *buf) { - k_delayed_work_submit(&link.prot_timer, PROTOCOL_TIMEOUT); + k_delayed_work_submit(&link.prot_timer, PROTOCOL_TIMEOUT); #if defined(CONFIG_BT_MESH_PB_GATT) - if (link.conn) { - return prov_send_gatt(buf); - } + if (link.conn) { + return prov_send_gatt(buf); + } #endif #if defined(CONFIG_BT_MESH_PB_ADV) - return prov_send_adv(buf); + return prov_send_adv(buf); #else - return 0; + return 0; #endif } static void prov_buf_init(struct net_buf_simple *buf, u8_t type) { - net_buf_simple_reserve(buf, PROV_BUF_HEADROOM); - net_buf_simple_add_u8(buf, type); + net_buf_simple_reserve(buf, PROV_BUF_HEADROOM); + net_buf_simple_add_u8(buf, type); } static void prov_send_fail_msg(u8_t err) { - PROV_BUF(buf, 2); + PROV_BUF(buf, 2); - prov_buf_init(&buf, PROV_FAILED); - net_buf_simple_add_u8(&buf, err); + prov_buf_init(&buf, PROV_FAILED); + net_buf_simple_add_u8(&buf, err); - if (prov_send(&buf)) { - BT_ERR("Failed to send Provisioning Failed message"); - } + if (prov_send(&buf)) { + BT_ERR("Failed to send Provisioning Failed message"); + } - atomic_set_bit(link.flags, LINK_INVALID); + atomic_set_bit(link.flags, LINK_INVALID); } static void prov_invite(const u8_t *data) { - PROV_BUF(buf, 12); + PROV_BUF(buf, 12); - BT_DBG("Attention Duration: %u seconds", data[0]); + BT_DBG("Attention Duration: %u seconds", data[0]); - if (data[0]) { - bt_mesh_attention(NULL, data[0]); - } + if (data[0]) { + bt_mesh_attention(NULL, data[0]); + } - link.conf_inputs[0] = data[0]; + link.conf_inputs[0] = data[0]; - prov_buf_init(&buf, PROV_CAPABILITIES); + prov_buf_init(&buf, PROV_CAPABILITIES); - /* Number of Elements supported */ - net_buf_simple_add_u8(&buf, bt_mesh_elem_count()); + /* Number of Elements supported */ + net_buf_simple_add_u8(&buf, bt_mesh_elem_count()); - /* Supported algorithms - FIPS P-256 Eliptic Curve */ - net_buf_simple_add_be16(&buf, BIT(PROV_ALG_P256)); + /* Supported algorithms - FIPS P-256 Eliptic Curve */ + net_buf_simple_add_be16(&buf, BIT(PROV_ALG_P256)); - /* Public Key Type, Only "No OOB" Public Key is supported */ - net_buf_simple_add_u8(&buf, PUB_KEY_NO_OOB); + /* Public Key Type, Only "No OOB" Public Key is supported */ + net_buf_simple_add_u8(&buf, PUB_KEY_NO_OOB); - /* Static OOB Type */ - net_buf_simple_add_u8(&buf, prov->static_val ? BIT(0) : 0x00); + /* Static OOB Type */ + net_buf_simple_add_u8(&buf, prov->static_val ? BIT(0) : 0x00); - /* Output OOB Size */ - net_buf_simple_add_u8(&buf, prov->output_size); + /* Output OOB Size */ + net_buf_simple_add_u8(&buf, prov->output_size); - /* Output OOB Action */ - net_buf_simple_add_be16(&buf, prov->output_actions); + /* Output OOB Action */ + net_buf_simple_add_be16(&buf, prov->output_actions); - /* Input OOB Size */ - net_buf_simple_add_u8(&buf, prov->input_size); + /* Input OOB Size */ + net_buf_simple_add_u8(&buf, prov->input_size); - /* Input OOB Action */ - net_buf_simple_add_be16(&buf, prov->input_actions); + /* Input OOB Action */ + net_buf_simple_add_be16(&buf, prov->input_actions); - memcpy(&link.conf_inputs[1], &buf.data[1], 11); + memcpy(&link.conf_inputs[1], &buf.data[1], 11); - if (prov_send(&buf)) { - BT_ERR("Failed to send capabilities"); - return; - } + if (prov_send(&buf)) { + BT_ERR("Failed to send capabilities"); + return; + } - link.expect = PROV_START; + link.expect = PROV_START; } static void prov_capabilities(const u8_t *data) { - u16_t algorithms, output_action, input_action; + u16_t algorithms, output_action, input_action; (void)algorithms; (void)output_action; (void)input_action; - BT_DBG("Elements: %u", data[0]); + BT_DBG("Elements: %u", data[0]); - algorithms = sys_get_be16(&data[1]); - BT_DBG("Algorithms: %u", algorithms); + algorithms = sys_get_be16(&data[1]); + BT_DBG("Algorithms: %u", algorithms); - BT_DBG("Public Key Type: 0x%02x", data[3]); - BT_DBG("Static OOB Type: 0x%02x", data[4]); - BT_DBG("Output OOB Size: %u", data[5]); + BT_DBG("Public Key Type: 0x%02x", data[3]); + BT_DBG("Static OOB Type: 0x%02x", data[4]); + BT_DBG("Output OOB Size: %u", data[5]); - output_action = sys_get_be16(&data[6]); - BT_DBG("Output OOB Action: 0x%04x", output_action); + output_action = sys_get_be16(&data[6]); + BT_DBG("Output OOB Action: 0x%04x", output_action); - BT_DBG("Input OOB Size: %u", data[8]); + BT_DBG("Input OOB Size: %u", data[8]); - input_action = sys_get_be16(&data[9]); - BT_DBG("Input OOB Action: 0x%04x", input_action); + input_action = sys_get_be16(&data[9]); + BT_DBG("Input OOB Action: 0x%04x", input_action); } static bt_mesh_output_action_t output_action(u8_t action) { - switch (action) { - case OUTPUT_OOB_BLINK: - return BT_MESH_BLINK; - case OUTPUT_OOB_BEEP: - return BT_MESH_BEEP; - case OUTPUT_OOB_VIBRATE: - return BT_MESH_VIBRATE; - case OUTPUT_OOB_NUMBER: - return BT_MESH_DISPLAY_NUMBER; - case OUTPUT_OOB_STRING: - return BT_MESH_DISPLAY_STRING; - default: - return BT_MESH_NO_OUTPUT; - } + switch (action) { + case OUTPUT_OOB_BLINK: + return BT_MESH_BLINK; + case OUTPUT_OOB_BEEP: + return BT_MESH_BEEP; + case OUTPUT_OOB_VIBRATE: + return BT_MESH_VIBRATE; + case OUTPUT_OOB_NUMBER: + return BT_MESH_DISPLAY_NUMBER; + case OUTPUT_OOB_STRING: + return BT_MESH_DISPLAY_STRING; + default: + return BT_MESH_NO_OUTPUT; + } } static bt_mesh_input_action_t input_action(u8_t action) { - switch (action) { - case INPUT_OOB_PUSH: - return BT_MESH_PUSH; - case INPUT_OOB_TWIST: - return BT_MESH_TWIST; - case INPUT_OOB_NUMBER: - return BT_MESH_ENTER_NUMBER; - case INPUT_OOB_STRING: - return BT_MESH_ENTER_STRING; - default: - return BT_MESH_NO_INPUT; - } + switch (action) { + case INPUT_OOB_PUSH: + return BT_MESH_PUSH; + case INPUT_OOB_TWIST: + return BT_MESH_TWIST; + case INPUT_OOB_NUMBER: + return BT_MESH_ENTER_NUMBER; + case INPUT_OOB_STRING: + return BT_MESH_ENTER_STRING; + default: + return BT_MESH_NO_INPUT; + } } static int prov_auth(u8_t method, u8_t action, u8_t size) { - bt_mesh_output_action_t output; - bt_mesh_input_action_t input; + bt_mesh_output_action_t output; + bt_mesh_input_action_t input; - switch (method) { - case AUTH_METHOD_NO_OOB: - if (action || size) { - return -EINVAL; - } + switch (method) { + case AUTH_METHOD_NO_OOB: + if (action || size) { + return -EINVAL; + } - (void)memset(link.auth, 0, sizeof(link.auth)); - return 0; - case AUTH_METHOD_STATIC: - if (action || size) { - return -EINVAL; - } + (void)memset(link.auth, 0, sizeof(link.auth)); + return 0; + case AUTH_METHOD_STATIC: + if (action || size) { + return -EINVAL; + } - memcpy(link.auth + 16 - prov->static_val_len, - prov->static_val, prov->static_val_len); - (void)memset(link.auth, 0, - sizeof(link.auth) - prov->static_val_len); - return 0; + memcpy(link.auth + 16 - prov->static_val_len, + prov->static_val, prov->static_val_len); + (void)memset(link.auth, 0, + sizeof(link.auth) - prov->static_val_len); + return 0; - case AUTH_METHOD_OUTPUT: - output = output_action(action); - if (!output) { - return -EINVAL; - } + case AUTH_METHOD_OUTPUT: + output = output_action(action); + if (!output) { + return -EINVAL; + } - if (!(prov->output_actions & output)) { - return -EINVAL; - } + if (!(prov->output_actions & output)) { + return -EINVAL; + } - if (size > prov->output_size) { - return -EINVAL; - } + if (size > prov->output_size) { + return -EINVAL; + } - if (output == BT_MESH_DISPLAY_STRING) { - unsigned char str[9]; - u8_t i; + if (output == BT_MESH_DISPLAY_STRING) { + unsigned char str[9]; + u8_t i; - bt_rand(str, size); + bt_rand(str, size); - /* Normalize to '0' .. '9' & 'A' .. 'Z' */ - for (i = 0U; i < size; i++) { - str[i] %= 36; - if (str[i] < 10) { - str[i] += '0'; - } else { - str[i] += 'A' - 10; - } - } - str[size] = '\0'; + /* Normalize to '0' .. '9' & 'A' .. 'Z' */ + for (i = 0U; i < size; i++) { + str[i] %= 36; + if (str[i] < 10) { + str[i] += '0'; + } else { + str[i] += 'A' - 10; + } + } + str[size] = '\0'; - memcpy(link.auth, str, size); - (void)memset(link.auth + size, 0, - sizeof(link.auth) - size); + memcpy(link.auth, str, size); + (void)memset(link.auth + size, 0, + sizeof(link.auth) - size); - return prov->output_string((char *)str); - } else { - u32_t div[8] = { 10, 100, 1000, 10000, 100000, - 1000000, 10000000, 100000000 }; - u32_t num; + return prov->output_string((char *)str); + } else { + u32_t div[8] = { 10, 100, 1000, 10000, 100000, + 1000000, 10000000, 100000000 }; + u32_t num; - bt_rand(&num, sizeof(num)); - num %= div[size - 1]; + bt_rand(&num, sizeof(num)); + num %= div[size - 1]; - sys_put_be32(num, &link.auth[12]); - (void)memset(link.auth, 0, 12); + sys_put_be32(num, &link.auth[12]); + (void)memset(link.auth, 0, 12); - return prov->output_number(output, num); - } + return prov->output_number(output, num); + } - case AUTH_METHOD_INPUT: - input = input_action(action); - if (!input) { - return -EINVAL; - } + case AUTH_METHOD_INPUT: + input = input_action(action); + if (!input) { + return -EINVAL; + } - if (!(prov->input_actions & input)) { - return -EINVAL; - } + if (!(prov->input_actions & input)) { + return -EINVAL; + } - if (size > prov->input_size) { - return -EINVAL; - } + if (size > prov->input_size) { + return -EINVAL; + } - if (input == BT_MESH_ENTER_STRING) { - atomic_set_bit(link.flags, WAIT_STRING); - } else { - atomic_set_bit(link.flags, WAIT_NUMBER); - } + if (input == BT_MESH_ENTER_STRING) { + atomic_set_bit(link.flags, WAIT_STRING); + } else { + atomic_set_bit(link.flags, WAIT_NUMBER); + } - return prov->input(input, size); + return prov->input(input, size); - default: - return -EINVAL; - } + default: + return -EINVAL; + } } static void prov_start(const u8_t *data) { - BT_DBG("Algorithm: 0x%02x", data[0]); - BT_DBG("Public Key: 0x%02x", data[1]); - BT_DBG("Auth Method: 0x%02x", data[2]); - BT_DBG("Auth Action: 0x%02x", data[3]); - BT_DBG("Auth Size: 0x%02x", data[4]); + BT_DBG("Algorithm: 0x%02x", data[0]); + BT_DBG("Public Key: 0x%02x", data[1]); + BT_DBG("Auth Method: 0x%02x", data[2]); + BT_DBG("Auth Action: 0x%02x", data[3]); + BT_DBG("Auth Size: 0x%02x", data[4]); - if (data[0] != PROV_ALG_P256) { - BT_ERR("Unknown algorithm 0x%02x", data[0]); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } + if (data[0] != PROV_ALG_P256) { + BT_ERR("Unknown algorithm 0x%02x", data[0]); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } - if (data[1] != PUB_KEY_NO_OOB) { - BT_ERR("Invalid public key type: 0x%02x", data[1]); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } + if (data[1] != PUB_KEY_NO_OOB) { + BT_ERR("Invalid public key type: 0x%02x", data[1]); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } - memcpy(&link.conf_inputs[12], data, 5); + memcpy(&link.conf_inputs[12], data, 5); - link.expect = PROV_PUB_KEY; + link.expect = PROV_PUB_KEY; - if (prov_auth(data[2], data[3], data[4]) < 0) { - BT_ERR("Invalid authentication method: 0x%02x; " - "action: 0x%02x; size: 0x%02x", data[2], data[3], - data[4]); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - } + if (prov_auth(data[2], data[3], data[4]) < 0) { + BT_ERR("Invalid authentication method: 0x%02x; " + "action: 0x%02x; size: 0x%02x", data[2], data[3], + data[4]); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + } } static void send_confirm(void) { - PROV_BUF(cfm, 17); + PROV_BUF(cfm, 17); - BT_DBG("ConfInputs[0] %s", bt_hex(link.conf_inputs, 64)); - BT_DBG("ConfInputs[64] %s", bt_hex(&link.conf_inputs[64], 64)); - BT_DBG("ConfInputs[128] %s", bt_hex(&link.conf_inputs[128], 17)); - - if (bt_mesh_prov_conf_salt(link.conf_inputs, link.conf_salt)) { - BT_ERR("Unable to generate confirmation salt"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + BT_DBG("ConfInputs[0] %s", bt_hex(link.conf_inputs, 64)); + BT_DBG("ConfInputs[64] %s", bt_hex(&link.conf_inputs[64], 64)); + BT_DBG("ConfInputs[128] %s", bt_hex(&link.conf_inputs[128], 17)); - BT_DBG("ConfirmationSalt: %s", bt_hex(link.conf_salt, 16)); + if (bt_mesh_prov_conf_salt(link.conf_inputs, link.conf_salt)) { + BT_ERR("Unable to generate confirmation salt"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - if (bt_mesh_prov_conf_key(link.dhkey, link.conf_salt, link.conf_key)) { - BT_ERR("Unable to generate confirmation key"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + BT_DBG("ConfirmationSalt: %s", bt_hex(link.conf_salt, 16)); - BT_DBG("ConfirmationKey: %s", bt_hex(link.conf_key, 16)); + if (bt_mesh_prov_conf_key(link.dhkey, link.conf_salt, link.conf_key)) { + BT_ERR("Unable to generate confirmation key"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - if (bt_rand(link.rand, 16)) { - BT_ERR("Unable to generate random number"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + BT_DBG("ConfirmationKey: %s", bt_hex(link.conf_key, 16)); - BT_DBG("LocalRandom: %s", bt_hex(link.rand, 16)); + if (bt_rand(link.rand, 16)) { + BT_ERR("Unable to generate random number"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - prov_buf_init(&cfm, PROV_CONFIRM); + BT_DBG("LocalRandom: %s", bt_hex(link.rand, 16)); - if (bt_mesh_prov_conf(link.conf_key, link.rand, link.auth, - net_buf_simple_add(&cfm, 16))) { - BT_ERR("Unable to generate confirmation value"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + prov_buf_init(&cfm, PROV_CONFIRM); - if (prov_send(&cfm)) { - BT_ERR("Failed to send Provisioning Confirm"); - return; - } + if (bt_mesh_prov_conf(link.conf_key, link.rand, link.auth, + net_buf_simple_add(&cfm, 16))) { + BT_ERR("Unable to generate confirmation value"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - link.expect = PROV_RANDOM; + if (prov_send(&cfm)) { + BT_ERR("Failed to send Provisioning Confirm"); + return; + } + + link.expect = PROV_RANDOM; } static void send_input_complete(void) { - PROV_BUF(buf, 1); + PROV_BUF(buf, 1); - prov_buf_init(&buf, PROV_INPUT_COMPLETE); - if (prov_send(&buf)) { - BT_ERR("Failed to send Provisioning Input Complete"); - } - link.expect = PROV_CONFIRM; + prov_buf_init(&buf, PROV_INPUT_COMPLETE); + if (prov_send(&buf)) { + BT_ERR("Failed to send Provisioning Input Complete"); + } + link.expect = PROV_CONFIRM; } int bt_mesh_input_number(u32_t num) { - BT_DBG("%u", num); + BT_DBG("%u", num); - if (!atomic_test_and_clear_bit(link.flags, WAIT_NUMBER)) { - return -EINVAL; - } + if (!atomic_test_and_clear_bit(link.flags, WAIT_NUMBER)) { + return -EINVAL; + } - sys_put_be32(num, &link.auth[12]); + sys_put_be32(num, &link.auth[12]); - send_input_complete(); + send_input_complete(); - return 0; + return 0; } int bt_mesh_input_string(const char *str) { - BT_DBG("%s", str); + BT_DBG("%s", str); - if (!atomic_test_and_clear_bit(link.flags, WAIT_STRING)) { - return -EINVAL; - } + if (!atomic_test_and_clear_bit(link.flags, WAIT_STRING)) { + return -EINVAL; + } #if defined(BFLB_BLE) strncpy((char *)link.auth, str, prov->input_size); #else - strncpy(link.auth, str, prov->input_size); + strncpy(link.auth, str, prov->input_size); #endif - send_input_complete(); + send_input_complete(); - return 0; + return 0; } static void send_pub_key(const u8_t dhkey[32]) { - PROV_BUF(buf, 65); - const u8_t *key; + PROV_BUF(buf, 65); + const u8_t *key; - BT_DBG("%p", dhkey); + BT_DBG("%p", dhkey); - if (!dhkey) { - BT_ERR("DHKey generation failed"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + if (!dhkey) { + BT_ERR("DHKey generation failed"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - sys_memcpy_swap(link.dhkey, dhkey, 32); + sys_memcpy_swap(link.dhkey, dhkey, 32); - BT_DBG("DHkey: %s", bt_hex(link.dhkey, 32)); + BT_DBG("DHkey: %s", bt_hex(link.dhkey, 32)); - key = bt_pub_key_get(); - if (!key) { - BT_ERR("No public key available"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + key = bt_pub_key_get(); + if (!key) { + BT_ERR("No public key available"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - BT_DBG("Local Public Key: %s", bt_hex(key, 64)); + BT_DBG("Local Public Key: %s", bt_hex(key, 64)); - prov_buf_init(&buf, PROV_PUB_KEY); + prov_buf_init(&buf, PROV_PUB_KEY); - /* Swap X and Y halves independently to big-endian */ - sys_memcpy_swap(net_buf_simple_add(&buf, 32), key, 32); - sys_memcpy_swap(net_buf_simple_add(&buf, 32), &key[32], 32); + /* Swap X and Y halves independently to big-endian */ + sys_memcpy_swap(net_buf_simple_add(&buf, 32), key, 32); + sys_memcpy_swap(net_buf_simple_add(&buf, 32), &key[32], 32); - memcpy(&link.conf_inputs[81], &buf.data[1], 64); + memcpy(&link.conf_inputs[81], &buf.data[1], 64); - if (prov_send(&buf)) { - BT_ERR("Failed to send Public Key"); - return; - } + if (prov_send(&buf)) { + BT_ERR("Failed to send Public Key"); + return; + } - if (atomic_test_bit(link.flags, WAIT_NUMBER) || atomic_test_bit(link.flags, WAIT_STRING)) { - link.expect = PROV_NO_PDU; /* Wait for input */ - } else { - link.expect = PROV_CONFIRM; - } + if (atomic_test_bit(link.flags, WAIT_NUMBER) || atomic_test_bit(link.flags, WAIT_STRING)) { + link.expect = PROV_NO_PDU; /* Wait for input */ + } else { + link.expect = PROV_CONFIRM; + } } static void prov_dh_key_gen(void) { - u8_t remote_pk[64]; + u8_t remote_pk[64]; - /* Copy remote key in little-endian for bt_dh_key_gen(). - * X and Y halves are swapped independently. Use response - * buffer as a temporary storage location. The bt_dh_key_gen() - * will also take care of validating the remote public key. - */ - sys_memcpy_swap(remote_pk, &link.conf_inputs[17], 32); - sys_memcpy_swap(&remote_pk[32], &link.conf_inputs[49], 32); - - if (bt_dh_key_gen(remote_pk, send_pub_key)) { - BT_ERR("Failed to generate DHKey"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - } + /* Copy remote key in little-endian for bt_dh_key_gen(). + * X and Y halves are swapped independently. Use response + * buffer as a temporary storage location. The bt_dh_key_gen() + * will also take care of validating the remote public key. + */ + sys_memcpy_swap(remote_pk, &link.conf_inputs[17], 32); + sys_memcpy_swap(&remote_pk[32], &link.conf_inputs[49], 32); + + if (bt_dh_key_gen(remote_pk, send_pub_key)) { + BT_ERR("Failed to generate DHKey"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + } } static void prov_pub_key(const u8_t *data) { - BT_DBG("Remote Public Key: %s", bt_hex(data, 64)); + BT_DBG("Remote Public Key: %s", bt_hex(data, 64)); - memcpy(&link.conf_inputs[17], data, 64); + memcpy(&link.conf_inputs[17], data, 64); - if (!bt_pub_key_get()) { - /* Clear retransmit timer */ + if (!bt_pub_key_get()) { + /* Clear retransmit timer */ #if defined(CONFIG_BT_MESH_PB_ADV) - prov_clear_tx(); + prov_clear_tx(); #endif - atomic_set_bit(link.flags, REMOTE_PUB_KEY); - BT_WARN("Waiting for local public key"); - return; - } + atomic_set_bit(link.flags, REMOTE_PUB_KEY); + BT_WARN("Waiting for local public key"); + return; + } - prov_dh_key_gen(); + prov_dh_key_gen(); } static void pub_key_ready(const u8_t *pkey) { - if (!pkey) { - BT_WARN("Public key not available"); - return; - } + if (!pkey) { + BT_WARN("Public key not available"); + return; + } - BT_DBG("Local public key ready"); + BT_DBG("Local public key ready"); - if (atomic_test_and_clear_bit(link.flags, REMOTE_PUB_KEY)) { - prov_dh_key_gen(); - } + if (atomic_test_and_clear_bit(link.flags, REMOTE_PUB_KEY)) { + prov_dh_key_gen(); + } } static void notify_input_complete(void) { - if (atomic_test_and_clear_bit(link.flags, NOTIFY_INPUT_COMPLETE) && - prov->input_complete) { - prov->input_complete(); - } + if (atomic_test_and_clear_bit(link.flags, NOTIFY_INPUT_COMPLETE) && + prov->input_complete) { + prov->input_complete(); + } } static void prov_input_complete(const u8_t *data) { - BT_DBG(""); - notify_input_complete(); + BT_DBG(""); + notify_input_complete(); } static void prov_confirm(const u8_t *data) { - BT_DBG("Remote Confirm: %s", bt_hex(data, 16)); + BT_DBG("Remote Confirm: %s", bt_hex(data, 16)); - memcpy(link.conf, data, 16); + memcpy(link.conf, data, 16); - send_confirm(); + send_confirm(); } static void prov_random(const u8_t *data) { - PROV_BUF(rnd, 16); - u8_t conf_verify[16]; + PROV_BUF(rnd, 16); + u8_t conf_verify[16]; - BT_DBG("Remote Random: %s", bt_hex(data, 16)); + BT_DBG("Remote Random: %s", bt_hex(data, 16)); - if (bt_mesh_prov_conf(link.conf_key, data, link.auth, conf_verify)) { - BT_ERR("Unable to calculate confirmation verification"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + if (bt_mesh_prov_conf(link.conf_key, data, link.auth, conf_verify)) { + BT_ERR("Unable to calculate confirmation verification"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - if (memcmp(conf_verify, link.conf, 16)) { - BT_ERR("Invalid confirmation value"); - BT_DBG("Received: %s", bt_hex(link.conf, 16)); - BT_DBG("Calculated: %s", bt_hex(conf_verify, 16)); - prov_send_fail_msg(PROV_ERR_CFM_FAILED); - return; - } + if (memcmp(conf_verify, link.conf, 16)) { + BT_ERR("Invalid confirmation value"); + BT_DBG("Received: %s", bt_hex(link.conf, 16)); + BT_DBG("Calculated: %s", bt_hex(conf_verify, 16)); + prov_send_fail_msg(PROV_ERR_CFM_FAILED); + return; + } - prov_buf_init(&rnd, PROV_RANDOM); - net_buf_simple_add_mem(&rnd, link.rand, 16); + prov_buf_init(&rnd, PROV_RANDOM); + net_buf_simple_add_mem(&rnd, link.rand, 16); - if (prov_send(&rnd)) { - BT_ERR("Failed to send Provisioning Random"); - return; - } + if (prov_send(&rnd)) { + BT_ERR("Failed to send Provisioning Random"); + return; + } - if (bt_mesh_prov_salt(link.conf_salt, data, link.rand, - link.prov_salt)) { - BT_ERR("Failed to generate provisioning salt"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + if (bt_mesh_prov_salt(link.conf_salt, data, link.rand, + link.prov_salt)) { + BT_ERR("Failed to generate provisioning salt"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - BT_DBG("ProvisioningSalt: %s", bt_hex(link.prov_salt, 16)); + BT_DBG("ProvisioningSalt: %s", bt_hex(link.prov_salt, 16)); - link.expect = PROV_DATA; + link.expect = PROV_DATA; } static inline bool is_pb_gatt(void) { #if defined(CONFIG_BT_MESH_PB_GATT) - return !!link.conn; + return !!link.conn; #else - return false; + return false; #endif } static void prov_data(const u8_t *data) { - PROV_BUF(msg, 1); - u8_t session_key[16]; - u8_t nonce[13]; - u8_t dev_key[16]; - u8_t pdu[25]; - u8_t flags; - u32_t iv_index; - u16_t addr; - u16_t net_idx; - int err; - bool identity_enable; + PROV_BUF(msg, 1); + u8_t session_key[16]; + u8_t nonce[13]; + u8_t dev_key[16]; + u8_t pdu[25]; + u8_t flags; + u32_t iv_index; + u16_t addr; + u16_t net_idx; + int err; + bool identity_enable; - BT_DBG(""); + BT_DBG(""); - err = bt_mesh_session_key(link.dhkey, link.prov_salt, session_key); - if (err) { - BT_ERR("Unable to generate session key"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + err = bt_mesh_session_key(link.dhkey, link.prov_salt, session_key); + if (err) { + BT_ERR("Unable to generate session key"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - BT_DBG("SessionKey: %s", bt_hex(session_key, 16)); + BT_DBG("SessionKey: %s", bt_hex(session_key, 16)); - err = bt_mesh_prov_nonce(link.dhkey, link.prov_salt, nonce); - if (err) { - BT_ERR("Unable to generate session nonce"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + err = bt_mesh_prov_nonce(link.dhkey, link.prov_salt, nonce); + if (err) { + BT_ERR("Unable to generate session nonce"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - BT_DBG("Nonce: %s", bt_hex(nonce, 13)); + BT_DBG("Nonce: %s", bt_hex(nonce, 13)); - err = bt_mesh_prov_decrypt(session_key, nonce, data, pdu); - if (err) { - BT_ERR("Unable to decrypt provisioning data"); - prov_send_fail_msg(PROV_ERR_DECRYPT); - return; - } + err = bt_mesh_prov_decrypt(session_key, nonce, data, pdu); + if (err) { + BT_ERR("Unable to decrypt provisioning data"); + prov_send_fail_msg(PROV_ERR_DECRYPT); + return; + } - err = bt_mesh_dev_key(link.dhkey, link.prov_salt, dev_key); - if (err) { - BT_ERR("Unable to generate device key"); - prov_send_fail_msg(PROV_ERR_UNEXP_ERR); - return; - } + err = bt_mesh_dev_key(link.dhkey, link.prov_salt, dev_key); + if (err) { + BT_ERR("Unable to generate device key"); + prov_send_fail_msg(PROV_ERR_UNEXP_ERR); + return; + } - BT_DBG("DevKey: %s", bt_hex(dev_key, 16)); + BT_DBG("DevKey: %s", bt_hex(dev_key, 16)); - net_idx = sys_get_be16(&pdu[16]); - flags = pdu[18]; - iv_index = sys_get_be32(&pdu[19]); - addr = sys_get_be16(&pdu[23]); + net_idx = sys_get_be16(&pdu[16]); + flags = pdu[18]; + iv_index = sys_get_be32(&pdu[19]); + addr = sys_get_be16(&pdu[23]); - BT_DBG("net_idx %u iv_index 0x%08x, addr 0x%04x", - net_idx, iv_index, addr); + BT_DBG("net_idx %u iv_index 0x%08x, addr 0x%04x", + net_idx, iv_index, addr); - prov_buf_init(&msg, PROV_COMPLETE); - if (prov_send(&msg)) { - BT_ERR("Failed to send Provisioning Complete"); - return; - } + prov_buf_init(&msg, PROV_COMPLETE); + if (prov_send(&msg)) { + BT_ERR("Failed to send Provisioning Complete"); + return; + } - /* Ignore any further PDUs on this link */ - link.expect = PROV_NO_PDU; + /* Ignore any further PDUs on this link */ + link.expect = PROV_NO_PDU; - /* Store info, since bt_mesh_provision() will end up clearing it */ - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { - identity_enable = is_pb_gatt(); - } else { - identity_enable = false; - } + /* Store info, since bt_mesh_provision() will end up clearing it */ + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { + identity_enable = is_pb_gatt(); + } else { + identity_enable = false; + } - err = bt_mesh_provision(pdu, net_idx, flags, iv_index, addr, dev_key); - if (err) { - BT_ERR("Failed to provision (err %d)", err); - return; - } + err = bt_mesh_provision(pdu, net_idx, flags, iv_index, addr, dev_key); + if (err) { + BT_ERR("Failed to provision (err %d)", err); + return; + } - /* After PB-GATT provisioning we should start advertising - * using Node Identity. - */ - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && identity_enable) { - bt_mesh_proxy_identity_enable(); - } + /* After PB-GATT provisioning we should start advertising + * using Node Identity. + */ + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && identity_enable) { + bt_mesh_proxy_identity_enable(); + } } static void prov_complete(const u8_t *data) { - BT_DBG(""); + BT_DBG(""); } static void prov_failed(const u8_t *data) { - BT_WARN("Error: 0x%02x", data[0]); + BT_WARN("Error: 0x%02x", data[0]); } static const struct { - void (*func)(const u8_t *data); - u16_t len; + void (*func)(const u8_t *data); + u16_t len; } prov_handlers[] = { - { prov_invite, 1 }, - { prov_capabilities, 11 }, - { prov_start, 5, }, - { prov_pub_key, 64 }, - { prov_input_complete, 0 }, - { prov_confirm, 16 }, - { prov_random, 16 }, - { prov_data, 33 }, - { prov_complete, 0 }, - { prov_failed, 1 }, + { prov_invite, 1 }, + { prov_capabilities, 11 }, + { prov_start, 5, }, + { prov_pub_key, 64 }, + { prov_input_complete, 0 }, + { prov_confirm, 16 }, + { prov_random, 16 }, + { prov_data, 33 }, + { prov_complete, 0 }, + { prov_failed, 1 }, }; #if defined(CONFIG_BT_MESH_PB_ADV) static void prov_retransmit(struct k_work *work) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - if (!atomic_test_bit(link.flags, LINK_ACTIVE)) { - BT_WARN("Link not active"); - return; - } + if (!atomic_test_bit(link.flags, LINK_ACTIVE)) { + BT_WARN("Link not active"); + return; + } - if (k_uptime_get() - link.tx.start > TRANSACTION_TIMEOUT) { + if (k_uptime_get() - link.tx.start > TRANSACTION_TIMEOUT) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Link (Link ID = 0x%08X) timeout", link.id); + BT_PTS("[PTS] Link (Link ID = 0x%08X) timeout", link.id); #endif - BT_WARN("Giving up transaction"); - reset_adv_link(); - return; - } + BT_WARN("Giving up transaction"); + reset_adv_link(); + return; + } - for (i = 0; i < ARRAY_SIZE(link.tx.buf); i++) { - struct net_buf *buf = link.tx.buf[i]; + for (i = 0; i < ARRAY_SIZE(link.tx.buf); i++) { + struct net_buf *buf = link.tx.buf[i]; - if (!buf) { - break; - } + if (!buf) { + break; + } - if (BT_MESH_ADV(buf)->busy) { - continue; - } + if (BT_MESH_ADV(buf)->busy) { + continue; + } - BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); - if (i + 1 < ARRAY_SIZE(link.tx.buf) && link.tx.buf[i + 1]) { - bt_mesh_adv_send(buf, NULL, NULL); - } else { - bt_mesh_adv_send(buf, &buf_sent_cb, NULL); - } + if (i + 1 < ARRAY_SIZE(link.tx.buf) && link.tx.buf[i + 1]) { + bt_mesh_adv_send(buf, NULL, NULL); + } else { + bt_mesh_adv_send(buf, &buf_sent_cb, NULL); + } - } + } } static void link_open(struct prov_rx *rx, struct net_buf_simple *buf) { - BT_DBG("len %u", buf->len); + BT_DBG("len %u", buf->len); - if (buf->len < 16) { - BT_ERR("Too short bearer open message (len %u)", buf->len); - return; - } + if (buf->len < 16) { + BT_ERR("Too short bearer open message (len %u)", buf->len); + return; + } - if (atomic_test_bit(link.flags, LINK_ACTIVE)) { - /* Send another link ack if the provisioner missed the last */ - if (link.id == rx->link_id && link.expect == PROV_INVITE) { - BT_DBG("Resending link ack"); - bearer_ctl_send(LINK_ACK, NULL, 0); - } else { - BT_WARN("Ignoring bearer open: link already active"); - } + if (atomic_test_bit(link.flags, LINK_ACTIVE)) { + /* Send another link ack if the provisioner missed the last */ + if (link.id == rx->link_id && link.expect == PROV_INVITE) { + BT_DBG("Resending link ack"); + bearer_ctl_send(LINK_ACK, NULL, 0); + } else { + BT_WARN("Ignoring bearer open: link already active"); + } - return; - } + return; + } - if (memcmp(buf->data, prov->uuid, 16)) { + if (memcmp(buf->data, prov->uuid, 16)) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Link Open (UUID = %s) received and ignored", bt_hex(buf->data, 16)); + BT_PTS("[PTS] Link Open (UUID = %s) received and ignored", bt_hex(buf->data, 16)); #endif - BT_DBG("Bearer open message not for us"); - return; - } + BT_DBG("Bearer open message not for us"); + return; + } #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Link Open (Link ID = 0x%08X) received", rx->link_id); + BT_PTS("[PTS] Link Open (Link ID = 0x%08X) received", rx->link_id); #endif - if (prov->link_open) { - prov->link_open(BT_MESH_PROV_ADV); - } + if (prov->link_open) { + prov->link_open(BT_MESH_PROV_ADV); + } - link.id = rx->link_id; - atomic_set_bit(link.flags, LINK_ACTIVE); - net_buf_simple_reset(link.rx.buf); + link.id = rx->link_id; + atomic_set_bit(link.flags, LINK_ACTIVE); + net_buf_simple_reset(link.rx.buf); - bearer_ctl_send(LINK_ACK, NULL, 0); + bearer_ctl_send(LINK_ACK, NULL, 0); - link.expect = PROV_INVITE; + link.expect = PROV_INVITE; } static void link_ack(struct prov_rx *rx, struct net_buf_simple *buf) { - BT_DBG("len %u", buf->len); + BT_DBG("len %u", buf->len); } static void link_close(struct prov_rx *rx, struct net_buf_simple *buf) { - BT_DBG("len %u", buf->len); + BT_DBG("len %u", buf->len); #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Link Close (Link ID = 0x%08X) received", rx->link_id); + BT_PTS("[PTS] Link Close (Link ID = 0x%08X) received", rx->link_id); #endif - reset_adv_link(); + reset_adv_link(); } static void gen_prov_ctl(struct prov_rx *rx, struct net_buf_simple *buf) { - BT_DBG("op 0x%02x len %u", BEARER_CTL(rx->gpc), buf->len); + BT_DBG("op 0x%02x len %u", BEARER_CTL(rx->gpc), buf->len); - switch (BEARER_CTL(rx->gpc)) { - case LINK_OPEN: - link_open(rx, buf); - break; - case LINK_ACK: - if (!atomic_test_bit(link.flags, LINK_ACTIVE)) { - return; - } + switch (BEARER_CTL(rx->gpc)) { + case LINK_OPEN: + link_open(rx, buf); + break; + case LINK_ACK: + if (!atomic_test_bit(link.flags, LINK_ACTIVE)) { + return; + } - link_ack(rx, buf); - break; - case LINK_CLOSE: - if (!atomic_test_bit(link.flags, LINK_ACTIVE)) { - return; - } + link_ack(rx, buf); + break; + case LINK_CLOSE: + if (!atomic_test_bit(link.flags, LINK_ACTIVE)) { + return; + } - link_close(rx, buf); - break; - default: + link_close(rx, buf); + break; + default: #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] RFU bearer opcode: 0x%02X", BEARER_CTL(rx->gpc)); + BT_PTS("[PTS] RFU bearer opcode: 0x%02X", BEARER_CTL(rx->gpc)); #endif - BT_ERR("Unknown bearer opcode: 0x%02x", BEARER_CTL(rx->gpc)); + BT_ERR("Unknown bearer opcode: 0x%02x", BEARER_CTL(rx->gpc)); #if defined(CONFIG_BT_TESTING) - /*if (IS_ENABLED(CONFIG_BT_TESTING))*/ { - bt_test_mesh_prov_invalid_bearer(BEARER_CTL(rx->gpc)); - } + /*if (IS_ENABLED(CONFIG_BT_TESTING))*/ { + bt_test_mesh_prov_invalid_bearer(BEARER_CTL(rx->gpc)); + } #endif - return; - } + return; + } } static void prov_msg_recv(void) { - u8_t type = link.rx.buf->data[0]; + u8_t type = link.rx.buf->data[0]; - BT_DBG("type 0x%02x len %u", type, link.rx.buf->len); + BT_DBG("type 0x%02x len %u", type, link.rx.buf->len); - k_delayed_work_submit(&link.prot_timer, PROTOCOL_TIMEOUT); + k_delayed_work_submit(&link.prot_timer, PROTOCOL_TIMEOUT); - if (!bt_mesh_fcs_check(link.rx.buf, link.rx.fcs)) { - BT_ERR("Incorrect FCS"); - return; - } + if (!bt_mesh_fcs_check(link.rx.buf, link.rx.fcs)) { + BT_ERR("Incorrect FCS"); + return; + } - gen_prov_ack_send(link.rx.id); - link.rx.prev_id = link.rx.id; - link.rx.id = 0U; + gen_prov_ack_send(link.rx.id); + link.rx.prev_id = link.rx.id; + link.rx.id = 0U; - if (atomic_test_bit(link.flags, LINK_INVALID)) { - BT_WARN("Unexpected msg 0x%02x on invalidated link", type); - prov_send_fail_msg(PROV_ERR_UNEXP_PDU); - return; - } + if (atomic_test_bit(link.flags, LINK_INVALID)) { + BT_WARN("Unexpected msg 0x%02x on invalidated link", type); + prov_send_fail_msg(PROV_ERR_UNEXP_PDU); + return; + } - if (type != PROV_FAILED && type != link.expect) { - BT_WARN("Unexpected msg 0x%02x != 0x%02x", type, link.expect); - prov_send_fail_msg(PROV_ERR_UNEXP_PDU); - return; - } + if (type != PROV_FAILED && type != link.expect) { + BT_WARN("Unexpected msg 0x%02x != 0x%02x", type, link.expect); + prov_send_fail_msg(PROV_ERR_UNEXP_PDU); + return; + } - if (type >= ARRAY_SIZE(prov_handlers)) { - BT_ERR("Unknown provisioning PDU type 0x%02x", type); - prov_send_fail_msg(PROV_ERR_NVAL_PDU); - return; - } + if (type >= ARRAY_SIZE(prov_handlers)) { + BT_ERR("Unknown provisioning PDU type 0x%02x", type); + prov_send_fail_msg(PROV_ERR_NVAL_PDU); + return; + } - if (1 + prov_handlers[type].len != link.rx.buf->len) { - BT_ERR("Invalid length %u for type 0x%02x", - link.rx.buf->len, type); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } + if (1 + prov_handlers[type].len != link.rx.buf->len) { + BT_ERR("Invalid length %u for type 0x%02x", + link.rx.buf->len, type); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } - prov_handlers[type].func(&link.rx.buf->data[1]); + prov_handlers[type].func(&link.rx.buf->data[1]); } static void gen_prov_cont(struct prov_rx *rx, struct net_buf_simple *buf) { - u8_t seg = CONT_SEG_INDEX(rx->gpc); + u8_t seg = CONT_SEG_INDEX(rx->gpc); - BT_DBG("len %u, seg_index %u", buf->len, seg); + BT_DBG("len %u, seg_index %u", buf->len, seg); - if (!link.rx.seg && link.rx.prev_id == rx->xact_id) { - BT_WARN("Resending ack"); - gen_prov_ack_send(rx->xact_id); - return; - } + if (!link.rx.seg && link.rx.prev_id == rx->xact_id) { + BT_WARN("Resending ack"); + gen_prov_ack_send(rx->xact_id); + return; + } - if (rx->xact_id != link.rx.id) { - BT_WARN("Data for unknown transaction (%u != %u)", - rx->xact_id, link.rx.id); - return; - } + if (rx->xact_id != link.rx.id) { + BT_WARN("Data for unknown transaction (%u != %u)", + rx->xact_id, link.rx.id); + return; + } - if (seg > link.rx.last_seg) { - BT_ERR("Invalid segment index %u", seg); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } else if (seg == link.rx.last_seg) { - u8_t expect_len; + if (seg > link.rx.last_seg) { + BT_ERR("Invalid segment index %u", seg); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } else if (seg == link.rx.last_seg) { + u8_t expect_len; - expect_len = (link.rx.buf->len - 20U - - ((link.rx.last_seg - 1) * 23U)); - if (expect_len != buf->len) { - BT_ERR("Incorrect last seg len: %u != %u", - expect_len, buf->len); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } - } + expect_len = (link.rx.buf->len - 20U - + ((link.rx.last_seg - 1) * 23U)); + if (expect_len != buf->len) { + BT_ERR("Incorrect last seg len: %u != %u", + expect_len, buf->len); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } + } - if (!(link.rx.seg & BIT(seg))) { - BT_WARN("Ignoring already received segment"); - return; - } + if (!(link.rx.seg & BIT(seg))) { + BT_WARN("Ignoring already received segment"); + return; + } - memcpy(XACT_SEG_DATA(seg), buf->data, buf->len); - XACT_SEG_RECV(seg); + memcpy(XACT_SEG_DATA(seg), buf->data, buf->len); + XACT_SEG_RECV(seg); - if (!link.rx.seg) { - prov_msg_recv(); - } + if (!link.rx.seg) { + prov_msg_recv(); + } } static void gen_prov_ack(struct prov_rx *rx, struct net_buf_simple *buf) { - BT_DBG("len %u", buf->len); + BT_DBG("len %u", buf->len); - if (!link.tx.buf[0]) { - return; - } + if (!link.tx.buf[0]) { + return; + } - if (rx->xact_id == link.tx.id) { - prov_clear_tx(); - } + if (rx->xact_id == link.tx.id) { + prov_clear_tx(); + } } static void gen_prov_start(struct prov_rx *rx, struct net_buf_simple *buf) { - if (link.rx.seg) { - BT_WARN("Got Start while there are unreceived segments"); - return; - } + if (link.rx.seg) { + BT_WARN("Got Start while there are unreceived segments"); + return; + } - if (link.rx.prev_id == rx->xact_id) { - BT_WARN("Resending ack"); - gen_prov_ack_send(rx->xact_id); - return; - } + if (link.rx.prev_id == rx->xact_id) { + BT_WARN("Resending ack"); + gen_prov_ack_send(rx->xact_id); + return; + } - link.rx.buf->len = net_buf_simple_pull_be16(buf); - link.rx.id = rx->xact_id; - link.rx.fcs = net_buf_simple_pull_u8(buf); + link.rx.buf->len = net_buf_simple_pull_be16(buf); + link.rx.id = rx->xact_id; + link.rx.fcs = net_buf_simple_pull_u8(buf); - BT_DBG("len %u last_seg %u total_len %u fcs 0x%02x", buf->len, - START_LAST_SEG(rx->gpc), link.rx.buf->len, link.rx.fcs); + BT_DBG("len %u last_seg %u total_len %u fcs 0x%02x", buf->len, + START_LAST_SEG(rx->gpc), link.rx.buf->len, link.rx.fcs); - if (link.rx.buf->len < 1) { - BT_ERR("Ignoring zero-length provisioning PDU"); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } + if (link.rx.buf->len < 1) { + BT_ERR("Ignoring zero-length provisioning PDU"); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } - if (link.rx.buf->len > link.rx.buf->size) { - BT_ERR("Too large provisioning PDU (%u bytes)", - link.rx.buf->len); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } + if (link.rx.buf->len > link.rx.buf->size) { + BT_ERR("Too large provisioning PDU (%u bytes)", + link.rx.buf->len); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } - if (START_LAST_SEG(rx->gpc) > 0 && link.rx.buf->len <= 20U) { - BT_ERR("Too small total length for multi-segment PDU"); - prov_send_fail_msg(PROV_ERR_NVAL_FMT); - return; - } + if (START_LAST_SEG(rx->gpc) > 0 && link.rx.buf->len <= 20U) { + BT_ERR("Too small total length for multi-segment PDU"); + prov_send_fail_msg(PROV_ERR_NVAL_FMT); + return; + } - link.rx.seg = (1 << (START_LAST_SEG(rx->gpc) + 1)) - 1; - link.rx.last_seg = START_LAST_SEG(rx->gpc); - memcpy(link.rx.buf->data, buf->data, buf->len); - XACT_SEG_RECV(0); + link.rx.seg = (1 << (START_LAST_SEG(rx->gpc) + 1)) - 1; + link.rx.last_seg = START_LAST_SEG(rx->gpc); + memcpy(link.rx.buf->data, buf->data, buf->len); + XACT_SEG_RECV(0); - if (!link.rx.seg) { - prov_msg_recv(); - } + if (!link.rx.seg) { + prov_msg_recv(); + } } static const struct { - void (*func)(struct prov_rx *rx, struct net_buf_simple *buf); - bool require_link; - u8_t min_len; + void (*func)(struct prov_rx *rx, struct net_buf_simple *buf); + bool require_link; + u8_t min_len; } gen_prov[] = { - { gen_prov_start, true, 3 }, - { gen_prov_ack, true, 0 }, - { gen_prov_cont, true, 0 }, - { gen_prov_ctl, false, 0 }, + { gen_prov_start, true, 3 }, + { gen_prov_ack, true, 0 }, + { gen_prov_cont, true, 0 }, + { gen_prov_ctl, false, 0 }, }; static void gen_prov_recv(struct prov_rx *rx, struct net_buf_simple *buf) { - if (buf->len < gen_prov[GPCF(rx->gpc)].min_len) { - BT_ERR("Too short GPC message type %u", GPCF(rx->gpc)); - return; - } + if (buf->len < gen_prov[GPCF(rx->gpc)].min_len) { + BT_ERR("Too short GPC message type %u", GPCF(rx->gpc)); + return; + } - if (!atomic_test_bit(link.flags, LINK_ACTIVE) && - gen_prov[GPCF(rx->gpc)].require_link) { - BT_DBG("Ignoring message that requires active link"); - return; - } + if (!atomic_test_bit(link.flags, LINK_ACTIVE) && + gen_prov[GPCF(rx->gpc)].require_link) { + BT_DBG("Ignoring message that requires active link"); + return; + } - gen_prov[GPCF(rx->gpc)].func(rx, buf); + gen_prov[GPCF(rx->gpc)].func(rx, buf); } void bt_mesh_pb_adv_recv(struct net_buf_simple *buf) { - struct prov_rx rx; + struct prov_rx rx; - if (!bt_prov_active() && bt_mesh_is_provisioned()) { - BT_DBG("Ignoring provisioning PDU - already provisioned"); - return; - } + if (!bt_prov_active() && bt_mesh_is_provisioned()) { + BT_DBG("Ignoring provisioning PDU - already provisioned"); + return; + } - if (buf->len < 6) { - BT_WARN("Too short provisioning packet (len %u)", buf->len); - return; - } + if (buf->len < 6) { + BT_WARN("Too short provisioning packet (len %u)", buf->len); + return; + } - rx.link_id = net_buf_simple_pull_be32(buf); - rx.xact_id = net_buf_simple_pull_u8(buf); - rx.gpc = net_buf_simple_pull_u8(buf); + rx.link_id = net_buf_simple_pull_be32(buf); + rx.xact_id = net_buf_simple_pull_u8(buf); + rx.gpc = net_buf_simple_pull_u8(buf); - BT_DBG("link_id 0x%08x xact_id %u", rx.link_id, rx.xact_id); + BT_DBG("link_id 0x%08x xact_id %u", rx.link_id, rx.xact_id); - if (atomic_test_bit(link.flags, LINK_ACTIVE) && link.id != rx.link_id) { - BT_DBG("Ignoring mesh beacon for unknown link"); - return; - } + if (atomic_test_bit(link.flags, LINK_ACTIVE) && link.id != rx.link_id) { + BT_DBG("Ignoring mesh beacon for unknown link"); + return; + } - gen_prov_recv(&rx, buf); + gen_prov_recv(&rx, buf); } #endif /* CONFIG_BT_MESH_PB_ADV */ #if defined(CONFIG_BT_MESH_PB_GATT) int bt_mesh_pb_gatt_recv(struct bt_conn *conn, struct net_buf_simple *buf) { - u8_t type; + u8_t type; - BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); - if (link.conn != conn) { - BT_WARN("Data for unexpected connection"); - return -ENOTCONN; - } + if (link.conn != conn) { + BT_WARN("Data for unexpected connection"); + return -ENOTCONN; + } - if (buf->len < 1) { - BT_WARN("Too short provisioning packet (len %u)", buf->len); - return -EINVAL; - } + if (buf->len < 1) { + BT_WARN("Too short provisioning packet (len %u)", buf->len); + return -EINVAL; + } - type = net_buf_simple_pull_u8(buf); - if (type != PROV_FAILED && type != link.expect) { - BT_WARN("Unexpected msg 0x%02x != 0x%02x", type, link.expect); - prov_send_fail_msg(PROV_ERR_UNEXP_PDU); - return -EINVAL; - } + type = net_buf_simple_pull_u8(buf); + if (type != PROV_FAILED && type != link.expect) { + BT_WARN("Unexpected msg 0x%02x != 0x%02x", type, link.expect); + prov_send_fail_msg(PROV_ERR_UNEXP_PDU); + return -EINVAL; + } - if (type >= ARRAY_SIZE(prov_handlers)) { - BT_ERR("Unknown provisioning PDU type 0x%02x", type); - return -EINVAL; - } + if (type >= ARRAY_SIZE(prov_handlers)) { + BT_ERR("Unknown provisioning PDU type 0x%02x", type); + return -EINVAL; + } - if (prov_handlers[type].len != buf->len) { - BT_ERR("Invalid length %u for type 0x%02x", buf->len, type); - return -EINVAL; - } + if (prov_handlers[type].len != buf->len) { + BT_ERR("Invalid length %u for type 0x%02x", buf->len, type); + return -EINVAL; + } - prov_handlers[type].func(buf->data); + prov_handlers[type].func(buf->data); - return 0; + return 0; } int bt_mesh_pb_gatt_open(struct bt_conn *conn) { - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - if (atomic_test_and_set_bit(link.flags, LINK_ACTIVE)) { - return -EBUSY; - } + if (atomic_test_and_set_bit(link.flags, LINK_ACTIVE)) { + return -EBUSY; + } - link.conn = bt_conn_ref(conn); - link.expect = PROV_INVITE; + link.conn = bt_conn_ref(conn); + link.expect = PROV_INVITE; - if (prov->link_open) { - prov->link_open(BT_MESH_PROV_GATT); - } + if (prov->link_open) { + prov->link_open(BT_MESH_PROV_GATT); + } - return 0; + return 0; } int bt_mesh_pb_gatt_close(struct bt_conn *conn) { - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - if (link.conn != conn) { - BT_ERR("Not connected"); - return -ENOTCONN; - } + if (link.conn != conn) { + BT_ERR("Not connected"); + return -ENOTCONN; + } - if (prov->link_close) { - prov->link_close(BT_MESH_PROV_GATT); - } + if (prov->link_close) { + prov->link_close(BT_MESH_PROV_GATT); + } - return reset_state(); + return reset_state(); } #endif /* CONFIG_BT_MESH_PB_GATT */ const struct bt_mesh_prov *bt_mesh_prov_get(void) { - return prov; + return prov; } bool bt_prov_active(void) { - return atomic_test_bit(link.flags, LINK_ACTIVE); + return atomic_test_bit(link.flags, LINK_ACTIVE); } static void protocol_timeout(struct k_work *work) { - BT_DBG("Protocol timeout"); + BT_DBG("Protocol timeout"); #if defined(CONFIG_BT_MESH_PB_GATT) - if (link.conn) { - bt_mesh_pb_gatt_close(link.conn); - return; - } + if (link.conn) { + bt_mesh_pb_gatt_close(link.conn); + return; + } #endif #if defined(CONFIG_BT_MESH_PB_ADV) - u8_t reason = CLOSE_REASON_TIMEOUT; + u8_t reason = CLOSE_REASON_TIMEOUT; - link.rx.seg = 0U; - bearer_ctl_send(LINK_CLOSE, &reason, sizeof(reason)); + link.rx.seg = 0U; + bearer_ctl_send(LINK_CLOSE, &reason, sizeof(reason)); #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Link Close (Link ID = 0x%08X) sent due to timeout", link.id); - if (prov->link_close) { - prov->link_close(BT_MESH_PROV_ADV); - } + BT_PTS("[PTS] Link Close (Link ID = 0x%08X) sent due to timeout", link.id); + if (prov->link_close) { + prov->link_close(BT_MESH_PROV_ADV); + } #endif - reset_state(); + reset_state(); #endif } int bt_mesh_prov_init(const struct bt_mesh_prov *prov_info) { - if (!prov_info) { - BT_ERR("No provisioning context provided"); - return -EINVAL; - } + if (!prov_info) { + BT_ERR("No provisioning context provided"); + return -EINVAL; + } - k_delayed_work_init(&link.prot_timer, protocol_timeout); + k_delayed_work_init(&link.prot_timer, protocol_timeout); - prov = prov_info; + prov = prov_info; #if defined(CONFIG_BT_MESH_PB_ADV) - k_delayed_work_init(&link.tx.retransmit, prov_retransmit); + k_delayed_work_init(&link.tx.retransmit, prov_retransmit); #endif - return reset_state(); + return reset_state(); } void bt_mesh_prov_complete(u16_t net_idx, u16_t addr) { - if (prov->complete) { - prov->complete(net_idx, addr); - } + if (prov->complete) { + prov->complete(net_idx, addr); + } } void bt_mesh_prov_reset(void) { - if (prov->reset) { - prov->reset(); - } + if (prov->reset) { + prov->reset(); + } } diff --git a/components/network/ble/blemesh/src/proxy.c b/components/network/ble/blemesh/src/proxy.c index 4f8b76b8..110af794 100644 --- a/components/network/ble/blemesh/src/proxy.c +++ b/components/network/ble/blemesh/src/proxy.c @@ -57,21 +57,21 @@ #if defined(CONFIG_BT_MESH_DEBUG_USE_ID_ADDR) #define ADV_OPT (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME | \ - BT_LE_ADV_OPT_USE_IDENTITY) + BT_LE_ADV_OPT_USE_IDENTITY) #else #define ADV_OPT (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME) #endif static const struct bt_le_adv_param slow_adv_param = { - .options = ADV_OPT, - .interval_min = BT_GAP_ADV_SLOW_INT_MIN, - .interval_max = BT_GAP_ADV_SLOW_INT_MAX, + .options = ADV_OPT, + .interval_min = BT_GAP_ADV_SLOW_INT_MIN, + .interval_max = BT_GAP_ADV_SLOW_INT_MAX, }; static const struct bt_le_adv_param fast_adv_param = { - .options = ADV_OPT, - .interval_min = BT_GAP_ADV_FAST_INT_MIN_2, - .interval_max = BT_GAP_ADV_FAST_INT_MAX_2, + .options = ADV_OPT, + .interval_min = BT_GAP_ADV_FAST_INT_MIN_2, + .interval_max = BT_GAP_ADV_FAST_INT_MAX_2, }; static bool proxy_adv_enabled; @@ -87,26 +87,26 @@ static bool prov_fast_adv; #endif static struct bt_mesh_proxy_client { - struct bt_conn *conn; - u16_t filter[CONFIG_BT_MESH_PROXY_FILTER_SIZE]; - enum __packed { - NONE, - WHITELIST, - BLACKLIST, - PROV, - } filter_type; - u8_t msg_type; + struct bt_conn *conn; + u16_t filter[CONFIG_BT_MESH_PROXY_FILTER_SIZE]; + enum __packed { + NONE, + WHITELIST, + BLACKLIST, + PROV, + } filter_type; + u8_t msg_type; #if defined(CONFIG_BT_MESH_GATT_PROXY) - struct k_work send_beacons; + struct k_work send_beacons; #endif - struct k_delayed_work sar_timer; - struct net_buf_simple buf; + struct k_delayed_work sar_timer; + struct net_buf_simple buf; } clients[CONFIG_BT_MAX_CONN] = { - [0 ... (CONFIG_BT_MAX_CONN - 1)] = { + [0 ... (CONFIG_BT_MAX_CONN - 1)] = { #if defined(CONFIG_BT_MESH_GATT_PROXY) - .send_beacons = _K_WORK_INITIALIZER(proxy_send_beacons), + .send_beacons = _K_WORK_INITIALIZER(proxy_send_beacons), #endif - }, + }, }; #if defined(BFLB_BLE) @@ -117,35 +117,35 @@ static u8_t __noinit client_buf_data[CLIENT_BUF_SIZE * CONFIG_BT_MAX_CONN]; /* Track which service is enabled */ static enum { - MESH_GATT_NONE, - MESH_GATT_PROV, - MESH_GATT_PROXY, + MESH_GATT_NONE, + MESH_GATT_PROV, + MESH_GATT_PROXY, } gatt_svc = MESH_GATT_NONE; static struct bt_mesh_proxy_client *find_client(struct bt_conn *conn) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(clients); i++) { - if (clients[i].conn == conn) { - return &clients[i]; - } - } + for (i = 0; i < ARRAY_SIZE(clients); i++) { + if (clients[i].conn == conn) { + return &clients[i]; + } + } - return NULL; + return NULL; } static void proxy_sar_timeout(struct k_work *work) { - struct bt_mesh_proxy_client *client; + struct bt_mesh_proxy_client *client; - BT_WARN("Proxy SAR timeout"); + BT_WARN("Proxy SAR timeout"); - client = CONTAINER_OF(work, struct bt_mesh_proxy_client, sar_timer); - if (client->conn) { - bt_conn_disconnect(client->conn, - BT_HCI_ERR_REMOTE_USER_TERM_CONN); - } + client = CONTAINER_OF(work, struct bt_mesh_proxy_client, sar_timer); + if (client->conn) { + bt_conn_disconnect(client->conn, + BT_HCI_ERR_REMOTE_USER_TERM_CONN); + } } #if defined(CONFIG_BT_MESH_GATT_PROXY) @@ -153,563 +153,563 @@ static void proxy_sar_timeout(struct k_work *work) static int next_idx; static int proxy_segment_and_send(struct bt_conn *conn, u8_t type, - struct net_buf_simple *msg); + struct net_buf_simple *msg); static int filter_set(struct bt_mesh_proxy_client *client, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - u8_t type; + u8_t type; - if (buf->len < 1) { - BT_WARN("Too short Filter Set message"); - return -EINVAL; - } + if (buf->len < 1) { + BT_WARN("Too short Filter Set message"); + return -EINVAL; + } - type = net_buf_simple_pull_u8(buf); - BT_DBG("type 0x%02x", type); + type = net_buf_simple_pull_u8(buf); + BT_DBG("type 0x%02x", type); - switch (type) { - case 0x00: - (void)memset(client->filter, 0, sizeof(client->filter)); - client->filter_type = WHITELIST; - break; - case 0x01: - (void)memset(client->filter, 0, sizeof(client->filter)); - client->filter_type = BLACKLIST; - break; - default: - BT_WARN("Prohibited Filter Type 0x%02x", type); - return -EINVAL; - } + switch (type) { + case 0x00: + (void)memset(client->filter, 0, sizeof(client->filter)); + client->filter_type = WHITELIST; + break; + case 0x01: + (void)memset(client->filter, 0, sizeof(client->filter)); + client->filter_type = BLACKLIST; + break; + default: + BT_WARN("Prohibited Filter Type 0x%02x", type); + return -EINVAL; + } - return 0; + return 0; } static void filter_add(struct bt_mesh_proxy_client *client, u16_t addr) { - int i; + int i; - BT_DBG("addr 0x%04x", addr); + BT_DBG("addr 0x%04x", addr); - if (addr == BT_MESH_ADDR_UNASSIGNED) { - return; - } + if (addr == BT_MESH_ADDR_UNASSIGNED) { + return; + } - for (i = 0; i < ARRAY_SIZE(client->filter); i++) { - if (client->filter[i] == addr) { - return; - } - } + for (i = 0; i < ARRAY_SIZE(client->filter); i++) { + if (client->filter[i] == addr) { + return; + } + } - for (i = 0; i < ARRAY_SIZE(client->filter); i++) { - if (client->filter[i] == BT_MESH_ADDR_UNASSIGNED) { - client->filter[i] = addr; - return; - } - } + for (i = 0; i < ARRAY_SIZE(client->filter); i++) { + if (client->filter[i] == BT_MESH_ADDR_UNASSIGNED) { + client->filter[i] = addr; + return; + } + } } static void filter_remove(struct bt_mesh_proxy_client *client, u16_t addr) { - int i; + int i; - BT_DBG("addr 0x%04x", addr); + BT_DBG("addr 0x%04x", addr); - if (addr == BT_MESH_ADDR_UNASSIGNED) { - return; - } + if (addr == BT_MESH_ADDR_UNASSIGNED) { + return; + } - for (i = 0; i < ARRAY_SIZE(client->filter); i++) { - if (client->filter[i] == addr) { - client->filter[i] = BT_MESH_ADDR_UNASSIGNED; - return; - } - } + for (i = 0; i < ARRAY_SIZE(client->filter); i++) { + if (client->filter[i] == addr) { + client->filter[i] = BT_MESH_ADDR_UNASSIGNED; + return; + } + } } static void send_filter_status(struct bt_mesh_proxy_client *client, - struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct bt_mesh_net_rx *rx, + struct net_buf_simple *buf) { - struct bt_mesh_net_tx tx = { - .sub = rx->sub, - .ctx = &rx->ctx, - .src = bt_mesh_primary_addr(), - }; - u16_t filter_size; - int i, err; + struct bt_mesh_net_tx tx = { + .sub = rx->sub, + .ctx = &rx->ctx, + .src = bt_mesh_primary_addr(), + }; + u16_t filter_size; + int i, err; - /* Configuration messages always have dst unassigned */ - tx.ctx->addr = BT_MESH_ADDR_UNASSIGNED; + /* Configuration messages always have dst unassigned */ + tx.ctx->addr = BT_MESH_ADDR_UNASSIGNED; - net_buf_simple_reset(buf); - net_buf_simple_reserve(buf, 10); + net_buf_simple_reset(buf); + net_buf_simple_reserve(buf, 10); - net_buf_simple_add_u8(buf, CFG_FILTER_STATUS); + net_buf_simple_add_u8(buf, CFG_FILTER_STATUS); - if (client->filter_type == WHITELIST) { - net_buf_simple_add_u8(buf, 0x00); - } else { - net_buf_simple_add_u8(buf, 0x01); - } + if (client->filter_type == WHITELIST) { + net_buf_simple_add_u8(buf, 0x00); + } else { + net_buf_simple_add_u8(buf, 0x01); + } - for (filter_size = 0U, i = 0; i < ARRAY_SIZE(client->filter); i++) { - if (client->filter[i] != BT_MESH_ADDR_UNASSIGNED) { - filter_size++; - } - } + for (filter_size = 0U, i = 0; i < ARRAY_SIZE(client->filter); i++) { + if (client->filter[i] != BT_MESH_ADDR_UNASSIGNED) { + filter_size++; + } + } - net_buf_simple_add_be16(buf, filter_size); + net_buf_simple_add_be16(buf, filter_size); - BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len)); - err = bt_mesh_net_encode(&tx, buf, true); - if (err) { - BT_ERR("Encoding Proxy cfg message failed (err %d)", err); - return; - } + err = bt_mesh_net_encode(&tx, buf, true); + if (err) { + BT_ERR("Encoding Proxy cfg message failed (err %d)", err); + return; + } - err = proxy_segment_and_send(client->conn, BT_MESH_PROXY_CONFIG, buf); - if (err) { - BT_ERR("Failed to send proxy cfg message (err %d)", err); - } + err = proxy_segment_and_send(client->conn, BT_MESH_PROXY_CONFIG, buf); + if (err) { + BT_ERR("Failed to send proxy cfg message (err %d)", err); + } } static void proxy_cfg(struct bt_mesh_proxy_client *client) { - NET_BUF_SIMPLE_DEFINE(buf, 29); - struct bt_mesh_net_rx rx; - u8_t opcode; - int err; + NET_BUF_SIMPLE_DEFINE(buf, 29); + struct bt_mesh_net_rx rx; + u8_t opcode; + int err; - err = bt_mesh_net_decode(&client->buf, BT_MESH_NET_IF_PROXY_CFG, - &rx, &buf); - if (err) { - BT_ERR("Failed to decode Proxy Configuration (err %d)", err); - return; - } + err = bt_mesh_net_decode(&client->buf, BT_MESH_NET_IF_PROXY_CFG, + &rx, &buf); + if (err) { + BT_ERR("Failed to decode Proxy Configuration (err %d)", err); + return; + } - /* Remove network headers */ - net_buf_simple_pull(&buf, BT_MESH_NET_HDR_LEN); + /* Remove network headers */ + net_buf_simple_pull(&buf, BT_MESH_NET_HDR_LEN); - BT_DBG("%u bytes: %s", buf.len, bt_hex(buf.data, buf.len)); + BT_DBG("%u bytes: %s", buf.len, bt_hex(buf.data, buf.len)); - if (buf.len < 1) { - BT_WARN("Too short proxy configuration PDU"); - return; - } + if (buf.len < 1) { + BT_WARN("Too short proxy configuration PDU"); + return; + } - opcode = net_buf_simple_pull_u8(&buf); - switch (opcode) { - case CFG_FILTER_SET: - filter_set(client, &buf); - send_filter_status(client, &rx, &buf); - break; - case CFG_FILTER_ADD: - while (buf.len >= 2) { - u16_t addr; + opcode = net_buf_simple_pull_u8(&buf); + switch (opcode) { + case CFG_FILTER_SET: + filter_set(client, &buf); + send_filter_status(client, &rx, &buf); + break; + case CFG_FILTER_ADD: + while (buf.len >= 2) { + u16_t addr; - addr = net_buf_simple_pull_be16(&buf); - filter_add(client, addr); - } - send_filter_status(client, &rx, &buf); - break; - case CFG_FILTER_REMOVE: - while (buf.len >= 2) { - u16_t addr; + addr = net_buf_simple_pull_be16(&buf); + filter_add(client, addr); + } + send_filter_status(client, &rx, &buf); + break; + case CFG_FILTER_REMOVE: + while (buf.len >= 2) { + u16_t addr; - addr = net_buf_simple_pull_be16(&buf); - filter_remove(client, addr); - } - send_filter_status(client, &rx, &buf); - break; - default: - BT_WARN("Unhandled configuration OpCode 0x%02x", opcode); - break; - } + addr = net_buf_simple_pull_be16(&buf); + filter_remove(client, addr); + } + send_filter_status(client, &rx, &buf); + break; + default: + BT_WARN("Unhandled configuration OpCode 0x%02x", opcode); + break; + } } static int beacon_send(struct bt_conn *conn, struct bt_mesh_subnet *sub) { - NET_BUF_SIMPLE_DEFINE(buf, 23); + NET_BUF_SIMPLE_DEFINE(buf, 23); - net_buf_simple_reserve(&buf, 1); - bt_mesh_beacon_create(sub, &buf); + net_buf_simple_reserve(&buf, 1); + bt_mesh_beacon_create(sub, &buf); - return proxy_segment_and_send(conn, BT_MESH_PROXY_BEACON, &buf); + return proxy_segment_and_send(conn, BT_MESH_PROXY_BEACON, &buf); } static void proxy_send_beacons(struct k_work *work) { - struct bt_mesh_proxy_client *client; - int i; + struct bt_mesh_proxy_client *client; + int i; - client = CONTAINER_OF(work, struct bt_mesh_proxy_client, send_beacons); + client = CONTAINER_OF(work, struct bt_mesh_proxy_client, send_beacons); - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx != BT_MESH_KEY_UNUSED) { - beacon_send(client->conn, sub); - } - } + if (sub->net_idx != BT_MESH_KEY_UNUSED) { + beacon_send(client->conn, sub); + } + } } void bt_mesh_proxy_beacon_send(struct bt_mesh_subnet *sub) { - int i; + int i; - if (!sub) { - /* NULL means we send on all subnets */ - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - if (bt_mesh.sub[i].net_idx != BT_MESH_KEY_UNUSED) { - bt_mesh_proxy_beacon_send(&bt_mesh.sub[i]); - } - } + if (!sub) { + /* NULL means we send on all subnets */ + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + if (bt_mesh.sub[i].net_idx != BT_MESH_KEY_UNUSED) { + bt_mesh_proxy_beacon_send(&bt_mesh.sub[i]); + } + } - return; - } + return; + } - for (i = 0; i < ARRAY_SIZE(clients); i++) { - if (clients[i].conn) { - beacon_send(clients[i].conn, sub); - } - } + for (i = 0; i < ARRAY_SIZE(clients); i++) { + if (clients[i].conn) { + beacon_send(clients[i].conn, sub); + } + } } void bt_mesh_proxy_identity_start(struct bt_mesh_subnet *sub) { - sub->node_id = BT_MESH_NODE_IDENTITY_RUNNING; - sub->node_id_start = k_uptime_get_32(); + sub->node_id = BT_MESH_NODE_IDENTITY_RUNNING; + sub->node_id_start = k_uptime_get_32(); - /* Prioritize the recently enabled subnet */ - next_idx = sub - bt_mesh.sub; + /* Prioritize the recently enabled subnet */ + next_idx = sub - bt_mesh.sub; } void bt_mesh_proxy_identity_stop(struct bt_mesh_subnet *sub) { - sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; - sub->node_id_start = 0U; + sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; + sub->node_id_start = 0U; } int bt_mesh_proxy_identity_enable(void) { - int i, count = 0; + int i, count = 0; - BT_DBG(""); + BT_DBG(""); - if (!bt_mesh_is_provisioned()) { - return -EAGAIN; - } + if (!bt_mesh_is_provisioned()) { + return -EAGAIN; + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - if (sub->node_id == BT_MESH_NODE_IDENTITY_NOT_SUPPORTED) { - continue; - } + if (sub->node_id == BT_MESH_NODE_IDENTITY_NOT_SUPPORTED) { + continue; + } - bt_mesh_proxy_identity_start(sub); - count++; - } + bt_mesh_proxy_identity_start(sub); + count++; + } - if (count) { - bt_mesh_adv_update(); - } + if (count) { + bt_mesh_adv_update(); + } - return 0; + return 0; } #endif /* GATT_PROXY */ static void proxy_complete_pdu(struct bt_mesh_proxy_client *client) { - switch (client->msg_type) { + switch (client->msg_type) { #if defined(CONFIG_BT_MESH_GATT_PROXY) - case BT_MESH_PROXY_NET_PDU: - BT_DBG("Mesh Network PDU"); - bt_mesh_net_recv(&client->buf, 0, BT_MESH_NET_IF_PROXY); - break; - case BT_MESH_PROXY_BEACON: - BT_DBG("Mesh Beacon PDU"); - bt_mesh_beacon_recv(&client->buf); - break; - case BT_MESH_PROXY_CONFIG: - BT_DBG("Mesh Configuration PDU"); - proxy_cfg(client); - break; + case BT_MESH_PROXY_NET_PDU: + BT_DBG("Mesh Network PDU"); + bt_mesh_net_recv(&client->buf, 0, BT_MESH_NET_IF_PROXY); + break; + case BT_MESH_PROXY_BEACON: + BT_DBG("Mesh Beacon PDU"); + bt_mesh_beacon_recv(&client->buf); + break; + case BT_MESH_PROXY_CONFIG: + BT_DBG("Mesh Configuration PDU"); + proxy_cfg(client); + break; #endif #if defined(CONFIG_BT_MESH_PB_GATT) - case BT_MESH_PROXY_PROV: - BT_DBG("Mesh Provisioning PDU"); - bt_mesh_pb_gatt_recv(client->conn, &client->buf); - break; + case BT_MESH_PROXY_PROV: + BT_DBG("Mesh Provisioning PDU"); + bt_mesh_pb_gatt_recv(client->conn, &client->buf); + break; #endif - default: - BT_WARN("Unhandled Message Type 0x%02x", client->msg_type); - break; - } + default: + BT_WARN("Unhandled Message Type 0x%02x", client->msg_type); + break; + } - net_buf_simple_reset(&client->buf); + net_buf_simple_reset(&client->buf); } #define ATTR_IS_PROV(attr) (attr->user_data != NULL) static ssize_t proxy_recv(struct bt_conn *conn, - const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, const void *buf, + u16_t len, u16_t offset, u8_t flags) { - struct bt_mesh_proxy_client *client = find_client(conn); - const u8_t *data = buf; + struct bt_mesh_proxy_client *client = find_client(conn); + const u8_t *data = buf; - if (!client) { - return -ENOTCONN; - } + if (!client) { + return -ENOTCONN; + } - if (len < 1) { - BT_WARN("Too small Proxy PDU"); - return -EINVAL; - } + if (len < 1) { + BT_WARN("Too small Proxy PDU"); + return -EINVAL; + } - if (ATTR_IS_PROV(attr) != (PDU_TYPE(data) == BT_MESH_PROXY_PROV)) { - BT_WARN("Proxy PDU type doesn't match GATT service"); - return -EINVAL; - } + if (ATTR_IS_PROV(attr) != (PDU_TYPE(data) == BT_MESH_PROXY_PROV)) { + BT_WARN("Proxy PDU type doesn't match GATT service"); + return -EINVAL; + } - if (len - 1 > net_buf_simple_tailroom(&client->buf)) { - BT_WARN("Too big proxy PDU"); - return -EINVAL; - } + if (len - 1 > net_buf_simple_tailroom(&client->buf)) { + BT_WARN("Too big proxy PDU"); + return -EINVAL; + } - switch (PDU_SAR(data)) { - case SAR_COMPLETE: - if (client->buf.len) { - BT_WARN("Complete PDU while a pending incomplete one"); - return -EINVAL; - } + switch (PDU_SAR(data)) { + case SAR_COMPLETE: + if (client->buf.len) { + BT_WARN("Complete PDU while a pending incomplete one"); + return -EINVAL; + } - client->msg_type = PDU_TYPE(data); - net_buf_simple_add_mem(&client->buf, data + 1, len - 1); - proxy_complete_pdu(client); - break; + client->msg_type = PDU_TYPE(data); + net_buf_simple_add_mem(&client->buf, data + 1, len - 1); + proxy_complete_pdu(client); + break; - case SAR_FIRST: - if (client->buf.len) { - BT_WARN("First PDU while a pending incomplete one"); - return -EINVAL; - } + case SAR_FIRST: + if (client->buf.len) { + BT_WARN("First PDU while a pending incomplete one"); + return -EINVAL; + } - k_delayed_work_submit(&client->sar_timer, PROXY_SAR_TIMEOUT); - client->msg_type = PDU_TYPE(data); - net_buf_simple_add_mem(&client->buf, data + 1, len - 1); - break; + k_delayed_work_submit(&client->sar_timer, PROXY_SAR_TIMEOUT); + client->msg_type = PDU_TYPE(data); + net_buf_simple_add_mem(&client->buf, data + 1, len - 1); + break; - case SAR_CONT: - if (!client->buf.len) { - BT_WARN("Continuation with no prior data"); - return -EINVAL; - } + case SAR_CONT: + if (!client->buf.len) { + BT_WARN("Continuation with no prior data"); + return -EINVAL; + } - if (client->msg_type != PDU_TYPE(data)) { - BT_WARN("Unexpected message type in continuation"); - return -EINVAL; - } + if (client->msg_type != PDU_TYPE(data)) { + BT_WARN("Unexpected message type in continuation"); + return -EINVAL; + } - k_delayed_work_submit(&client->sar_timer, PROXY_SAR_TIMEOUT); - net_buf_simple_add_mem(&client->buf, data + 1, len - 1); - break; + k_delayed_work_submit(&client->sar_timer, PROXY_SAR_TIMEOUT); + net_buf_simple_add_mem(&client->buf, data + 1, len - 1); + break; - case SAR_LAST: - if (!client->buf.len) { - BT_WARN("Last SAR PDU with no prior data"); - return -EINVAL; - } + case SAR_LAST: + if (!client->buf.len) { + BT_WARN("Last SAR PDU with no prior data"); + return -EINVAL; + } - if (client->msg_type != PDU_TYPE(data)) { - BT_WARN("Unexpected message type in last SAR PDU"); - return -EINVAL; - } + if (client->msg_type != PDU_TYPE(data)) { + BT_WARN("Unexpected message type in last SAR PDU"); + return -EINVAL; + } - k_delayed_work_cancel(&client->sar_timer); - net_buf_simple_add_mem(&client->buf, data + 1, len - 1); - proxy_complete_pdu(client); - break; - } + k_delayed_work_cancel(&client->sar_timer); + net_buf_simple_add_mem(&client->buf, data + 1, len - 1); + proxy_complete_pdu(client); + break; + } - return len; + return len; } static int conn_count; static void proxy_connected(struct bt_conn *conn, u8_t err) { - struct bt_mesh_proxy_client *client; - int i; + struct bt_mesh_proxy_client *client; + int i; - BT_DBG("conn %p err 0x%02x", conn, err); + BT_DBG("conn %p err 0x%02x", conn, err); - conn_count++; + conn_count++; - /* Since we use ADV_OPT_ONE_TIME */ - proxy_adv_enabled = false; + /* Since we use ADV_OPT_ONE_TIME */ + proxy_adv_enabled = false; - /* Try to re-enable advertising in case it's possible */ - if (conn_count < CONFIG_BT_MAX_CONN) { - bt_mesh_adv_update(); - } + /* Try to re-enable advertising in case it's possible */ + if (conn_count < CONFIG_BT_MAX_CONN) { + bt_mesh_adv_update(); + } - for (client = NULL, i = 0; i < ARRAY_SIZE(clients); i++) { - if (!clients[i].conn) { - client = &clients[i]; - break; - } - } + for (client = NULL, i = 0; i < ARRAY_SIZE(clients); i++) { + if (!clients[i].conn) { + client = &clients[i]; + break; + } + } - if (!client) { - BT_ERR("No free Proxy Client objects"); - return; - } + if (!client) { + BT_ERR("No free Proxy Client objects"); + return; + } - client->conn = bt_conn_ref(conn); - client->filter_type = NONE; - (void)memset(client->filter, 0, sizeof(client->filter)); - net_buf_simple_reset(&client->buf); + client->conn = bt_conn_ref(conn); + client->filter_type = NONE; + (void)memset(client->filter, 0, sizeof(client->filter)); + net_buf_simple_reset(&client->buf); } static void proxy_disconnected(struct bt_conn *conn, u8_t reason) { - int i; + int i; - BT_DBG("conn %p reason 0x%02x", conn, reason); + BT_DBG("conn %p reason 0x%02x", conn, reason); - conn_count--; + conn_count--; - for (i = 0; i < ARRAY_SIZE(clients); i++) { - struct bt_mesh_proxy_client *client = &clients[i]; + for (i = 0; i < ARRAY_SIZE(clients); i++) { + struct bt_mesh_proxy_client *client = &clients[i]; - if (client->conn == conn) { - if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && - client->filter_type == PROV) { - bt_mesh_pb_gatt_close(conn); - } + if (client->conn == conn) { + if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && + client->filter_type == PROV) { + bt_mesh_pb_gatt_close(conn); + } - k_delayed_work_cancel(&client->sar_timer); - bt_conn_unref(client->conn); - client->conn = NULL; - break; - } - } + k_delayed_work_cancel(&client->sar_timer); + bt_conn_unref(client->conn); + client->conn = NULL; + break; + } + } - bt_mesh_adv_update(); + bt_mesh_adv_update(); } struct net_buf_simple *bt_mesh_proxy_get_buf(void) { - struct net_buf_simple *buf = &clients[0].buf; + struct net_buf_simple *buf = &clients[0].buf; - net_buf_simple_reset(buf); + net_buf_simple_reset(buf); - return buf; + return buf; } #if defined(CONFIG_BT_MESH_PB_GATT) #if 0 static void prov_ccc_changed(const struct bt_gatt_attr *attr, u16_t value) { - BT_DBG("value 0x%04x", value); + BT_DBG("value 0x%04x", value); } static bool prov_ccc_write(struct bt_conn *conn, - const struct bt_gatt_attr *attr, u16_t value) + const struct bt_gatt_attr *attr, u16_t value) { - struct bt_mesh_proxy_client *client; + struct bt_mesh_proxy_client *client; - BT_DBG("value 0x%04x", value); + BT_DBG("value 0x%04x", value); - if (value != BT_GATT_CCC_NOTIFY) { - BT_WARN("Client wrote 0x%04x instead enabling notify", value); - return false; - } + if (value != BT_GATT_CCC_NOTIFY) { + BT_WARN("Client wrote 0x%04x instead enabling notify", value); + return false; + } - /* If a connection exists there must be a client */ - client = find_client(conn); - __ASSERT(client, "No client for connection"); + /* If a connection exists there must be a client */ + client = find_client(conn); + __ASSERT(client, "No client for connection"); - if (client->filter_type == NONE) { - client->filter_type = PROV; - bt_mesh_pb_gatt_open(conn); - } + if (client->filter_type == NONE) { + client->filter_type = PROV; + bt_mesh_pb_gatt_open(conn); + } - return true; + return true; } #else static ssize_t prov_ccc_write(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - const void *buf, u16_t len, - u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, + const void *buf, u16_t len, + u16_t offset, u8_t flags) { - struct bt_mesh_proxy_client *client; - u16_t *value = attr->user_data; + struct bt_mesh_proxy_client *client; + u16_t *value = attr->user_data; - BT_DBG("len %u: %s", len, bt_hex(buf, len)); + BT_DBG("len %u: %s", len, bt_hex(buf, len)); - if (len != sizeof(*value)) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); - } + if (len != sizeof(*value)) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } - *value = sys_get_le16(buf); - if (*value != BT_GATT_CCC_NOTIFY) { - BT_WARN("Client wrote 0x%04x instead enabling notify", *value); - return len; - } + *value = sys_get_le16(buf); + if (*value != BT_GATT_CCC_NOTIFY) { + BT_WARN("Client wrote 0x%04x instead enabling notify", *value); + return len; + } - /* If a connection exists there must be a client */ - client = find_client(conn); - __ASSERT(client, "No client for connection"); + /* If a connection exists there must be a client */ + client = find_client(conn); + __ASSERT(client, "No client for connection"); - if (client->filter_type == NONE) { - client->filter_type = PROV; - bt_mesh_pb_gatt_open(conn); - } + if (client->filter_type == NONE) { + client->filter_type = PROV; + bt_mesh_pb_gatt_open(conn); + } - return len; + return len; } #endif static ssize_t prov_ccc_read(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset) { - u16_t *value = attr->user_data; + u16_t *value = attr->user_data; - return bt_gatt_attr_read(conn, attr, buf, len, offset, value, - sizeof(*value)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, value, + sizeof(*value)); } /* Mesh Provisioning Service Declaration */ static struct bt_gatt_attr prov_attrs[] = { - BT_GATT_PRIMARY_SERVICE(BT_UUID_MESH_PROV), + BT_GATT_PRIMARY_SERVICE(BT_UUID_MESH_PROV), - BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROV_DATA_IN, - BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_WRITE, NULL, proxy_recv, - (void *)1), + BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROV_DATA_IN, + BT_GATT_CHRC_WRITE_WITHOUT_RESP, + BT_GATT_PERM_WRITE, NULL, proxy_recv, + (void *)1), - BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROV_DATA_OUT, - BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_NONE, - NULL, NULL, NULL), - #if 0 - BT_GATT_CCC_MANAGED(prov_ccc_changed, prov_ccc_write, NULL), - #else - /* Add custom CCC as clients need to be tracked individually */ - BT_GATT_DESCRIPTOR(BT_UUID_GATT_CCC, - BT_GATT_PERM_WRITE | BT_GATT_PERM_READ, - prov_ccc_read, prov_ccc_write, &prov_ccc_val), + BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROV_DATA_OUT, + BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_NONE, + NULL, NULL, NULL), + #if 0 + BT_GATT_CCC_MANAGED(prov_ccc_changed, prov_ccc_write, NULL), + #else + /* Add custom CCC as clients need to be tracked individually */ + BT_GATT_DESCRIPTOR(BT_UUID_GATT_CCC, + BT_GATT_PERM_WRITE | BT_GATT_PERM_READ, + prov_ccc_read, prov_ccc_write, &prov_ccc_val), #endif }; @@ -717,68 +717,68 @@ static struct bt_gatt_service prov_svc = BT_GATT_SERVICE(prov_attrs); int bt_mesh_proxy_prov_enable(void) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - if (gatt_svc == MESH_GATT_PROV) { - return -EALREADY; - } + if (gatt_svc == MESH_GATT_PROV) { + return -EALREADY; + } - if (gatt_svc != MESH_GATT_NONE) { - return -EBUSY; - } + if (gatt_svc != MESH_GATT_NONE) { + return -EBUSY; + } - bt_gatt_service_register(&prov_svc); - gatt_svc = MESH_GATT_PROV; - prov_fast_adv = true; + bt_gatt_service_register(&prov_svc); + gatt_svc = MESH_GATT_PROV; + prov_fast_adv = true; - for (i = 0; i < ARRAY_SIZE(clients); i++) { - if (clients[i].conn) { - clients[i].filter_type = PROV; - } - } + for (i = 0; i < ARRAY_SIZE(clients); i++) { + if (clients[i].conn) { + clients[i].filter_type = PROV; + } + } - return 0; + return 0; } int bt_mesh_proxy_prov_disable(bool disconnect) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - if (gatt_svc == MESH_GATT_NONE) { - return -EALREADY; - } + if (gatt_svc == MESH_GATT_NONE) { + return -EALREADY; + } - if (gatt_svc != MESH_GATT_PROV) { - return -EBUSY; - } + if (gatt_svc != MESH_GATT_PROV) { + return -EBUSY; + } - bt_gatt_service_unregister(&prov_svc); - gatt_svc = MESH_GATT_NONE; + bt_gatt_service_unregister(&prov_svc); + gatt_svc = MESH_GATT_NONE; - for (i = 0; i < ARRAY_SIZE(clients); i++) { - struct bt_mesh_proxy_client *client = &clients[i]; + for (i = 0; i < ARRAY_SIZE(clients); i++) { + struct bt_mesh_proxy_client *client = &clients[i]; - if (!client->conn || client->filter_type != PROV) { - continue; - } + if (!client->conn || client->filter_type != PROV) { + continue; + } - if (disconnect) { - bt_conn_disconnect(client->conn, - BT_HCI_ERR_REMOTE_USER_TERM_CONN); - } else { - bt_mesh_pb_gatt_close(client->conn); - client->filter_type = NONE; - } - } + if (disconnect) { + bt_conn_disconnect(client->conn, + BT_HCI_ERR_REMOTE_USER_TERM_CONN); + } else { + bt_mesh_pb_gatt_close(client->conn); + client->filter_type = NONE; + } + } - bt_mesh_adv_update(); + bt_mesh_adv_update(); - return 0; + return 0; } #endif /* CONFIG_BT_MESH_PB_GATT */ @@ -787,96 +787,96 @@ int bt_mesh_proxy_prov_disable(bool disconnect) #if 0 static void proxy_ccc_changed(const struct bt_gatt_attr *attr, u16_t value) { - BT_DBG("value 0x%04x", value); + BT_DBG("value 0x%04x", value); } static bool proxy_ccc_write(struct bt_conn *conn, - const struct bt_gatt_attr *attr, u16_t value) + const struct bt_gatt_attr *attr, u16_t value) { - struct bt_mesh_proxy_client *client; + struct bt_mesh_proxy_client *client; - BT_DBG("value: 0x%04x", value); + BT_DBG("value: 0x%04x", value); - if (value != BT_GATT_CCC_NOTIFY) { - BT_WARN("Client wrote 0x%04x instead enabling notify", value); - return false; - } + if (value != BT_GATT_CCC_NOTIFY) { + BT_WARN("Client wrote 0x%04x instead enabling notify", value); + return false; + } - /* If a connection exists there must be a client */ - client = find_client(conn); - __ASSERT(client, "No client for connection"); + /* If a connection exists there must be a client */ + client = find_client(conn); + __ASSERT(client, "No client for connection"); - if (client->filter_type == NONE) { - client->filter_type = WHITELIST; - k_work_submit(&client->send_beacons); - } + if (client->filter_type == NONE) { + client->filter_type = WHITELIST; + k_work_submit(&client->send_beacons); + } - return true; + return true; } #else static ssize_t proxy_ccc_write(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - const void *buf, u16_t len, - u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, + const void *buf, u16_t len, + u16_t offset, u8_t flags) { - struct bt_mesh_proxy_client *client; - u16_t value; + struct bt_mesh_proxy_client *client; + u16_t value; - BT_DBG("len %u: %s", len, bt_hex(buf, len)); + BT_DBG("len %u: %s", len, bt_hex(buf, len)); - if (len != sizeof(value)) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); - } + if (len != sizeof(value)) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } - value = sys_get_le16(buf); - if (value != BT_GATT_CCC_NOTIFY) { - BT_WARN("Client wrote 0x%04x instead enabling notify", value); - return len; - } + value = sys_get_le16(buf); + if (value != BT_GATT_CCC_NOTIFY) { + BT_WARN("Client wrote 0x%04x instead enabling notify", value); + return len; + } - /* If a connection exists there must be a client */ - client = find_client(conn); - __ASSERT(client, "No client for connection"); + /* If a connection exists there must be a client */ + client = find_client(conn); + __ASSERT(client, "No client for connection"); - if (client->filter_type == NONE) { - client->filter_type = WHITELIST; - k_work_submit(&client->send_beacons); - } + if (client->filter_type == NONE) { + client->filter_type = WHITELIST; + k_work_submit(&client->send_beacons); + } - return len; + return len; } #endif static ssize_t proxy_ccc_read(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset) { - u16_t *value = attr->user_data; + u16_t *value = attr->user_data; - return bt_gatt_attr_read(conn, attr, buf, len, offset, value, - sizeof(*value)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, value, + sizeof(*value)); } /* Mesh Proxy Service Declaration */ static struct bt_gatt_attr proxy_attrs[] = { - BT_GATT_PRIMARY_SERVICE(BT_UUID_MESH_PROXY), + BT_GATT_PRIMARY_SERVICE(BT_UUID_MESH_PROXY), - BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_IN, - BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_WRITE, - NULL, proxy_recv, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_IN, + BT_GATT_CHRC_WRITE_WITHOUT_RESP, + BT_GATT_PERM_WRITE, + NULL, proxy_recv, NULL), - BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_OUT, - BT_GATT_CHRC_NOTIFY, - BT_GATT_PERM_NONE, - NULL, NULL, NULL), - #if 0 - BT_GATT_CCC_MANAGED(proxy_ccc_changed, proxy_ccc_write, NULL), - #else + BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_OUT, + BT_GATT_CHRC_NOTIFY, + BT_GATT_PERM_NONE, + NULL, NULL, NULL), + #if 0 + BT_GATT_CCC_MANAGED(proxy_ccc_changed, proxy_ccc_write, NULL), + #else /* Add custom CCC as clients need to be tracked individually */ - BT_GATT_DESCRIPTOR(BT_UUID_GATT_CCC, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - proxy_ccc_read, proxy_ccc_write, &proxy_ccc_val), + BT_GATT_DESCRIPTOR(BT_UUID_GATT_CCC, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + proxy_ccc_read, proxy_ccc_write, &proxy_ccc_val), #endif }; @@ -884,224 +884,224 @@ static struct bt_gatt_service proxy_svc = BT_GATT_SERVICE(proxy_attrs); int bt_mesh_proxy_gatt_enable(void) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - if (gatt_svc == MESH_GATT_PROXY) { - return -EALREADY; - } + if (gatt_svc == MESH_GATT_PROXY) { + return -EALREADY; + } - if (gatt_svc != MESH_GATT_NONE) { - return -EBUSY; - } + if (gatt_svc != MESH_GATT_NONE) { + return -EBUSY; + } - bt_gatt_service_register(&proxy_svc); - gatt_svc = MESH_GATT_PROXY; + bt_gatt_service_register(&proxy_svc); + gatt_svc = MESH_GATT_PROXY; - for (i = 0; i < ARRAY_SIZE(clients); i++) { - if (clients[i].conn) { - clients[i].filter_type = WHITELIST; - } - } + for (i = 0; i < ARRAY_SIZE(clients); i++) { + if (clients[i].conn) { + clients[i].filter_type = WHITELIST; + } + } - return 0; + return 0; } void bt_mesh_proxy_gatt_disconnect(void) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - for (i = 0; i < ARRAY_SIZE(clients); i++) { - struct bt_mesh_proxy_client *client = &clients[i]; + for (i = 0; i < ARRAY_SIZE(clients); i++) { + struct bt_mesh_proxy_client *client = &clients[i]; - if (client->conn && (client->filter_type == WHITELIST || - client->filter_type == BLACKLIST)) { - client->filter_type = NONE; - bt_conn_disconnect(client->conn, - BT_HCI_ERR_REMOTE_USER_TERM_CONN); - } - } + if (client->conn && (client->filter_type == WHITELIST || + client->filter_type == BLACKLIST)) { + client->filter_type = NONE; + bt_conn_disconnect(client->conn, + BT_HCI_ERR_REMOTE_USER_TERM_CONN); + } + } } int bt_mesh_proxy_gatt_disable(void) { - BT_DBG(""); + BT_DBG(""); - if (gatt_svc == MESH_GATT_NONE) { - return -EALREADY; - } + if (gatt_svc == MESH_GATT_NONE) { + return -EALREADY; + } - if (gatt_svc != MESH_GATT_PROXY) { - return -EBUSY; - } + if (gatt_svc != MESH_GATT_PROXY) { + return -EBUSY; + } - bt_mesh_proxy_gatt_disconnect(); + bt_mesh_proxy_gatt_disconnect(); - bt_gatt_service_unregister(&proxy_svc); - gatt_svc = MESH_GATT_NONE; + bt_gatt_service_unregister(&proxy_svc); + gatt_svc = MESH_GATT_NONE; - return 0; + return 0; } void bt_mesh_proxy_addr_add(struct net_buf_simple *buf, u16_t addr) { - struct bt_mesh_proxy_client *client = - CONTAINER_OF(buf, struct bt_mesh_proxy_client, buf); + struct bt_mesh_proxy_client *client = + CONTAINER_OF(buf, struct bt_mesh_proxy_client, buf); - BT_DBG("filter_type %u addr 0x%04x", client->filter_type, addr); + BT_DBG("filter_type %u addr 0x%04x", client->filter_type, addr); - if (client->filter_type == WHITELIST) { - filter_add(client, addr); - } else if (client->filter_type == BLACKLIST) { - filter_remove(client, addr); - } + if (client->filter_type == WHITELIST) { + filter_add(client, addr); + } else if (client->filter_type == BLACKLIST) { + filter_remove(client, addr); + } } static bool client_filter_match(struct bt_mesh_proxy_client *client, - u16_t addr) + u16_t addr) { - int i; + int i; - BT_DBG("filter_type %u addr 0x%04x", client->filter_type, addr); + BT_DBG("filter_type %u addr 0x%04x", client->filter_type, addr); - if (client->filter_type == WHITELIST) { - for (i = 0; i < ARRAY_SIZE(client->filter); i++) { - if (client->filter[i] == addr) { - return true; - } - } + if (client->filter_type == WHITELIST) { + for (i = 0; i < ARRAY_SIZE(client->filter); i++) { + if (client->filter[i] == addr) { + return true; + } + } - return false; - } + return false; + } - if (client->filter_type == BLACKLIST) { - for (i = 0; i < ARRAY_SIZE(client->filter); i++) { - if (client->filter[i] == addr) { - return false; - } - } + if (client->filter_type == BLACKLIST) { + for (i = 0; i < ARRAY_SIZE(client->filter); i++) { + if (client->filter[i] == addr) { + return false; + } + } - return true; - } + return true; + } - return false; + return false; } bool bt_mesh_proxy_relay(struct net_buf_simple *buf, u16_t dst) { - bool relayed = false; - int i; + bool relayed = false; + int i; - BT_DBG("%u bytes to dst 0x%04x", buf->len, dst); + BT_DBG("%u bytes to dst 0x%04x", buf->len, dst); - for (i = 0; i < ARRAY_SIZE(clients); i++) { - struct bt_mesh_proxy_client *client = &clients[i]; - NET_BUF_SIMPLE_DEFINE(msg, 32); + for (i = 0; i < ARRAY_SIZE(clients); i++) { + struct bt_mesh_proxy_client *client = &clients[i]; + NET_BUF_SIMPLE_DEFINE(msg, 32); - if (!client->conn) { - continue; - } + if (!client->conn) { + continue; + } - if (!client_filter_match(client, dst)) { - continue; - } + if (!client_filter_match(client, dst)) { + continue; + } - /* Proxy PDU sending modifies the original buffer, - * so we need to make a copy. - */ - net_buf_simple_reserve(&msg, 1); - net_buf_simple_add_mem(&msg, buf->data, buf->len); + /* Proxy PDU sending modifies the original buffer, + * so we need to make a copy. + */ + net_buf_simple_reserve(&msg, 1); + net_buf_simple_add_mem(&msg, buf->data, buf->len); - bt_mesh_proxy_send(client->conn, BT_MESH_PROXY_NET_PDU, &msg); - relayed = true; - } + bt_mesh_proxy_send(client->conn, BT_MESH_PROXY_NET_PDU, &msg); + relayed = true; + } - return relayed; + return relayed; } #endif /* CONFIG_BT_MESH_GATT_PROXY */ static int proxy_send(struct bt_conn *conn, const void *data, u16_t len) { - BT_DBG("%u bytes: %s", len, bt_hex(data, len)); + BT_DBG("%u bytes: %s", len, bt_hex(data, len)); #if defined(CONFIG_BT_MESH_GATT_PROXY) - if (gatt_svc == MESH_GATT_PROXY) { - return bt_gatt_notify(conn, &proxy_attrs[3], data, len); - } + if (gatt_svc == MESH_GATT_PROXY) { + return bt_gatt_notify(conn, &proxy_attrs[3], data, len); + } #endif #if defined(CONFIG_BT_MESH_PB_GATT) - if (gatt_svc == MESH_GATT_PROV) { - return bt_gatt_notify(conn, &prov_attrs[3], data, len); - } + if (gatt_svc == MESH_GATT_PROV) { + return bt_gatt_notify(conn, &prov_attrs[3], data, len); + } #endif - return 0; + return 0; } static int proxy_segment_and_send(struct bt_conn *conn, u8_t type, - struct net_buf_simple *msg) + struct net_buf_simple *msg) { - u16_t mtu; + u16_t mtu; - BT_DBG("conn %p type 0x%02x len %u: %s", conn, type, msg->len, - bt_hex(msg->data, msg->len)); + BT_DBG("conn %p type 0x%02x len %u: %s", conn, type, msg->len, + bt_hex(msg->data, msg->len)); - /* ATT_MTU - OpCode (1 byte) - Handle (2 bytes) */ - mtu = bt_gatt_get_mtu(conn) - 3; - if (mtu > msg->len) { - net_buf_simple_push_u8(msg, PDU_HDR(SAR_COMPLETE, type)); - return proxy_send(conn, msg->data, msg->len); - } + /* ATT_MTU - OpCode (1 byte) - Handle (2 bytes) */ + mtu = bt_gatt_get_mtu(conn) - 3; + if (mtu > msg->len) { + net_buf_simple_push_u8(msg, PDU_HDR(SAR_COMPLETE, type)); + return proxy_send(conn, msg->data, msg->len); + } - net_buf_simple_push_u8(msg, PDU_HDR(SAR_FIRST, type)); - proxy_send(conn, msg->data, mtu); - net_buf_simple_pull(msg, mtu); + net_buf_simple_push_u8(msg, PDU_HDR(SAR_FIRST, type)); + proxy_send(conn, msg->data, mtu); + net_buf_simple_pull(msg, mtu); - while (msg->len) { - if (msg->len + 1 < mtu) { - net_buf_simple_push_u8(msg, PDU_HDR(SAR_LAST, type)); - proxy_send(conn, msg->data, msg->len); - break; - } + while (msg->len) { + if (msg->len + 1 < mtu) { + net_buf_simple_push_u8(msg, PDU_HDR(SAR_LAST, type)); + proxy_send(conn, msg->data, msg->len); + break; + } - net_buf_simple_push_u8(msg, PDU_HDR(SAR_CONT, type)); - proxy_send(conn, msg->data, mtu); - net_buf_simple_pull(msg, mtu); - } + net_buf_simple_push_u8(msg, PDU_HDR(SAR_CONT, type)); + proxy_send(conn, msg->data, mtu); + net_buf_simple_pull(msg, mtu); + } - return 0; + return 0; } int bt_mesh_proxy_send(struct bt_conn *conn, u8_t type, - struct net_buf_simple *msg) + struct net_buf_simple *msg) { - struct bt_mesh_proxy_client *client = find_client(conn); + struct bt_mesh_proxy_client *client = find_client(conn); - if (!client) { - BT_ERR("No Proxy Client found"); - return -ENOTCONN; - } + if (!client) { + BT_ERR("No Proxy Client found"); + return -ENOTCONN; + } - if ((client->filter_type == PROV) != (type == BT_MESH_PROXY_PROV)) { - BT_ERR("Invalid PDU type for Proxy Client"); - return -EINVAL; - } + if ((client->filter_type == PROV) != (type == BT_MESH_PROXY_PROV)) { + BT_ERR("Invalid PDU type for Proxy Client"); + return -EINVAL; + } - return proxy_segment_and_send(conn, type, msg); + return proxy_segment_and_send(conn, type, msg); } #if defined(CONFIG_BT_MESH_PB_GATT) static u8_t prov_svc_data[20] = { 0x27, 0x18, }; static const struct bt_data prov_ad[] = { - BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), - BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x27, 0x18), - BT_DATA(BT_DATA_SVC_DATA16, prov_svc_data, sizeof(prov_svc_data)), + BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), + BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x27, 0x18), + BT_DATA(BT_DATA_SVC_DATA16, prov_svc_data, sizeof(prov_svc_data)), }; #endif /* PB_GATT */ @@ -1118,312 +1118,312 @@ static const struct bt_data prov_ad[] = { static u8_t proxy_svc_data[NODE_ID_LEN] = { 0x28, 0x18, }; static const struct bt_data node_id_ad[] = { - BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), - BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x28, 0x18), - BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NODE_ID_LEN), + BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), + BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x28, 0x18), + BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NODE_ID_LEN), }; static const struct bt_data net_id_ad[] = { - BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), - BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x28, 0x18), - BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NET_ID_LEN), + BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), + BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x28, 0x18), + BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NET_ID_LEN), }; static int node_id_adv(struct bt_mesh_subnet *sub) { - u8_t tmp[16]; - int err; + u8_t tmp[16]; + int err; - BT_DBG(""); + BT_DBG(""); - proxy_svc_data[2] = ID_TYPE_NODE; + proxy_svc_data[2] = ID_TYPE_NODE; - err = bt_rand(proxy_svc_data + 11, 8); - if (err) { - return err; - } + err = bt_rand(proxy_svc_data + 11, 8); + if (err) { + return err; + } - (void)memset(tmp, 0, 6); - memcpy(tmp + 6, proxy_svc_data + 11, 8); - sys_put_be16(bt_mesh_primary_addr(), tmp + 14); + (void)memset(tmp, 0, 6); + memcpy(tmp + 6, proxy_svc_data + 11, 8); + sys_put_be16(bt_mesh_primary_addr(), tmp + 14); - err = bt_encrypt_be(sub->keys[sub->kr_flag].identity, tmp, tmp); - if (err) { - return err; - } + err = bt_encrypt_be(sub->keys[sub->kr_flag].identity, tmp, tmp); + if (err) { + return err; + } - memcpy(proxy_svc_data + 3, tmp + 8, 8); + memcpy(proxy_svc_data + 3, tmp + 8, 8); - err = bt_le_adv_start(&fast_adv_param, node_id_ad, - ARRAY_SIZE(node_id_ad), NULL, 0); - if (err) { - BT_WARN("Failed to advertise using Node ID (err %d)", err); - return err; - } + err = bt_le_adv_start(&fast_adv_param, node_id_ad, + ARRAY_SIZE(node_id_ad), NULL, 0); + if (err) { + BT_WARN("Failed to advertise using Node ID (err %d)", err); + return err; + } - proxy_adv_enabled = true; + proxy_adv_enabled = true; - return 0; + return 0; } static int net_id_adv(struct bt_mesh_subnet *sub) { - int err; + int err; - BT_DBG(""); + BT_DBG(""); - proxy_svc_data[2] = ID_TYPE_NET; + proxy_svc_data[2] = ID_TYPE_NET; - BT_DBG("Advertising with NetId %s", - bt_hex(sub->keys[sub->kr_flag].net_id, 8)); + BT_DBG("Advertising with NetId %s", + bt_hex(sub->keys[sub->kr_flag].net_id, 8)); - memcpy(proxy_svc_data + 3, sub->keys[sub->kr_flag].net_id, 8); + memcpy(proxy_svc_data + 3, sub->keys[sub->kr_flag].net_id, 8); - err = bt_le_adv_start(&slow_adv_param, net_id_ad, - ARRAY_SIZE(net_id_ad), NULL, 0); - if (err) { - BT_WARN("Failed to advertise using Network ID (err %d)", err); - return err; - } + err = bt_le_adv_start(&slow_adv_param, net_id_ad, + ARRAY_SIZE(net_id_ad), NULL, 0); + if (err) { + BT_WARN("Failed to advertise using Network ID (err %d)", err); + return err; + } - proxy_adv_enabled = true; + proxy_adv_enabled = true; - return 0; + return 0; } static bool advertise_subnet(struct bt_mesh_subnet *sub) { - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - return false; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + return false; + } - return (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING || - bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED); + return (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING || + bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED); } static struct bt_mesh_subnet *next_sub(void) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub; - sub = &bt_mesh.sub[(i + next_idx) % ARRAY_SIZE(bt_mesh.sub)]; - if (advertise_subnet(sub)) { - next_idx = (next_idx + 1) % ARRAY_SIZE(bt_mesh.sub); - return sub; - } - } + sub = &bt_mesh.sub[(i + next_idx) % ARRAY_SIZE(bt_mesh.sub)]; + if (advertise_subnet(sub)) { + next_idx = (next_idx + 1) % ARRAY_SIZE(bt_mesh.sub); + return sub; + } + } - return NULL; + return NULL; } static int sub_count(void) { - int i, count = 0; + int i, count = 0; - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - if (advertise_subnet(sub)) { - count++; - } - } + if (advertise_subnet(sub)) { + count++; + } + } - return count; + return count; } static s32_t gatt_proxy_advertise(struct bt_mesh_subnet *sub) { - s32_t remaining = K_FOREVER; - int subnet_count; + s32_t remaining = K_FOREVER; + int subnet_count; - BT_DBG(""); + BT_DBG(""); - if (conn_count == CONFIG_BT_MAX_CONN) { - BT_DBG("Connectable advertising deferred (max connections)"); - return remaining; - } + if (conn_count == CONFIG_BT_MAX_CONN) { + BT_DBG("Connectable advertising deferred (max connections)"); + return remaining; + } - if (!sub) { - BT_WARN("No subnets to advertise on"); - return remaining; - } + if (!sub) { + BT_WARN("No subnets to advertise on"); + return remaining; + } - if (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING) { - u32_t active = k_uptime_get_32() - sub->node_id_start; + if (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING) { + u32_t active = k_uptime_get_32() - sub->node_id_start; - if (active < NODE_ID_TIMEOUT) { - remaining = NODE_ID_TIMEOUT - active; - BT_DBG("Node ID active for %u ms, %d ms remaining", - active, remaining); - node_id_adv(sub); - } else { - bt_mesh_proxy_identity_stop(sub); - BT_DBG("Node ID stopped"); - } - } + if (active < NODE_ID_TIMEOUT) { + remaining = NODE_ID_TIMEOUT - active; + BT_DBG("Node ID active for %u ms, %d ms remaining", + active, remaining); + node_id_adv(sub); + } else { + bt_mesh_proxy_identity_stop(sub); + BT_DBG("Node ID stopped"); + } + } - if (sub->node_id == BT_MESH_NODE_IDENTITY_STOPPED) { - if (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { - net_id_adv(sub); - } else { - return gatt_proxy_advertise(next_sub()); - } - } + if (sub->node_id == BT_MESH_NODE_IDENTITY_STOPPED) { + if (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { + net_id_adv(sub); + } else { + return gatt_proxy_advertise(next_sub()); + } + } - subnet_count = sub_count(); - BT_DBG("sub_count %u", subnet_count); - if (subnet_count > 1) { - s32_t max_timeout; + subnet_count = sub_count(); + BT_DBG("sub_count %u", subnet_count); + if (subnet_count > 1) { + s32_t max_timeout; - /* We use NODE_ID_TIMEOUT as a starting point since it may - * be less than 60 seconds. Divide this period into at least - * 6 slices, but make sure that a slice is at least one - * second long (to avoid excessive rotation). - */ - max_timeout = NODE_ID_TIMEOUT / MAX(subnet_count, 6); - max_timeout = MAX(max_timeout, K_SECONDS(1)); + /* We use NODE_ID_TIMEOUT as a starting point since it may + * be less than 60 seconds. Divide this period into at least + * 6 slices, but make sure that a slice is at least one + * second long (to avoid excessive rotation). + */ + max_timeout = NODE_ID_TIMEOUT / MAX(subnet_count, 6); + max_timeout = MAX(max_timeout, K_SECONDS(1)); - if (remaining > max_timeout || remaining < 0) { - remaining = max_timeout; - } - } + if (remaining > max_timeout || remaining < 0) { + remaining = max_timeout; + } + } - BT_DBG("Advertising %d ms for net_idx 0x%04x", remaining, sub->net_idx); + BT_DBG("Advertising %d ms for net_idx 0x%04x", remaining, sub->net_idx); - return remaining; + return remaining; } #endif /* GATT_PROXY */ #if defined(CONFIG_BT_MESH_PB_GATT) static size_t gatt_prov_adv_create(struct bt_data prov_sd[2]) { - const struct bt_mesh_prov *prov = bt_mesh_prov_get(); - const char *name = bt_get_name(); - size_t name_len = strlen(name); - size_t prov_sd_len = 0; - size_t sd_space = 31; + const struct bt_mesh_prov *prov = bt_mesh_prov_get(); + const char *name = bt_get_name(); + size_t name_len = strlen(name); + size_t prov_sd_len = 0; + size_t sd_space = 31; - memcpy(prov_svc_data + 2, prov->uuid, 16); - sys_put_be16(prov->oob_info, prov_svc_data + 18); + memcpy(prov_svc_data + 2, prov->uuid, 16); + sys_put_be16(prov->oob_info, prov_svc_data + 18); - if (prov->uri) { - size_t uri_len = strlen(prov->uri); + if (prov->uri) { + size_t uri_len = strlen(prov->uri); - if (uri_len > 29) { - /* There's no way to shorten an URI */ - BT_WARN("Too long URI to fit advertising packet"); - } else { - prov_sd[0].type = BT_DATA_URI; - prov_sd[0].data_len = uri_len; - prov_sd[0].data = (const u8_t *)prov->uri; - sd_space -= 2 + uri_len; - prov_sd_len++; - } - } + if (uri_len > 29) { + /* There's no way to shorten an URI */ + BT_WARN("Too long URI to fit advertising packet"); + } else { + prov_sd[0].type = BT_DATA_URI; + prov_sd[0].data_len = uri_len; + prov_sd[0].data = (const u8_t *)prov->uri; + sd_space -= 2 + uri_len; + prov_sd_len++; + } + } - if (sd_space > 2 && name_len > 0) { - sd_space -= 2; + if (sd_space > 2 && name_len > 0) { + sd_space -= 2; - if (sd_space < name_len) { - prov_sd[prov_sd_len].type = BT_DATA_NAME_SHORTENED; - prov_sd[prov_sd_len].data_len = sd_space; - } else { - prov_sd[prov_sd_len].type = BT_DATA_NAME_COMPLETE; - prov_sd[prov_sd_len].data_len = name_len; - } + if (sd_space < name_len) { + prov_sd[prov_sd_len].type = BT_DATA_NAME_SHORTENED; + prov_sd[prov_sd_len].data_len = sd_space; + } else { + prov_sd[prov_sd_len].type = BT_DATA_NAME_COMPLETE; + prov_sd[prov_sd_len].data_len = name_len; + } - prov_sd[prov_sd_len].data = (const u8_t *)name; - prov_sd_len++; - } + prov_sd[prov_sd_len].data = (const u8_t *)name; + prov_sd_len++; + } - return prov_sd_len; + return prov_sd_len; } #endif /* CONFIG_BT_MESH_PB_GATT */ s32_t bt_mesh_proxy_adv_start(void) { - BT_DBG(""); + BT_DBG(""); - if (gatt_svc == MESH_GATT_NONE) { - return K_FOREVER; - } + if (gatt_svc == MESH_GATT_NONE) { + return K_FOREVER; + } #if defined(CONFIG_BT_MESH_PB_GATT) - if (!bt_mesh_is_provisioned()) { - const struct bt_le_adv_param *param; - struct bt_data prov_sd[2]; - size_t prov_sd_len; + if (!bt_mesh_is_provisioned()) { + const struct bt_le_adv_param *param; + struct bt_data prov_sd[2]; + size_t prov_sd_len; - if (prov_fast_adv) { - param = &fast_adv_param; - } else { - param = &slow_adv_param; - } + if (prov_fast_adv) { + param = &fast_adv_param; + } else { + param = &slow_adv_param; + } - prov_sd_len = gatt_prov_adv_create(prov_sd); + prov_sd_len = gatt_prov_adv_create(prov_sd); - if (bt_le_adv_start(param, prov_ad, ARRAY_SIZE(prov_ad), - prov_sd, prov_sd_len) == 0) { - proxy_adv_enabled = true; + if (bt_le_adv_start(param, prov_ad, ARRAY_SIZE(prov_ad), + prov_sd, prov_sd_len) == 0) { + proxy_adv_enabled = true; - /* Advertise 60 seconds using fast interval */ - if (prov_fast_adv) { - prov_fast_adv = false; - return K_SECONDS(60); - } - } - } + /* Advertise 60 seconds using fast interval */ + if (prov_fast_adv) { + prov_fast_adv = false; + return K_SECONDS(60); + } + } + } #endif /* PB_GATT */ #if defined(CONFIG_BT_MESH_GATT_PROXY) - if (bt_mesh_is_provisioned()) { - return gatt_proxy_advertise(next_sub()); - } + if (bt_mesh_is_provisioned()) { + return gatt_proxy_advertise(next_sub()); + } #endif /* GATT_PROXY */ - return K_FOREVER; + return K_FOREVER; } void bt_mesh_proxy_adv_stop(void) { - int err; + int err; - BT_DBG("adv_enabled %u", proxy_adv_enabled); + BT_DBG("adv_enabled %u", proxy_adv_enabled); - if (!proxy_adv_enabled) { - return; - } + if (!proxy_adv_enabled) { + return; + } - err = bt_le_adv_stop(); - if (err) { - BT_ERR("Failed to stop advertising (err %d)", err); - } else { - proxy_adv_enabled = false; - } + err = bt_le_adv_stop(); + if (err) { + BT_ERR("Failed to stop advertising (err %d)", err); + } else { + proxy_adv_enabled = false; + } } static struct bt_conn_cb conn_callbacks = { - .connected = proxy_connected, - .disconnected = proxy_disconnected, + .connected = proxy_connected, + .disconnected = proxy_disconnected, }; int bt_mesh_proxy_init(void) { - int i; + int i; - /* Initialize the client receive buffers */ - for (i = 0; i < ARRAY_SIZE(clients); i++) { - struct bt_mesh_proxy_client *client = &clients[i]; + /* Initialize the client receive buffers */ + for (i = 0; i < ARRAY_SIZE(clients); i++) { + struct bt_mesh_proxy_client *client = &clients[i]; - client->buf.size = CLIENT_BUF_SIZE; - client->buf.__buf = client_buf_data + (i * CLIENT_BUF_SIZE); + client->buf.size = CLIENT_BUF_SIZE; + client->buf.__buf = client_buf_data + (i * CLIENT_BUF_SIZE); - k_delayed_work_init(&client->sar_timer, proxy_sar_timeout); - } + k_delayed_work_init(&client->sar_timer, proxy_sar_timeout); + } - bt_conn_cb_register(&conn_callbacks); + bt_conn_cb_register(&conn_callbacks); - return 0; + return 0; } diff --git a/components/network/ble/blemesh/src/proxy.h b/components/network/ble/blemesh/src/proxy.h index 96520955..4ce28a99 100644 --- a/components/network/ble/blemesh/src/proxy.h +++ b/components/network/ble/blemesh/src/proxy.h @@ -14,7 +14,7 @@ #define BT_MESH_PROXY_PROV 0x03 int bt_mesh_proxy_send(struct bt_conn *conn, u8_t type, - struct net_buf_simple *msg); + struct net_buf_simple *msg); int bt_mesh_proxy_prov_enable(void); int bt_mesh_proxy_prov_disable(bool disconnect); diff --git a/components/network/ble/blemesh/src/settings.c b/components/network/ble/blemesh/src/settings.c index 4bd12bec..e9caa423 100644 --- a/components/network/ble/blemesh/src/settings.c +++ b/components/network/ble/blemesh/src/settings.c @@ -48,198 +48,198 @@ * gets deleted its struct becomes invalid and may be reused for other keys. */ static struct key_update { - u16_t key_idx:12, /* AppKey or NetKey Index */ - valid:1, /* 1 if this entry is valid, 0 if not */ - app_key:1, /* 1 if this is an AppKey, 0 if a NetKey */ - clear:1; /* 1 if key needs clearing, 0 if storing */ + u16_t key_idx:12, /* AppKey or NetKey Index */ + valid:1, /* 1 if this entry is valid, 0 if not */ + app_key:1, /* 1 if this is an AppKey, 0 if a NetKey */ + clear:1; /* 1 if key needs clearing, 0 if storing */ } key_updates[CONFIG_BT_MESH_APP_KEY_COUNT + CONFIG_BT_MESH_SUBNET_COUNT]; static struct k_delayed_work pending_store; /* Mesh network storage information */ struct net_val { - u16_t primary_addr; - u8_t dev_key[16]; + u16_t primary_addr; + u8_t dev_key[16]; } __packed; /* Sequence number storage */ struct seq_val { - u8_t val[3]; + u8_t val[3]; } __packed; /* Heartbeat Publication storage */ struct hb_pub_val { - u16_t dst; - u8_t period; - u8_t ttl; - u16_t feat; - u16_t net_idx:12, - indefinite:1; + u16_t dst; + u8_t period; + u8_t ttl; + u16_t feat; + u16_t net_idx:12, + indefinite:1; }; /* Miscellaneous configuration server model states */ struct cfg_val { - u8_t net_transmit; - u8_t relay; - u8_t relay_retransmit; - u8_t beacon; - u8_t gatt_proxy; - u8_t frnd; - u8_t default_ttl; + u8_t net_transmit; + u8_t relay; + u8_t relay_retransmit; + u8_t beacon; + u8_t gatt_proxy; + u8_t frnd; + u8_t default_ttl; }; /* IV Index & IV Update storage */ struct iv_val { - u32_t iv_index; - u8_t iv_update:1, - iv_duration:7; + u32_t iv_index; + u8_t iv_update:1, + iv_duration:7; } __packed; /* Replay Protection List storage */ struct rpl_val { - u32_t seq:24, - old_iv:1; + u32_t seq:24, + old_iv:1; }; /* NetKey storage information */ struct net_key_val { - u8_t kr_flag:1, - kr_phase:7; - u8_t val[2][16]; + u8_t kr_flag:1, + kr_phase:7; + u8_t val[2][16]; } __packed; /* AppKey storage information */ struct app_key_val { - u16_t net_idx; - bool updated; - u8_t val[2][16]; + u16_t net_idx; + bool updated; + u8_t val[2][16]; } __packed; struct mod_pub_val { - u16_t addr; - u16_t key; - u8_t ttl; - u8_t retransmit; - u8_t period; - u8_t period_div:4, - cred:1; + u16_t addr; + u16_t key; + u8_t ttl; + u8_t retransmit; + u8_t period; + u8_t period_div:4, + cred:1; }; /* We need this so we don't overwrite app-hardcoded values in case FCB * contains a history of changes but then has a NULL at the end. */ static struct { - bool valid; - struct cfg_val cfg; + bool valid; + struct cfg_val cfg; } stored_cfg; #if defined(BFLB_BLE) struct net_key { u16_t net_idx; - struct net_key_val key_val; + struct net_key_val key_val; } __packed; struct app_key { u16_t app_idx; - struct app_key_val key_val; + struct app_key_val key_val; } __packed; struct mesh_rpl_val { - u16_t src; - struct rpl_val rpl; + u16_t src; + struct rpl_val rpl; } __packed; u16_t mesh_netkey_idx[CONFIG_BT_MESH_SUBNET_COUNT]; u16_t mesh_appkey_idx[CONFIG_BT_MESH_APP_KEY_COUNT]; static void encode_mod_path(struct bt_mesh_model *mod, bool vnd, - const char *key, char *path, size_t path_len); + const char *key, char *path, size_t path_len); static int net_set(void) { - struct net_val net; - int err; + struct net_val net; + int err; err = bt_settings_get_bin(NV_MESH_NET, (u8_t *)&net, sizeof(net), NULL); - if (err || !net.primary_addr) { - bt_mesh_comp_unprovision(); - (void)memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key)); - return 0; - } + if (err || !net.primary_addr) { + bt_mesh_comp_unprovision(); + (void)memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key)); + return 0; + } - memcpy(bt_mesh.dev_key, net.dev_key, sizeof(bt_mesh.dev_key)); - bt_mesh_comp_provision(net.primary_addr); + memcpy(bt_mesh.dev_key, net.dev_key, sizeof(bt_mesh.dev_key)); + bt_mesh_comp_provision(net.primary_addr); - BT_DBG("Provisioned with primary address 0x%04x", net.primary_addr); - BT_DBG("Recovered DevKey %s", bt_hex(bt_mesh.dev_key, 16)); + BT_DBG("Provisioned with primary address 0x%04x", net.primary_addr); + BT_DBG("Recovered DevKey %s", bt_hex(bt_mesh.dev_key, 16)); - return 0; + return 0; } static int iv_set(void) { - struct iv_val iv; - int err; + struct iv_val iv; + int err; err = bt_settings_get_bin(NV_MESH_IV, (u8_t *)&iv, sizeof(iv), NULL); - if (err) { - bt_mesh.iv_index = 0U; - atomic_clear_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); - return 0; - } + if (err) { + bt_mesh.iv_index = 0U; + atomic_clear_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); + return 0; + } - bt_mesh.iv_index = iv.iv_index; - atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv.iv_update); - bt_mesh.ivu_duration = iv.iv_duration; + bt_mesh.iv_index = iv.iv_index; + atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv.iv_update); + bt_mesh.ivu_duration = iv.iv_duration; - BT_DBG("IV Index 0x%04x (IV Update Flag %u) duration %u hours", - iv.iv_index, iv.iv_update, iv.iv_duration); + BT_DBG("IV Index 0x%04x (IV Update Flag %u) duration %u hours", + iv.iv_index, iv.iv_update, iv.iv_duration); - return 0; + return 0; } static int seq_set(void) { - struct seq_val seq; - int err; + struct seq_val seq; + int err; err = bt_settings_get_bin(NV_MESH_SEQ, (u8_t *)&seq, sizeof(seq), NULL); - if (err) { - bt_mesh.seq = 0U; - return 0; - } + if (err) { + bt_mesh.seq = 0U; + return 0; + } - bt_mesh.seq = ((u32_t)seq.val[0] | ((u32_t)seq.val[1] << 8) | - ((u32_t)seq.val[2] << 16)); + bt_mesh.seq = ((u32_t)seq.val[0] | ((u32_t)seq.val[1] << 8) | + ((u32_t)seq.val[2] << 16)); - if (CONFIG_BT_MESH_SEQ_STORE_RATE > 0) { - /* Make sure we have a large enough sequence number. We - * subtract 1 so that the first transmission causes a write - * to the settings storage. - */ - bt_mesh.seq += (CONFIG_BT_MESH_SEQ_STORE_RATE - - (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)); - bt_mesh.seq--; - } + if (CONFIG_BT_MESH_SEQ_STORE_RATE > 0) { + /* Make sure we have a large enough sequence number. We + * subtract 1 so that the first transmission causes a write + * to the settings storage. + */ + bt_mesh.seq += (CONFIG_BT_MESH_SEQ_STORE_RATE - + (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)); + bt_mesh.seq--; + } - BT_DBG("Sequence Number 0x%06x", bt_mesh.seq); + BT_DBG("Sequence Number 0x%06x", bt_mesh.seq); - return 0; + return 0; } static int rpl_set(void) { - bt_settings_get_bin(NV_MESH_RPL, (u8_t *)bt_mesh.rpl, sizeof(bt_mesh.rpl), NULL); - return 0; + bt_settings_get_bin(NV_MESH_RPL, (u8_t *)bt_mesh.rpl, sizeof(bt_mesh.rpl), NULL); + return 0; } static int net_key_set(void) { - struct bt_mesh_subnet *sub; - struct net_key_val key; + struct bt_mesh_subnet *sub; + struct net_key_val key; char path[20]; - int i, j, err; + int i, j, err; err = bt_settings_get_bin("bt/mesh/NetKeyIndex", (u8_t *)mesh_netkey_idx, sizeof(mesh_netkey_idx), NULL); if(err){ @@ -250,27 +250,27 @@ static int net_key_set(void) if(mesh_netkey_idx[i] == BT_MESH_KEY_UNUSED){ continue; } - - snprintk(path, sizeof(path), "bt/mesh/NetKey/%x", mesh_netkey_idx[i]); + + snprintk(path, sizeof(path), "bt/mesh/NetKey/%x", mesh_netkey_idx[i]); err = bt_settings_get_bin((const char *)path, (u8_t *)&key, sizeof(key), NULL); if(err){ BT_ERR("Failed to load netkey with netkey index %d", mesh_netkey_idx[i]); return err; } sub = bt_mesh_subnet_get(mesh_netkey_idx[i]); - - if (!sub){ + + if (!sub){ for (j = 0; j < ARRAY_SIZE(bt_mesh.sub); j++) { - if (bt_mesh.sub[j].net_idx == BT_MESH_KEY_UNUSED) { - sub = &bt_mesh.sub[j]; - break; - } - } + if (bt_mesh.sub[j].net_idx == BT_MESH_KEY_UNUSED) { + sub = &bt_mesh.sub[j]; + break; + } + } if (!sub){ - BT_ERR("No space to allocate a new subnet"); - return -ENOMEM; - } + BT_ERR("No space to allocate a new subnet"); + return -ENOMEM; + } } @@ -280,20 +280,20 @@ static int net_key_set(void) sub->kr_phase = key.kr_phase; memcpy(sub->keys[0].net, &key.val[0], 16); memcpy(sub->keys[1].net, &key.val[1], 16); - + BT_DBG("NetKeyIndex 0x%03x recovered from storage", mesh_netkey_idx[i]); } } - return 0; + return 0; } static int app_key_set(void) { - struct bt_mesh_app_key *app; - struct app_key_val key; + struct bt_mesh_app_key *app; + struct app_key_val key; char path[20]; - int err, i; + int err, i; err = bt_settings_get_bin("bt/mesh/AppKeyIndex", (u8_t *)mesh_appkey_idx, sizeof(mesh_appkey_idx), NULL); if(err){ @@ -305,8 +305,8 @@ static int app_key_set(void) if(mesh_appkey_idx[i] == BT_MESH_KEY_UNUSED){ continue; } - - snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", mesh_appkey_idx[i]); + + snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", mesh_appkey_idx[i]); err = bt_settings_get_bin((const char *)path, (u8_t *)&key, sizeof(key), NULL); if(err){ BT_ERR("Failed to load netkey with netkey index %d", mesh_appkey_idx[i]); @@ -315,88 +315,88 @@ static int app_key_set(void) app = bt_mesh_app_key_find(mesh_appkey_idx[i]); if (!app) { - app = bt_mesh_app_key_alloc(mesh_appkey_idx[i]); + app = bt_mesh_app_key_alloc(mesh_appkey_idx[i]); } if (!app) { - BT_ERR("No space for a new app key"); - return -ENOMEM; - } + BT_ERR("No space for a new app key"); + return -ENOMEM; + } app->net_idx = key.net_idx; app->app_idx = mesh_appkey_idx[i]; app->updated = key.updated; memcpy(app->keys[0].val, key.val[0], 16); memcpy(app->keys[1].val, key.val[1], 16); - + bt_mesh_app_id(app->keys[0].val, &app->keys[0].id); bt_mesh_app_id(app->keys[1].val, &app->keys[1].id); - - BT_DBG("AppKeyIndex 0x%03x recovered from storage", app->app_idx); - } - return 0; + BT_DBG("AppKeyIndex 0x%03x recovered from storage", app->app_idx); + } + + return 0; } static int hb_pub_set(void) { - struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get(); - struct hb_pub_val hb_val; - int err; + struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get(); + struct hb_pub_val hb_val; + int err; - if (!pub) { - return -ENOENT; - } + if (!pub) { + return -ENOENT; + } err = bt_settings_get_bin(NV_MESH_HBPUB, (u8_t *)&hb_val, sizeof(hb_val), NULL); - - if (err) { - pub->dst = BT_MESH_ADDR_UNASSIGNED; - pub->count = 0U; - pub->ttl = 0U; - pub->period = 0U; - pub->feat = 0U; - return 0; - } + if (err) { + pub->dst = BT_MESH_ADDR_UNASSIGNED; + pub->count = 0U; + pub->ttl = 0U; + pub->period = 0U; + pub->feat = 0U; - pub->dst = hb_val.dst; - pub->period = hb_val.period; - pub->ttl = hb_val.ttl; - pub->feat = hb_val.feat; - pub->net_idx = hb_val.net_idx; + return 0; + } - if (hb_val.indefinite) { - pub->count = 0xffff; - } else { - pub->count = 0U; - } + pub->dst = hb_val.dst; + pub->period = hb_val.period; + pub->ttl = hb_val.ttl; + pub->feat = hb_val.feat; + pub->net_idx = hb_val.net_idx; - BT_DBG("Restored heartbeat publication"); + if (hb_val.indefinite) { + pub->count = 0xffff; + } else { + pub->count = 0U; + } - return 0; + BT_DBG("Restored heartbeat publication"); + + return 0; } static int cfg_set(void) { - struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); - int err; + struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); + int err; - if (!cfg) { - return -ENOENT; - } + if (!cfg) { + return -ENOENT; + } err = bt_settings_get_bin(NV_MESH_CFG, (u8_t *)&stored_cfg.cfg, sizeof(stored_cfg.cfg), NULL); - - if (err) { - stored_cfg.valid = false; - return 0; - } - stored_cfg.valid = true; - BT_DBG("Restored configuration state"); + if (err) { + stored_cfg.valid = false; + return 0; + } - return 0; + stored_cfg.valid = true; + BT_DBG("Restored configuration state"); + + return 0; } static int mod_set_bind(struct bt_mesh_model *mod, bool vnd) @@ -404,75 +404,75 @@ static int mod_set_bind(struct bt_mesh_model *mod, bool vnd) char path[20]; encode_mod_path(mod, vnd, "bind", path, sizeof(path)); - + bt_settings_get_bin((const char *)path, (u8_t *)(mod->keys), sizeof(mod->keys), NULL); - - return 0; + + return 0; } static int mod_set_sub(struct bt_mesh_model *mod, bool vnd) { char path[20]; - /* Start with empty array regardless of cleared or set value */ - (void)memset(mod->groups, 0, sizeof(mod->groups)); + /* Start with empty array regardless of cleared or set value */ + (void)memset(mod->groups, 0, sizeof(mod->groups)); encode_mod_path(mod, vnd, "sub", path, sizeof(path)); bt_settings_get_bin((const char *)path, (u8_t *)(mod->groups), sizeof(mod->groups), NULL); - - return 0; + + return 0; } static int mod_set_pub(struct bt_mesh_model *mod, bool vnd) { - struct mod_pub_val pub; - int err; + struct mod_pub_val pub; + int err; char path[20]; - if (!mod->pub) { - BT_WARN("Model has no publication context!"); - return -EINVAL; - } + if (!mod->pub) { + BT_WARN("Model has no publication context!"); + return -EINVAL; + } encode_mod_path(mod, vnd, "pub", path, sizeof(path)); err = bt_settings_get_bin((const char *)path, (u8_t *)&pub, sizeof(pub), NULL); - - if (err) { - mod->pub->addr = BT_MESH_ADDR_UNASSIGNED; - mod->pub->key = 0U; - mod->pub->cred = 0U; - mod->pub->ttl = 0U; - mod->pub->period = 0U; - mod->pub->retransmit = 0U; - mod->pub->count = 0U; - BT_DBG("Cleared publication for model"); - return 0; - } + if (err) { + mod->pub->addr = BT_MESH_ADDR_UNASSIGNED; + mod->pub->key = 0U; + mod->pub->cred = 0U; + mod->pub->ttl = 0U; + mod->pub->period = 0U; + mod->pub->retransmit = 0U; + mod->pub->count = 0U; - mod->pub->addr = pub.addr; - mod->pub->key = pub.key; - mod->pub->cred = pub.cred; - mod->pub->ttl = pub.ttl; - mod->pub->period = pub.period; - mod->pub->retransmit = pub.retransmit; - mod->pub->count = 0U; + BT_DBG("Cleared publication for model"); + return 0; + } - BT_DBG("Restored model publication, dst 0x%04x app_idx 0x%03x", - pub.addr, pub.key); + mod->pub->addr = pub.addr; + mod->pub->key = pub.key; + mod->pub->cred = pub.cred; + mod->pub->ttl = pub.ttl; + mod->pub->period = pub.period; + mod->pub->retransmit = pub.retransmit; + mod->pub->count = 0U; - return 0; + BT_DBG("Restored model publication, dst 0x%04x app_idx 0x%03x", + pub.addr, pub.key); + + return 0; } static int mod_set(bool vnd, struct bt_mesh_model *model) { mod_set_bind(model, vnd); mod_set_sub(model, vnd); - mod_set_pub(model, vnd); - - return 0; + mod_set_pub(model, vnd); + + return 0; } static int sig_mod_set(void) @@ -484,7 +484,7 @@ static int sig_mod_set(void) int err; comp = bt_mesh_comp_get(); - + for(i = 0; i < comp->elem_count; i++) { elem = &comp->elem[i]; for(j = 0; j < elem->model_count; j++) { @@ -500,7 +500,7 @@ static int sig_mod_set(void) static int vnd_mod_set(void) { - struct bt_mesh_elem *elem; + struct bt_mesh_elem *elem; struct bt_mesh_model *model; const struct bt_mesh_comp * comp; int i, j; @@ -516,583 +516,583 @@ static int vnd_mod_set(void) return err; } } - + return 0; } #else static inline int mesh_x_set(settings_read_cb read_cb, void *cb_arg, void *out, - size_t read_len) + size_t read_len) { - ssize_t len; + ssize_t len; - len = read_cb(cb_arg, out, read_len); - if (len < 0) { - BT_ERR("Failed to read value (err %zu)", len); - return len; - } + len = read_cb(cb_arg, out, read_len); + if (len < 0) { + BT_ERR("Failed to read value (err %zu)", len); + return len; + } - BT_HEXDUMP_DBG(out, len, "val"); + BT_HEXDUMP_DBG(out, len, "val"); - if (len != read_len) { - BT_ERR("Unexpected value length (%zu != %zu)", len, read_len); - return -EINVAL; - } + if (len != read_len) { + BT_ERR("Unexpected value length (%zu != %zu)", len, read_len); + return -EINVAL; + } - return 0; + return 0; } static int net_set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) { - struct net_val net; - int err; + struct net_val net; + int err; - if (len_rd == 0) { - BT_DBG("val (null)"); + if (len_rd == 0) { + BT_DBG("val (null)"); - bt_mesh_comp_unprovision(); - (void)memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key)); - return 0; - } + bt_mesh_comp_unprovision(); + (void)memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key)); + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &net, sizeof(net)); - if (err) { - BT_ERR("Failed to set \'net\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &net, sizeof(net)); + if (err) { + BT_ERR("Failed to set \'net\'"); + return err; + } - memcpy(bt_mesh.dev_key, net.dev_key, sizeof(bt_mesh.dev_key)); - bt_mesh_comp_provision(net.primary_addr); + memcpy(bt_mesh.dev_key, net.dev_key, sizeof(bt_mesh.dev_key)); + bt_mesh_comp_provision(net.primary_addr); - BT_DBG("Provisioned with primary address 0x%04x", net.primary_addr); - BT_DBG("Recovered DevKey %s", bt_hex(bt_mesh.dev_key, 16)); + BT_DBG("Provisioned with primary address 0x%04x", net.primary_addr); + BT_DBG("Recovered DevKey %s", bt_hex(bt_mesh.dev_key, 16)); - return 0; + return 0; } static int iv_set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) { - struct iv_val iv; - int err; + struct iv_val iv; + int err; - if (len_rd == 0) { - BT_DBG("IV deleted"); + if (len_rd == 0) { + BT_DBG("IV deleted"); - bt_mesh.iv_index = 0U; - atomic_clear_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); - return 0; - } + bt_mesh.iv_index = 0U; + atomic_clear_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &iv, sizeof(iv)); - if (err) { - BT_ERR("Failed to set \'iv\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &iv, sizeof(iv)); + if (err) { + BT_ERR("Failed to set \'iv\'"); + return err; + } - bt_mesh.iv_index = iv.iv_index; - atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv.iv_update); - bt_mesh.ivu_duration = iv.iv_duration; + bt_mesh.iv_index = iv.iv_index; + atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv.iv_update); + bt_mesh.ivu_duration = iv.iv_duration; - BT_DBG("IV Index 0x%04x (IV Update Flag %u) duration %u hours", - iv.iv_index, iv.iv_update, iv.iv_duration); + BT_DBG("IV Index 0x%04x (IV Update Flag %u) duration %u hours", + iv.iv_index, iv.iv_update, iv.iv_duration); - return 0; + return 0; } static int seq_set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) { - struct seq_val seq; - int err; + struct seq_val seq; + int err; - if (len_rd == 0) { - BT_DBG("val (null)"); + if (len_rd == 0) { + BT_DBG("val (null)"); - bt_mesh.seq = 0U; - return 0; - } + bt_mesh.seq = 0U; + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &seq, sizeof(seq)); - if (err) { - BT_ERR("Failed to set \'seq\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &seq, sizeof(seq)); + if (err) { + BT_ERR("Failed to set \'seq\'"); + return err; + } - bt_mesh.seq = ((u32_t)seq.val[0] | ((u32_t)seq.val[1] << 8) | - ((u32_t)seq.val[2] << 16)); + bt_mesh.seq = ((u32_t)seq.val[0] | ((u32_t)seq.val[1] << 8) | + ((u32_t)seq.val[2] << 16)); - if (CONFIG_BT_MESH_SEQ_STORE_RATE > 0) { - /* Make sure we have a large enough sequence number. We - * subtract 1 so that the first transmission causes a write - * to the settings storage. - */ - bt_mesh.seq += (CONFIG_BT_MESH_SEQ_STORE_RATE - - (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)); - bt_mesh.seq--; - } + if (CONFIG_BT_MESH_SEQ_STORE_RATE > 0) { + /* Make sure we have a large enough sequence number. We + * subtract 1 so that the first transmission causes a write + * to the settings storage. + */ + bt_mesh.seq += (CONFIG_BT_MESH_SEQ_STORE_RATE - + (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)); + bt_mesh.seq--; + } - BT_DBG("Sequence Number 0x%06x", bt_mesh.seq); + BT_DBG("Sequence Number 0x%06x", bt_mesh.seq); - return 0; + return 0; } static struct bt_mesh_rpl *rpl_find(u16_t src) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { - if (bt_mesh.rpl[i].src == src) { - return &bt_mesh.rpl[i]; - } - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { + if (bt_mesh.rpl[i].src == src) { + return &bt_mesh.rpl[i]; + } + } - return NULL; + return NULL; } static struct bt_mesh_rpl *rpl_alloc(u16_t src) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { - if (!bt_mesh.rpl[i].src) { - bt_mesh.rpl[i].src = src; - return &bt_mesh.rpl[i]; - } - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { + if (!bt_mesh.rpl[i].src) { + bt_mesh.rpl[i].src = src; + return &bt_mesh.rpl[i]; + } + } - return NULL; + return NULL; } static int rpl_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - struct bt_mesh_rpl *entry; - struct rpl_val rpl; - int err; - u16_t src; + struct bt_mesh_rpl *entry; + struct rpl_val rpl; + int err; + u16_t src; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -ENOENT; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -ENOENT; + } - src = strtol(name, NULL, 16); - entry = rpl_find(src); + src = strtol(name, NULL, 16); + entry = rpl_find(src); - if (len_rd == 0) { - BT_DBG("val (null)"); - if (entry) { - (void)memset(entry, 0, sizeof(*entry)); - } else { - BT_WARN("Unable to find RPL entry for 0x%04x", src); - } + if (len_rd == 0) { + BT_DBG("val (null)"); + if (entry) { + (void)memset(entry, 0, sizeof(*entry)); + } else { + BT_WARN("Unable to find RPL entry for 0x%04x", src); + } - return 0; - } + return 0; + } - if (!entry) { - entry = rpl_alloc(src); - if (!entry) { - BT_ERR("Unable to allocate RPL entry for 0x%04x", src); - return -ENOMEM; - } - } + if (!entry) { + entry = rpl_alloc(src); + if (!entry) { + BT_ERR("Unable to allocate RPL entry for 0x%04x", src); + return -ENOMEM; + } + } - err = mesh_x_set(read_cb, cb_arg, &rpl, sizeof(rpl)); - if (err) { - BT_ERR("Failed to set `net`"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &rpl, sizeof(rpl)); + if (err) { + BT_ERR("Failed to set `net`"); + return err; + } - entry->seq = rpl.seq; - entry->old_iv = rpl.old_iv; + entry->seq = rpl.seq; + entry->old_iv = rpl.old_iv; - BT_DBG("RPL entry for 0x%04x: Seq 0x%06x old_iv %u", entry->src, - entry->seq, entry->old_iv); + BT_DBG("RPL entry for 0x%04x: Seq 0x%06x old_iv %u", entry->src, + entry->seq, entry->old_iv); - return 0; + return 0; } static int net_key_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - struct bt_mesh_subnet *sub; - struct net_key_val key; - int i, err; - u16_t net_idx; + struct bt_mesh_subnet *sub; + struct net_key_val key; + int i, err; + u16_t net_idx; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -ENOENT; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -ENOENT; + } - net_idx = strtol(name, NULL, 16); - sub = bt_mesh_subnet_get(net_idx); + net_idx = strtol(name, NULL, 16); + sub = bt_mesh_subnet_get(net_idx); - if (len_rd == 0) { - BT_DBG("val (null)"); - if (!sub) { - BT_ERR("No subnet with NetKeyIndex 0x%03x", net_idx); - return -ENOENT; - } + if (len_rd == 0) { + BT_DBG("val (null)"); + if (!sub) { + BT_ERR("No subnet with NetKeyIndex 0x%03x", net_idx); + return -ENOENT; + } - BT_DBG("Deleting NetKeyIndex 0x%03x", net_idx); - bt_mesh_subnet_del(sub, false); - return 0; - } + BT_DBG("Deleting NetKeyIndex 0x%03x", net_idx); + bt_mesh_subnet_del(sub, false); + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key)); - if (err) { - BT_ERR("Failed to set \'net-key\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key)); + if (err) { + BT_ERR("Failed to set \'net-key\'"); + return err; + } - if (sub) { - BT_DBG("Updating existing NetKeyIndex 0x%03x", net_idx); + if (sub) { + BT_DBG("Updating existing NetKeyIndex 0x%03x", net_idx); - sub->kr_flag = key.kr_flag; - sub->kr_phase = key.kr_phase; - memcpy(sub->keys[0].net, &key.val[0], 16); - memcpy(sub->keys[1].net, &key.val[1], 16); + sub->kr_flag = key.kr_flag; + sub->kr_phase = key.kr_phase; + memcpy(sub->keys[0].net, &key.val[0], 16); + memcpy(sub->keys[1].net, &key.val[1], 16); - return 0; - } + return 0; + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - if (bt_mesh.sub[i].net_idx == BT_MESH_KEY_UNUSED) { - sub = &bt_mesh.sub[i]; - break; - } - } + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + if (bt_mesh.sub[i].net_idx == BT_MESH_KEY_UNUSED) { + sub = &bt_mesh.sub[i]; + break; + } + } - if (!sub) { - BT_ERR("No space to allocate a new subnet"); - return -ENOMEM; - } + if (!sub) { + BT_ERR("No space to allocate a new subnet"); + return -ENOMEM; + } - sub->net_idx = net_idx; - sub->kr_flag = key.kr_flag; - sub->kr_phase = key.kr_phase; - memcpy(sub->keys[0].net, &key.val[0], 16); - memcpy(sub->keys[1].net, &key.val[1], 16); + sub->net_idx = net_idx; + sub->kr_flag = key.kr_flag; + sub->kr_phase = key.kr_phase; + memcpy(sub->keys[0].net, &key.val[0], 16); + memcpy(sub->keys[1].net, &key.val[1], 16); - BT_DBG("NetKeyIndex 0x%03x recovered from storage", net_idx); + BT_DBG("NetKeyIndex 0x%03x recovered from storage", net_idx); - return 0; + return 0; } static int app_key_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - struct bt_mesh_app_key *app; - struct app_key_val key; - u16_t app_idx; - int err; + struct bt_mesh_app_key *app; + struct app_key_val key; + u16_t app_idx; + int err; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -ENOENT; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -ENOENT; + } - app_idx = strtol(name, NULL, 16); + app_idx = strtol(name, NULL, 16); - if (len_rd == 0) { - BT_DBG("val (null)"); - BT_DBG("Deleting AppKeyIndex 0x%03x", app_idx); + if (len_rd == 0) { + BT_DBG("val (null)"); + BT_DBG("Deleting AppKeyIndex 0x%03x", app_idx); - app = bt_mesh_app_key_find(app_idx); - if (app) { - bt_mesh_app_key_del(app, false); - } + app = bt_mesh_app_key_find(app_idx); + if (app) { + bt_mesh_app_key_del(app, false); + } - return 0; - } + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key)); - if (err) { - BT_ERR("Failed to set \'app-key\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key)); + if (err) { + BT_ERR("Failed to set \'app-key\'"); + return err; + } - app = bt_mesh_app_key_find(app_idx); - if (!app) { - app = bt_mesh_app_key_alloc(app_idx); - } + app = bt_mesh_app_key_find(app_idx); + if (!app) { + app = bt_mesh_app_key_alloc(app_idx); + } - if (!app) { - BT_ERR("No space for a new app key"); - return -ENOMEM; - } + if (!app) { + BT_ERR("No space for a new app key"); + return -ENOMEM; + } - app->net_idx = key.net_idx; - app->app_idx = app_idx; - app->updated = key.updated; - memcpy(app->keys[0].val, key.val[0], 16); - memcpy(app->keys[1].val, key.val[1], 16); + app->net_idx = key.net_idx; + app->app_idx = app_idx; + app->updated = key.updated; + memcpy(app->keys[0].val, key.val[0], 16); + memcpy(app->keys[1].val, key.val[1], 16); - bt_mesh_app_id(app->keys[0].val, &app->keys[0].id); - bt_mesh_app_id(app->keys[1].val, &app->keys[1].id); + bt_mesh_app_id(app->keys[0].val, &app->keys[0].id); + bt_mesh_app_id(app->keys[1].val, &app->keys[1].id); - BT_DBG("AppKeyIndex 0x%03x recovered from storage", app_idx); + BT_DBG("AppKeyIndex 0x%03x recovered from storage", app_idx); - return 0; + return 0; } static int hb_pub_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get(); - struct hb_pub_val hb_val; - int err; + struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get(); + struct hb_pub_val hb_val; + int err; - if (!pub) { - return -ENOENT; - } + if (!pub) { + return -ENOENT; + } - if (len_rd == 0) { - pub->dst = BT_MESH_ADDR_UNASSIGNED; - pub->count = 0U; - pub->ttl = 0U; - pub->period = 0U; - pub->feat = 0U; + if (len_rd == 0) { + pub->dst = BT_MESH_ADDR_UNASSIGNED; + pub->count = 0U; + pub->ttl = 0U; + pub->period = 0U; + pub->feat = 0U; - BT_DBG("Cleared heartbeat publication"); - return 0; - } + BT_DBG("Cleared heartbeat publication"); + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &hb_val, sizeof(hb_val)); - if (err) { - BT_ERR("Failed to set \'hb_val\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &hb_val, sizeof(hb_val)); + if (err) { + BT_ERR("Failed to set \'hb_val\'"); + return err; + } - pub->dst = hb_val.dst; - pub->period = hb_val.period; - pub->ttl = hb_val.ttl; - pub->feat = hb_val.feat; - pub->net_idx = hb_val.net_idx; + pub->dst = hb_val.dst; + pub->period = hb_val.period; + pub->ttl = hb_val.ttl; + pub->feat = hb_val.feat; + pub->net_idx = hb_val.net_idx; - if (hb_val.indefinite) { - pub->count = 0xffff; - } else { - pub->count = 0U; - } + if (hb_val.indefinite) { + pub->count = 0xffff; + } else { + pub->count = 0U; + } - BT_DBG("Restored heartbeat publication"); + BT_DBG("Restored heartbeat publication"); - return 0; + return 0; } static int cfg_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); - int err; + struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); + int err; - if (!cfg) { - return -ENOENT; - } + if (!cfg) { + return -ENOENT; + } - if (len_rd == 0) { - stored_cfg.valid = false; - BT_DBG("Cleared configuration state"); - return 0; - } + if (len_rd == 0) { + stored_cfg.valid = false; + BT_DBG("Cleared configuration state"); + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &stored_cfg.cfg, - sizeof(stored_cfg.cfg)); - if (err) { - BT_ERR("Failed to set \'cfg\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &stored_cfg.cfg, + sizeof(stored_cfg.cfg)); + if (err) { + BT_ERR("Failed to set \'cfg\'"); + return err; + } - stored_cfg.valid = true; - BT_DBG("Restored configuration state"); + stored_cfg.valid = true; + BT_DBG("Restored configuration state"); - return 0; + return 0; } static int mod_set_bind(struct bt_mesh_model *mod, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - ssize_t len; - int i; + ssize_t len; + int i; - /* Start with empty array regardless of cleared or set value */ - for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { - mod->keys[i] = BT_MESH_KEY_UNUSED; - } + /* Start with empty array regardless of cleared or set value */ + for (i = 0; i < ARRAY_SIZE(mod->keys); i++) { + mod->keys[i] = BT_MESH_KEY_UNUSED; + } - if (len_rd == 0) { - BT_DBG("Cleared bindings for model"); - return 0; - } + if (len_rd == 0) { + BT_DBG("Cleared bindings for model"); + return 0; + } - len = read_cb(cb_arg, mod->keys, sizeof(mod->keys)); - if (len < 0) { - BT_ERR("Failed to read value (err %zu)", len); - return len; - } + len = read_cb(cb_arg, mod->keys, sizeof(mod->keys)); + if (len < 0) { + BT_ERR("Failed to read value (err %zu)", len); + return len; + } - BT_DBG("Decoded %zu bound keys for model", len / sizeof(mod->keys[0])); - return 0; + BT_DBG("Decoded %zu bound keys for model", len / sizeof(mod->keys[0])); + return 0; } static int mod_set_sub(struct bt_mesh_model *mod, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - ssize_t len; + ssize_t len; - /* Start with empty array regardless of cleared or set value */ - (void)memset(mod->groups, 0, sizeof(mod->groups)); + /* Start with empty array regardless of cleared or set value */ + (void)memset(mod->groups, 0, sizeof(mod->groups)); - if (len_rd == 0) { - BT_DBG("Cleared subscriptions for model"); - return 0; - } + if (len_rd == 0) { + BT_DBG("Cleared subscriptions for model"); + return 0; + } - len = read_cb(cb_arg, mod->groups, sizeof(mod->groups)); - if (len < 0) { - BT_ERR("Failed to read value (err %zu)", len); - return len; - } + len = read_cb(cb_arg, mod->groups, sizeof(mod->groups)); + if (len < 0) { + BT_ERR("Failed to read value (err %zu)", len); + return len; + } - BT_DBG("Decoded %zu subscribed group addresses for model", - len / sizeof(mod->groups[0])); - return 0; + BT_DBG("Decoded %zu subscribed group addresses for model", + len / sizeof(mod->groups[0])); + return 0; } static int mod_set_pub(struct bt_mesh_model *mod, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - struct mod_pub_val pub; - int err; + struct mod_pub_val pub; + int err; - if (!mod->pub) { - BT_WARN("Model has no publication context!"); - return -EINVAL; - } + if (!mod->pub) { + BT_WARN("Model has no publication context!"); + return -EINVAL; + } - if (len_rd == 0) { - mod->pub->addr = BT_MESH_ADDR_UNASSIGNED; - mod->pub->key = 0U; - mod->pub->cred = 0U; - mod->pub->ttl = 0U; - mod->pub->period = 0U; - mod->pub->retransmit = 0U; - mod->pub->count = 0U; + if (len_rd == 0) { + mod->pub->addr = BT_MESH_ADDR_UNASSIGNED; + mod->pub->key = 0U; + mod->pub->cred = 0U; + mod->pub->ttl = 0U; + mod->pub->period = 0U; + mod->pub->retransmit = 0U; + mod->pub->count = 0U; - BT_DBG("Cleared publication for model"); - return 0; - } + BT_DBG("Cleared publication for model"); + return 0; + } - err = mesh_x_set(read_cb, cb_arg, &pub, sizeof(pub)); - if (err) { - BT_ERR("Failed to set \'model-pub\'"); - return err; - } + err = mesh_x_set(read_cb, cb_arg, &pub, sizeof(pub)); + if (err) { + BT_ERR("Failed to set \'model-pub\'"); + return err; + } - mod->pub->addr = pub.addr; - mod->pub->key = pub.key; - mod->pub->cred = pub.cred; - mod->pub->ttl = pub.ttl; - mod->pub->period = pub.period; - mod->pub->retransmit = pub.retransmit; - mod->pub->count = 0U; + mod->pub->addr = pub.addr; + mod->pub->key = pub.key; + mod->pub->cred = pub.cred; + mod->pub->ttl = pub.ttl; + mod->pub->period = pub.period; + mod->pub->retransmit = pub.retransmit; + mod->pub->count = 0U; - BT_DBG("Restored model publication, dst 0x%04x app_idx 0x%03x", - pub.addr, pub.key); + BT_DBG("Restored model publication, dst 0x%04x app_idx 0x%03x", + pub.addr, pub.key); - return 0; + return 0; } static int mod_set(bool vnd, const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - struct bt_mesh_model *mod; - u8_t elem_idx, mod_idx; - u16_t mod_key; - int len; - const char *next; + struct bt_mesh_model *mod; + u8_t elem_idx, mod_idx; + u16_t mod_key; + int len; + const char *next; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -ENOENT; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -ENOENT; + } - mod_key = strtol(name, NULL, 16); - elem_idx = mod_key >> 8; - mod_idx = mod_key; + mod_key = strtol(name, NULL, 16); + elem_idx = mod_key >> 8; + mod_idx = mod_key; - BT_DBG("Decoded mod_key 0x%04x as elem_idx %u mod_idx %u", - mod_key, elem_idx, mod_idx); + BT_DBG("Decoded mod_key 0x%04x as elem_idx %u mod_idx %u", + mod_key, elem_idx, mod_idx); - mod = bt_mesh_model_get(vnd, elem_idx, mod_idx); - if (!mod) { - BT_ERR("Failed to get model for elem_idx %u mod_idx %u", - elem_idx, mod_idx); - return -ENOENT; - } + mod = bt_mesh_model_get(vnd, elem_idx, mod_idx); + if (!mod) { + BT_ERR("Failed to get model for elem_idx %u mod_idx %u", + elem_idx, mod_idx); + return -ENOENT; + } - len = settings_name_next(name, &next); + len = settings_name_next(name, &next); - if (!next) { - BT_ERR("Insufficient number of arguments"); - return -ENOENT; - } + if (!next) { + BT_ERR("Insufficient number of arguments"); + return -ENOENT; + } - if (!strncmp(next, "bind", len)) { - return mod_set_bind(mod, len_rd, read_cb, cb_arg); - } + if (!strncmp(next, "bind", len)) { + return mod_set_bind(mod, len_rd, read_cb, cb_arg); + } - if (!strncmp(next, "sub", len)) { - return mod_set_sub(mod, len_rd, read_cb, cb_arg); - } + if (!strncmp(next, "sub", len)) { + return mod_set_sub(mod, len_rd, read_cb, cb_arg); + } - if (!strncmp(next, "pub", len)) { - return mod_set_pub(mod, len_rd, read_cb, cb_arg); - } + if (!strncmp(next, "pub", len)) { + return mod_set_pub(mod, len_rd, read_cb, cb_arg); + } - BT_WARN("Unknown module key %s", next); - return -ENOENT; + BT_WARN("Unknown module key %s", next); + return -ENOENT; } static int sig_mod_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - return mod_set(false, name, len_rd, read_cb, cb_arg); + return mod_set(false, name, len_rd, read_cb, cb_arg); } static int vnd_mod_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - return mod_set(true, name, len_rd, read_cb, cb_arg); + return mod_set(true, name, len_rd, read_cb, cb_arg); } #endif const struct mesh_setting { - const char *name; + const char *name; #if defined(BFLB_BLE) int (*func)(void); #else - int (*func)(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg); + int (*func)(const char *name, size_t len_rd, + settings_read_cb read_cb, void *cb_arg); #endif } settings[] = { - { "Net", net_set }, - { "IV", iv_set }, - { "Seq", seq_set }, - { "RPL", rpl_set }, - { "NetKey", net_key_set }, - { "AppKey", app_key_set }, - { "HBPub", hb_pub_set }, - { "Cfg", cfg_set }, - { "s", sig_mod_set }, - { "v", vnd_mod_set }, + { "Net", net_set }, + { "IV", iv_set }, + { "Seq", seq_set }, + { "RPL", rpl_set }, + { "NetKey", net_key_set }, + { "AppKey", app_key_set }, + { "HBPub", hb_pub_set }, + { "Cfg", cfg_set }, + { "s", sig_mod_set }, + { "v", vnd_mod_set }, }; #if defined(BFLB_BLE) @@ -1108,72 +1108,72 @@ int mesh_set(void) } #else static int mesh_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - int i, len; - const char *next; + int i, len; + const char *next; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -EINVAL; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -EINVAL; + } - len = settings_name_next(name, &next); + len = settings_name_next(name, &next); - for (i = 0; i < ARRAY_SIZE(settings); i++) { - if (!strncmp(settings[i].name, name, len)) { - return settings[i].func(next, len_rd, read_cb, cb_arg); - } - } + for (i = 0; i < ARRAY_SIZE(settings); i++) { + if (!strncmp(settings[i].name, name, len)) { + return settings[i].func(next, len_rd, read_cb, cb_arg); + } + } - BT_WARN("No matching handler for key %s", log_strdup(name)); + BT_WARN("No matching handler for key %s", log_strdup(name)); - return -ENOENT; + return -ENOENT; } #endif static int subnet_init(struct bt_mesh_subnet *sub) { - int err; + int err; - err = bt_mesh_net_keys_create(&sub->keys[0], sub->keys[0].net); - if (err) { - BT_ERR("Unable to generate keys for subnet"); - return -EIO; - } + err = bt_mesh_net_keys_create(&sub->keys[0], sub->keys[0].net); + if (err) { + BT_ERR("Unable to generate keys for subnet"); + return -EIO; + } - if (sub->kr_phase != BT_MESH_KR_NORMAL) { - err = bt_mesh_net_keys_create(&sub->keys[1], sub->keys[1].net); - if (err) { - BT_ERR("Unable to generate keys for subnet"); - (void)memset(&sub->keys[0], 0, sizeof(sub->keys[0])); - return -EIO; - } - } + if (sub->kr_phase != BT_MESH_KR_NORMAL) { + err = bt_mesh_net_keys_create(&sub->keys[1], sub->keys[1].net); + if (err) { + BT_ERR("Unable to generate keys for subnet"); + (void)memset(&sub->keys[0], 0, sizeof(sub->keys[0])); + return -EIO; + } + } - if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { - sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; - } else { - sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED; - } + if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) { + sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED; + } else { + sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED; + } - /* Make sure we have valid beacon data to be sent */ - bt_mesh_net_beacon_update(sub); + /* Make sure we have valid beacon data to be sent */ + bt_mesh_net_beacon_update(sub); - return 0; + return 0; } static void commit_mod(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, - bool vnd, bool primary, void *user_data) + bool vnd, bool primary, void *user_data) { - if (mod->pub && mod->pub->update && - mod->pub->addr != BT_MESH_ADDR_UNASSIGNED) { - s32_t ms = bt_mesh_model_pub_period_get(mod); - if (ms) { - BT_DBG("Starting publish timer (period %u ms)", ms); - k_delayed_work_submit(&mod->pub->timer, ms); - } - } + if (mod->pub && mod->pub->update && + mod->pub->addr != BT_MESH_ADDR_UNASSIGNED) { + s32_t ms = bt_mesh_model_pub_period_get(mod); + if (ms) { + BT_DBG("Starting publish timer (period %u ms)", ms); + k_delayed_work_submit(&mod->pub->timer, ms); + } + } } #if defined(BFLB_BLE) @@ -1182,214 +1182,214 @@ int mesh_commit(void) static int mesh_commit(void) #endif { - struct bt_mesh_hb_pub *hb_pub; - struct bt_mesh_cfg_srv *cfg; - int i; + struct bt_mesh_hb_pub *hb_pub; + struct bt_mesh_cfg_srv *cfg; + int i; - BT_DBG("sub[0].net_idx 0x%03x", bt_mesh.sub[0].net_idx); + BT_DBG("sub[0].net_idx 0x%03x", bt_mesh.sub[0].net_idx); - if (bt_mesh.sub[0].net_idx == BT_MESH_KEY_UNUSED) { - /* Nothing to do since we're not yet provisioned */ - return 0; - } + if (bt_mesh.sub[0].net_idx == BT_MESH_KEY_UNUSED) { + /* Nothing to do since we're not yet provisioned */ + return 0; + } - if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT)) { - bt_mesh_proxy_prov_disable(true); - } + if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT)) { + bt_mesh_proxy_prov_disable(true); + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { - struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; - int err; + for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) { + struct bt_mesh_subnet *sub = &bt_mesh.sub[i]; + int err; - if (sub->net_idx == BT_MESH_KEY_UNUSED) { - continue; - } + if (sub->net_idx == BT_MESH_KEY_UNUSED) { + continue; + } - err = subnet_init(sub); - if (err) { - BT_ERR("Failed to init subnet 0x%03x", sub->net_idx); - } - } + err = subnet_init(sub); + if (err) { + BT_ERR("Failed to init subnet 0x%03x", sub->net_idx); + } + } - if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) { - k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT); - } + if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) { + k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT); + } - bt_mesh_model_foreach(commit_mod, NULL); + bt_mesh_model_foreach(commit_mod, NULL); - hb_pub = bt_mesh_hb_pub_get(); - if (hb_pub && hb_pub->dst != BT_MESH_ADDR_UNASSIGNED && - hb_pub->count && hb_pub->period) { - BT_DBG("Starting heartbeat publication"); - k_work_submit(&hb_pub->timer.work); - } + hb_pub = bt_mesh_hb_pub_get(); + if (hb_pub && hb_pub->dst != BT_MESH_ADDR_UNASSIGNED && + hb_pub->count && hb_pub->period) { + BT_DBG("Starting heartbeat publication"); + k_work_submit(&hb_pub->timer.work); + } - cfg = bt_mesh_cfg_get(); - if (cfg && stored_cfg.valid) { - cfg->net_transmit = stored_cfg.cfg.net_transmit; - cfg->relay = stored_cfg.cfg.relay; - cfg->relay_retransmit = stored_cfg.cfg.relay_retransmit; - cfg->beacon = stored_cfg.cfg.beacon; - cfg->gatt_proxy = stored_cfg.cfg.gatt_proxy; - cfg->frnd = stored_cfg.cfg.frnd; - cfg->default_ttl = stored_cfg.cfg.default_ttl; - } + cfg = bt_mesh_cfg_get(); + if (cfg && stored_cfg.valid) { + cfg->net_transmit = stored_cfg.cfg.net_transmit; + cfg->relay = stored_cfg.cfg.relay; + cfg->relay_retransmit = stored_cfg.cfg.relay_retransmit; + cfg->beacon = stored_cfg.cfg.beacon; + cfg->gatt_proxy = stored_cfg.cfg.gatt_proxy; + cfg->frnd = stored_cfg.cfg.frnd; + cfg->default_ttl = stored_cfg.cfg.default_ttl; + } - atomic_set_bit(bt_mesh.flags, BT_MESH_VALID); + atomic_set_bit(bt_mesh.flags, BT_MESH_VALID); - bt_mesh_net_start(); + bt_mesh_net_start(); - return 0; + return 0; } #if !defined(BFLB_BLE) SETTINGS_STATIC_HANDLER_DEFINE(bt_mesh, "bt/mesh", NULL, mesh_set, mesh_commit, - NULL); + NULL); #endif /* Pending flags that use K_NO_WAIT as the storage timeout */ #define NO_WAIT_PENDING_BITS (BIT(BT_MESH_NET_PENDING) | \ - BIT(BT_MESH_IV_PENDING) | \ - BIT(BT_MESH_SEQ_PENDING)) + BIT(BT_MESH_IV_PENDING) | \ + BIT(BT_MESH_SEQ_PENDING)) /* Pending flags that use CONFIG_BT_MESH_STORE_TIMEOUT */ #define GENERIC_PENDING_BITS (BIT(BT_MESH_KEYS_PENDING) | \ - BIT(BT_MESH_HB_PUB_PENDING) | \ - BIT(BT_MESH_CFG_PENDING) | \ - BIT(BT_MESH_MOD_PENDING)) + BIT(BT_MESH_HB_PUB_PENDING) | \ + BIT(BT_MESH_CFG_PENDING) | \ + BIT(BT_MESH_MOD_PENDING)) static void schedule_store(int flag) { - s32_t timeout, remaining; + s32_t timeout, remaining; - atomic_set_bit(bt_mesh.flags, flag); + atomic_set_bit(bt_mesh.flags, flag); - if (atomic_get(bt_mesh.flags) & NO_WAIT_PENDING_BITS) { - timeout = K_NO_WAIT; - } else if (atomic_test_bit(bt_mesh.flags, BT_MESH_RPL_PENDING) && - (!(atomic_get(bt_mesh.flags) & GENERIC_PENDING_BITS) || - (CONFIG_BT_MESH_RPL_STORE_TIMEOUT < - CONFIG_BT_MESH_STORE_TIMEOUT))) { - timeout = K_SECONDS(CONFIG_BT_MESH_RPL_STORE_TIMEOUT); - } else { - timeout = K_SECONDS(CONFIG_BT_MESH_STORE_TIMEOUT); - } + if (atomic_get(bt_mesh.flags) & NO_WAIT_PENDING_BITS) { + timeout = K_NO_WAIT; + } else if (atomic_test_bit(bt_mesh.flags, BT_MESH_RPL_PENDING) && + (!(atomic_get(bt_mesh.flags) & GENERIC_PENDING_BITS) || + (CONFIG_BT_MESH_RPL_STORE_TIMEOUT < + CONFIG_BT_MESH_STORE_TIMEOUT))) { + timeout = K_SECONDS(CONFIG_BT_MESH_RPL_STORE_TIMEOUT); + } else { + timeout = K_SECONDS(CONFIG_BT_MESH_STORE_TIMEOUT); + } - remaining = k_delayed_work_remaining_get(&pending_store); - if (remaining && remaining < timeout) { - BT_DBG("Not rescheduling due to existing earlier deadline"); - return; - } + remaining = k_delayed_work_remaining_get(&pending_store); + if (remaining && remaining < timeout) { + BT_DBG("Not rescheduling due to existing earlier deadline"); + return; + } - BT_DBG("Waiting %d seconds", timeout / MSEC_PER_SEC); + BT_DBG("Waiting %d seconds", timeout / MSEC_PER_SEC); - k_delayed_work_submit(&pending_store, timeout); + k_delayed_work_submit(&pending_store, timeout); } static void clear_iv(void) { - int err; + int err; - err = settings_delete(NV_MESH_IV); - if (err) { - BT_ERR("Failed to clear IV"); - } else { - BT_DBG("Cleared IV"); - } + err = settings_delete(NV_MESH_IV); + if (err) { + BT_ERR("Failed to clear IV"); + } else { + BT_DBG("Cleared IV"); + } } static void clear_net(void) { - int err; + int err; - err = settings_delete(NV_MESH_NET); + err = settings_delete(NV_MESH_NET); - if (err) { - BT_ERR("Failed to clear Network, err(%d)", err); - } else { - BT_DBG("Cleared Network"); - } + if (err) { + BT_ERR("Failed to clear Network, err(%d)", err); + } else { + BT_DBG("Cleared Network"); + } } static void store_pending_net(void) { - struct net_val net; - int err; + struct net_val net; + int err; - BT_DBG("addr 0x%04x DevKey %s", bt_mesh_primary_addr(), - bt_hex(bt_mesh.dev_key, 16)); + BT_DBG("addr 0x%04x DevKey %s", bt_mesh_primary_addr(), + bt_hex(bt_mesh.dev_key, 16)); - net.primary_addr = bt_mesh_primary_addr(); - memcpy(net.dev_key, bt_mesh.dev_key, 16); + net.primary_addr = bt_mesh_primary_addr(); + memcpy(net.dev_key, bt_mesh.dev_key, 16); - err = settings_save_one(NV_MESH_NET, (const u8_t *)&net, sizeof(net)); + err = settings_save_one(NV_MESH_NET, (const u8_t *)&net, sizeof(net)); - if (err) { - BT_ERR("Failed to store Network value"); - } else { - BT_DBG("Stored Network value"); - } + if (err) { + BT_ERR("Failed to store Network value"); + } else { + BT_DBG("Stored Network value"); + } } void bt_mesh_store_net(void) { - schedule_store(BT_MESH_NET_PENDING); + schedule_store(BT_MESH_NET_PENDING); } static void store_pending_iv(void) { - struct iv_val iv; - int err; + struct iv_val iv; + int err; - iv.iv_index = bt_mesh.iv_index; - iv.iv_update = atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); - iv.iv_duration = bt_mesh.ivu_duration; + iv.iv_index = bt_mesh.iv_index; + iv.iv_update = atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS); + iv.iv_duration = bt_mesh.ivu_duration; - err = settings_save_one(NV_MESH_IV, (const u8_t *)&iv, sizeof(iv)); + err = settings_save_one(NV_MESH_IV, (const u8_t *)&iv, sizeof(iv)); - if (err) { - BT_ERR("Failed to store IV value"); - } else { - BT_DBG("Stored IV value"); - } + if (err) { + BT_ERR("Failed to store IV value"); + } else { + BT_DBG("Stored IV value"); + } } void bt_mesh_store_iv(bool only_duration) { - schedule_store(BT_MESH_IV_PENDING); + schedule_store(BT_MESH_IV_PENDING); - if (!only_duration) { - /* Always update Seq whenever IV changes */ - schedule_store(BT_MESH_SEQ_PENDING); - } + if (!only_duration) { + /* Always update Seq whenever IV changes */ + schedule_store(BT_MESH_SEQ_PENDING); + } } static void store_pending_seq(void) { - struct seq_val seq; - int err; + struct seq_val seq; + int err; - seq.val[0] = bt_mesh.seq; - seq.val[1] = bt_mesh.seq >> 8; - seq.val[2] = bt_mesh.seq >> 16; + seq.val[0] = bt_mesh.seq; + seq.val[1] = bt_mesh.seq >> 8; + seq.val[2] = bt_mesh.seq >> 16; - err = settings_save_one(NV_MESH_SEQ, (const u8_t *)&seq, sizeof(seq)); + err = settings_save_one(NV_MESH_SEQ, (const u8_t *)&seq, sizeof(seq)); - if (err) { - BT_ERR("Failed to stor Seq value"); - } else { - BT_DBG("Stored Seq value"); - } + if (err) { + BT_ERR("Failed to stor Seq value"); + } else { + BT_DBG("Stored Seq value"); + } } void bt_mesh_store_seq(void) { - if (CONFIG_BT_MESH_SEQ_STORE_RATE && - (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)) { - return; - } + if (CONFIG_BT_MESH_SEQ_STORE_RATE && + (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)) { + return; + } - schedule_store(BT_MESH_SEQ_PENDING); + schedule_store(BT_MESH_SEQ_PENDING); } @@ -1397,278 +1397,278 @@ void bt_mesh_store_seq(void) #if defined(CONFIG_BT_SETTINGS) static void store_rpl(struct bt_mesh_rpl *entry) { - bt_settings_set_bin(NV_MESH_RPL, (const u8_t *)bt_mesh.rpl, sizeof(bt_mesh.rpl)); + bt_settings_set_bin(NV_MESH_RPL, (const u8_t *)bt_mesh.rpl, sizeof(bt_mesh.rpl)); } #endif static void clear_rpl(void) { #if defined(CONFIG_BT_SETTINGS) - int err; + int err; - err = ef_del_env(NV_MESH_RPL); + err = ef_del_env(NV_MESH_RPL); - if (err) { - BT_ERR("Failed to clear RPL err(%d)", err); - } else { - BT_DBG("Cleared RPL"); - } + if (err) { + BT_ERR("Failed to clear RPL err(%d)", err); + } else { + BT_DBG("Cleared RPL"); + } #endif - (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); + (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); } #else static void store_rpl(struct bt_mesh_rpl *entry) { - struct rpl_val rpl; - char path[18]; - int err; + struct rpl_val rpl; + char path[18]; + int err; - BT_DBG("src 0x%04x seq 0x%06x old_iv %u", entry->src, entry->seq, - entry->old_iv); + BT_DBG("src 0x%04x seq 0x%06x old_iv %u", entry->src, entry->seq, + entry->old_iv); - rpl.seq = entry->seq; - rpl.old_iv = entry->old_iv; + rpl.seq = entry->seq; + rpl.old_iv = entry->old_iv; - snprintk(path, sizeof(path), "bt/mesh/RPL/%x", entry->src); + snprintk(path, sizeof(path), "bt/mesh/RPL/%x", entry->src); - err = settings_save_one(path, &rpl, sizeof(rpl)); + err = settings_save_one(path, &rpl, sizeof(rpl)); - if (err) { - BT_ERR("Failed to store RPL %s value", log_strdup(path)); - } else { - BT_DBG("Stored RPL %s value", log_strdup(path)); - } + if (err) { + BT_ERR("Failed to store RPL %s value", log_strdup(path)); + } else { + BT_DBG("Stored RPL %s value", log_strdup(path)); + } } static void clear_rpl(void) { - int i, err; + int i, err; - BT_DBG(""); + BT_DBG(""); - for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { - struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; - char path[18]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { + struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; + char path[18]; - if (!rpl->src) { - continue; - } + if (!rpl->src) { + continue; + } - snprintk(path, sizeof(path), "bt/mesh/RPL/%x", rpl->src); + snprintk(path, sizeof(path), "bt/mesh/RPL/%x", rpl->src); - err = settings_delete(path); + err = settings_delete(path); - if (err) { - BT_ERR("Failed to clear RPL"); - } else { - BT_DBG("Cleared RPL"); - } + if (err) { + BT_ERR("Failed to clear RPL"); + } else { + BT_DBG("Cleared RPL"); + } - (void)memset(rpl, 0, sizeof(*rpl)); - } + (void)memset(rpl, 0, sizeof(*rpl)); + } } #endif static void store_pending_rpl(void) { - BT_DBG(""); + BT_DBG(""); #ifdef CONFIG_BT_SETTINGS - for (int i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { - struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; + for (int i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { + struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; - if (rpl->store) { - rpl->store = false; - store_rpl(rpl); - } - } + if (rpl->store) { + rpl->store = false; + store_rpl(rpl); + } + } #endif } static void store_pending_hb_pub(void) { - struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get(); - struct hb_pub_val val; - int err; + struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get(); + struct hb_pub_val val; + int err; - if (!pub) { - return; - } + if (!pub) { + return; + } - if (pub->dst == BT_MESH_ADDR_UNASSIGNED) { - err = settings_delete(NV_MESH_HBPUB); - } else { - val.indefinite = (pub->count == 0xffff); - val.dst = pub->dst; - val.period = pub->period; - val.ttl = pub->ttl; - val.feat = pub->feat; - val.net_idx = pub->net_idx; - - err = settings_save_one(NV_MESH_HBPUB, (const u8_t *)&val, sizeof(val)); - } + if (pub->dst == BT_MESH_ADDR_UNASSIGNED) { + err = settings_delete(NV_MESH_HBPUB); + } else { + val.indefinite = (pub->count == 0xffff); + val.dst = pub->dst; + val.period = pub->period; + val.ttl = pub->ttl; + val.feat = pub->feat; + val.net_idx = pub->net_idx; - if (err) { - BT_ERR("Failed to store Heartbeat Publication"); - } else { - BT_DBG("Stored Heartbeat Publication"); - } + err = settings_save_one(NV_MESH_HBPUB, (const u8_t *)&val, sizeof(val)); + } + + if (err) { + BT_ERR("Failed to store Heartbeat Publication"); + } else { + BT_DBG("Stored Heartbeat Publication"); + } } static void store_pending_cfg(void) { - struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); - struct cfg_val val; - int err; + struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); + struct cfg_val val; + int err; - if (!cfg) { - return; - } + if (!cfg) { + return; + } - val.net_transmit = cfg->net_transmit; - val.relay = cfg->relay; - val.relay_retransmit = cfg->relay_retransmit; - val.beacon = cfg->beacon; - val.gatt_proxy = cfg->gatt_proxy; - val.frnd = cfg->frnd; - val.default_ttl = cfg->default_ttl; + val.net_transmit = cfg->net_transmit; + val.relay = cfg->relay; + val.relay_retransmit = cfg->relay_retransmit; + val.beacon = cfg->beacon; + val.gatt_proxy = cfg->gatt_proxy; + val.frnd = cfg->frnd; + val.default_ttl = cfg->default_ttl; - err = settings_save_one(NV_MESH_CFG, (const u8_t *)&val, sizeof(val)); + err = settings_save_one(NV_MESH_CFG, (const u8_t *)&val, sizeof(val)); - if (err) { - BT_ERR("Failed to store configuration value"); - } else { - BT_DBG("Stored configuration value"); + if (err) { + BT_ERR("Failed to store configuration value"); + } else { + BT_DBG("Stored configuration value"); #if !defined(BFLB_BLE) - BT_HEXDUMP_DBG(&val, sizeof(val), "raw value"); + BT_HEXDUMP_DBG(&val, sizeof(val), "raw value"); #endif - } + } } static void clear_cfg(void) { - int err; + int err; - err = settings_delete(NV_MESH_CFG); + err = settings_delete(NV_MESH_CFG); - if (err) { - BT_ERR("Failed to clear configuration err(%d)", err); - } else { - BT_DBG("Cleared configuration"); - } + if (err) { + BT_ERR("Failed to clear configuration err(%d)", err); + } else { + BT_DBG("Cleared configuration"); + } } static void clear_app_key(u16_t app_idx) { - char path[20]; - int err; + char path[20]; + int err; #if defined(BFLB_BLE) bool del = true; #endif - snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", app_idx); - err = settings_delete(path); - if (err) { - BT_ERR("Failed to clear AppKeyIndex 0x%03x", app_idx); - } else { - BT_DBG("Cleared AppKeyIndex 0x%03x", app_idx); - } + snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", app_idx); + err = settings_delete(path); + if (err) { + BT_ERR("Failed to clear AppKeyIndex 0x%03x", app_idx); + } else { + BT_DBG("Cleared AppKeyIndex 0x%03x", app_idx); + } #if defined(BFLB_BLE) for(int i = 0; i < CONFIG_BT_MESH_APP_KEY_COUNT; i++){ if(mesh_appkey_idx[i] == app_idx){ mesh_appkey_idx[i] = BT_MESH_KEY_UNUSED; }else if(mesh_appkey_idx[i] != BT_MESH_KEY_UNUSED){ - del = false; + del = false; } } if(del){ err = settings_delete("bt/mesh/AppKeyIndex"); if (err) - BT_ERR("Failed to delte AppKeyIndex after clear app key"); + BT_ERR("Failed to delte AppKeyIndex after clear app key"); }else{ err = settings_save_one("bt/mesh/AppKeyIndex", (const u8_t *)mesh_netkey_idx, sizeof(mesh_netkey_idx)); if (err) - BT_ERR("Failed to store AppKeyIndex after clear app key"); + BT_ERR("Failed to store AppKeyIndex after clear app key"); } #endif } static void clear_net_key(u16_t net_idx) { - char path[20]; - int err; + char path[20]; + int err; #if defined(BFLB_BLE) bool del = true; #endif - BT_DBG("NetKeyIndex 0x%03x", net_idx); - + BT_DBG("NetKeyIndex 0x%03x", net_idx); + snprintk(path, sizeof(path), "bt/mesh/NetKey/%x", net_idx); - err = settings_delete(path); + err = settings_delete(path); - if (err) { - BT_ERR("Failed to clear NetKeyIndex 0x%03x", net_idx); - } else { - BT_DBG("Cleared NetKeyIndex 0x%03x", net_idx); - } + if (err) { + BT_ERR("Failed to clear NetKeyIndex 0x%03x", net_idx); + } else { + BT_DBG("Cleared NetKeyIndex 0x%03x", net_idx); + } #if defined(BFLB_BLE) for(int i = 0; i < CONFIG_BT_MESH_SUBNET_COUNT; i++){ if(mesh_netkey_idx[i] == net_idx){ mesh_netkey_idx[i] = BT_MESH_KEY_UNUSED; }else if(mesh_netkey_idx[i] != BT_MESH_KEY_UNUSED){ - del = false; + del = false; } } if(del){ err = settings_delete("bt/mesh/NetKeyIndex"); if (err) - BT_ERR("Failed to delte NetKeyIndex after clear net key"); + BT_ERR("Failed to delte NetKeyIndex after clear net key"); }else{ err = settings_save_one("bt/mesh/NetKeyIndex", (const u8_t *)mesh_netkey_idx, sizeof(mesh_netkey_idx)); if (err) - BT_ERR("Failed to store NetKeyIndex after clear net key"); + BT_ERR("Failed to store NetKeyIndex after clear net key"); } #endif } static void store_net_key(struct bt_mesh_subnet *sub) { - struct net_key_val key; - char path[20]; - int err; + struct net_key_val key; + char path[20]; + int err; #if defined(BFLB_BLE) u8_t empty_entry = 0xff; #endif - BT_DBG("NetKeyIndex 0x%03x NetKey %s", sub->net_idx, - bt_hex(sub->keys[0].net, 16)); + BT_DBG("NetKeyIndex 0x%03x NetKey %s", sub->net_idx, + bt_hex(sub->keys[0].net, 16)); - memcpy(&key.val[0], sub->keys[0].net, 16); - memcpy(&key.val[1], sub->keys[1].net, 16); - key.kr_flag = sub->kr_flag; - key.kr_phase = sub->kr_phase; + memcpy(&key.val[0], sub->keys[0].net, 16); + memcpy(&key.val[1], sub->keys[1].net, 16); + key.kr_flag = sub->kr_flag; + key.kr_phase = sub->kr_phase; - snprintk(path, sizeof(path), "bt/mesh/NetKey/%x", sub->net_idx); + snprintk(path, sizeof(path), "bt/mesh/NetKey/%x", sub->net_idx); err = settings_save_one(path, (const u8_t *)&key, sizeof(key)); - if (err) { - BT_ERR("Failed to store NetKey value"); - } else { - BT_DBG("Stored NetKey value"); - } + if (err) { + BT_ERR("Failed to store NetKey value"); + } else { + BT_DBG("Stored NetKey value"); + } #if defined(BFLB_BLE) for(int i = 0; i < CONFIG_BT_MESH_SUBNET_COUNT; i++){ if(mesh_netkey_idx[i] == sub->net_idx) return; else if(empty_entry == 0xff && mesh_netkey_idx[i] == BT_MESH_KEY_UNUSED) - empty_entry= i; + empty_entry= i; } - + if(empty_entry != 0xff){ mesh_netkey_idx[empty_entry] = sub->net_idx; err = settings_save_one("bt/mesh/NetKeyIndex", (const u8_t *)mesh_netkey_idx, sizeof(mesh_netkey_idx)); @@ -1683,33 +1683,33 @@ static void store_net_key(struct bt_mesh_subnet *sub) static void store_app_key(struct bt_mesh_app_key *app) { - struct app_key_val key; - char path[20]; - int err; + struct app_key_val key; + char path[20]; + int err; #if defined(BFLB_BLE) u8_t empty_entry = 0xff; #endif - key.net_idx = app->net_idx; - key.updated = app->updated; - memcpy(key.val[0], app->keys[0].val, 16); - memcpy(key.val[1], app->keys[1].val, 16); + key.net_idx = app->net_idx; + key.updated = app->updated; + memcpy(key.val[0], app->keys[0].val, 16); + memcpy(key.val[1], app->keys[1].val, 16); - snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", app->app_idx); + snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", app->app_idx); - err = settings_save_one(path, (const u8_t *)&key, sizeof(key)); - if (err) { - BT_ERR("Failed to store AppKey %s value", path); - } else { - BT_DBG("Stored AppKey %s value", path); - } + err = settings_save_one(path, (const u8_t *)&key, sizeof(key)); + if (err) { + BT_ERR("Failed to store AppKey %s value", path); + } else { + BT_DBG("Stored AppKey %s value", path); + } #if defined(BFLB_BLE) for(int i = 0; i < CONFIG_BT_MESH_APP_KEY_COUNT; i++){ if(mesh_appkey_idx[i] == app->app_idx) return; else if(empty_entry == 0xff && mesh_appkey_idx[i] == BT_MESH_KEY_UNUSED) - empty_entry= i; + empty_entry= i; } if(empty_entry != 0xff){ @@ -1726,465 +1726,465 @@ static void store_app_key(struct bt_mesh_app_key *app) static void store_pending_keys(void) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(key_updates); i++) { - struct key_update *update = &key_updates[i]; + for (i = 0; i < ARRAY_SIZE(key_updates); i++) { + struct key_update *update = &key_updates[i]; - if (!update->valid) { - continue; - } + if (!update->valid) { + continue; + } - if (update->clear) { - if (update->app_key) { - clear_app_key(update->key_idx); - } else { - clear_net_key(update->key_idx); - } - } else { - if (update->app_key) { - struct bt_mesh_app_key *key; + if (update->clear) { + if (update->app_key) { + clear_app_key(update->key_idx); + } else { + clear_net_key(update->key_idx); + } + } else { + if (update->app_key) { + struct bt_mesh_app_key *key; - key = bt_mesh_app_key_find(update->key_idx); - if (key) { - store_app_key(key); - } else { - BT_WARN("AppKeyIndex 0x%03x not found", - update->key_idx); - } + key = bt_mesh_app_key_find(update->key_idx); + if (key) { + store_app_key(key); + } else { + BT_WARN("AppKeyIndex 0x%03x not found", + update->key_idx); + } - } else { - struct bt_mesh_subnet *sub; + } else { + struct bt_mesh_subnet *sub; - sub = bt_mesh_subnet_get(update->key_idx); - if (sub) { - store_net_key(sub); - } else { - BT_WARN("NetKeyIndex 0x%03x not found", - update->key_idx); - } - } - } + sub = bt_mesh_subnet_get(update->key_idx); + if (sub) { + store_net_key(sub); + } else { + BT_WARN("NetKeyIndex 0x%03x not found", + update->key_idx); + } + } + } - update->valid = 0U; - } + update->valid = 0U; + } } static void encode_mod_path(struct bt_mesh_model *mod, bool vnd, - const char *key, char *path, size_t path_len) + const char *key, char *path, size_t path_len) { - u16_t mod_key = (((u16_t)mod->elem_idx << 8) | mod->mod_idx); + u16_t mod_key = (((u16_t)mod->elem_idx << 8) | mod->mod_idx); - if (vnd) { - snprintk(path, path_len, "bt/mesh/v/%x/%s", mod_key, key); - } else { - snprintk(path, path_len, "bt/mesh/s/%x/%s", mod_key, key); - } + if (vnd) { + snprintk(path, path_len, "bt/mesh/v/%x/%s", mod_key, key); + } else { + snprintk(path, path_len, "bt/mesh/s/%x/%s", mod_key, key); + } } static void store_pending_mod_bind(struct bt_mesh_model *mod, bool vnd) { - u16_t keys[CONFIG_BT_MESH_MODEL_KEY_COUNT]; - char path[20]; - int i, count, err = 0; + u16_t keys[CONFIG_BT_MESH_MODEL_KEY_COUNT]; + char path[20]; + int i, count, err = 0; #if defined(BFLB_BLE) memset(keys, 0, sizeof(keys)); #endif - - for (i = 0, count = 0; i < ARRAY_SIZE(mod->keys); i++) { - if (mod->keys[i] != BT_MESH_KEY_UNUSED) { - keys[count++] = mod->keys[i]; - BT_DBG("model key 0x%04x", mod->keys[i]); - } - } - encode_mod_path(mod, vnd, "bind", path, sizeof(path)); + for (i = 0, count = 0; i < ARRAY_SIZE(mod->keys); i++) { + if (mod->keys[i] != BT_MESH_KEY_UNUSED) { + keys[count++] = mod->keys[i]; + BT_DBG("model key 0x%04x", mod->keys[i]); + } + } - if (count) { + encode_mod_path(mod, vnd, "bind", path, sizeof(path)); + + if (count) { #if defined(BFLB_BLE) - err = bt_settings_set_bin((const char *)path, (const u8_t *)keys, sizeof(keys)); + err = bt_settings_set_bin((const char *)path, (const u8_t *)keys, sizeof(keys)); #else - err = settings_save_one(path, keys, count * sizeof(keys[0])); + err = settings_save_one(path, keys, count * sizeof(keys[0])); #endif - } else { - #if defined(BFLB_BLE) - #if defined(CONFIG_BT_SETTINGS) + } else { + #if defined(BFLB_BLE) + #if defined(CONFIG_BT_SETTINGS) err = ef_del_env((const char *)path); #endif #else - err = settings_delete(path); + err = settings_delete(path); #endif - } + } - if (err) { + if (err) { #if defined(BFLB_BLE) BT_ERR("Failed to store mod bind"); #else - BT_ERR("Failed to store %s value", log_strdup(path)); + BT_ERR("Failed to store %s value", log_strdup(path)); #endif - } else { - #if defined(BFLB_BLE) + } else { + #if defined(BFLB_BLE) BT_DBG("Stored mod bind"); #else - BT_DBG("Stored %s value", log_strdup(path)); + BT_DBG("Stored %s value", log_strdup(path)); #endif - } + } } static void store_pending_mod_sub(struct bt_mesh_model *mod, bool vnd) { - u16_t groups[CONFIG_BT_MESH_MODEL_GROUP_COUNT]; - char path[20]; - int i, count, err = 0; + u16_t groups[CONFIG_BT_MESH_MODEL_GROUP_COUNT]; + char path[20]; + int i, count, err = 0; #if defined(BFLB_BLE) memset(groups, 0, sizeof(groups)); #endif - - for (i = 0, count = 0; i < ARRAY_SIZE(mod->groups); i++) { - if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { - groups[count++] = mod->groups[i]; - } - } - encode_mod_path(mod, vnd, "sub", path, sizeof(path)); + for (i = 0, count = 0; i < ARRAY_SIZE(mod->groups); i++) { + if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) { + groups[count++] = mod->groups[i]; + } + } - if (count) { + encode_mod_path(mod, vnd, "sub", path, sizeof(path)); + + if (count) { #if defined(BFLB_BLE) - err = bt_settings_set_bin((const char *)path, (const u8_t *)groups, sizeof(groups)); + err = bt_settings_set_bin((const char *)path, (const u8_t *)groups, sizeof(groups)); #else - err = settings_save_one(path, groups, - count * sizeof(groups[0])); + err = settings_save_one(path, groups, + count * sizeof(groups[0])); #endif - } else { - #if defined(BFLB_BLE) - #if defined(CONFIG_BT_SETTINGS) + } else { + #if defined(BFLB_BLE) + #if defined(CONFIG_BT_SETTINGS) err = ef_del_env((const char *)path); #endif #else - err = settings_delete(path); + err = settings_delete(path); #endif - } + } - if (err) { + if (err) { #if defined(BFLB_BLE) BT_ERR("Failed to store mod sub"); #else - BT_ERR("Failed to store %s value", log_strdup(path)); + BT_ERR("Failed to store %s value", log_strdup(path)); #endif - } else { - #if defined(BFLB_BLE) + } else { + #if defined(BFLB_BLE) BT_DBG("Stored mod sub"); #else - BT_DBG("Stored %s value", log_strdup(path)); + BT_DBG("Stored %s value", log_strdup(path)); #endif - } + } } static void store_pending_mod_pub(struct bt_mesh_model *mod, bool vnd) { - struct mod_pub_val pub; - char path[20]; - int err = 0; - - encode_mod_path(mod, vnd, "pub", path, sizeof(path)); + struct mod_pub_val pub; + char path[20]; + int err = 0; - if (!mod->pub || mod->pub->addr == BT_MESH_ADDR_UNASSIGNED) { + encode_mod_path(mod, vnd, "pub", path, sizeof(path)); + + if (!mod->pub || mod->pub->addr == BT_MESH_ADDR_UNASSIGNED) { #if defined(BFLB_BLE) #if defined(CONFIG_BT_SETTINGS) err = ef_del_env((const char *)path); #endif #else - err = settings_delete(path); + err = settings_delete(path); #endif - } else { - pub.addr = mod->pub->addr; - pub.key = mod->pub->key; - pub.ttl = mod->pub->ttl; - pub.retransmit = mod->pub->retransmit; - pub.period = mod->pub->period; - pub.period_div = mod->pub->period_div; - pub.cred = mod->pub->cred; + } else { + pub.addr = mod->pub->addr; + pub.key = mod->pub->key; + pub.ttl = mod->pub->ttl; + pub.retransmit = mod->pub->retransmit; + pub.period = mod->pub->period; + pub.period_div = mod->pub->period_div; + pub.cred = mod->pub->cred; #if defined(BFLB_BLE) err = bt_settings_set_bin((const char *)path, (const u8_t *)&pub, sizeof(pub)); #else - err = settings_save_one(path, &pub, sizeof(pub)); + err = settings_save_one(path, &pub, sizeof(pub)); #endif - } + } - if (err) { + if (err) { #if defined(BFLB_BLE) BT_ERR("Failed to store mod sub"); #else - BT_ERR("Failed to store %s value", log_strdup(path)); + BT_ERR("Failed to store %s value", log_strdup(path)); #endif - } else { - #if defined(BFLB_BLE) + } else { + #if defined(BFLB_BLE) BT_DBG("Stored %s value"); #else - BT_DBG("Stored %s value", log_strdup(path)); + BT_DBG("Stored %s value", log_strdup(path)); #endif - } + } } static void store_pending_mod(struct bt_mesh_model *mod, - struct bt_mesh_elem *elem, bool vnd, - bool primary, void *user_data) + struct bt_mesh_elem *elem, bool vnd, + bool primary, void *user_data) { - if (!mod->flags) { - return; - } + if (!mod->flags) { + return; + } - if (mod->flags & BT_MESH_MOD_BIND_PENDING) { - mod->flags &= ~BT_MESH_MOD_BIND_PENDING; - store_pending_mod_bind(mod, vnd); - } + if (mod->flags & BT_MESH_MOD_BIND_PENDING) { + mod->flags &= ~BT_MESH_MOD_BIND_PENDING; + store_pending_mod_bind(mod, vnd); + } - if (mod->flags & BT_MESH_MOD_SUB_PENDING) { - mod->flags &= ~BT_MESH_MOD_SUB_PENDING; - store_pending_mod_sub(mod, vnd); - } + if (mod->flags & BT_MESH_MOD_SUB_PENDING) { + mod->flags &= ~BT_MESH_MOD_SUB_PENDING; + store_pending_mod_sub(mod, vnd); + } - if (mod->flags & BT_MESH_MOD_PUB_PENDING) { - mod->flags &= ~BT_MESH_MOD_PUB_PENDING; - store_pending_mod_pub(mod, vnd); - } + if (mod->flags & BT_MESH_MOD_PUB_PENDING) { + mod->flags &= ~BT_MESH_MOD_PUB_PENDING; + store_pending_mod_pub(mod, vnd); + } } static void store_pending(struct k_work *work) { - BT_DBG(""); + BT_DBG(""); - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_RPL_PENDING)) { - if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { - store_pending_rpl(); - } else { - clear_rpl(); - } - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_RPL_PENDING)) { + if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { + store_pending_rpl(); + } else { + clear_rpl(); + } + } - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_KEYS_PENDING)) { - store_pending_keys(); - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_KEYS_PENDING)) { + store_pending_keys(); + } - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_NET_PENDING)) { - if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { - store_pending_net(); - } else { - clear_net(); - } - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_NET_PENDING)) { + if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { + store_pending_net(); + } else { + clear_net(); + } + } - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_IV_PENDING)) { - if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { - store_pending_iv(); - } else { - clear_iv(); - } - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_IV_PENDING)) { + if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { + store_pending_iv(); + } else { + clear_iv(); + } + } - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_SEQ_PENDING)) { - store_pending_seq(); - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_SEQ_PENDING)) { + store_pending_seq(); + } - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_HB_PUB_PENDING)) { - store_pending_hb_pub(); - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_HB_PUB_PENDING)) { + store_pending_hb_pub(); + } - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_CFG_PENDING)) { - if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { - store_pending_cfg(); - } else { - clear_cfg(); - } - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_CFG_PENDING)) { + if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) { + store_pending_cfg(); + } else { + clear_cfg(); + } + } - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_MOD_PENDING)) { - bt_mesh_model_foreach(store_pending_mod, NULL); - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_MOD_PENDING)) { + bt_mesh_model_foreach(store_pending_mod, NULL); + } } void bt_mesh_store_rpl(struct bt_mesh_rpl *entry) { #ifdef CONFIG_BT_SETTINGS - entry->store = true; + entry->store = true; #endif - schedule_store(BT_MESH_RPL_PENDING); + schedule_store(BT_MESH_RPL_PENDING); } static struct key_update *key_update_find(bool app_key, u16_t key_idx, - struct key_update **free_slot) + struct key_update **free_slot) { - struct key_update *match; - int i; + struct key_update *match; + int i; - match = NULL; - *free_slot = NULL; + match = NULL; + *free_slot = NULL; - for (i = 0; i < ARRAY_SIZE(key_updates); i++) { - struct key_update *update = &key_updates[i]; + for (i = 0; i < ARRAY_SIZE(key_updates); i++) { + struct key_update *update = &key_updates[i]; - if (!update->valid) { - *free_slot = update; - continue; - } + if (!update->valid) { + *free_slot = update; + continue; + } - if (update->app_key != app_key) { - continue; - } + if (update->app_key != app_key) { + continue; + } - if (update->key_idx == key_idx) { - match = update; - } - } + if (update->key_idx == key_idx) { + match = update; + } + } - return match; + return match; } void bt_mesh_store_subnet(struct bt_mesh_subnet *sub) { - struct key_update *update, *free_slot; + struct key_update *update, *free_slot; - BT_DBG("NetKeyIndex 0x%03x", sub->net_idx); + BT_DBG("NetKeyIndex 0x%03x", sub->net_idx); - update = key_update_find(false, sub->net_idx, &free_slot); - if (update) { - update->clear = 0U; - schedule_store(BT_MESH_KEYS_PENDING); - return; - } + update = key_update_find(false, sub->net_idx, &free_slot); + if (update) { + update->clear = 0U; + schedule_store(BT_MESH_KEYS_PENDING); + return; + } - if (!free_slot) { - store_net_key(sub); - return; - } + if (!free_slot) { + store_net_key(sub); + return; + } - free_slot->valid = 1U; - free_slot->key_idx = sub->net_idx; - free_slot->app_key = 0U; - free_slot->clear = 0U; + free_slot->valid = 1U; + free_slot->key_idx = sub->net_idx; + free_slot->app_key = 0U; + free_slot->clear = 0U; - schedule_store(BT_MESH_KEYS_PENDING); + schedule_store(BT_MESH_KEYS_PENDING); } void bt_mesh_store_app_key(struct bt_mesh_app_key *key) { - struct key_update *update, *free_slot; + struct key_update *update, *free_slot; - BT_DBG("AppKeyIndex 0x%03x", key->app_idx); + BT_DBG("AppKeyIndex 0x%03x", key->app_idx); - update = key_update_find(true, key->app_idx, &free_slot); - if (update) { - update->clear = 0U; - schedule_store(BT_MESH_KEYS_PENDING); - return; - } + update = key_update_find(true, key->app_idx, &free_slot); + if (update) { + update->clear = 0U; + schedule_store(BT_MESH_KEYS_PENDING); + return; + } - if (!free_slot) { - store_app_key(key); - return; - } + if (!free_slot) { + store_app_key(key); + return; + } - free_slot->valid = 1U; - free_slot->key_idx = key->app_idx; - free_slot->app_key = 1U; - free_slot->clear = 0U; + free_slot->valid = 1U; + free_slot->key_idx = key->app_idx; + free_slot->app_key = 1U; + free_slot->clear = 0U; - schedule_store(BT_MESH_KEYS_PENDING); + schedule_store(BT_MESH_KEYS_PENDING); } void bt_mesh_store_hb_pub(void) { - schedule_store(BT_MESH_HB_PUB_PENDING); + schedule_store(BT_MESH_HB_PUB_PENDING); } void bt_mesh_store_cfg(void) { - schedule_store(BT_MESH_CFG_PENDING); + schedule_store(BT_MESH_CFG_PENDING); } void bt_mesh_clear_net(void) { - schedule_store(BT_MESH_NET_PENDING); - schedule_store(BT_MESH_IV_PENDING); - schedule_store(BT_MESH_CFG_PENDING); + schedule_store(BT_MESH_NET_PENDING); + schedule_store(BT_MESH_IV_PENDING); + schedule_store(BT_MESH_CFG_PENDING); } void bt_mesh_clear_subnet(struct bt_mesh_subnet *sub) { - struct key_update *update, *free_slot; + struct key_update *update, *free_slot; - BT_DBG("NetKeyIndex 0x%03x", sub->net_idx); + BT_DBG("NetKeyIndex 0x%03x", sub->net_idx); - update = key_update_find(false, sub->net_idx, &free_slot); - if (update) { - update->clear = 1U; - schedule_store(BT_MESH_KEYS_PENDING); - return; - } + update = key_update_find(false, sub->net_idx, &free_slot); + if (update) { + update->clear = 1U; + schedule_store(BT_MESH_KEYS_PENDING); + return; + } - if (!free_slot) { - clear_net_key(sub->net_idx); - return; - } + if (!free_slot) { + clear_net_key(sub->net_idx); + return; + } - free_slot->valid = 1U; - free_slot->key_idx = sub->net_idx; - free_slot->app_key = 0U; - free_slot->clear = 1U; + free_slot->valid = 1U; + free_slot->key_idx = sub->net_idx; + free_slot->app_key = 0U; + free_slot->clear = 1U; - schedule_store(BT_MESH_KEYS_PENDING); + schedule_store(BT_MESH_KEYS_PENDING); } void bt_mesh_clear_app_key(struct bt_mesh_app_key *key) { - struct key_update *update, *free_slot; + struct key_update *update, *free_slot; - BT_DBG("AppKeyIndex 0x%03x", key->app_idx); + BT_DBG("AppKeyIndex 0x%03x", key->app_idx); - update = key_update_find(true, key->app_idx, &free_slot); - if (update) { - update->clear = 1U; - schedule_store(BT_MESH_KEYS_PENDING); - return; - } + update = key_update_find(true, key->app_idx, &free_slot); + if (update) { + update->clear = 1U; + schedule_store(BT_MESH_KEYS_PENDING); + return; + } - if (!free_slot) { - clear_app_key(key->app_idx); - return; - } + if (!free_slot) { + clear_app_key(key->app_idx); + return; + } - free_slot->valid = 1U; - free_slot->key_idx = key->app_idx; - free_slot->app_key = 1U; - free_slot->clear = 1U; + free_slot->valid = 1U; + free_slot->key_idx = key->app_idx; + free_slot->app_key = 1U; + free_slot->clear = 1U; - schedule_store(BT_MESH_KEYS_PENDING); + schedule_store(BT_MESH_KEYS_PENDING); } void bt_mesh_clear_rpl(void) { - schedule_store(BT_MESH_RPL_PENDING); + schedule_store(BT_MESH_RPL_PENDING); } void bt_mesh_store_mod_bind(struct bt_mesh_model *mod) { - mod->flags |= BT_MESH_MOD_BIND_PENDING; - schedule_store(BT_MESH_MOD_PENDING); + mod->flags |= BT_MESH_MOD_BIND_PENDING; + schedule_store(BT_MESH_MOD_PENDING); } void bt_mesh_store_mod_sub(struct bt_mesh_model *mod) { - mod->flags |= BT_MESH_MOD_SUB_PENDING; - schedule_store(BT_MESH_MOD_PENDING); + mod->flags |= BT_MESH_MOD_SUB_PENDING; + schedule_store(BT_MESH_MOD_PENDING); } void bt_mesh_store_mod_pub(struct bt_mesh_model *mod) { - mod->flags |= BT_MESH_MOD_PUB_PENDING; - schedule_store(BT_MESH_MOD_PENDING); + mod->flags |= BT_MESH_MOD_PUB_PENDING; + schedule_store(BT_MESH_MOD_PENDING); } void bt_mesh_settings_init(void) @@ -2197,6 +2197,6 @@ void bt_mesh_settings_init(void) for(i = 0; i < ARRAY_SIZE(mesh_appkey_idx); i++){ mesh_appkey_idx[i] = BT_MESH_KEY_UNUSED; } - - k_delayed_work_init(&pending_store, store_pending); + + k_delayed_work_init(&pending_store, store_pending); } diff --git a/components/network/ble/blemesh/src/test.c b/components/network/ble/blemesh/src/test.c index 7839114e..6c0d39af 100644 --- a/components/network/ble/blemesh/src/test.c +++ b/components/network/ble/blemesh/src/test.c @@ -19,5 +19,5 @@ int bt_mesh_test(void) { - return 0; + return 0; } diff --git a/components/network/ble/blemesh/src/test.h b/components/network/ble/blemesh/src/test.h index 0c8db71f..fe1fd103 100644 --- a/components/network/ble/blemesh/src/test.h +++ b/components/network/ble/blemesh/src/test.h @@ -13,7 +13,7 @@ int bt_mesh_test(void); #else static inline int bt_mesh_test(void) { - return 0; + return 0; } #endif diff --git a/components/network/ble/blemesh/src/transport.c b/components/network/ble/blemesh/src/transport.c index b2b327fa..671056a4 100644 --- a/components/network/ble/blemesh/src/transport.c +++ b/components/network/ble/blemesh/src/transport.c @@ -84,42 +84,42 @@ BUILD_ASSERT(CONFIG_BT_MESH_ADV_BUF_COUNT >= (CONFIG_BT_MESH_TX_SEG_MAX + 3)); #define BUF_TIMEOUT K_NO_WAIT static struct seg_tx { - struct bt_mesh_subnet *sub; - struct net_buf *seg[CONFIG_BT_MESH_TX_SEG_MAX]; - u64_t seq_auth; - u16_t dst; - u8_t seg_n:5, /* Last segment index */ - new_key:1; /* New/old key */ - u8_t nack_count; /* Number of unacked segs */ - u8_t ttl; - const struct bt_mesh_send_cb *cb; - void *cb_data; - struct k_delayed_work retransmit; /* Retransmit timer */ + struct bt_mesh_subnet *sub; + struct net_buf *seg[CONFIG_BT_MESH_TX_SEG_MAX]; + u64_t seq_auth; + u16_t dst; + u8_t seg_n:5, /* Last segment index */ + new_key:1; /* New/old key */ + u8_t nack_count; /* Number of unacked segs */ + u8_t ttl; + const struct bt_mesh_send_cb *cb; + void *cb_data; + struct k_delayed_work retransmit; /* Retransmit timer */ } seg_tx[CONFIG_BT_MESH_TX_SEG_MSG_COUNT]; static struct seg_rx { - struct bt_mesh_subnet *sub; - u64_t seq_auth; - u8_t seg_n:5, - ctl:1, - in_use:1, - obo:1; - u8_t hdr; - u8_t ttl; - u16_t src; - u16_t dst; - u32_t block; - u32_t last; - struct k_delayed_work ack; - struct net_buf_simple buf; + struct bt_mesh_subnet *sub; + u64_t seq_auth; + u8_t seg_n:5, + ctl:1, + in_use:1, + obo:1; + u8_t hdr; + u8_t ttl; + u16_t src; + u16_t dst; + u32_t block; + u32_t last; + struct k_delayed_work ack; + struct net_buf_simple buf; } seg_rx[CONFIG_BT_MESH_RX_SEG_MSG_COUNT] = { - [0 ... (CONFIG_BT_MESH_RX_SEG_MSG_COUNT - 1)] = { - .buf.size = CONFIG_BT_MESH_RX_SDU_MAX, - }, + [0 ... (CONFIG_BT_MESH_RX_SEG_MSG_COUNT - 1)] = { + .buf.size = CONFIG_BT_MESH_RX_SDU_MAX, + }, }; static u8_t /*__noinit*/ seg_rx_buf_data[(CONFIG_BT_MESH_RX_SEG_MSG_COUNT * - CONFIG_BT_MESH_RX_SDU_MAX)]; + CONFIG_BT_MESH_RX_SDU_MAX)]; static u16_t hb_sub_dst = BT_MESH_ADDR_UNASSIGNED; @@ -144,461 +144,461 @@ s32_t bt_mesh_get_seg_retrans_timeout(u8_t ttl) void bt_mesh_set_hb_sub_dst(u16_t addr) { - hb_sub_dst = addr; + hb_sub_dst = addr; } static int send_unseg(struct bt_mesh_net_tx *tx, struct net_buf_simple *sdu, - const struct bt_mesh_send_cb *cb, void *cb_data) + const struct bt_mesh_send_cb *cb, void *cb_data) { - struct net_buf *buf; + struct net_buf *buf; - BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x sdu_len %u", - tx->src, tx->ctx->addr, tx->ctx->app_idx, sdu->len); + BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x sdu_len %u", + tx->src, tx->ctx->addr, tx->ctx->app_idx, sdu->len); - buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT); - if (!buf) { - BT_ERR("Out of network buffers"); - return -ENOBUFS; - } + buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT); + if (!buf) { + BT_ERR("Out of network buffers"); + return -ENOBUFS; + } - net_buf_reserve(buf, BT_MESH_NET_HDR_LEN); + net_buf_reserve(buf, BT_MESH_NET_HDR_LEN); - if (tx->ctx->app_idx == BT_MESH_KEY_DEV) { - net_buf_add_u8(buf, UNSEG_HDR(0, 0)); - } else { - net_buf_add_u8(buf, UNSEG_HDR(1, tx->aid)); - } + if (tx->ctx->app_idx == BT_MESH_KEY_DEV) { + net_buf_add_u8(buf, UNSEG_HDR(0, 0)); + } else { + net_buf_add_u8(buf, UNSEG_HDR(1, tx->aid)); + } - net_buf_add_mem(buf, sdu->data, sdu->len); + net_buf_add_mem(buf, sdu->data, sdu->len); - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - if (!bt_mesh_friend_queue_has_space(tx->sub->net_idx, - tx->src, tx->ctx->addr, - NULL, 1)) { - if (BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { - BT_ERR("Not enough space in Friend Queue"); - net_buf_unref(buf); - return -ENOBUFS; - } else { - BT_WARN("No space in Friend Queue"); - goto send; - } - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + if (!bt_mesh_friend_queue_has_space(tx->sub->net_idx, + tx->src, tx->ctx->addr, + NULL, 1)) { + if (BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { + BT_ERR("Not enough space in Friend Queue"); + net_buf_unref(buf); + return -ENOBUFS; + } else { + BT_WARN("No space in Friend Queue"); + goto send; + } + } - if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, - NULL, 1, &buf->b) && - BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { - /* PDUs for a specific Friend should only go - * out through the Friend Queue. - */ - net_buf_unref(buf); - send_cb_finalize(cb, cb_data); - return 0; - } - } + if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, + NULL, 1, &buf->b) && + BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { + /* PDUs for a specific Friend should only go + * out through the Friend Queue. + */ + net_buf_unref(buf); + send_cb_finalize(cb, cb_data); + return 0; + } + } send: - return bt_mesh_net_send(tx, buf, cb, cb_data); + return bt_mesh_net_send(tx, buf, cb, cb_data); } bool bt_mesh_tx_in_progress(void) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { - if (seg_tx[i].nack_count) { - return true; - } - } + for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { + if (seg_tx[i].nack_count) { + return true; + } + } - return false; + return false; } static void seg_tx_reset(struct seg_tx *tx) { - int i; + int i; - k_delayed_work_cancel(&tx->retransmit); + k_delayed_work_cancel(&tx->retransmit); - tx->cb = NULL; - tx->cb_data = NULL; - tx->seq_auth = 0U; - tx->sub = NULL; - tx->dst = BT_MESH_ADDR_UNASSIGNED; + tx->cb = NULL; + tx->cb_data = NULL; + tx->seq_auth = 0U; + tx->sub = NULL; + tx->dst = BT_MESH_ADDR_UNASSIGNED; - if (!tx->nack_count) { - return; - } + if (!tx->nack_count) { + return; + } - for (i = 0; i <= tx->seg_n; i++) { - if (!tx->seg[i]) { - continue; - } + for (i = 0; i <= tx->seg_n; i++) { + if (!tx->seg[i]) { + continue; + } - net_buf_unref(tx->seg[i]); - tx->seg[i] = NULL; - } + net_buf_unref(tx->seg[i]); + tx->seg[i] = NULL; + } - tx->nack_count = 0U; + tx->nack_count = 0U; - if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_IVU_PENDING)) { - BT_DBG("Proceeding with pending IV Update"); - /* bt_mesh_net_iv_update() will re-enable the flag if this - * wasn't the only transfer. - */ - if (bt_mesh_net_iv_update(bt_mesh.iv_index, false)) { - bt_mesh_net_sec_update(NULL); - } - } + if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_IVU_PENDING)) { + BT_DBG("Proceeding with pending IV Update"); + /* bt_mesh_net_iv_update() will re-enable the flag if this + * wasn't the only transfer. + */ + if (bt_mesh_net_iv_update(bt_mesh.iv_index, false)) { + bt_mesh_net_sec_update(NULL); + } + } } static inline void seg_tx_complete(struct seg_tx *tx, int err) { - if (tx->cb && tx->cb->end) { - tx->cb->end(err, tx->cb_data); - } + if (tx->cb && tx->cb->end) { + tx->cb->end(err, tx->cb_data); + } - seg_tx_reset(tx); + seg_tx_reset(tx); } static void seg_first_send_start(u16_t duration, int err, void *user_data) { - struct seg_tx *tx = user_data; + struct seg_tx *tx = user_data; - if (tx->cb && tx->cb->start) { - tx->cb->start(duration, err, tx->cb_data); - } + if (tx->cb && tx->cb->start) { + tx->cb->start(duration, err, tx->cb_data); + } } static void seg_send_start(u16_t duration, int err, void *user_data) { - struct seg_tx *tx = user_data; + struct seg_tx *tx = user_data; - /* If there's an error in transmitting the 'sent' callback will never - * be called. Make sure that we kick the retransmit timer also in this - * case since otherwise we risk the transmission of becoming stale. - */ - if (err) { - k_delayed_work_submit(&tx->retransmit, - SEG_RETRANSMIT_TIMEOUT(tx)); - } + /* If there's an error in transmitting the 'sent' callback will never + * be called. Make sure that we kick the retransmit timer also in this + * case since otherwise we risk the transmission of becoming stale. + */ + if (err) { + k_delayed_work_submit(&tx->retransmit, + SEG_RETRANSMIT_TIMEOUT(tx)); + } } static void seg_sent(int err, void *user_data) { - struct seg_tx *tx = user_data; + struct seg_tx *tx = user_data; - k_delayed_work_submit(&tx->retransmit, - SEG_RETRANSMIT_TIMEOUT(tx)); + k_delayed_work_submit(&tx->retransmit, + SEG_RETRANSMIT_TIMEOUT(tx)); } static const struct bt_mesh_send_cb first_sent_cb = { - .start = seg_first_send_start, - .end = seg_sent, + .start = seg_first_send_start, + .end = seg_sent, }; static const struct bt_mesh_send_cb seg_sent_cb = { - .start = seg_send_start, - .end = seg_sent, + .start = seg_send_start, + .end = seg_sent, }; static void seg_tx_send_unacked(struct seg_tx *tx) { - int i, err; + int i, err; - for (i = 0; i <= tx->seg_n; i++) { - struct net_buf *seg = tx->seg[i]; + for (i = 0; i <= tx->seg_n; i++) { + struct net_buf *seg = tx->seg[i]; - if (!seg) { - continue; - } + if (!seg) { + continue; + } - if (BT_MESH_ADV(seg)->busy) { - BT_DBG("Skipping segment that's still advertising"); - continue; - } + if (BT_MESH_ADV(seg)->busy) { + BT_DBG("Skipping segment that's still advertising"); + continue; + } - if (!(BT_MESH_ADV(seg)->seg.attempts--)) { - BT_ERR("Ran out of retransmit attempts"); - seg_tx_complete(tx, -ETIMEDOUT); - return; - } + if (!(BT_MESH_ADV(seg)->seg.attempts--)) { + BT_ERR("Ran out of retransmit attempts"); + seg_tx_complete(tx, -ETIMEDOUT); + return; + } #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Resending segment %u/%u (SeqZero = 0x%04X)", i, tx->seg_n, (u16_t)(tx->seq_auth & 0x1FFF)); + BT_PTS("[PTS] Resending segment %u/%u (SeqZero = 0x%04X)", i, tx->seg_n, (u16_t)(tx->seq_auth & 0x1FFF)); #endif - BT_DBG("resending %u/%u", i, tx->seg_n); + BT_DBG("resending %u/%u", i, tx->seg_n); - err = bt_mesh_net_resend(tx->sub, seg, tx->new_key, - &seg_sent_cb, tx); - if (err) { - BT_ERR("Sending segment failed"); - seg_tx_complete(tx, -EIO); - return; - } - } + err = bt_mesh_net_resend(tx->sub, seg, tx->new_key, + &seg_sent_cb, tx); + if (err) { + BT_ERR("Sending segment failed"); + seg_tx_complete(tx, -EIO); + return; + } + } } static void seg_retransmit(struct k_work *work) { - struct seg_tx *tx = CONTAINER_OF(work, struct seg_tx, retransmit); + struct seg_tx *tx = CONTAINER_OF(work, struct seg_tx, retransmit); - seg_tx_send_unacked(tx); + seg_tx_send_unacked(tx); } static int send_seg(struct bt_mesh_net_tx *net_tx, struct net_buf_simple *sdu, - const struct bt_mesh_send_cb *cb, void *cb_data) + const struct bt_mesh_send_cb *cb, void *cb_data) { - u8_t seg_hdr, seg_o; - u16_t seq_zero; - struct seg_tx *tx; - int i; + u8_t seg_hdr, seg_o; + u16_t seq_zero; + struct seg_tx *tx; + int i; - BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x aszmic %u sdu_len %u", - net_tx->src, net_tx->ctx->addr, net_tx->ctx->app_idx, - net_tx->aszmic, sdu->len); + BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x aszmic %u sdu_len %u", + net_tx->src, net_tx->ctx->addr, net_tx->ctx->app_idx, + net_tx->aszmic, sdu->len); - if (sdu->len < 1) { - BT_ERR("Zero-length SDU not allowed"); - return -EINVAL; - } + if (sdu->len < 1) { + BT_ERR("Zero-length SDU not allowed"); + return -EINVAL; + } - if (sdu->len > BT_MESH_TX_SDU_MAX) { - BT_ERR("Not enough segment buffers for length %u", sdu->len); - return -EMSGSIZE; - } + if (sdu->len > BT_MESH_TX_SDU_MAX) { + BT_ERR("Not enough segment buffers for length %u", sdu->len); + return -EMSGSIZE; + } - for (tx = NULL, i = 0; i < ARRAY_SIZE(seg_tx); i++) { - if (!seg_tx[i].nack_count) { - tx = &seg_tx[i]; - break; - } - } + for (tx = NULL, i = 0; i < ARRAY_SIZE(seg_tx); i++) { + if (!seg_tx[i].nack_count) { + tx = &seg_tx[i]; + break; + } + } - if (!tx) { - BT_ERR("No multi-segment message contexts available"); - return -EBUSY; - } + if (!tx) { + BT_ERR("No multi-segment message contexts available"); + return -EBUSY; + } - if (net_tx->ctx->app_idx == BT_MESH_KEY_DEV) { - seg_hdr = SEG_HDR(0, 0); - } else { - seg_hdr = SEG_HDR(1, net_tx->aid); - } + if (net_tx->ctx->app_idx == BT_MESH_KEY_DEV) { + seg_hdr = SEG_HDR(0, 0); + } else { + seg_hdr = SEG_HDR(1, net_tx->aid); + } - seg_o = 0U; - tx->dst = net_tx->ctx->addr; - tx->seg_n = (sdu->len - 1) / 12U; - tx->nack_count = tx->seg_n + 1; - tx->seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_TX, bt_mesh.seq); - tx->sub = net_tx->sub; - tx->new_key = net_tx->sub->kr_flag; - tx->cb = cb; - tx->cb_data = cb_data; + seg_o = 0U; + tx->dst = net_tx->ctx->addr; + tx->seg_n = (sdu->len - 1) / 12U; + tx->nack_count = tx->seg_n + 1; + tx->seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_TX, bt_mesh.seq); + tx->sub = net_tx->sub; + tx->new_key = net_tx->sub->kr_flag; + tx->cb = cb; + tx->cb_data = cb_data; - if (net_tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) { - tx->ttl = bt_mesh_default_ttl_get(); - } else { - tx->ttl = net_tx->ctx->send_ttl; - } + if (net_tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) { + tx->ttl = bt_mesh_default_ttl_get(); + } else { + tx->ttl = net_tx->ctx->send_ttl; + } - seq_zero = tx->seq_auth & 0x1fff; + seq_zero = tx->seq_auth & 0x1fff; - BT_DBG("SeqZero 0x%04x", seq_zero); + BT_DBG("SeqZero 0x%04x", seq_zero); - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && - !bt_mesh_friend_queue_has_space(tx->sub->net_idx, net_tx->src, - tx->dst, &tx->seq_auth, - tx->seg_n + 1) && - BT_MESH_ADDR_IS_UNICAST(tx->dst)) { - BT_ERR("Not enough space in Friend Queue for %u segments", - tx->seg_n + 1); - seg_tx_reset(tx); - return -ENOBUFS; - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && + !bt_mesh_friend_queue_has_space(tx->sub->net_idx, net_tx->src, + tx->dst, &tx->seq_auth, + tx->seg_n + 1) && + BT_MESH_ADDR_IS_UNICAST(tx->dst)) { + BT_ERR("Not enough space in Friend Queue for %u segments", + tx->seg_n + 1); + seg_tx_reset(tx); + return -ENOBUFS; + } - for (seg_o = 0U; sdu->len; seg_o++) { - struct net_buf *seg; - u16_t len; - int err; + for (seg_o = 0U; sdu->len; seg_o++) { + struct net_buf *seg; + u16_t len; + int err; - seg = bt_mesh_adv_create(BT_MESH_ADV_DATA, net_tx->xmit, - BUF_TIMEOUT); - if (!seg) { - BT_ERR("Out of segment buffers"); - seg_tx_reset(tx); - return -ENOBUFS; - } + seg = bt_mesh_adv_create(BT_MESH_ADV_DATA, net_tx->xmit, + BUF_TIMEOUT); + if (!seg) { + BT_ERR("Out of segment buffers"); + seg_tx_reset(tx); + return -ENOBUFS; + } - BT_MESH_ADV(seg)->seg.attempts = SEG_RETRANSMIT_ATTEMPTS; + BT_MESH_ADV(seg)->seg.attempts = SEG_RETRANSMIT_ATTEMPTS; - net_buf_reserve(seg, BT_MESH_NET_HDR_LEN); + net_buf_reserve(seg, BT_MESH_NET_HDR_LEN); - net_buf_add_u8(seg, seg_hdr); - net_buf_add_u8(seg, (net_tx->aszmic << 7) | seq_zero >> 6); - net_buf_add_u8(seg, (((seq_zero & 0x3f) << 2) | - (seg_o >> 3))); - net_buf_add_u8(seg, ((seg_o & 0x07) << 5) | tx->seg_n); + net_buf_add_u8(seg, seg_hdr); + net_buf_add_u8(seg, (net_tx->aszmic << 7) | seq_zero >> 6); + net_buf_add_u8(seg, (((seq_zero & 0x3f) << 2) | + (seg_o >> 3))); + net_buf_add_u8(seg, ((seg_o & 0x07) << 5) | tx->seg_n); - len = MIN(sdu->len, 12); - net_buf_add_mem(seg, sdu->data, len); - net_buf_simple_pull(sdu, len); + len = MIN(sdu->len, 12); + net_buf_add_mem(seg, sdu->data, len); + net_buf_simple_pull(sdu, len); - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - enum bt_mesh_friend_pdu_type type; + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + enum bt_mesh_friend_pdu_type type; - if (seg_o == tx->seg_n) { - type = BT_MESH_FRIEND_PDU_COMPLETE; - } else { - type = BT_MESH_FRIEND_PDU_PARTIAL; - } + if (seg_o == tx->seg_n) { + type = BT_MESH_FRIEND_PDU_COMPLETE; + } else { + type = BT_MESH_FRIEND_PDU_PARTIAL; + } - if (bt_mesh_friend_enqueue_tx(net_tx, type, - &tx->seq_auth, - tx->seg_n + 1, - &seg->b) && - BT_MESH_ADDR_IS_UNICAST(net_tx->ctx->addr)) { - /* PDUs for a specific Friend should only go - * out through the Friend Queue. - */ - net_buf_unref(seg); - continue; - } - } + if (bt_mesh_friend_enqueue_tx(net_tx, type, + &tx->seq_auth, + tx->seg_n + 1, + &seg->b) && + BT_MESH_ADDR_IS_UNICAST(net_tx->ctx->addr)) { + /* PDUs for a specific Friend should only go + * out through the Friend Queue. + */ + net_buf_unref(seg); + continue; + } + } - tx->seg[seg_o] = net_buf_ref(seg); + tx->seg[seg_o] = net_buf_ref(seg); #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Sending segment %u/%u (SeqZero = 0x%04X)", seg_o, tx->seg_n, seq_zero); + BT_PTS("[PTS] Sending segment %u/%u (SeqZero = 0x%04X)", seg_o, tx->seg_n, seq_zero); #endif - BT_DBG("Sending %u/%u", seg_o, tx->seg_n); + BT_DBG("Sending %u/%u", seg_o, tx->seg_n); - err = bt_mesh_net_send(net_tx, seg, - seg_o ? &seg_sent_cb : &first_sent_cb, - tx); - if (err) { - BT_ERR("Sending segment failed"); - seg_tx_reset(tx); - return err; - } - } + err = bt_mesh_net_send(net_tx, seg, + seg_o ? &seg_sent_cb : &first_sent_cb, + tx); + if (err) { + BT_ERR("Sending segment failed"); + seg_tx_reset(tx); + return err; + } + } - /* This can happen if segments only went into the Friend Queue */ - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !tx->seg[0]) { - seg_tx_reset(tx); + /* This can happen if segments only went into the Friend Queue */ + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !tx->seg[0]) { + seg_tx_reset(tx); - /* If there was a callback notify sending immediately since - * there's no other way to track this (at least currently) - * with the Friend Queue. - */ - send_cb_finalize(cb, cb_data); - } + /* If there was a callback notify sending immediately since + * there's no other way to track this (at least currently) + * with the Friend Queue. + */ + send_cb_finalize(cb, cb_data); + } - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && - bt_mesh_lpn_established()) { - bt_mesh_lpn_poll(); - } + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && + bt_mesh_lpn_established()) { + bt_mesh_lpn_poll(); + } - return 0; + return 0; } struct bt_mesh_app_key *bt_mesh_app_key_find(u16_t app_idx) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { - struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { + struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - if (key->net_idx != BT_MESH_KEY_UNUSED && - key->app_idx == app_idx) { - return key; - } - } + if (key->net_idx != BT_MESH_KEY_UNUSED && + key->app_idx == app_idx) { + return key; + } + } - return NULL; + return NULL; } int bt_mesh_trans_send(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg, - const struct bt_mesh_send_cb *cb, void *cb_data) + const struct bt_mesh_send_cb *cb, void *cb_data) { - const u8_t *key; - u8_t *ad; - int err; + const u8_t *key; + u8_t *ad; + int err; - if (net_buf_simple_tailroom(msg) < 4) { - BT_ERR("Insufficient tailroom for Transport MIC"); - return -EINVAL; - } + if (net_buf_simple_tailroom(msg) < 4) { + BT_ERR("Insufficient tailroom for Transport MIC"); + return -EINVAL; + } - if (msg->len > 11) { - tx->ctx->send_rel = true; - } + if (msg->len > 11) { + tx->ctx->send_rel = true; + } - BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->sub->net_idx, - tx->ctx->app_idx, tx->ctx->addr); - BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len)); + BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->sub->net_idx, + tx->ctx->app_idx, tx->ctx->addr); + BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len)); - if (tx->ctx->app_idx == BT_MESH_KEY_DEV) { - key = bt_mesh.dev_key; - tx->aid = 0U; - } else { - struct bt_mesh_app_key *app_key; + if (tx->ctx->app_idx == BT_MESH_KEY_DEV) { + key = bt_mesh.dev_key; + tx->aid = 0U; + } else { + struct bt_mesh_app_key *app_key; - app_key = bt_mesh_app_key_find(tx->ctx->app_idx); - if (!app_key) { - return -EINVAL; - } + app_key = bt_mesh_app_key_find(tx->ctx->app_idx); + if (!app_key) { + return -EINVAL; + } - if (tx->sub->kr_phase == BT_MESH_KR_PHASE_2 && - app_key->updated) { - key = app_key->keys[1].val; - tx->aid = app_key->keys[1].id; - } else { - key = app_key->keys[0].val; - tx->aid = app_key->keys[0].id; - } - } + if (tx->sub->kr_phase == BT_MESH_KR_PHASE_2 && + app_key->updated) { + key = app_key->keys[1].val; + tx->aid = app_key->keys[1].id; + } else { + key = app_key->keys[0].val; + tx->aid = app_key->keys[0].id; + } + } - if (!tx->ctx->send_rel || net_buf_simple_tailroom(msg) < 8) { - tx->aszmic = 0U; - } else { - tx->aszmic = 1U; - } + if (!tx->ctx->send_rel || net_buf_simple_tailroom(msg) < 8) { + tx->aszmic = 0U; + } else { + tx->aszmic = 1U; + } - if (BT_MESH_ADDR_IS_VIRTUAL(tx->ctx->addr)) { - ad = bt_mesh_label_uuid_get(tx->ctx->addr); - } else { - ad = NULL; - } + if (BT_MESH_ADDR_IS_VIRTUAL(tx->ctx->addr)) { + ad = bt_mesh_label_uuid_get(tx->ctx->addr); + } else { + ad = NULL; + } - err = bt_mesh_app_encrypt(key, tx->ctx->app_idx == BT_MESH_KEY_DEV, - tx->aszmic, msg, ad, tx->src, - tx->ctx->addr, bt_mesh.seq, - BT_MESH_NET_IVI_TX); - if (err) { - return err; - } + err = bt_mesh_app_encrypt(key, tx->ctx->app_idx == BT_MESH_KEY_DEV, + tx->aszmic, msg, ad, tx->src, + tx->ctx->addr, bt_mesh.seq, + BT_MESH_NET_IVI_TX); + if (err) { + return err; + } - if (tx->ctx->send_rel) { - err = send_seg(tx, msg, cb, cb_data); - } else { - err = send_unseg(tx, msg, cb, cb_data); - } + if (tx->ctx->send_rel) { + err = send_seg(tx, msg, cb, cb_data); + } else { + err = send_unseg(tx, msg, cb, cb_data); + } - return err; + return err; } static void update_rpl(struct bt_mesh_rpl *rpl, struct bt_mesh_net_rx *rx) { - rpl->src = rx->ctx.addr; - rpl->seq = rx->seq; - rpl->old_iv = rx->old_iv; + rpl->src = rx->ctx.addr; + rpl->seq = rx->seq; + rpl->old_iv = rx->old_iv; - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_store_rpl(rpl); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_store_rpl(rpl); + } } /* Check the Replay Protection List for a replay attempt. If non-NULL match @@ -608,1084 +608,1084 @@ static void update_rpl(struct bt_mesh_rpl *rpl, struct bt_mesh_net_rx *rx) */ static bool is_replay(struct bt_mesh_net_rx *rx, struct bt_mesh_rpl **match) { - int i; + int i; - /* Don't bother checking messages from ourselves */ - if (rx->net_if == BT_MESH_NET_IF_LOCAL) { - return false; - } + /* Don't bother checking messages from ourselves */ + if (rx->net_if == BT_MESH_NET_IF_LOCAL) { + return false; + } - /* The RPL is used only for the local node */ - if (!rx->local_match) { - return false; - } + /* The RPL is used only for the local node */ + if (!rx->local_match) { + return false; + } - for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { - struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; + for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) { + struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i]; - /* Empty slot */ - if (!rpl->src) { - if (match) { - *match = rpl; - } else { - update_rpl(rpl, rx); - } + /* Empty slot */ + if (!rpl->src) { + if (match) { + *match = rpl; + } else { + update_rpl(rpl, rx); + } - return false; - } + return false; + } - /* Existing slot for given address */ - if (rpl->src == rx->ctx.addr) { - if (rx->old_iv && !rpl->old_iv) { - return true; - } + /* Existing slot for given address */ + if (rpl->src == rx->ctx.addr) { + if (rx->old_iv && !rpl->old_iv) { + return true; + } - if ((!rx->old_iv && rpl->old_iv) || - rpl->seq < rx->seq) { - if (match) { - *match = rpl; - } else { - update_rpl(rpl, rx); - } + if ((!rx->old_iv && rpl->old_iv) || + rpl->seq < rx->seq) { + if (match) { + *match = rpl; + } else { + update_rpl(rpl, rx); + } - return false; - } else { - return true; - } - } - } + return false; + } else { + return true; + } + } + } - BT_ERR("RPL is full!"); - return true; + BT_ERR("RPL is full!"); + return true; } static int sdu_recv(struct bt_mesh_net_rx *rx, u32_t seq, u8_t hdr, - u8_t aszmic, struct net_buf_simple *buf) + u8_t aszmic, struct net_buf_simple *buf) { - NET_BUF_SIMPLE_DEFINE(sdu, CONFIG_BT_MESH_RX_SDU_MAX - 4); - u8_t *ad; - u16_t i; - int err; + NET_BUF_SIMPLE_DEFINE(sdu, CONFIG_BT_MESH_RX_SDU_MAX - 4); + u8_t *ad; + u16_t i; + int err; - BT_DBG("ASZMIC %u AKF %u AID 0x%02x", aszmic, AKF(&hdr), AID(&hdr)); - BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); + BT_DBG("ASZMIC %u AKF %u AID 0x%02x", aszmic, AKF(&hdr), AID(&hdr)); + BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len)); - if (buf->len < 1 + APP_MIC_LEN(aszmic)) { - BT_ERR("Too short SDU + MIC"); - return -EINVAL; - } + if (buf->len < 1 + APP_MIC_LEN(aszmic)) { + BT_ERR("Too short SDU + MIC"); + return -EINVAL; + } - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !rx->local_match) { - BT_DBG("Ignoring PDU for LPN 0x%04x of this Friend", - rx->ctx.recv_dst); - return 0; - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !rx->local_match) { + BT_DBG("Ignoring PDU for LPN 0x%04x of this Friend", + rx->ctx.recv_dst); + return 0; + } - if (BT_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) { - ad = bt_mesh_label_uuid_get(rx->ctx.recv_dst); - } else { - ad = NULL; - } + if (BT_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) { + ad = bt_mesh_label_uuid_get(rx->ctx.recv_dst); + } else { + ad = NULL; + } - /* Adjust the length to not contain the MIC at the end */ - buf->len -= APP_MIC_LEN(aszmic); + /* Adjust the length to not contain the MIC at the end */ + buf->len -= APP_MIC_LEN(aszmic); - if (!AKF(&hdr)) { - err = bt_mesh_app_decrypt(bt_mesh.dev_key, true, aszmic, buf, - &sdu, ad, rx->ctx.addr, - rx->ctx.recv_dst, seq, - BT_MESH_NET_IVI_RX(rx)); - if (err) { + if (!AKF(&hdr)) { + err = bt_mesh_app_decrypt(bt_mesh.dev_key, true, aszmic, buf, + &sdu, ad, rx->ctx.addr, + rx->ctx.recv_dst, seq, + BT_MESH_NET_IVI_RX(rx)); + if (err) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Unknown device key"); + BT_PTS("[PTS] Unknown device key"); #endif - BT_ERR("Unable to decrypt with DevKey"); - return -EINVAL; - } + BT_ERR("Unable to decrypt with DevKey"); + return -EINVAL; + } - rx->ctx.app_idx = BT_MESH_KEY_DEV; - bt_mesh_model_recv(rx, &sdu); - return 0; - } + rx->ctx.app_idx = BT_MESH_KEY_DEV; + bt_mesh_model_recv(rx, &sdu); + return 0; + } - for (i = 0U; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { - struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; - struct bt_mesh_app_keys *keys; + for (i = 0U; i < ARRAY_SIZE(bt_mesh.app_keys); i++) { + struct bt_mesh_app_key *key = &bt_mesh.app_keys[i]; + struct bt_mesh_app_keys *keys; - /* Check that this AppKey matches received net_idx */ - if (key->net_idx != rx->sub->net_idx) { - continue; - } + /* Check that this AppKey matches received net_idx */ + if (key->net_idx != rx->sub->net_idx) { + continue; + } - if (rx->new_key && key->updated) { - keys = &key->keys[1]; - } else { - keys = &key->keys[0]; - } + if (rx->new_key && key->updated) { + keys = &key->keys[1]; + } else { + keys = &key->keys[0]; + } - /* Check that the AppKey ID matches */ - if (AID(&hdr) != keys->id) { - continue; - } + /* Check that the AppKey ID matches */ + if (AID(&hdr) != keys->id) { + continue; + } - net_buf_simple_reset(&sdu); - err = bt_mesh_app_decrypt(keys->val, false, aszmic, buf, - &sdu, ad, rx->ctx.addr, - rx->ctx.recv_dst, seq, - BT_MESH_NET_IVI_RX(rx)); - if (err) { - BT_WARN("Unable to decrypt with AppKey 0x%03x", - key->app_idx); - continue; + net_buf_simple_reset(&sdu); + err = bt_mesh_app_decrypt(keys->val, false, aszmic, buf, + &sdu, ad, rx->ctx.addr, + rx->ctx.recv_dst, seq, + BT_MESH_NET_IVI_RX(rx)); + if (err) { + BT_WARN("Unable to decrypt with AppKey 0x%03x", + key->app_idx); + continue; - } + } - rx->ctx.app_idx = key->app_idx; + rx->ctx.app_idx = key->app_idx; - bt_mesh_model_recv(rx, &sdu); - return 0; - } + bt_mesh_model_recv(rx, &sdu); + return 0; + } #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Unknown application key"); + BT_PTS("[PTS] Unknown application key"); #endif - BT_WARN("No matching AppKey"); + BT_WARN("No matching AppKey"); - return -EINVAL; + return -EINVAL; } static struct seg_tx *seg_tx_lookup(u16_t seq_zero, u8_t obo, u16_t addr) { - struct seg_tx *tx; - int i; + struct seg_tx *tx; + int i; - for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { - tx = &seg_tx[i]; + for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { + tx = &seg_tx[i]; - if ((tx->seq_auth & 0x1fff) != seq_zero) { - continue; - } + if ((tx->seq_auth & 0x1fff) != seq_zero) { + continue; + } - if (tx->dst == addr) { - return tx; - } + if (tx->dst == addr) { + return tx; + } - /* If the expected remote address doesn't match, - * but the OBO flag is set and this is the first - * acknowledgement, assume it's a Friend that's - * responding and therefore accept the message. - */ - if (obo && tx->nack_count == tx->seg_n + 1) { - tx->dst = addr; - return tx; - } - } + /* If the expected remote address doesn't match, + * but the OBO flag is set and this is the first + * acknowledgement, assume it's a Friend that's + * responding and therefore accept the message. + */ + if (obo && tx->nack_count == tx->seg_n + 1) { + tx->dst = addr; + return tx; + } + } - return NULL; + return NULL; } #if defined(BFLB_BLE) extern unsigned int find_msb_set(uint32_t data); #endif static int trans_ack(struct bt_mesh_net_rx *rx, u8_t hdr, - struct net_buf_simple *buf, u64_t *seq_auth) + struct net_buf_simple *buf, u64_t *seq_auth) { - struct seg_tx *tx; - unsigned int bit; - u32_t ack; - u16_t seq_zero; - u8_t obo; + struct seg_tx *tx; + unsigned int bit; + u32_t ack; + u16_t seq_zero; + u8_t obo; - if (buf->len < 6) { - BT_ERR("Too short ack message"); - return -EINVAL; - } + if (buf->len < 6) { + BT_ERR("Too short ack message"); + return -EINVAL; + } - seq_zero = net_buf_simple_pull_be16(buf); - obo = seq_zero >> 15; - seq_zero = (seq_zero >> 2) & 0x1fff; + seq_zero = net_buf_simple_pull_be16(buf); + obo = seq_zero >> 15; + seq_zero = (seq_zero >> 2) & 0x1fff; - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match) { - BT_DBG("Ack for LPN 0x%04x of this Friend", rx->ctx.recv_dst); - /* Best effort - we don't have enough info for true SeqAuth */ - *seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(rx), seq_zero); - return 0; - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match) { + BT_DBG("Ack for LPN 0x%04x of this Friend", rx->ctx.recv_dst); + /* Best effort - we don't have enough info for true SeqAuth */ + *seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(rx), seq_zero); + return 0; + } - ack = net_buf_simple_pull_be32(buf); + ack = net_buf_simple_pull_be32(buf); #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] - SeqZero: 0x%04X", seq_zero); - BT_PTS("[PTS] - BlockAck: 0x%08X", ack); + BT_PTS("[PTS] - SeqZero: 0x%04X", seq_zero); + BT_PTS("[PTS] - BlockAck: 0x%08X", ack); #endif - BT_DBG("OBO %u seq_zero 0x%04x ack 0x%08x", obo, seq_zero, ack); + BT_DBG("OBO %u seq_zero 0x%04x ack 0x%08x", obo, seq_zero, ack); - tx = seg_tx_lookup(seq_zero, obo, rx->ctx.addr); - if (!tx) { - BT_WARN("No matching TX context for ack"); - return -EINVAL; - } + tx = seg_tx_lookup(seq_zero, obo, rx->ctx.addr); + if (!tx) { + BT_WARN("No matching TX context for ack"); + return -EINVAL; + } - *seq_auth = tx->seq_auth; + *seq_auth = tx->seq_auth; - if (!ack) { + if (!ack) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Transmission cancelled"); + BT_PTS("[PTS] Transmission cancelled"); #endif - BT_WARN("SDU canceled"); - seg_tx_complete(tx, -ECANCELED); - return 0; - } + BT_WARN("SDU canceled"); + seg_tx_complete(tx, -ECANCELED); + return 0; + } - if (find_msb_set(ack) - 1 > tx->seg_n) { - BT_ERR("Too large segment number in ack"); - return -EINVAL; - } + if (find_msb_set(ack) - 1 > tx->seg_n) { + BT_ERR("Too large segment number in ack"); + return -EINVAL; + } - k_delayed_work_cancel(&tx->retransmit); + k_delayed_work_cancel(&tx->retransmit); - while ((bit = find_lsb_set(ack))) { - if (tx->seg[bit - 1]) { - BT_DBG("seg %u/%u acked", bit - 1, tx->seg_n); - net_buf_unref(tx->seg[bit - 1]); - tx->seg[bit - 1] = NULL; - tx->nack_count--; - } + while ((bit = find_lsb_set(ack))) { + if (tx->seg[bit - 1]) { + BT_DBG("seg %u/%u acked", bit - 1, tx->seg_n); + net_buf_unref(tx->seg[bit - 1]); + tx->seg[bit - 1] = NULL; + tx->nack_count--; + } - ack &= ~BIT(bit - 1); - } + ack &= ~BIT(bit - 1); + } - if (tx->nack_count) { - seg_tx_send_unacked(tx); - } else { + if (tx->nack_count) { + seg_tx_send_unacked(tx); + } else { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] All segments sent and acknowledged"); + BT_PTS("[PTS] All segments sent and acknowledged"); #endif - BT_DBG("SDU TX complete"); - seg_tx_complete(tx, 0); - } + BT_DBG("SDU TX complete"); + seg_tx_complete(tx, 0); + } - return 0; + return 0; } static int trans_heartbeat(struct bt_mesh_net_rx *rx, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - u8_t init_ttl, hops; - u16_t feat; + u8_t init_ttl, hops; + u16_t feat; - if (buf->len < 3) { - BT_ERR("Too short heartbeat message"); - return -EINVAL; - } + if (buf->len < 3) { + BT_ERR("Too short heartbeat message"); + return -EINVAL; + } - if (rx->ctx.recv_dst != hb_sub_dst) { - BT_WARN("Ignoring heartbeat to non-subscribed destination"); - return 0; - } + if (rx->ctx.recv_dst != hb_sub_dst) { + BT_WARN("Ignoring heartbeat to non-subscribed destination"); + return 0; + } - init_ttl = (net_buf_simple_pull_u8(buf) & 0x7f); - feat = net_buf_simple_pull_be16(buf); + init_ttl = (net_buf_simple_pull_u8(buf) & 0x7f); + feat = net_buf_simple_pull_be16(buf); - hops = (init_ttl - rx->ctx.recv_ttl + 1); + hops = (init_ttl - rx->ctx.recv_ttl + 1); - BT_DBG("src 0x%04x TTL %u InitTTL %u (%u hop%s) feat 0x%04x", - rx->ctx.addr, rx->ctx.recv_ttl, init_ttl, hops, - (hops == 1U) ? "" : "s", feat); + BT_DBG("src 0x%04x TTL %u InitTTL %u (%u hop%s) feat 0x%04x", + rx->ctx.addr, rx->ctx.recv_ttl, init_ttl, hops, + (hops == 1U) ? "" : "s", feat); - bt_mesh_heartbeat(rx->ctx.addr, rx->ctx.recv_dst, hops, feat); + bt_mesh_heartbeat(rx->ctx.addr, rx->ctx.recv_dst, hops, feat); - return 0; + return 0; } static int ctl_recv(struct bt_mesh_net_rx *rx, u8_t hdr, - struct net_buf_simple *buf, u64_t *seq_auth) + struct net_buf_simple *buf, u64_t *seq_auth) { - u8_t ctl_op = TRANS_CTL_OP(&hdr); + u8_t ctl_op = TRANS_CTL_OP(&hdr); - BT_DBG("OpCode 0x%02x len %u", ctl_op, buf->len); + BT_DBG("OpCode 0x%02x len %u", ctl_op, buf->len); - switch (ctl_op) { - case TRANS_CTL_OP_ACK: - return trans_ack(rx, hdr, buf, seq_auth); - case TRANS_CTL_OP_HEARTBEAT: - return trans_heartbeat(rx, buf); - } + switch (ctl_op) { + case TRANS_CTL_OP_ACK: + return trans_ack(rx, hdr, buf, seq_auth); + case TRANS_CTL_OP_HEARTBEAT: + return trans_heartbeat(rx, buf); + } - /* Only acks and heartbeats may need processing without local_match */ - if (!rx->local_match) { - return 0; - } + /* Only acks and heartbeats may need processing without local_match */ + if (!rx->local_match) { + return 0; + } - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !bt_mesh_lpn_established()) { - switch (ctl_op) { - case TRANS_CTL_OP_FRIEND_POLL: - return bt_mesh_friend_poll(rx, buf); - case TRANS_CTL_OP_FRIEND_REQ: - return bt_mesh_friend_req(rx, buf); - case TRANS_CTL_OP_FRIEND_CLEAR: - return bt_mesh_friend_clear(rx, buf); - case TRANS_CTL_OP_FRIEND_CLEAR_CFM: - return bt_mesh_friend_clear_cfm(rx, buf); - case TRANS_CTL_OP_FRIEND_SUB_ADD: - return bt_mesh_friend_sub_add(rx, buf); - case TRANS_CTL_OP_FRIEND_SUB_REM: - return bt_mesh_friend_sub_rem(rx, buf); - } - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !bt_mesh_lpn_established()) { + switch (ctl_op) { + case TRANS_CTL_OP_FRIEND_POLL: + return bt_mesh_friend_poll(rx, buf); + case TRANS_CTL_OP_FRIEND_REQ: + return bt_mesh_friend_req(rx, buf); + case TRANS_CTL_OP_FRIEND_CLEAR: + return bt_mesh_friend_clear(rx, buf); + case TRANS_CTL_OP_FRIEND_CLEAR_CFM: + return bt_mesh_friend_clear_cfm(rx, buf); + case TRANS_CTL_OP_FRIEND_SUB_ADD: + return bt_mesh_friend_sub_add(rx, buf); + case TRANS_CTL_OP_FRIEND_SUB_REM: + return bt_mesh_friend_sub_rem(rx, buf); + } + } #if defined(CONFIG_BT_MESH_LOW_POWER) - if (ctl_op == TRANS_CTL_OP_FRIEND_OFFER) { - return bt_mesh_lpn_friend_offer(rx, buf); - } + if (ctl_op == TRANS_CTL_OP_FRIEND_OFFER) { + return bt_mesh_lpn_friend_offer(rx, buf); + } - if (rx->ctx.addr == bt_mesh.lpn.frnd) { - if (ctl_op == TRANS_CTL_OP_FRIEND_CLEAR_CFM) { - return bt_mesh_lpn_friend_clear_cfm(rx, buf); - } + if (rx->ctx.addr == bt_mesh.lpn.frnd) { + if (ctl_op == TRANS_CTL_OP_FRIEND_CLEAR_CFM) { + return bt_mesh_lpn_friend_clear_cfm(rx, buf); + } - if (!rx->friend_cred) { - BT_WARN("Message from friend with wrong credentials"); - return -EINVAL; - } + if (!rx->friend_cred) { + BT_WARN("Message from friend with wrong credentials"); + return -EINVAL; + } - switch (ctl_op) { - case TRANS_CTL_OP_FRIEND_UPDATE: - return bt_mesh_lpn_friend_update(rx, buf); - case TRANS_CTL_OP_FRIEND_SUB_CFM: - return bt_mesh_lpn_friend_sub_cfm(rx, buf); - } - } + switch (ctl_op) { + case TRANS_CTL_OP_FRIEND_UPDATE: + return bt_mesh_lpn_friend_update(rx, buf); + case TRANS_CTL_OP_FRIEND_SUB_CFM: + return bt_mesh_lpn_friend_sub_cfm(rx, buf); + } + } #endif /* CONFIG_BT_MESH_LOW_POWER */ - BT_WARN("Unhandled TransOpCode 0x%02x", ctl_op); + BT_WARN("Unhandled TransOpCode 0x%02x", ctl_op); - return -ENOENT; + return -ENOENT; } static int trans_unseg(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx, - u64_t *seq_auth) + u64_t *seq_auth) { - u8_t hdr; + u8_t hdr; - BT_DBG("AFK %u AID 0x%02x", AKF(buf->data), AID(buf->data)); + BT_DBG("AFK %u AID 0x%02x", AKF(buf->data), AID(buf->data)); - if (buf->len < 1) { - BT_ERR("Too small unsegmented PDU"); - return -EINVAL; - } + if (buf->len < 1) { + BT_ERR("Too small unsegmented PDU"); + return -EINVAL; + } - if (is_replay(rx, NULL)) { + if (is_replay(rx, NULL)) { #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Replayed message (SEQ = 0x%06X) ignored", rx->seq); + BT_PTS("[PTS] Replayed message (SEQ = 0x%06X) ignored", rx->seq); #endif - BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", - rx->ctx.addr, rx->ctx.recv_dst, rx->seq); - return -EINVAL; - } + BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", + rx->ctx.addr, rx->ctx.recv_dst, rx->seq); + return -EINVAL; + } - hdr = net_buf_simple_pull_u8(buf); + hdr = net_buf_simple_pull_u8(buf); - if (rx->ctl) { - return ctl_recv(rx, hdr, buf, seq_auth); - } else { - /* SDUs must match a local element or an LPN of this Friend. */ - if (!rx->local_match && !rx->friend_match) { - return 0; - } + if (rx->ctl) { + return ctl_recv(rx, hdr, buf, seq_auth); + } else { + /* SDUs must match a local element or an LPN of this Friend. */ + if (!rx->local_match && !rx->friend_match) { + return 0; + } - return sdu_recv(rx, rx->seq, hdr, 0, buf); - } + return sdu_recv(rx, rx->seq, hdr, 0, buf); + } } static inline s32_t ack_timeout(struct seg_rx *rx) { - s32_t to; - u8_t ttl; + s32_t to; + u8_t ttl; - if (rx->ttl == BT_MESH_TTL_DEFAULT) { - ttl = bt_mesh_default_ttl_get(); - } else { - ttl = rx->ttl; - } + if (rx->ttl == BT_MESH_TTL_DEFAULT) { + ttl = bt_mesh_default_ttl_get(); + } else { + ttl = rx->ttl; + } - /* The acknowledgment timer shall be set to a minimum of - * 150 + 50 * TTL milliseconds. - */ - to = K_MSEC(150 + (ttl * 50U)); + /* The acknowledgment timer shall be set to a minimum of + * 150 + 50 * TTL milliseconds. + */ + to = K_MSEC(150 + (ttl * 50U)); - /* 100 ms for every not yet received segment */ - to += K_MSEC(((rx->seg_n + 1) - popcount(rx->block)) * 100U); + /* 100 ms for every not yet received segment */ + to += K_MSEC(((rx->seg_n + 1) - popcount(rx->block)) * 100U); - /* Make sure we don't send more frequently than the duration for - * each packet (default is 300ms). - */ - return MAX(to, K_MSEC(400)); + /* Make sure we don't send more frequently than the duration for + * each packet (default is 300ms). + */ + return MAX(to, K_MSEC(400)); } int bt_mesh_ctl_send(struct bt_mesh_net_tx *tx, u8_t ctl_op, void *data, - size_t data_len, u64_t *seq_auth, - const struct bt_mesh_send_cb *cb, void *cb_data) + size_t data_len, u64_t *seq_auth, + const struct bt_mesh_send_cb *cb, void *cb_data) { - struct net_buf *buf; + struct net_buf *buf; - BT_DBG("src 0x%04x dst 0x%04x ttl 0x%02x ctl 0x%02x", tx->src, - tx->ctx->addr, tx->ctx->send_ttl, ctl_op); - BT_DBG("len %zu: %s", data_len, bt_hex(data, data_len)); + BT_DBG("src 0x%04x dst 0x%04x ttl 0x%02x ctl 0x%02x", tx->src, + tx->ctx->addr, tx->ctx->send_ttl, ctl_op); + BT_DBG("len %zu: %s", data_len, bt_hex(data, data_len)); - buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT); - if (!buf) { - BT_ERR("Out of transport buffers"); - return -ENOBUFS; - } + buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT); + if (!buf) { + BT_ERR("Out of transport buffers"); + return -ENOBUFS; + } - net_buf_reserve(buf, BT_MESH_NET_HDR_LEN); + net_buf_reserve(buf, BT_MESH_NET_HDR_LEN); - net_buf_add_u8(buf, TRANS_CTL_HDR(ctl_op, 0)); + net_buf_add_u8(buf, TRANS_CTL_HDR(ctl_op, 0)); - net_buf_add_mem(buf, data, data_len); + net_buf_add_mem(buf, data, data_len); - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, - seq_auth, 1, &buf->b) && - BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { - /* PDUs for a specific Friend should only go - * out through the Friend Queue. - */ - net_buf_unref(buf); - return 0; - } - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, + seq_auth, 1, &buf->b) && + BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) { + /* PDUs for a specific Friend should only go + * out through the Friend Queue. + */ + net_buf_unref(buf); + return 0; + } + } - return bt_mesh_net_send(tx, buf, cb, cb_data); + return bt_mesh_net_send(tx, buf, cb, cb_data); } static int send_ack(struct bt_mesh_subnet *sub, u16_t src, u16_t dst, - u8_t ttl, u64_t *seq_auth, u32_t block, u8_t obo) + u8_t ttl, u64_t *seq_auth, u32_t block, u8_t obo) { - struct bt_mesh_msg_ctx ctx = { - .net_idx = sub->net_idx, - .app_idx = BT_MESH_KEY_UNUSED, - .addr = dst, - .send_ttl = ttl, - }; - struct bt_mesh_net_tx tx = { - .sub = sub, - .ctx = &ctx, - .src = obo ? bt_mesh_primary_addr() : src, - .xmit = bt_mesh_net_transmit_get(), - }; - u16_t seq_zero = *seq_auth & 0x1fff; - u8_t buf[6]; + struct bt_mesh_msg_ctx ctx = { + .net_idx = sub->net_idx, + .app_idx = BT_MESH_KEY_UNUSED, + .addr = dst, + .send_ttl = ttl, + }; + struct bt_mesh_net_tx tx = { + .sub = sub, + .ctx = &ctx, + .src = obo ? bt_mesh_primary_addr() : src, + .xmit = bt_mesh_net_transmit_get(), + }; + u16_t seq_zero = *seq_auth & 0x1fff; + u8_t buf[6]; - BT_DBG("SeqZero 0x%04x Block 0x%08x OBO %u", seq_zero, block, obo); + BT_DBG("SeqZero 0x%04x Block 0x%08x OBO %u", seq_zero, block, obo); - if (bt_mesh_lpn_established()) { - BT_WARN("Not sending ack when LPN is enabled"); - return 0; - } + if (bt_mesh_lpn_established()) { + BT_WARN("Not sending ack when LPN is enabled"); + return 0; + } - /* This can happen if the segmented message was destined for a group - * or virtual address. - */ - if (!BT_MESH_ADDR_IS_UNICAST(src)) { - BT_WARN("Not sending ack for non-unicast address"); - return 0; - } + /* This can happen if the segmented message was destined for a group + * or virtual address. + */ + if (!BT_MESH_ADDR_IS_UNICAST(src)) { + BT_WARN("Not sending ack for non-unicast address"); + return 0; + } #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] Sending BlockAck 0x%08X (SeqZero = 0x%04X)", block, seq_zero); + BT_PTS("[PTS] Sending BlockAck 0x%08X (SeqZero = 0x%04X)", block, seq_zero); #endif - sys_put_be16(((seq_zero << 2) & 0x7ffc) | (obo << 15), buf); - sys_put_be32(block, &buf[2]); + sys_put_be16(((seq_zero << 2) & 0x7ffc) | (obo << 15), buf); + sys_put_be32(block, &buf[2]); - return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_ACK, buf, sizeof(buf), - NULL, NULL, NULL); + return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_ACK, buf, sizeof(buf), + NULL, NULL, NULL); } static void seg_rx_reset(struct seg_rx *rx, bool full_reset) { - BT_DBG("rx %p", rx); + BT_DBG("rx %p", rx); - k_delayed_work_cancel(&rx->ack); + k_delayed_work_cancel(&rx->ack); - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->obo && - rx->block != BLOCK_COMPLETE(rx->seg_n)) { - BT_WARN("Clearing incomplete buffers from Friend queue"); - bt_mesh_friend_clear_incomplete(rx->sub, rx->src, rx->dst, - &rx->seq_auth); - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->obo && + rx->block != BLOCK_COMPLETE(rx->seg_n)) { + BT_WARN("Clearing incomplete buffers from Friend queue"); + bt_mesh_friend_clear_incomplete(rx->sub, rx->src, rx->dst, + &rx->seq_auth); + } - rx->in_use = 0U; + rx->in_use = 0U; - /* We don't always reset these values since we need to be able to - * send an ack if we receive a segment after we've already received - * the full SDU. - */ - if (full_reset) { - rx->seq_auth = 0U; - rx->sub = NULL; - rx->src = BT_MESH_ADDR_UNASSIGNED; - rx->dst = BT_MESH_ADDR_UNASSIGNED; - } + /* We don't always reset these values since we need to be able to + * send an ack if we receive a segment after we've already received + * the full SDU. + */ + if (full_reset) { + rx->seq_auth = 0U; + rx->sub = NULL; + rx->src = BT_MESH_ADDR_UNASSIGNED; + rx->dst = BT_MESH_ADDR_UNASSIGNED; + } } static void seg_ack(struct k_work *work) { - struct seg_rx *rx = CONTAINER_OF(work, struct seg_rx, ack); + struct seg_rx *rx = CONTAINER_OF(work, struct seg_rx, ack); - BT_DBG("rx %p", rx); + BT_DBG("rx %p", rx); #ifndef CONFIG_BT_MESH_PTS - if (k_uptime_get_32() - rx->last > K_SECONDS(60)) { - BT_WARN("Incomplete timer expired"); + if (k_uptime_get_32() - rx->last > K_SECONDS(60)) { + BT_WARN("Incomplete timer expired"); #else - if (k_uptime_get_32() - rx->last > K_SECONDS(10)) { - BT_PTS("[PTS] Incomplete timer expired"); + if (k_uptime_get_32() - rx->last > K_SECONDS(10)) { + BT_PTS("[PTS] Incomplete timer expired"); #endif - seg_rx_reset(rx, false); + seg_rx_reset(rx, false); #if defined(CONFIG_BT_TESTING) - /*if (IS_ENABLED(CONFIG_BT_TESTING))*/ { - bt_test_mesh_trans_incomp_timer_exp(); - } + /*if (IS_ENABLED(CONFIG_BT_TESTING))*/ { + bt_test_mesh_trans_incomp_timer_exp(); + } #endif - return; - } + return; + } - send_ack(rx->sub, rx->dst, rx->src, rx->ttl, &rx->seq_auth, - rx->block, rx->obo); + send_ack(rx->sub, rx->dst, rx->src, rx->ttl, &rx->seq_auth, + rx->block, rx->obo); - k_delayed_work_submit(&rx->ack, ack_timeout(rx)); + k_delayed_work_submit(&rx->ack, ack_timeout(rx)); } static inline u8_t seg_len(bool ctl) { - if (ctl) { - return 8; - } else { - return 12; - } + if (ctl) { + return 8; + } else { + return 12; + } } static inline bool sdu_len_is_ok(bool ctl, u8_t seg_n) { - return ((seg_n * seg_len(ctl) + 1) <= CONFIG_BT_MESH_RX_SDU_MAX); + return ((seg_n * seg_len(ctl) + 1) <= CONFIG_BT_MESH_RX_SDU_MAX); } static struct seg_rx *seg_rx_find(struct bt_mesh_net_rx *net_rx, - const u64_t *seq_auth) + const u64_t *seq_auth) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { - struct seg_rx *rx = &seg_rx[i]; + for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { + struct seg_rx *rx = &seg_rx[i]; - if (rx->src != net_rx->ctx.addr || - rx->dst != net_rx->ctx.recv_dst) { - continue; - } + if (rx->src != net_rx->ctx.addr || + rx->dst != net_rx->ctx.recv_dst) { + continue; + } - /* Return newer RX context in addition to an exact match, so - * the calling function can properly discard an old SeqAuth. - */ - if (rx->seq_auth >= *seq_auth) { - return rx; - } + /* Return newer RX context in addition to an exact match, so + * the calling function can properly discard an old SeqAuth. + */ + if (rx->seq_auth >= *seq_auth) { + return rx; + } - if (rx->in_use) { - BT_WARN("Duplicate SDU from src 0x%04x", - net_rx->ctx.addr); + if (rx->in_use) { + BT_WARN("Duplicate SDU from src 0x%04x", + net_rx->ctx.addr); - /* Clear out the old context since the sender - * has apparently started sending a new SDU. - */ - seg_rx_reset(rx, true); + /* Clear out the old context since the sender + * has apparently started sending a new SDU. + */ + seg_rx_reset(rx, true); - /* Return non-match so caller can re-allocate */ - return NULL; - } - } + /* Return non-match so caller can re-allocate */ + return NULL; + } + } - return NULL; + return NULL; } static bool seg_rx_is_valid(struct seg_rx *rx, struct bt_mesh_net_rx *net_rx, - const u8_t *hdr, u8_t seg_n) + const u8_t *hdr, u8_t seg_n) { - if (rx->hdr != *hdr || rx->seg_n != seg_n) { - BT_ERR("Invalid segment for ongoing session"); - return false; - } + if (rx->hdr != *hdr || rx->seg_n != seg_n) { + BT_ERR("Invalid segment for ongoing session"); + return false; + } - if (rx->src != net_rx->ctx.addr || rx->dst != net_rx->ctx.recv_dst) { - BT_ERR("Invalid source or destination for segment"); - return false; - } + if (rx->src != net_rx->ctx.addr || rx->dst != net_rx->ctx.recv_dst) { + BT_ERR("Invalid source or destination for segment"); + return false; + } - if (rx->ctl != net_rx->ctl) { - BT_ERR("Inconsistent CTL in segment"); - return false; - } + if (rx->ctl != net_rx->ctl) { + BT_ERR("Inconsistent CTL in segment"); + return false; + } - return true; + return true; } static struct seg_rx *seg_rx_alloc(struct bt_mesh_net_rx *net_rx, - const u8_t *hdr, const u64_t *seq_auth, - u8_t seg_n) + const u8_t *hdr, const u64_t *seq_auth, + u8_t seg_n) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { - struct seg_rx *rx = &seg_rx[i]; + for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { + struct seg_rx *rx = &seg_rx[i]; - if (rx->in_use) { - continue; - } + if (rx->in_use) { + continue; + } - rx->in_use = 1U; - net_buf_simple_reset(&rx->buf); - rx->sub = net_rx->sub; - rx->ctl = net_rx->ctl; - rx->seq_auth = *seq_auth; - rx->seg_n = seg_n; - rx->hdr = *hdr; - rx->ttl = net_rx->ctx.send_ttl; - rx->src = net_rx->ctx.addr; - rx->dst = net_rx->ctx.recv_dst; - rx->block = 0U; + rx->in_use = 1U; + net_buf_simple_reset(&rx->buf); + rx->sub = net_rx->sub; + rx->ctl = net_rx->ctl; + rx->seq_auth = *seq_auth; + rx->seg_n = seg_n; + rx->hdr = *hdr; + rx->ttl = net_rx->ctx.send_ttl; + rx->src = net_rx->ctx.addr; + rx->dst = net_rx->ctx.recv_dst; + rx->block = 0U; - BT_DBG("New RX context. Block Complete 0x%08x", - BLOCK_COMPLETE(seg_n)); + BT_DBG("New RX context. Block Complete 0x%08x", + BLOCK_COMPLETE(seg_n)); - return rx; - } + return rx; + } - return NULL; + return NULL; } static int trans_seg(struct net_buf_simple *buf, struct bt_mesh_net_rx *net_rx, - enum bt_mesh_friend_pdu_type *pdu_type, u64_t *seq_auth, - u8_t *seg_count) + enum bt_mesh_friend_pdu_type *pdu_type, u64_t *seq_auth, + u8_t *seg_count) { - struct bt_mesh_rpl *rpl = NULL; - struct seg_rx *rx; - u8_t *hdr = buf->data; - u16_t seq_zero; - u8_t seg_n; - u8_t seg_o; - int err; + struct bt_mesh_rpl *rpl = NULL; + struct seg_rx *rx; + u8_t *hdr = buf->data; + u16_t seq_zero; + u8_t seg_n; + u8_t seg_o; + int err; - if (buf->len < 5) { - BT_ERR("Too short segmented message (len %u)", buf->len); - return -EINVAL; - } + if (buf->len < 5) { + BT_ERR("Too short segmented message (len %u)", buf->len); + return -EINVAL; + } - if (is_replay(net_rx, &rpl)) { - BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", - net_rx->ctx.addr, net_rx->ctx.recv_dst, net_rx->seq); - return -EINVAL; - } + if (is_replay(net_rx, &rpl)) { + BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", + net_rx->ctx.addr, net_rx->ctx.recv_dst, net_rx->seq); + return -EINVAL; + } - BT_DBG("ASZMIC %u AKF %u AID 0x%02x", ASZMIC(hdr), AKF(hdr), AID(hdr)); + BT_DBG("ASZMIC %u AKF %u AID 0x%02x", ASZMIC(hdr), AKF(hdr), AID(hdr)); - net_buf_simple_pull(buf, 1); + net_buf_simple_pull(buf, 1); - seq_zero = net_buf_simple_pull_be16(buf); - seg_o = (seq_zero & 0x03) << 3; - seq_zero = (seq_zero >> 2) & 0x1fff; - seg_n = net_buf_simple_pull_u8(buf); - seg_o |= seg_n >> 5; - seg_n &= 0x1f; + seq_zero = net_buf_simple_pull_be16(buf); + seg_o = (seq_zero & 0x03) << 3; + seq_zero = (seq_zero >> 2) & 0x1fff; + seg_n = net_buf_simple_pull_u8(buf); + seg_o |= seg_n >> 5; + seg_n &= 0x1f; #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] - SeqZero: 0x%04X", seq_zero); - BT_PTS("[PTS] - Segment: %u/%u", seg_o, seg_n); + BT_PTS("[PTS] - SeqZero: 0x%04X", seq_zero); + BT_PTS("[PTS] - Segment: %u/%u", seg_o, seg_n); #endif - BT_DBG("SeqZero 0x%04x SegO %u SegN %u", seq_zero, seg_o, seg_n); + BT_DBG("SeqZero 0x%04x SegO %u SegN %u", seq_zero, seg_o, seg_n); - if (seg_o > seg_n) { - BT_ERR("SegO greater than SegN (%u > %u)", seg_o, seg_n); - return -EINVAL; - } + if (seg_o > seg_n) { + BT_ERR("SegO greater than SegN (%u > %u)", seg_o, seg_n); + return -EINVAL; + } - /* According to Mesh 1.0 specification: - * "The SeqAuth is composed of the IV Index and the sequence number - * (SEQ) of the first segment" - * - * Therefore we need to calculate very first SEQ in order to find - * seqAuth. We can calculate as below: - * - * SEQ(0) = SEQ(n) - (delta between seqZero and SEQ(n) by looking into - * 14 least significant bits of SEQ(n)) - * - * Mentioned delta shall be >= 0, if it is not then seq_auth will - * be broken and it will be verified by the code below. - */ - *seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(net_rx), - (net_rx->seq - - ((((net_rx->seq & BIT_MASK(14)) - seq_zero)) & - BIT_MASK(13)))); + /* According to Mesh 1.0 specification: + * "The SeqAuth is composed of the IV Index and the sequence number + * (SEQ) of the first segment" + * + * Therefore we need to calculate very first SEQ in order to find + * seqAuth. We can calculate as below: + * + * SEQ(0) = SEQ(n) - (delta between seqZero and SEQ(n) by looking into + * 14 least significant bits of SEQ(n)) + * + * Mentioned delta shall be >= 0, if it is not then seq_auth will + * be broken and it will be verified by the code below. + */ + *seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(net_rx), + (net_rx->seq - + ((((net_rx->seq & BIT_MASK(14)) - seq_zero)) & + BIT_MASK(13)))); - *seg_count = seg_n + 1; + *seg_count = seg_n + 1; - /* Look for old RX sessions */ - rx = seg_rx_find(net_rx, seq_auth); - if (rx) { - /* Discard old SeqAuth packet */ - if (rx->seq_auth > *seq_auth) { - BT_WARN("Ignoring old SeqAuth"); - return -EINVAL; - } + /* Look for old RX sessions */ + rx = seg_rx_find(net_rx, seq_auth); + if (rx) { + /* Discard old SeqAuth packet */ + if (rx->seq_auth > *seq_auth) { + BT_WARN("Ignoring old SeqAuth"); + return -EINVAL; + } - if (!seg_rx_is_valid(rx, net_rx, hdr, seg_n)) { - return -EINVAL; - } + if (!seg_rx_is_valid(rx, net_rx, hdr, seg_n)) { + return -EINVAL; + } - if (rx->in_use) { - BT_DBG("Existing RX context. Block 0x%08x", rx->block); - goto found_rx; - } + if (rx->in_use) { + BT_DBG("Existing RX context. Block 0x%08x", rx->block); + goto found_rx; + } - if (rx->block == BLOCK_COMPLETE(rx->seg_n)) { - BT_WARN("Got segment for already complete SDU"); + if (rx->block == BLOCK_COMPLETE(rx->seg_n)) { + BT_WARN("Got segment for already complete SDU"); - send_ack(net_rx->sub, net_rx->ctx.recv_dst, - net_rx->ctx.addr, net_rx->ctx.send_ttl, - seq_auth, rx->block, rx->obo); + send_ack(net_rx->sub, net_rx->ctx.recv_dst, + net_rx->ctx.addr, net_rx->ctx.send_ttl, + seq_auth, rx->block, rx->obo); - if (rpl) { - update_rpl(rpl, net_rx); - } + if (rpl) { + update_rpl(rpl, net_rx); + } - return -EALREADY; - } + return -EALREADY; + } - /* We ignore instead of sending block ack 0 since the - * ack timer is always smaller than the incomplete - * timer, i.e. the sender is misbehaving. - */ - BT_WARN("Got segment for canceled SDU"); - return -EINVAL; - } + /* We ignore instead of sending block ack 0 since the + * ack timer is always smaller than the incomplete + * timer, i.e. the sender is misbehaving. + */ + BT_WARN("Got segment for canceled SDU"); + return -EINVAL; + } - /* Bail out early if we're not ready to receive such a large SDU */ - if (!sdu_len_is_ok(net_rx->ctl, seg_n)) { - BT_ERR("Too big incoming SDU length"); - send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, - net_rx->ctx.send_ttl, seq_auth, 0, - net_rx->friend_match); - return -EMSGSIZE; - } + /* Bail out early if we're not ready to receive such a large SDU */ + if (!sdu_len_is_ok(net_rx->ctl, seg_n)) { + BT_ERR("Too big incoming SDU length"); + send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, + net_rx->ctx.send_ttl, seq_auth, 0, + net_rx->friend_match); + return -EMSGSIZE; + } - /* Verify early that there will be space in the Friend Queue(s) in - * case this message is destined to an LPN of ours. - */ - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && - net_rx->friend_match && !net_rx->local_match && - !bt_mesh_friend_queue_has_space(net_rx->sub->net_idx, - net_rx->ctx.addr, - net_rx->ctx.recv_dst, seq_auth, - *seg_count)) { - BT_ERR("No space in Friend Queue for %u segments", *seg_count); - send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, - net_rx->ctx.send_ttl, seq_auth, 0, - net_rx->friend_match); - return -ENOBUFS; - } + /* Verify early that there will be space in the Friend Queue(s) in + * case this message is destined to an LPN of ours. + */ + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && + net_rx->friend_match && !net_rx->local_match && + !bt_mesh_friend_queue_has_space(net_rx->sub->net_idx, + net_rx->ctx.addr, + net_rx->ctx.recv_dst, seq_auth, + *seg_count)) { + BT_ERR("No space in Friend Queue for %u segments", *seg_count); + send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, + net_rx->ctx.send_ttl, seq_auth, 0, + net_rx->friend_match); + return -ENOBUFS; + } - /* Look for free slot for a new RX session */ - rx = seg_rx_alloc(net_rx, hdr, seq_auth, seg_n); - if (!rx) { - /* Warn but don't cancel since the existing slots willl - * eventually be freed up and we'll be able to process - * this one. - */ - BT_WARN("No free slots for new incoming segmented messages"); - return -ENOMEM; - } + /* Look for free slot for a new RX session */ + rx = seg_rx_alloc(net_rx, hdr, seq_auth, seg_n); + if (!rx) { + /* Warn but don't cancel since the existing slots willl + * eventually be freed up and we'll be able to process + * this one. + */ + BT_WARN("No free slots for new incoming segmented messages"); + return -ENOMEM; + } - rx->obo = net_rx->friend_match; + rx->obo = net_rx->friend_match; found_rx: - if (BIT(seg_o) & rx->block) { - BT_WARN("Received already received fragment"); - return -EALREADY; - } + if (BIT(seg_o) & rx->block) { + BT_WARN("Received already received fragment"); + return -EALREADY; + } - /* All segments, except the last one, must either have 8 bytes of - * payload (for 64bit Net MIC) or 12 bytes of payload (for 32bit - * Net MIC). - */ - if (seg_o == seg_n) { - /* Set the expected final buffer length */ - rx->buf.len = seg_n * seg_len(rx->ctl) + buf->len; - BT_DBG("Target len %u * %u + %u = %u", seg_n, seg_len(rx->ctl), - buf->len, rx->buf.len); + /* All segments, except the last one, must either have 8 bytes of + * payload (for 64bit Net MIC) or 12 bytes of payload (for 32bit + * Net MIC). + */ + if (seg_o == seg_n) { + /* Set the expected final buffer length */ + rx->buf.len = seg_n * seg_len(rx->ctl) + buf->len; + BT_DBG("Target len %u * %u + %u = %u", seg_n, seg_len(rx->ctl), + buf->len, rx->buf.len); - if (rx->buf.len > CONFIG_BT_MESH_RX_SDU_MAX) { - BT_ERR("Too large SDU len"); - send_ack(net_rx->sub, net_rx->ctx.recv_dst, - net_rx->ctx.addr, net_rx->ctx.send_ttl, - seq_auth, 0, rx->obo); - seg_rx_reset(rx, true); - return -EMSGSIZE; - } - } else { - if (buf->len != seg_len(rx->ctl)) { - BT_ERR("Incorrect segment size for message type"); - return -EINVAL; - } - } + if (rx->buf.len > CONFIG_BT_MESH_RX_SDU_MAX) { + BT_ERR("Too large SDU len"); + send_ack(net_rx->sub, net_rx->ctx.recv_dst, + net_rx->ctx.addr, net_rx->ctx.send_ttl, + seq_auth, 0, rx->obo); + seg_rx_reset(rx, true); + return -EMSGSIZE; + } + } else { + if (buf->len != seg_len(rx->ctl)) { + BT_ERR("Incorrect segment size for message type"); + return -EINVAL; + } + } - /* Reset the Incomplete Timer */ - rx->last = k_uptime_get_32(); + /* Reset the Incomplete Timer */ + rx->last = k_uptime_get_32(); - if (!k_delayed_work_remaining_get(&rx->ack) && - !bt_mesh_lpn_established()) { - k_delayed_work_submit(&rx->ack, ack_timeout(rx)); - } + if (!k_delayed_work_remaining_get(&rx->ack) && + !bt_mesh_lpn_established()) { + k_delayed_work_submit(&rx->ack, ack_timeout(rx)); + } - /* Location in buffer can be calculated based on seg_o & rx->ctl */ - memcpy(rx->buf.data + (seg_o * seg_len(rx->ctl)), buf->data, buf->len); + /* Location in buffer can be calculated based on seg_o & rx->ctl */ + memcpy(rx->buf.data + (seg_o * seg_len(rx->ctl)), buf->data, buf->len); - BT_DBG("Received %u/%u", seg_o, seg_n); + BT_DBG("Received %u/%u", seg_o, seg_n); - /* Mark segment as received */ - rx->block |= BIT(seg_o); + /* Mark segment as received */ + rx->block |= BIT(seg_o); - if (rx->block != BLOCK_COMPLETE(seg_n)) { - *pdu_type = BT_MESH_FRIEND_PDU_PARTIAL; - return 0; - } + if (rx->block != BLOCK_COMPLETE(seg_n)) { + *pdu_type = BT_MESH_FRIEND_PDU_PARTIAL; + return 0; + } #ifdef CONFIG_BT_MESH_PTS - BT_PTS("[PTS] All segments received"); + BT_PTS("[PTS] All segments received"); #endif - BT_DBG("Complete SDU"); + BT_DBG("Complete SDU"); - if (rpl) { - update_rpl(rpl, net_rx); - } + if (rpl) { + update_rpl(rpl, net_rx); + } - *pdu_type = BT_MESH_FRIEND_PDU_COMPLETE; + *pdu_type = BT_MESH_FRIEND_PDU_COMPLETE; - k_delayed_work_cancel(&rx->ack); - send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, - net_rx->ctx.send_ttl, seq_auth, rx->block, rx->obo); + k_delayed_work_cancel(&rx->ack); + send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, + net_rx->ctx.send_ttl, seq_auth, rx->block, rx->obo); - if (net_rx->ctl) { - err = ctl_recv(net_rx, *hdr, &rx->buf, seq_auth); - } else { - err = sdu_recv(net_rx, (rx->seq_auth & 0xffffff), *hdr, - ASZMIC(hdr), &rx->buf); - } + if (net_rx->ctl) { + err = ctl_recv(net_rx, *hdr, &rx->buf, seq_auth); + } else { + err = sdu_recv(net_rx, (rx->seq_auth & 0xffffff), *hdr, + ASZMIC(hdr), &rx->buf); + } - seg_rx_reset(rx, false); + seg_rx_reset(rx, false); - return err; + return err; } int bt_mesh_trans_recv(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx) { - u64_t seq_auth = TRANS_SEQ_AUTH_NVAL; - enum bt_mesh_friend_pdu_type pdu_type = BT_MESH_FRIEND_PDU_SINGLE; - struct net_buf_simple_state state; - u8_t seg_count = 0; - int err; + u64_t seq_auth = TRANS_SEQ_AUTH_NVAL; + enum bt_mesh_friend_pdu_type pdu_type = BT_MESH_FRIEND_PDU_SINGLE; + struct net_buf_simple_state state; + u8_t seg_count = 0; + int err; - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { - rx->friend_match = bt_mesh_friend_match(rx->sub->net_idx, - rx->ctx.recv_dst); - } else { - rx->friend_match = false; - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) { + rx->friend_match = bt_mesh_friend_match(rx->sub->net_idx, + rx->ctx.recv_dst); + } else { + rx->friend_match = false; + } - BT_DBG("src 0x%04x dst 0x%04x seq 0x%08x friend_match %u", - rx->ctx.addr, rx->ctx.recv_dst, rx->seq, rx->friend_match); + BT_DBG("src 0x%04x dst 0x%04x seq 0x%08x friend_match %u", + rx->ctx.addr, rx->ctx.recv_dst, rx->seq, rx->friend_match); - /* Remove network headers */ - net_buf_simple_pull(buf, BT_MESH_NET_HDR_LEN); + /* Remove network headers */ + net_buf_simple_pull(buf, BT_MESH_NET_HDR_LEN); - BT_DBG("Payload %s", bt_hex(buf->data, buf->len)); + BT_DBG("Payload %s", bt_hex(buf->data, buf->len)); #if defined(CONFIG_BT_TESTING) - /*if (IS_ENABLED(CONFIG_BT_TESTING))*/ { - - bt_test_mesh_net_recv(rx->ctx.recv_ttl, rx->ctl, rx->ctx.addr, - rx->ctx.recv_dst, buf->data, buf->len); - } + /*if (IS_ENABLED(CONFIG_BT_TESTING))*/ { + + bt_test_mesh_net_recv(rx->ctx.recv_ttl, rx->ctl, rx->ctx.addr, + rx->ctx.recv_dst, buf->data, buf->len); + } #endif - /* If LPN mode is enabled messages are only accepted when we've - * requested the Friend to send them. The messages must also - * be encrypted using the Friend Credentials. - */ - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && - bt_mesh_lpn_established() && rx->net_if == BT_MESH_NET_IF_ADV && - (!bt_mesh_lpn_waiting_update() || !rx->friend_cred)) { - BT_WARN("Ignoring unexpected message in Low Power mode"); - return -EAGAIN; - } + /* If LPN mode is enabled messages are only accepted when we've + * requested the Friend to send them. The messages must also + * be encrypted using the Friend Credentials. + */ + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && + bt_mesh_lpn_established() && rx->net_if == BT_MESH_NET_IF_ADV && + (!bt_mesh_lpn_waiting_update() || !rx->friend_cred)) { + BT_WARN("Ignoring unexpected message in Low Power mode"); + return -EAGAIN; + } - /* Save the app-level state so the buffer can later be placed in - * the Friend Queue. - */ - net_buf_simple_save(buf, &state); + /* Save the app-level state so the buffer can later be placed in + * the Friend Queue. + */ + net_buf_simple_save(buf, &state); - if (SEG(buf->data)) { - /* Segmented messages must match a local element or an - * LPN of this Friend. - */ - if (!rx->local_match && !rx->friend_match) { - return 0; - } + if (SEG(buf->data)) { + /* Segmented messages must match a local element or an + * LPN of this Friend. + */ + if (!rx->local_match && !rx->friend_match) { + return 0; + } - err = trans_seg(buf, rx, &pdu_type, &seq_auth, &seg_count); - } else { - seg_count = 1; - err = trans_unseg(buf, rx, &seq_auth); - } + err = trans_seg(buf, rx, &pdu_type, &seq_auth, &seg_count); + } else { + seg_count = 1; + err = trans_unseg(buf, rx, &seq_auth); + } - /* Notify LPN state machine so a Friend Poll will be sent. If the - * message was a Friend Update it's possible that a Poll was already - * queued for sending, however that's fine since then the - * bt_mesh_lpn_waiting_update() function will return false: - * we still need to go through the actual sending to the bearer and - * wait for ReceiveDelay before transitioning to WAIT_UPDATE state. - * Another situation where we want to notify the LPN state machine - * is if it's configured to use an automatic Friendship establishment - * timer, in which case we want to reset the timer at this point. - * - */ - if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && - (bt_mesh_lpn_timer() || - (bt_mesh_lpn_established() && bt_mesh_lpn_waiting_update()))) { - bt_mesh_lpn_msg_received(rx); - } + /* Notify LPN state machine so a Friend Poll will be sent. If the + * message was a Friend Update it's possible that a Poll was already + * queued for sending, however that's fine since then the + * bt_mesh_lpn_waiting_update() function will return false: + * we still need to go through the actual sending to the bearer and + * wait for ReceiveDelay before transitioning to WAIT_UPDATE state. + * Another situation where we want to notify the LPN state machine + * is if it's configured to use an automatic Friendship establishment + * timer, in which case we want to reset the timer at this point. + * + */ + if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && + (bt_mesh_lpn_timer() || + (bt_mesh_lpn_established() && bt_mesh_lpn_waiting_update()))) { + bt_mesh_lpn_msg_received(rx); + } - net_buf_simple_restore(buf, &state); + net_buf_simple_restore(buf, &state); - if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match && !err) { - if (seq_auth == TRANS_SEQ_AUTH_NVAL) { - bt_mesh_friend_enqueue_rx(rx, pdu_type, NULL, - seg_count, buf); - } else { - bt_mesh_friend_enqueue_rx(rx, pdu_type, &seq_auth, - seg_count, buf); - } - } + if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match && !err) { + if (seq_auth == TRANS_SEQ_AUTH_NVAL) { + bt_mesh_friend_enqueue_rx(rx, pdu_type, NULL, + seg_count, buf); + } else { + bt_mesh_friend_enqueue_rx(rx, pdu_type, &seq_auth, + seg_count, buf); + } + } - return err; + return err; } void bt_mesh_rx_reset(void) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { - seg_rx_reset(&seg_rx[i], true); - } + for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { + seg_rx_reset(&seg_rx[i], true); + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_mesh_clear_rpl(); - } else { - (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_mesh_clear_rpl(); + } else { + (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); + } } void bt_mesh_tx_reset(void) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { - seg_tx_reset(&seg_tx[i]); - } + for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { + seg_tx_reset(&seg_tx[i]); + } } void bt_mesh_trans_init(void) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { - k_delayed_work_init(&seg_tx[i].retransmit, seg_retransmit); - } + for (i = 0; i < ARRAY_SIZE(seg_tx); i++) { + k_delayed_work_init(&seg_tx[i].retransmit, seg_retransmit); + } - for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { - k_delayed_work_init(&seg_rx[i].ack, seg_ack); - seg_rx[i].buf.__buf = (seg_rx_buf_data + - (i * CONFIG_BT_MESH_RX_SDU_MAX)); - seg_rx[i].buf.data = seg_rx[i].buf.__buf; - } + for (i = 0; i < ARRAY_SIZE(seg_rx); i++) { + k_delayed_work_init(&seg_rx[i].ack, seg_ack); + seg_rx[i].buf.__buf = (seg_rx_buf_data + + (i * CONFIG_BT_MESH_RX_SDU_MAX)); + seg_rx[i].buf.data = seg_rx[i].buf.__buf; + } } void bt_mesh_rpl_clear(void) { - BT_DBG(""); - (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); + BT_DBG(""); + (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl)); } void bt_mesh_heartbeat_send(void) { - struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); - u16_t feat = 0U; - struct __packed { - u8_t init_ttl; - u16_t feat; - } hb; - struct bt_mesh_msg_ctx ctx = { - .net_idx = cfg->hb_pub.net_idx, - .app_idx = BT_MESH_KEY_UNUSED, - .addr = cfg->hb_pub.dst, - .send_ttl = cfg->hb_pub.ttl, - }; - struct bt_mesh_net_tx tx = { - .sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx), - .ctx = &ctx, - .src = bt_mesh_model_elem(cfg->model)->addr, - .xmit = bt_mesh_net_transmit_get(), - }; + struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get(); + u16_t feat = 0U; + struct __packed { + u8_t init_ttl; + u16_t feat; + } hb; + struct bt_mesh_msg_ctx ctx = { + .net_idx = cfg->hb_pub.net_idx, + .app_idx = BT_MESH_KEY_UNUSED, + .addr = cfg->hb_pub.dst, + .send_ttl = cfg->hb_pub.ttl, + }; + struct bt_mesh_net_tx tx = { + .sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx), + .ctx = &ctx, + .src = bt_mesh_model_elem(cfg->model)->addr, + .xmit = bt_mesh_net_transmit_get(), + }; - /* Do nothing if heartbeat publication is not enabled */ - if (cfg->hb_pub.dst == BT_MESH_ADDR_UNASSIGNED) { - return; - } + /* Do nothing if heartbeat publication is not enabled */ + if (cfg->hb_pub.dst == BT_MESH_ADDR_UNASSIGNED) { + return; + } - hb.init_ttl = cfg->hb_pub.ttl; + hb.init_ttl = cfg->hb_pub.ttl; - if (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED) { - feat |= BT_MESH_FEAT_RELAY; - } + if (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED) { + feat |= BT_MESH_FEAT_RELAY; + } - if (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { - feat |= BT_MESH_FEAT_PROXY; - } + if (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) { + feat |= BT_MESH_FEAT_PROXY; + } - if (bt_mesh_friend_get() == BT_MESH_FRIEND_ENABLED) { - feat |= BT_MESH_FEAT_FRIEND; - } + if (bt_mesh_friend_get() == BT_MESH_FRIEND_ENABLED) { + feat |= BT_MESH_FEAT_FRIEND; + } - if (bt_mesh_lpn_established()) { - feat |= BT_MESH_FEAT_LOW_POWER; - } + if (bt_mesh_lpn_established()) { + feat |= BT_MESH_FEAT_LOW_POWER; + } - hb.feat = sys_cpu_to_be16(feat); + hb.feat = sys_cpu_to_be16(feat); - BT_DBG("InitTTL %u feat 0x%04x", cfg->hb_pub.ttl, feat); + BT_DBG("InitTTL %u feat 0x%04x", cfg->hb_pub.ttl, feat); - bt_mesh_ctl_send(&tx, TRANS_CTL_OP_HEARTBEAT, &hb, sizeof(hb), - NULL, NULL, NULL); + bt_mesh_ctl_send(&tx, TRANS_CTL_OP_HEARTBEAT, &hb, sizeof(hb), + NULL, NULL, NULL); } diff --git a/components/network/ble/blemesh/src/transport.h b/components/network/ble/blemesh/src/transport.h index f017a13a..be549187 100644 --- a/components/network/ble/blemesh/src/transport.h +++ b/components/network/ble/blemesh/src/transport.h @@ -35,50 +35,50 @@ #define TRANS_CTL_OP_HEARTBEAT 0x0a struct bt_mesh_ctl_friend_poll { - u8_t fsn; + u8_t fsn; } __packed; struct bt_mesh_ctl_friend_update { - u8_t flags; - u32_t iv_index; - u8_t md; + u8_t flags; + u32_t iv_index; + u8_t md; } __packed; struct bt_mesh_ctl_friend_req { - u8_t criteria; - u8_t recv_delay; - u8_t poll_to[3]; - u16_t prev_addr; - u8_t num_elem; - u16_t lpn_counter; + u8_t criteria; + u8_t recv_delay; + u8_t poll_to[3]; + u16_t prev_addr; + u8_t num_elem; + u16_t lpn_counter; } __packed; struct bt_mesh_ctl_friend_offer { - u8_t recv_win; - u8_t queue_size; - u8_t sub_list_size; - s8_t rssi; - u16_t frnd_counter; + u8_t recv_win; + u8_t queue_size; + u8_t sub_list_size; + s8_t rssi; + u16_t frnd_counter; } __packed; struct bt_mesh_ctl_friend_clear { - u16_t lpn_addr; - u16_t lpn_counter; + u16_t lpn_addr; + u16_t lpn_counter; } __packed; struct bt_mesh_ctl_friend_clear_confirm { - u16_t lpn_addr; - u16_t lpn_counter; + u16_t lpn_addr; + u16_t lpn_counter; } __packed; #define BT_MESH_FRIEND_SUB_MIN_LEN (1 + 2) struct bt_mesh_ctl_friend_sub { - u8_t xact; - u16_t addr_list[5]; + u8_t xact; + u16_t addr_list[5]; } __packed; struct bt_mesh_ctl_friend_sub_confirm { - u8_t xact; + u8_t xact; } __packed; u8_t bt_mesh_get_seg_retrans_num(void); @@ -95,11 +95,11 @@ void bt_mesh_rx_reset(void); void bt_mesh_tx_reset(void); int bt_mesh_ctl_send(struct bt_mesh_net_tx *tx, u8_t ctl_op, void *data, - size_t data_len, u64_t *seq_auth, - const struct bt_mesh_send_cb *cb, void *cb_data); + size_t data_len, u64_t *seq_auth, + const struct bt_mesh_send_cb *cb, void *cb_data); int bt_mesh_trans_send(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg, - const struct bt_mesh_send_cb *cb, void *cb_data); + const struct bt_mesh_send_cb *cb, void *cb_data); int bt_mesh_trans_recv(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx); diff --git a/components/network/ble/blestack/bouffalo.mk b/components/network/ble/blestack/bouffalo.mk index 5e170d1b..53e348d4 100644 --- a/components/network/ble/blestack/bouffalo.mk +++ b/components/network/ble/blestack/bouffalo.mk @@ -51,7 +51,7 @@ COMPONENT_ADD_INCLUDEDIRS := $(ble_stack_srcs_include_dirs) ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src ble_stack_srcs := src/port/bl_port.c \ src/common/atomic_c.c \ src/common/buf.c \ @@ -87,12 +87,12 @@ ble_stack_srcs := src/port/bl_port.c \ src/host/hci_ecc.c \ src/host/l2cap.c \ src/host/uuid.c \ - + ifneq ($(CONFIG_DISABLE_BT_SMP), 1) ble_stack_srcs += src/host/smp.c \ src/host/keys.c endif - + ifeq ($(CONFIG_BT_OAD_CLIENT),1) ble_stack_srcs += src/host_cmdproc/oadc_cmdproc.c endif diff --git a/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c b/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c index 4dbce4c9..cb0b6acb 100644 --- a/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c +++ b/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c @@ -39,10 +39,10 @@ struct rx_msg_struct* bl_find_valid_queued_entry(void) { struct rx_msg_struct empty_msg; memset(&empty_msg, 0, sizeof(struct rx_msg_struct)); - + for(int i = 0; i < sizeof(msg_array)/(sizeof(struct rx_msg_struct)); i++){ if(!memcmp(&msg_array[i], &empty_msg, sizeof(struct rx_msg_struct))) - return (msg_array + i); + return (msg_array + i); } return NULL; @@ -60,10 +60,10 @@ void bl_handle_queued_msg(void) buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT); if(!buf) return; - + msg = k_fifo_get(&msg_queue, K_NO_WAIT); BT_ASSERT(buf); - + bl_onchiphci_rx_packet_handler(msg->pkt_type, msg->src_id, msg->param, msg->param_len, buf); if(msg->param){ k_free(msg->param); @@ -74,7 +74,7 @@ void bl_handle_queued_msg(void) void bl_onchiphci_interface_deinit(void) { struct rx_msg_struct *msg; - + do{ msg = k_fifo_get(&msg_queue, K_NO_WAIT); if(msg){ @@ -85,7 +85,7 @@ void bl_onchiphci_interface_deinit(void) break; } }while(1); - + k_queue_free(&msg_queue); } #endif @@ -96,7 +96,7 @@ uint8_t bl_onchiphci_interface_init(void) memset(msg_array, 0, sizeof(msg_array)); k_queue_init(&msg_queue, 9); #endif - return bt_onchiphci_interface_init(bl_onchiphci_rx_packet_handler); + return bt_onchiphci_interface_init(bl_onchiphci_rx_packet_handler); } int bl_onchiphci_send_2_controller(struct net_buf *buf) @@ -108,11 +108,11 @@ int bl_onchiphci_send_2_controller(struct net_buf *buf) hci_pkt_struct pkt; buf_type = bt_buf_get_type(buf); - + switch(buf_type) { - case BT_BUF_CMD: - { + case BT_BUF_CMD: + { struct bt_hci_cmd_hdr *chdr; if(buf->len < sizeof(struct bt_hci_cmd_hdr)) @@ -127,45 +127,45 @@ int bl_onchiphci_send_2_controller(struct net_buf *buf) opcode = sys_le16_to_cpu(chdr->opcode); //move buf to the payload net_buf_pull(buf, sizeof(struct bt_hci_cmd_hdr)); - - switch(opcode) - { + + switch(opcode) + { //Refer to hci_cmd_desc_tab_le, for the ones of which dest_ll is BLE_CTRL - case BT_HCI_OP_LE_CONN_UPDATE: - case BT_HCI_OP_LE_READ_CHAN_MAP: + case BT_HCI_OP_LE_CONN_UPDATE: + case BT_HCI_OP_LE_READ_CHAN_MAP: case BT_HCI_OP_LE_READ_REMOTE_FEATURES: - case BT_HCI_OP_LE_START_ENCRYPTION: - case BT_HCI_OP_LE_LTK_REQ_REPLY: - case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY: - case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY: - case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY: - case BT_HCI_OP_LE_SET_DATA_LEN: - case BT_HCI_OP_LE_READ_PHY: - case BT_HCI_OP_LE_SET_PHY: - { + case BT_HCI_OP_LE_START_ENCRYPTION: + case BT_HCI_OP_LE_LTK_REQ_REPLY: + case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY: + case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY: + case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY: + case BT_HCI_OP_LE_SET_DATA_LEN: + case BT_HCI_OP_LE_READ_PHY: + case BT_HCI_OP_LE_SET_PHY: + { //dest_id is connectin handle - dest_id = buf->data[0]; - } + dest_id = buf->data[0]; + } default: break; - } + } pkt.p.hci_cmd.opcode = opcode; pkt.p.hci_cmd.param_len = chdr->param_len; pkt.p.hci_cmd.params = buf->data; - - #if defined(CONFIG_BTSOONP_PRINT) + + #if defined(CONFIG_BTSOONP_PRINT) printf("[btsnoop]:opcode =[0x%x],len =[0x%x],data=[%s]\r\n",opcode,chdr->param_len,bt_hex(buf->data,chdr->param_len)); - printf("[btsnoop]:Stop\r\n"); - #endif - - break; - break; - } - case BT_BUF_ACL_OUT: - { + printf("[btsnoop]:Stop\r\n"); + #endif + + break; + break; + } + case BT_BUF_ACL_OUT: + { struct bt_hci_acl_hdr *acl; //connhandle +l2cap field - uint16_t connhdl_l2cf, tlt_len; + uint16_t connhdl_l2cf, tlt_len; if(buf->len < sizeof(struct bt_hci_acl_hdr)) return -EINVAL; @@ -181,35 +181,35 @@ int bl_onchiphci_send_2_controller(struct net_buf *buf) return -EINVAL; //get connection_handle - dest_id = bt_acl_handle(connhdl_l2cf); + dest_id = bt_acl_handle(connhdl_l2cf); pkt.p.acl_data.conhdl = dest_id; pkt.p.acl_data.pb_bc_flag = bt_acl_flags(connhdl_l2cf); pkt.p.acl_data.len = tlt_len; pkt.p.acl_data.buffer = (uint8_t *)buf->data; - - #if defined(CONFIG_BTSOONP_PRINT) - /************************************************************************** - * Need to subtract size of struct of @bt_hci_acl_hdr, it's 4bytes. - * the buf's data need to match the HCI package, otherwise ellisys failes to parses the data. - * Acl format: its total size is 4bytes - * connection_hanlde : 12bits - * Packet Boundary Flag: 2bits - * Broadcast Flag :2bits - * total_length: 2bytes - * - ***************************************************************************/ - printf("[btsnoop]:Acl_out_handle =[0x%x],pb_bc_flag =[0x%x],len =[0x%x],data=[%s]\r\n",pkt.p.acl_data.conhdl,pkt.p.acl_data.pb_bc_flag, - tlt_len,bt_hex(pkt.p.acl_data.buffer,tlt_len)); - printf("[btsnoop]:Stop\r\n"); - #endif - break; - } - + #if defined(CONFIG_BTSOONP_PRINT) + /************************************************************************** + * Need to subtract size of struct of @bt_hci_acl_hdr, it's 4bytes. + * the buf's data need to match the HCI package, otherwise ellisys failes to parses the data. + * Acl format: its total size is 4bytes + * connection_hanlde : 12bits + * Packet Boundary Flag: 2bits + * Broadcast Flag :2bits + * total_length: 2bytes + * + ***************************************************************************/ + printf("[btsnoop]:Acl_out_handle =[0x%x],pb_bc_flag =[0x%x],len =[0x%x],data=[%s]\r\n",pkt.p.acl_data.conhdl,pkt.p.acl_data.pb_bc_flag, + tlt_len,bt_hex(pkt.p.acl_data.buffer,tlt_len)); + printf("[btsnoop]:Stop\r\n"); + #endif + + break; + } + default: - return -EINVAL; + return -EINVAL; } - + return bt_onchiphci_send(pkt_type, dest_id, &pkt); } @@ -222,16 +222,16 @@ static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, ui #endif { uint8_t nb_h2c_cmd_pkts = 0x01, buf_type, *buf_data; - uint16_t tlt_len; - bool prio = true; + uint16_t tlt_len; + bool prio = true; - #if defined(CONFIG_BTSOONP_PRINT) - uint8_t *tbuf_data; - #endif + #if defined(CONFIG_BTSOONP_PRINT) + uint8_t *tbuf_data; + #endif - struct net_buf *buf = NULL; - static uint32_t monitor = 0;// used to monitor buf pool - #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) + struct net_buf *buf = NULL; + static uint32_t monitor = 0;// used to monitor buf pool + #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) struct rx_msg_struct *rx_msg; #endif @@ -239,27 +239,27 @@ static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, ui #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) if(!rx_buf){ #endif - buf_type = (pkt_type == BT_HCI_ACL_DATA)? BT_BUF_ACL_IN: BT_BUF_EVT; + buf_type = (pkt_type == BT_HCI_ACL_DATA)? BT_BUF_ACL_IN: BT_BUF_EVT; if(pkt_type == BT_HCI_CMD_CMP_EVT || pkt_type == BT_HCI_CMD_STAT_EVT) buf = bt_buf_get_cmd_complete(K_FOREVER); else{ - do{ - /* When deal with LE ADV report, Don't use reserve buf*/ - if((pkt_type == BT_HCI_LE_EVT && param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) && - (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT)){ - break; - } - /*not use K_FOREVER, rw main loop thread cannot be blocked here. if there is no rx buffer,directly igore. - otherwise, if rw main loop blocked here, hci command cannot be handled.*/ - buf = bt_buf_get_rx(buf_type, K_NO_WAIT); - }while(0); + do{ + /* When deal with LE ADV report, Don't use reserve buf*/ + if((pkt_type == BT_HCI_LE_EVT && param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) && + (bt_buf_get_rx_avail_cnt() <= CONFIG_BT_RX_BUF_RSV_COUNT)){ + break; + } + /*not use K_FOREVER, rw main loop thread cannot be blocked here. if there is no rx buffer,directly igore. + otherwise, if rw main loop blocked here, hci command cannot be handled.*/ + buf = bt_buf_get_rx(buf_type, K_NO_WAIT); + }while(0); } - + if(!buf){ - if(((++monitor)&0xff) == 0){ - puts("hci_rx_pool is not available\n"); - } + if(((++monitor)&0xff) == 0){ + puts("hci_rx_pool is not available\n"); + } #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) //if it is le adv pkt, discard it. if(pkt_type == BT_HCI_LE_EVT && param[0] == BT_HCI_EVT_LE_ADVERTISING_REPORT) @@ -280,24 +280,24 @@ static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, ui k_fifo_put(&msg_queue, rx_msg); return; } - } + } #else//OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER return; #endif } - monitor = 0; + monitor = 0; #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) }else{ buf = rx_buf; } #endif - + buf_data = net_buf_tail(buf); - - switch(pkt_type) - { - case BT_HCI_CMD_CMP_EVT: - { + + switch(pkt_type) + { + case BT_HCI_CMD_CMP_EVT: + { tlt_len = BT_HCI_EVT_CC_PARAM_OFFSET + param_len; *buf_data++ = BT_HCI_EVT_CMD_COMPLETE; *buf_data++ = BT_HCI_CCEVT_HDR_PARLEN + param_len; @@ -310,15 +310,15 @@ static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, ui memcpy(buf_data, param, param_len); #if defined(CONFIG_BTSOONP_PRINT) tbuf_data += param_len; - + printf("[btsnoop]:pkt_type =[0x%x],len =[0x%x],data=[%s]\r\n",pkt_type,3+param_len,bt_hex(tbuf_data-(3+param_len),3+param_len)); printf("[btsnoop]:Stop\r\n"); - #endif - - break; - } - case BT_HCI_CMD_STAT_EVT: - { + #endif + + break; + } + case BT_HCI_CMD_STAT_EVT: + { tlt_len = BT_HCI_CSEVT_LEN; *buf_data++ = BT_HCI_EVT_CMD_STATUS; *buf_data++ = BT_HCI_CSVT_PARLEN; @@ -330,89 +330,89 @@ static void bl_onchiphci_rx_packet_handler(uint8_t pkt_type, uint16_t src_id, ui sys_put_le16(src_id, buf_data); #if defined(CONFIG_BTSOONP_PRINT) tbuf_data += 2; - - /************************************************************************** - * Status : 1 byte - * Num hci command packet: 1byte - * OCF: 1byte - * OGF: 1byte - ***************************************************************************/ + + /************************************************************************** + * Status : 1 byte + * Num hci command packet: 1byte + * OCF: 1byte + * OGF: 1byte + ***************************************************************************/ printf("[btsnoop]:pkt_type =[0x%x],len =[0x%x],data=[%s]\r\n",pkt_type,4,bt_hex(tbuf_data-4,4)); printf("[btsnoop]:Stop\r\n"); #endif - + break; - } - case BT_HCI_LE_EVT: - { + } + case BT_HCI_LE_EVT: + { prio = false; bt_buf_set_type(buf, BT_BUF_EVT); - tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len; + tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len; *buf_data++ = BT_HCI_EVT_LE_META_EVENT; *buf_data++ = param_len; - + memcpy(buf_data, param, param_len); - - #if defined(CONFIG_BTSOONP_PRINT) + + #if defined(CONFIG_BTSOONP_PRINT) printf("[btsnoop]:pkt_type =[0x%x],len =[0x%x],data=[%s]\r\n",pkt_type,param_len,bt_hex(buf_data,param_len)); - printf("[btsnoop]:Stop\r\n"); - #endif - - break; - } - case BT_HCI_EVT: - { + printf("[btsnoop]:Stop\r\n"); + #endif + + break; + } + case BT_HCI_EVT: + { if(src_id != BT_HCI_EVT_NUM_COMPLETED_PACKETS) prio = false; bt_buf_set_type(buf, BT_BUF_EVT); - tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len; - + tlt_len = BT_HCI_EVT_LE_PARAM_OFFSET + param_len; + *buf_data++ = src_id; *buf_data++ = param_len; - - memcpy(buf_data, param, param_len); - #if defined(CONFIG_BTSOONP_PRINT) - if(!prio){ - printf("[btsnoop]:pkt_type =[0x%x],len =[0x%x],data=[%s]\r\n",pkt_type,param_len,bt_hex(buf_data-2,param_len+2)); - printf("[btsnoop]:Stop\r\n"); - }else{ - /*ignore :BT_HCI_EVT_NUM_COMPLETED_PACKETS */ - } - #endif - break; - } - case BT_HCI_ACL_DATA: - { + + memcpy(buf_data, param, param_len); + #if defined(CONFIG_BTSOONP_PRINT) + if(!prio){ + printf("[btsnoop]:pkt_type =[0x%x],len =[0x%x],data=[%s]\r\n",pkt_type,param_len,bt_hex(buf_data-2,param_len+2)); + printf("[btsnoop]:Stop\r\n"); + }else{ + /*ignore :BT_HCI_EVT_NUM_COMPLETED_PACKETS */ + } + #endif + break; + } + case BT_HCI_ACL_DATA: + { prio = false; bt_buf_set_type(buf, BT_BUF_ACL_IN); - #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) + #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) tlt_len = bt_onchiphci_hanlde_rx_acl(param, buf_data); #else - tlt_len = param_len; - memcpy(buf_data, param, param_len); + tlt_len = param_len; + memcpy(buf_data, param, param_len); #endif - - #if defined(CONFIG_BTSOONP_PRINT) - /************************************************************************** - * Need to subtract size of struct of @bt_hci_acl_hdr, it's 4bytes. - * the buf's data need to match the HCI package, otherwise ellisys failes to parses the data. - * Acl format: its total size is 4bytes - * connection_hanlde : 12bits - * Packet Boundary Flag: 2bits - * Broadcast Flag :2bits - * total_length: 2bytes - * - ***************************************************************************/ - printf("[btsnoop]:Acl_in_handle =[0x%x],pb_bc_flag =[0x%x],len =[0x%x],data=[%s]\r\n",buf_data[0],buf_data[1],tlt_len-4,bt_hex(buf_data+4,tlt_len-4)); - printf("[btsnoop]:Stop\r\n"); - #endif - - break; - } - default: - return; - } + + #if defined(CONFIG_BTSOONP_PRINT) + /************************************************************************** + * Need to subtract size of struct of @bt_hci_acl_hdr, it's 4bytes. + * the buf's data need to match the HCI package, otherwise ellisys failes to parses the data. + * Acl format: its total size is 4bytes + * connection_hanlde : 12bits + * Packet Boundary Flag: 2bits + * Broadcast Flag :2bits + * total_length: 2bytes + * + ***************************************************************************/ + printf("[btsnoop]:Acl_in_handle =[0x%x],pb_bc_flag =[0x%x],len =[0x%x],data=[%s]\r\n",buf_data[0],buf_data[1],tlt_len-4,bt_hex(buf_data+4,tlt_len-4)); + printf("[btsnoop]:Stop\r\n"); + #endif + + break; + } + default: + return; + } net_buf_add(buf, tlt_len); diff --git a/components/network/ble/blestack/src/cli_cmds/ble_cli_cmds.c b/components/network/ble/blestack/src/cli_cmds/ble_cli_cmds.c index a234445f..354ffff7 100644 --- a/components/network/ble/blestack/src/cli_cmds/ble_cli_cmds.c +++ b/components/network/ble/blestack/src/cli_cmds/ble_cli_cmds.c @@ -11,18 +11,18 @@ #include "multi_adv.h" #endif -#define PASSKEY_MAX 0xF423F -#define NAME_LEN 30 -#define CHAR_SIZE_MAX 512 +#define PASSKEY_MAX 0xF423F +#define NAME_LEN 30 +#define CHAR_SIZE_MAX 512 -static u8_t selected_id = BT_ID_DEFAULT; -bool ble_inited = false; +static u8_t selected_id = BT_ID_DEFAULT; +bool ble_inited = false; #if defined(CONFIG_BT_CONN) struct bt_conn *default_conn = NULL; #endif struct bt_data ad_discov[2] = { - BT_DATA_BYTES(BT_DATA_FLAGS,(BT_LE_AD_NO_BREDR | BT_LE_AD_GENERAL)), + BT_DATA_BYTES(BT_DATA_FLAGS,(BT_LE_AD_NO_BREDR | BT_LE_AD_GENERAL)), BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, 13), }; @@ -93,7 +93,7 @@ const struct cli_command btStackCmdSet[] STATIC_CLI_CMD_ATTRIBUTE = { [Mode, 0:discov, 1:non-discov]\r\n\ [Adv Interval Min,0x0020-4000,e.g.0030]\r\n\ [Adv Interval Max,0x0020-4000,e.g.0060]\r\n", ble_start_advertise}, - + {"ble_stop_adv", "\r\nble_stop_adv:[Stop advertising]\r\nParameter[Null]\r\n", ble_stop_advertise}, {"ble_read_local_address", "\r\nble_read_local_address:[Read local address]\r\n", ble_read_local_address}, @@ -105,15 +105,15 @@ const struct cli_command btStackCmdSet[] STATIC_CLI_CMD_ATTRIBUTE = { [Address type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND]\r\n\ [Address value, e.g.112233AABBCC]\r\n", ble_connect}, #endif //CONFIG_BT_CENTRAL - + {"ble_disconnect", "\r\nble_disconnect:[Disconnect remote device]\r\n\ [Address type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND]\r\n\ [Address value,e.g.112233AABBCC]\r\n", ble_disconnect}, - + {"ble_select_conn", "\r\nble_select_conn:[Select a specific connection]\r\n\ [Address type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND]\r\n\ [Address value, e.g.112233AABBCC]\r\n", ble_select_conn}, - + {"ble_unpair", "\r\nble_unpair:[Unpair connection]\r\n\ [Address type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND]\r\n\ [Address value, all 0: unpair all connection, otherwise:unpair specific connection]\r\n", ble_unpair}, @@ -124,7 +124,7 @@ const struct cli_command btStackCmdSet[] STATIC_CLI_CMD_ATTRIBUTE = { [Conn Latency,0x0000-01f3,e.g.0004]\r\n\ [Supervision Timeout,0x000A-0C80,e.g.0010]\r\n", ble_conn_update}, #endif //CONFIG_BT_CONN - + #if defined(CONFIG_BT_SMP) {"ble_security", "\r\nble_security:[Start security]\r\n\ [Security level, Default value 4, 2:BT_SECURITY_MEDIUM, 3:BT_SECURITY_HIGH, 4:BT_SECURITY_FIPS]\r\n", ble_security}, @@ -247,70 +247,70 @@ const struct cli_command btStackCmdSet[] STATIC_CLI_CMD_ATTRIBUTE = { #if defined(CONFIG_BT_CONN) static void connected(struct bt_conn *conn, u8_t err) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - if (err) { - vOutputString("Failed to connect to %s (%u) \r\n", addr, - err); - return; - } + if (err) { + vOutputString("Failed to connect to %s (%u) \r\n", addr, + err); + return; + } - vOutputString("Connected: %s \r\n", addr); + vOutputString("Connected: %s \r\n", addr); - if (!default_conn) { - default_conn = conn; - } + if (!default_conn) { + default_conn = conn; + } } static void disconnected(struct bt_conn *conn, u8_t reason) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - vOutputString("Disconnected: %s (reason %u) \r\n", addr, reason); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + vOutputString("Disconnected: %s (reason %u) \r\n", addr, reason); - if (default_conn == conn) { - default_conn = NULL; - } + if (default_conn == conn) { + default_conn = NULL; + } } static void le_param_updated(struct bt_conn *conn, u16_t interval, - u16_t latency, u16_t timeout) + u16_t latency, u16_t timeout) { - vOutputString("LE conn param updated: int 0x%04x lat %d to %d \r\n", interval, latency, timeout); + vOutputString("LE conn param updated: int 0x%04x lat %d to %d \r\n", interval, latency, timeout); } #if defined(CONFIG_BT_SMP) static void identity_resolved(struct bt_conn *conn, const bt_addr_le_t *rpa, - const bt_addr_le_t *identity) + const bt_addr_le_t *identity) { - char addr_identity[BT_ADDR_LE_STR_LEN]; - char addr_rpa[BT_ADDR_LE_STR_LEN]; + char addr_identity[BT_ADDR_LE_STR_LEN]; + char addr_rpa[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(identity, addr_identity, sizeof(addr_identity)); - bt_addr_le_to_str(rpa, addr_rpa, sizeof(addr_rpa)); + bt_addr_le_to_str(identity, addr_identity, sizeof(addr_identity)); + bt_addr_le_to_str(rpa, addr_rpa, sizeof(addr_rpa)); - vOutputString("Identity resolved %s -> %s \r\n", addr_rpa, addr_identity); + vOutputString("Identity resolved %s -> %s \r\n", addr_rpa, addr_identity); } static void security_changed(struct bt_conn *conn, bt_security_t level, enum bt_security_err err) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - vOutputString("Security changed: %s level %u \r\n", addr, level); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + vOutputString("Security changed: %s level %u \r\n", addr, level); } #endif static struct bt_conn_cb conn_callbacks = { - .connected = connected, - .disconnected = disconnected, - .le_param_updated = le_param_updated, + .connected = connected, + .disconnected = disconnected, + .le_param_updated = le_param_updated, #if defined(CONFIG_BT_SMP) - .identity_resolved = identity_resolved, - .security_changed = security_changed, + .identity_resolved = identity_resolved, + .security_changed = security_changed, #endif }; #endif //CONFIG_BT_CONN @@ -335,59 +335,59 @@ static void ble_init(char *pcWriteBuffer, int xWriteBufferLen, int argc, char ** static void ble_get_device_name(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - const char *device_name = bt_get_name(); + const char *device_name = bt_get_name(); - if(device_name){ - vOutputString("device_name: %s\r\n",device_name); - }else - vOutputString("Failed to read device name\r\n"); + if(device_name){ + vOutputString("device_name: %s\r\n",device_name); + }else + vOutputString("Failed to read device name\r\n"); } static void ble_set_device_name(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err = 0; + int err = 0; - if(strlen(argv[1]) > 0 && strlen(argv[1])<=CONFIG_BT_DEVICE_NAME_MAX){ - err = bt_set_name((char*)argv[1]); - if(err){ - vOutputString("Failed to set device name\r\n"); - }else - vOutputString("Set the device name successfully\r\n"); - }else{ - vOutputString("Invaild lenth(%d)\r\n",strlen(argv[1])); - } + if(strlen(argv[1]) > 0 && strlen(argv[1])<=CONFIG_BT_DEVICE_NAME_MAX){ + err = bt_set_name((char*)argv[1]); + if(err){ + vOutputString("Failed to set device name\r\n"); + }else + vOutputString("Set the device name successfully\r\n"); + }else{ + vOutputString("Invaild lenth(%d)\r\n",strlen(argv[1])); + } } #if defined(CONFIG_BT_OBSERVER) static bool data_cb(struct bt_data *data, void *user_data) { - char *name = user_data; + char *name = user_data; u8_t len; - switch (data->type) { - case BT_DATA_NAME_SHORTENED: - case BT_DATA_NAME_COMPLETE: + switch (data->type) { + case BT_DATA_NAME_SHORTENED: + case BT_DATA_NAME_COMPLETE: len = (data->data_len > NAME_LEN - 1)?(NAME_LEN - 1):(data->data_len); - memcpy(name, data->data, len); - return false; - default: - return true; - } + memcpy(name, data->data, len); + return false; + default: + return true; + } } static void device_found(const bt_addr_le_t *addr, s8_t rssi, u8_t evtype, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - char le_addr[BT_ADDR_LE_STR_LEN]; - char name[NAME_LEN]; + char le_addr[BT_ADDR_LE_STR_LEN]; + char name[NAME_LEN]; - (void)memset(name, 0, sizeof(name)); - bt_data_parse(buf, data_cb, name); - bt_addr_le_to_str(addr, le_addr, sizeof(le_addr)); - - vOutputString("[DEVICE]: %s, AD evt type %u, RSSI %i %s \r\n",le_addr, evtype, rssi, name); + (void)memset(name, 0, sizeof(name)); + bt_data_parse(buf, data_cb, name); + bt_addr_le_to_str(addr, le_addr, sizeof(le_addr)); + + vOutputString("[DEVICE]: %s, AD evt type %u, RSSI %i %s \r\n",le_addr, evtype, rssi, name); } static void ble_start_scan(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) @@ -403,15 +403,15 @@ static void ble_start_scan(char *pcWriteBuffer, int xWriteBufferLen, int argc, c } get_uint8_from_string(&argv[1], &scan_param.type); - + get_uint8_from_string(&argv[2], &scan_param.filter_dup); - + get_uint16_from_string(&argv[3], &scan_param.interval); - + get_uint16_from_string(&argv[4], &scan_param.window); err = bt_le_scan_start(&scan_param, device_found); - + if(err){ vOutputString("Failed to start scan (err %d) \r\n", err); }else{ @@ -422,14 +422,14 @@ static void ble_start_scan(char *pcWriteBuffer, int xWriteBufferLen, int argc, c static void ble_stop_scan(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; - - err = bt_le_scan_stop(); - if (err) { - vOutputString("Stopping scanning failed (err %d)\r\n", err); - } else { - vOutputString("Scan successfully stopped \r\n"); - } + int err; + + err = bt_le_scan_stop(); + if (err) { + vOutputString("Stopping scanning failed (err %d)\r\n", err); + } else { + vOutputString("Scan successfully stopped \r\n"); + } } #endif //#if defined(CONFIG_BT_OBSERVER) @@ -437,17 +437,17 @@ static void ble_stop_scan(char *pcWriteBuffer, int xWriteBufferLen, int argc, ch #if defined(CONFIG_BT_PERIPHERAL) static void ble_read_local_address(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - bt_addr_le_t local_pub_addr; - bt_addr_le_t local_ram_addr; - char le_addr[BT_ADDR_LE_STR_LEN]; + bt_addr_le_t local_pub_addr; + bt_addr_le_t local_ram_addr; + char le_addr[BT_ADDR_LE_STR_LEN]; bt_get_local_public_address(&local_pub_addr); - bt_addr_le_to_str(&local_pub_addr, le_addr, sizeof(le_addr)); - vOutputString("Local public addr : %s\r\n", le_addr); + bt_addr_le_to_str(&local_pub_addr, le_addr, sizeof(le_addr)); + vOutputString("Local public addr : %s\r\n", le_addr); - bt_get_local_ramdon_address(&local_ram_addr); - bt_addr_le_to_str(&local_ram_addr, le_addr, sizeof(le_addr)); - vOutputString("Local random addr : %s\r\n", le_addr); + bt_get_local_ramdon_address(&local_ram_addr); + bt_addr_le_to_str(&local_ram_addr, le_addr, sizeof(le_addr)); + vOutputString("Local random addr : %s\r\n", le_addr); } static void ble_set_adv_channel(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) @@ -479,7 +479,7 @@ static void ble_start_advertise(char *pcWriteBuffer, int xWriteBufferLen, int ar size_t ad_len; int err = 0; uint8_t adv_type, mode; - + if(argc != 3 && argc != 5){ vOutputString("Number of Parameters is not correct\r\n"); return; @@ -502,29 +502,29 @@ static void ble_start_advertise(char *pcWriteBuffer, int xWriteBufferLen, int ar vOutputString("Arg1 is invalid\r\n"); return; } - + /*Get mode, 0:General discoverable, 1:non discoverable, 2:limit discoverable*/ get_uint8_from_string(&argv[2], &mode); vOutputString("mode 0x%x\r\n",mode); if(mode == 0 || mode == 1 || mode == 2){ - + if(mode == 0){ struct bt_data gen_disc_data = (struct bt_data)BT_DATA_BYTES(BT_DATA_FLAGS,(BT_LE_AD_NO_BREDR | BT_LE_AD_GENERAL)); ad_discov[0] = gen_disc_data; }else if(mode == 1){ - struct bt_data non_disc_data = (struct bt_data)BT_DATA_BYTES(BT_DATA_FLAGS,BT_LE_AD_NO_BREDR); + struct bt_data non_disc_data = (struct bt_data)BT_DATA_BYTES(BT_DATA_FLAGS,BT_LE_AD_NO_BREDR); ad_discov[0] = non_disc_data; }else if(mode == 2){ - struct bt_data limt_disc_data = (struct bt_data)BT_DATA_BYTES(BT_DATA_FLAGS,(BT_LE_AD_NO_BREDR | BT_LE_AD_LIMITED)); - ad_discov[0] = limt_disc_data; + struct bt_data limt_disc_data = (struct bt_data)BT_DATA_BYTES(BT_DATA_FLAGS,(BT_LE_AD_NO_BREDR | BT_LE_AD_LIMITED)); + ad_discov[0] = limt_disc_data; }else{ - vOutputString("Invalied AD Mode 0x%x\r\n",mode); + vOutputString("Invalied AD Mode 0x%x\r\n",mode); } - + const char *name = bt_get_name(); struct bt_data data = (struct bt_data)BT_DATA(BT_DATA_NAME_COMPLETE,name, strlen(name)); ad_discov[1] = data; - + ad = ad_discov; ad_len = ARRAY_SIZE(ad_discov); @@ -537,16 +537,16 @@ static void ble_start_advertise(char *pcWriteBuffer, int xWriteBufferLen, int ar get_uint16_from_string(&argv[3], ¶m.interval_min); get_uint16_from_string(&argv[4], ¶m.interval_max); - vOutputString("interval min 0x%x\r\n",param.interval_min); - vOutputString("interval max 0x%x\r\n",param.interval_max); + vOutputString("interval min 0x%x\r\n",param.interval_min); + vOutputString("interval max 0x%x\r\n",param.interval_max); } - + if(adv_type == 1 || adv_type == 0){ - err = bt_le_adv_start(¶m, ad, ad_len, &ad_discov[0], 1); + err = bt_le_adv_start(¶m, ad, ad_len, &ad_discov[0], 1); }else{ err = bt_le_adv_start(¶m, ad, ad_len, NULL, 0); } - + if(err){ vOutputString("Failed to start advertising (err %d) \r\n", err); }else{ @@ -558,8 +558,8 @@ static void ble_start_advertise(char *pcWriteBuffer, int xWriteBufferLen, int ar static void ble_stop_advertise(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { if(bt_le_adv_stop()){ - vOutputString("Failed to stop advertising\r\n"); - }else{ + vOutputString("Failed to stop advertising\r\n"); + }else{ vOutputString("Advertising stopped\r\n"); } } @@ -640,35 +640,35 @@ static void ble_connect(char *pcWriteBuffer, int xWriteBufferLen, int argc, char bt_addr_le_t addr; struct bt_conn *conn; u8_t addr_val[6]; - s8_t type = -1; - int i=0; + s8_t type = -1; + int i=0; - struct bt_le_conn_param param = { - .interval_min = BT_GAP_INIT_CONN_INT_MIN, - .interval_max = BT_GAP_INIT_CONN_INT_MAX, - .latency = 0, - .timeout = 400, - }; + struct bt_le_conn_param param = { + .interval_min = BT_GAP_INIT_CONN_INT_MIN, + .interval_max = BT_GAP_INIT_CONN_INT_MAX, + .latency = 0, + .timeout = 400, + }; - (void)memset(addr_val,0,6); + (void)memset(addr_val,0,6); if(argc != 3){ vOutputString("Number of Parameters is not correct\r\n"); return; } - + get_uint8_from_string(&argv[1], (u8_t *)&type); - /*Get addr type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ + /*Get addr type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ addr.type = type; get_bytearray_from_string(&argv[2], addr_val,6); for(i=0;i<6;i++){ - vOutputString("addr[%d]:[0x%x]\r\n",i,addr_val[i]); + vOutputString("addr[%d]:[0x%x]\r\n",i,addr_val[i]); } - + reverse_bytearray(addr_val, addr.a.val, 6); - + conn = bt_conn_create_le(&addr, /*BT_LE_CONN_PARAM_DEFAULT*/¶m); if(!conn){ @@ -685,8 +685,8 @@ static void ble_disconnect(char *pcWriteBuffer, int xWriteBufferLen, int argc, c bt_addr_le_t addr; u8_t addr_val[6]; struct bt_conn *conn; - s8_t type = -1; - + s8_t type = -1; + if(argc != 3){ vOutputString("Number of Parameters is not correct\r\n"); return; @@ -695,7 +695,7 @@ static void ble_disconnect(char *pcWriteBuffer, int xWriteBufferLen, int argc, c get_bytearray_from_string(&argv[2], addr_val,6); reverse_bytearray(addr_val, addr.a.val, 6); - /*Get addr type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ + /*Get addr type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ addr.type = type; conn = bt_conn_lookup_addr_le(selected_id, &addr); @@ -733,9 +733,9 @@ static void ble_select_conn(char *pcWriteBuffer, int xWriteBufferLen, int argc, get_bytearray_from_string(&argv[2], addr_val,6); reverse_bytearray(addr_val, addr.a.val, 6); - + conn = bt_conn_lookup_addr_le(selected_id, &addr); - + if(!conn){ vOutputString("No matching connection found\r\n"); return; @@ -761,11 +761,11 @@ static void ble_unpair(char *pcWriteBuffer, int xWriteBufferLen, int argc, char /*Get addr type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ get_uint8_from_string(&argv[1], &addr.type); - + get_bytearray_from_string(&argv[2], addr_val,6); reverse_bytearray(addr_val, addr.a.val, 6); - + err = bt_unpair(selected_id, &addr); if(err){ @@ -777,8 +777,8 @@ static void ble_unpair(char *pcWriteBuffer, int xWriteBufferLen, int argc, char static void ble_conn_update(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_le_conn_param param; - int err; + struct bt_le_conn_param param; + int err; if(argc != 5){ vOutputString("Number of Parameters is not correct\r\n"); @@ -787,14 +787,14 @@ static void ble_conn_update(char *pcWriteBuffer, int xWriteBufferLen, int argc, get_uint16_from_string(&argv[1], ¶m.interval_min); get_uint16_from_string(&argv[2], ¶m.interval_max); get_uint16_from_string(&argv[3], ¶m.latency); - get_uint16_from_string(&argv[4], ¶m.timeout); + get_uint16_from_string(&argv[4], ¶m.timeout); err = bt_conn_le_param_update(default_conn, ¶m); - if (err) { - vOutputString("conn update failed (err %d)\r\n", err); - } else { - vOutputString("conn update initiated\r\n"); - } + if (err) { + vOutputString("conn update failed (err %d)\r\n", err); + } else { + vOutputString("conn update initiated\r\n"); + } } #endif //#if defined(CONFIG_BT_CONN) @@ -802,7 +802,7 @@ static void ble_conn_update(char *pcWriteBuffer, int xWriteBufferLen, int argc, static void ble_security(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { int err; - u8_t sec_level = /*BT_SECURITY_FIPS*/BT_SECURITY_L4; + u8_t sec_level = /*BT_SECURITY_FIPS*/BT_SECURITY_L4; if(!default_conn){ vOutputString("Please firstly choose the connection using ble_select_conn\r\n"); @@ -811,7 +811,7 @@ static void ble_security(char *pcWriteBuffer, int xWriteBufferLen, int argc, cha if(argc == 2) get_uint8_from_string(&argv[1], &sec_level); - + err = bt_conn_set_security(default_conn, sec_level); if(err){ @@ -825,72 +825,72 @@ static void auth_passkey_display(struct bt_conn *conn, unsigned int passkey) { char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); vOutputString("passkey_str is: %06u\r\n", passkey); } static void auth_passkey_confirm(struct bt_conn *conn, unsigned int passkey) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - vOutputString("Confirm passkey for %s: %06u\r\n", addr, passkey); + vOutputString("Confirm passkey for %s: %06u\r\n", addr, passkey); } static void auth_passkey_entry(struct bt_conn *conn) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - vOutputString("Enter passkey for %s\r\n", addr); + vOutputString("Enter passkey for %s\r\n", addr); } static void auth_cancel(struct bt_conn *conn) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - - vOutputString("Pairing cancelled: %s\r\n", addr); + + vOutputString("Pairing cancelled: %s\r\n", addr); } static void auth_pairing_confirm(struct bt_conn *conn) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - vOutputString("Confirm pairing for %s\r\n", addr); + vOutputString("Confirm pairing for %s\r\n", addr); } static void auth_pairing_complete(struct bt_conn *conn, bool bonded) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - vOutputString("%s with %s\r\n", bonded ? "Bonded" : "Paired", addr); + vOutputString("%s with %s\r\n", bonded ? "Bonded" : "Paired", addr); } static void auth_pairing_failed(struct bt_conn *conn, enum bt_security_err reason) { - char addr[BT_ADDR_LE_STR_LEN]; + char addr[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); - vOutputString("Pairing failed with %s\r\n", addr); + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + vOutputString("Pairing failed with %s\r\n", addr); } static struct bt_conn_auth_cb auth_cb_display = { - .passkey_display = auth_passkey_display, - .passkey_entry = auth_passkey_entry, - .passkey_confirm = auth_passkey_confirm, - .cancel = auth_cancel, - .pairing_confirm = auth_pairing_confirm, - .pairing_failed = auth_pairing_failed, - .pairing_complete = auth_pairing_complete, + .passkey_display = auth_passkey_display, + .passkey_entry = auth_passkey_entry, + .passkey_confirm = auth_passkey_confirm, + .cancel = auth_cancel, + .pairing_confirm = auth_pairing_confirm, + .pairing_failed = auth_pairing_failed, + .pairing_complete = auth_pairing_complete, }; static void ble_auth(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) @@ -908,95 +908,95 @@ static void ble_auth(char *pcWriteBuffer, int xWriteBufferLen, int argc, char ** static void ble_auth_cancel(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_conn *conn; - - if (default_conn) { - conn = default_conn; - }else { - conn = NULL; - } + struct bt_conn *conn; - if (!conn) { + if (default_conn) { + conn = default_conn; + }else { + conn = NULL; + } + + if (!conn) { vOutputString("Not connected\r\n"); - return; - } + return; + } - bt_conn_auth_cancel(conn); + bt_conn_auth_cancel(conn); } static void ble_auth_passkey_confirm(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } - bt_conn_auth_passkey_confirm(default_conn); + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } + + bt_conn_auth_passkey_confirm(default_conn); } static void ble_auth_pairing_confirm(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } - bt_conn_auth_pairing_confirm(default_conn); + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } + + bt_conn_auth_pairing_confirm(default_conn); } static void ble_auth_passkey(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - uint32_t passkey; + uint32_t passkey; if(argc != 2){ vOutputString("Number of Parameters is not correct\r\n"); return; } - - if (!default_conn) { + + if (!default_conn) { vOutputString("Not connected\r\n"); - return; - } + return; + } passkey = atoi(argv[1]); - if (passkey > PASSKEY_MAX) { + if (passkey > PASSKEY_MAX) { vOutputString("Passkey should be between 0-999999\r\n"); - return; - } + return; + } - bt_conn_auth_passkey_entry(default_conn, passkey); + bt_conn_auth_passkey_entry(default_conn, passkey); } #endif //#if defined(CONFIG_BT_SMP) #if defined(CONFIG_BT_GATT_CLIENT) static void exchange_func(struct bt_conn *conn, u8_t err, - struct bt_gatt_exchange_params *params) + struct bt_gatt_exchange_params *params) { - vOutputString("Exchange %s MTU Size =%d \r\n", err == 0U ? "successful" : "failed",bt_gatt_get_mtu(conn)); + vOutputString("Exchange %s MTU Size =%d \r\n", err == 0U ? "successful" : "failed",bt_gatt_get_mtu(conn)); } static struct bt_gatt_exchange_params exchange_params; static void ble_exchange_mtu(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; - - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } + int err; - exchange_params.func = exchange_func; + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } - err = bt_gatt_exchange_mtu(default_conn, &exchange_params); - if (err) { - vOutputString("Exchange failed (err %d)\r\n", err); - } else { - vOutputString("Exchange pending\r\n"); - } + exchange_params.func = exchange_func; + + err = bt_gatt_exchange_mtu(default_conn, &exchange_params); + if (err) { + vOutputString("Exchange failed (err %d)\r\n", err); + } else { + vOutputString("Exchange pending\r\n"); + } } static struct bt_gatt_discover_params discover_params; @@ -1004,100 +1004,100 @@ static struct bt_uuid_16 uuid = BT_UUID_INIT_16(0); static void print_chrc_props(u8_t properties) { - vOutputString("Properties: "); + vOutputString("Properties: "); - if (properties & BT_GATT_CHRC_BROADCAST) { - vOutputString("[bcast]\r\n"); - } + if (properties & BT_GATT_CHRC_BROADCAST) { + vOutputString("[bcast]\r\n"); + } - if (properties & BT_GATT_CHRC_READ) { - vOutputString("[read]\r\n"); - } + if (properties & BT_GATT_CHRC_READ) { + vOutputString("[read]\r\n"); + } - if (properties & BT_GATT_CHRC_WRITE) { - vOutputString("[write]\r\n"); - } + if (properties & BT_GATT_CHRC_WRITE) { + vOutputString("[write]\r\n"); + } - if (properties & BT_GATT_CHRC_WRITE_WITHOUT_RESP) { - vOutputString("[write w/w rsp]\r\n"); - } + if (properties & BT_GATT_CHRC_WRITE_WITHOUT_RESP) { + vOutputString("[write w/w rsp]\r\n"); + } - if (properties & BT_GATT_CHRC_NOTIFY) { - vOutputString("[notify]\r\n"); - } + if (properties & BT_GATT_CHRC_NOTIFY) { + vOutputString("[notify]\r\n"); + } - if (properties & BT_GATT_CHRC_INDICATE) { - vOutputString("[indicate]"); - } + if (properties & BT_GATT_CHRC_INDICATE) { + vOutputString("[indicate]"); + } - if (properties & BT_GATT_CHRC_AUTH) { - vOutputString("[auth]\r\n"); - } + if (properties & BT_GATT_CHRC_AUTH) { + vOutputString("[auth]\r\n"); + } - if (properties & BT_GATT_CHRC_EXT_PROP) { - vOutputString("[ext prop]\r\n"); - } + if (properties & BT_GATT_CHRC_EXT_PROP) { + vOutputString("[ext prop]\r\n"); + } } u8_t discover_func(struct bt_conn *conn, const struct bt_gatt_attr *attr, struct bt_gatt_discover_params *params) { - struct bt_gatt_service_val *gatt_service; - struct bt_gatt_chrc *gatt_chrc; - struct bt_gatt_include *gatt_include; - char str[37]; + struct bt_gatt_service_val *gatt_service; + struct bt_gatt_chrc *gatt_chrc; + struct bt_gatt_include *gatt_include; + char str[37]; - if (!attr) { - vOutputString( "Discover complete\r\n"); - (void)memset(params, 0, sizeof(*params)); - return BT_GATT_ITER_STOP; - } + if (!attr) { + vOutputString( "Discover complete\r\n"); + (void)memset(params, 0, sizeof(*params)); + return BT_GATT_ITER_STOP; + } - switch (params->type) { - case BT_GATT_DISCOVER_SECONDARY: - case BT_GATT_DISCOVER_PRIMARY: - gatt_service = attr->user_data; - bt_uuid_to_str(gatt_service->uuid, str, sizeof(str)); - vOutputString("Service %s found: start handle %x, end_handle %x\r\n", str, attr->handle, gatt_service->end_handle); - break; - case BT_GATT_DISCOVER_CHARACTERISTIC: - gatt_chrc = attr->user_data; - bt_uuid_to_str(gatt_chrc->uuid, str, sizeof(str)); - vOutputString("Characteristic %s found: attr->handle %x chrc->handle %x \r\n", str, attr->handle,gatt_chrc->value_handle); - print_chrc_props(gatt_chrc->properties); - break; - case BT_GATT_DISCOVER_INCLUDE: - gatt_include = attr->user_data; - bt_uuid_to_str(gatt_include->uuid, str, sizeof(str)); - vOutputString("Include %s found: handle %x, start %x, end %x\r\n", str, attr->handle, - gatt_include->start_handle, gatt_include->end_handle); - break; - default: - bt_uuid_to_str(attr->uuid, str, sizeof(str)); - vOutputString("Descriptor %s found: handle %x\r\n", str, attr->handle); - break; - } + switch (params->type) { + case BT_GATT_DISCOVER_SECONDARY: + case BT_GATT_DISCOVER_PRIMARY: + gatt_service = attr->user_data; + bt_uuid_to_str(gatt_service->uuid, str, sizeof(str)); + vOutputString("Service %s found: start handle %x, end_handle %x\r\n", str, attr->handle, gatt_service->end_handle); + break; + case BT_GATT_DISCOVER_CHARACTERISTIC: + gatt_chrc = attr->user_data; + bt_uuid_to_str(gatt_chrc->uuid, str, sizeof(str)); + vOutputString("Characteristic %s found: attr->handle %x chrc->handle %x \r\n", str, attr->handle,gatt_chrc->value_handle); + print_chrc_props(gatt_chrc->properties); + break; + case BT_GATT_DISCOVER_INCLUDE: + gatt_include = attr->user_data; + bt_uuid_to_str(gatt_include->uuid, str, sizeof(str)); + vOutputString("Include %s found: handle %x, start %x, end %x\r\n", str, attr->handle, + gatt_include->start_handle, gatt_include->end_handle); + break; + default: + bt_uuid_to_str(attr->uuid, str, sizeof(str)); + vOutputString("Descriptor %s found: handle %x\r\n", str, attr->handle); + break; + } - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static void ble_discover(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; + int err; u8_t disc_type; if(argc != 5){ vOutputString("Number of Parameters is not correct\r\n"); return; } - - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } - discover_params.func = discover_func; - discover_params.start_handle = 0x0001; - discover_params.end_handle = 0xffff; + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } + + discover_params.func = discover_func; + discover_params.start_handle = 0x0001; + discover_params.end_handle = 0xffff; get_uint8_from_string(&argv[1], &disc_type); if(disc_type == 0){ @@ -1115,7 +1115,7 @@ static void ble_discover(char *pcWriteBuffer, int xWriteBufferLen, int argc, cha return; } get_uint16_from_string(&argv[2], &uuid.val); - + if(uuid.val) discover_params.uuid = &uuid.uuid; else @@ -1124,153 +1124,153 @@ static void ble_discover(char *pcWriteBuffer, int xWriteBufferLen, int argc, cha get_uint16_from_string(&argv[3], &discover_params.start_handle); get_uint16_from_string(&argv[4], &discover_params.end_handle); - err = bt_gatt_discover(default_conn, &discover_params); - if (err) { - vOutputString("Discover failed (err %d)\r\n", err); - } else { - vOutputString("Discover pending\r\n"); - } + err = bt_gatt_discover(default_conn, &discover_params); + if (err) { + vOutputString("Discover failed (err %d)\r\n", err); + } else { + vOutputString("Discover pending\r\n"); + } } static struct bt_gatt_read_params read_params; static u8_t read_func(struct bt_conn *conn, u8_t err, struct bt_gatt_read_params *params, const void *data, u16_t length) { - vOutputString("Read complete: err %u length %u \r\n", err, length); + vOutputString("Read complete: err %u length %u \r\n", err, length); - char str[22]; - u8_t *buf = (u8_t *)data; + char str[22]; + u8_t *buf = (u8_t *)data; int i=0; - memset(str,0,15); - - if(length > 0 && length <= sizeof(str)){ - memcpy(str,buf,length); - vOutputString("device name : %s \r\n",str); + memset(str,0,15); + + if(length > 0 && length <= sizeof(str)){ + memcpy(str,buf,length); + vOutputString("device name : %s \r\n",str); for(i=0;i sizeof(gatt_write_buf)? (sizeof(gatt_write_buf)):(write_params.length); get_bytearray_from_string(&argv[4], gatt_write_buf,data_len); - - write_params.data = gatt_write_buf; - write_params.length = data_len; - write_params.func = write_func; - - err = bt_gatt_write(default_conn, &write_params); - if (err) { - vOutputString("Write failed (err %d)\r\n", err); - } else { - vOutputString("Write pending\r\n"); - } + write_params.data = gatt_write_buf; + write_params.length = data_len; + write_params.func = write_func; + + err = bt_gatt_write(default_conn, &write_params); + + if (err) { + vOutputString("Write failed (err %d)\r\n", err); + } else { + vOutputString("Write pending\r\n"); + } } static void ble_write_without_rsp(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u16_t handle; - int err; - u16_t len; - bool sign; + u16_t handle; + int err; + u16_t len; + bool sign; if(argc != 5){ vOutputString("Number of Parameters is not correct\r\n"); return; } - - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } + + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } get_uint8_from_string(&argv[1], (uint8_t *)&sign); get_uint16_from_string(&argv[2], &handle); - get_uint16_from_string(&argv[3], &len); + get_uint16_from_string(&argv[3], &len); len = len > sizeof(gatt_write_buf)? (sizeof(gatt_write_buf)):(len); - get_bytearray_from_string(&argv[4], gatt_write_buf,len); - - err = bt_gatt_write_without_response(default_conn, handle, gatt_write_buf, len, sign); + get_bytearray_from_string(&argv[4], gatt_write_buf,len); - vOutputString("Write Complete (err %d)\r\n", err); + err = bt_gatt_write_without_response(default_conn, handle, gatt_write_buf, len, sign); + + vOutputString("Write Complete (err %d)\r\n", err); } static struct bt_gatt_subscribe_params subscribe_params; static u8_t notify_func(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params, - const void *data, u16_t length) + struct bt_gatt_subscribe_params *params, + const void *data, u16_t length) { if (!params->value) { vOutputString("Unsubscribed\r\n"); @@ -1331,31 +1331,31 @@ static void ble_unsubscribe(char *pcWriteBuffer, int xWriteBufferLen, int argc, static void ble_set_data_len(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u16_t tx_octets; - u16_t tx_time; - int err; + u16_t tx_octets; + u16_t tx_time; + int err; - if(argc != 3){ - vOutputString("Number of Parameters is not correct\r\n"); - return; - } + if(argc != 3){ + vOutputString("Number of Parameters is not correct\r\n"); + return; + } - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } - get_uint16_from_string(&argv[1], &tx_octets); - get_uint16_from_string(&argv[2], &tx_time); + get_uint16_from_string(&argv[1], &tx_octets); + get_uint16_from_string(&argv[2], &tx_time); - err = bt_le_set_data_len(default_conn, tx_octets, tx_time); - if (err) { - vOutputString("ble_set_data_len, LE Set Data Length (err %d)\r\n", err); - } - else - { - vOutputString("ble_set_data_len, LE Set Data Length success\r\n"); - } + err = bt_le_set_data_len(default_conn, tx_octets, tx_time); + if (err) { + vOutputString("ble_set_data_len, LE Set Data Length (err %d)\r\n", err); + } + else + { + vOutputString("ble_set_data_len, LE Set Data Length success\r\n"); + } } static void ble_get_all_conn_info(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) @@ -1375,8 +1375,8 @@ static void ble_get_all_conn_info(char *pcWriteBuffer, int xWriteBufferLen, int vOutputString("ble connected devices count: %d\r\n", link_num); for(int i = 0; i < link_num; i++) { - bt_addr_le_to_str(info[i].le.remote, le_addr, sizeof(le_addr)); - vOutputString("[%d]: address %s\r\n", i, le_addr); + bt_addr_le_to_str(info[i].le.remote, le_addr, sizeof(le_addr)); + vOutputString("[%d]: address %s\r\n", i, le_addr); } } @@ -1387,9 +1387,9 @@ static void ble_set_tx_pwr(char *pcWriteBuffer, int xWriteBufferLen, int argc, c int err; if(argc != 2){ - vOutputString("Number of Parameters is not correct\r\n"); - return; - } + vOutputString("Number of Parameters is not correct\r\n"); + return; + } get_uint8_from_string(&argv[1],&power); @@ -1397,23 +1397,23 @@ static void ble_set_tx_pwr(char *pcWriteBuffer, int xWriteBufferLen, int argc, c vOutputString("ble_set_tx_pwr, invalid value, value shall be in [0x%x - 0x%x]\r\n", 0x00, 0x14); return; } - + err = bt_set_tx_pwr((int8_t)power); if(err){ - vOutputString("ble_set_tx_pwr, Fail to set tx power (err %d)\r\n", err); - } - else{ - vOutputString("ble_set_tx_pwr, Set tx power successfully\r\n"); - } - + vOutputString("ble_set_tx_pwr, Fail to set tx power (err %d)\r\n", err); + } + else{ + vOutputString("ble_set_tx_pwr, Set tx power successfully\r\n"); + } + } #endif #if defined(BFLB_DISABLE_BT) static void ble_disable(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; + int err; err = bt_disable(); if(err){ diff --git a/components/network/ble/blestack/src/cli_cmds/pts_cli_cmds.c b/components/network/ble/blestack/src/cli_cmds/pts_cli_cmds.c index 36e432a3..44fce7d9 100644 --- a/components/network/ble/blestack/src/cli_cmds/pts_cli_cmds.c +++ b/components/network/ble/blestack/src/cli_cmds/pts_cli_cmds.c @@ -11,53 +11,53 @@ #include "rpa.h" #include "log.h" -#define LIM_ADV_TIME 30720 -#define LIM_SCAN_TIME 10240 -#define PASSKEY_MAX 0xF423F -#define NAME_LEN 30 +#define LIM_ADV_TIME 30720 +#define LIM_SCAN_TIME 10240 +#define PASSKEY_MAX 0xF423F +#define NAME_LEN 30 #define CHAR_SIZE_MAX 512 u8_t peer_irk[16] = { - 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef, - 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef + 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef, + 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef }; - + u8_t pts_address[6] = { - //0xE9,0x20,0xF2,0xDC,0x1b,0x00 - //0xCA,0x97,0xDE,0x05,0xB9,0x18 - 0x18,0xB9,0x05,0xDE,0x97,0xCA -}; + //0xE9,0x20,0xF2,0xDC,0x1b,0x00 + //0xCA,0x97,0xDE,0x05,0xB9,0x18 + 0x18,0xB9,0x05,0xDE,0x97,0xCA +}; const u8_t discover_mode[] = { - (BT_LE_AD_LIMITED | BT_LE_AD_NO_BREDR) + (BT_LE_AD_LIMITED | BT_LE_AD_NO_BREDR) }; static const u8_t service_uuid[16] = { - 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, - 0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f + 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, + 0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f }; #if defined(PTS_TEST_CASE_INSUFFICIENT_KEY) struct gatt_value { - u16_t len; - u8_t *data; - u8_t enc_key_size; - u8_t flags[1]; + u16_t len; + u8_t *data; + u8_t enc_key_size; + u8_t flags[1]; }; static struct gatt_value value; #endif -static const u8_t service_data[]= {0x00,0x01}; +static const u8_t service_data[]= {0x00,0x01}; static const u8_t data_manu[4]= {0x71,0x01,0x04,0x13}; static const u8_t tx_power[1]= {0x50}; static const u8_t data_appearance[2]= {0x80, 0x01}; -static const u8_t name[] = "BL702-BLE-DEV"; +static const u8_t name[] = "BL702-BLE-DEV"; extern volatile u8_t event_flag; extern struct bt_conn *default_conn; //extern struct bt_data ad_discov[2]; static struct bt_data ad_discov[2] = { - BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), + BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), #if defined(BL602) BT_DATA(BT_DATA_NAME_COMPLETE, "BL602-BLE-DEV-PTS", 17), #else @@ -66,7 +66,7 @@ static struct bt_data ad_discov[2] = { }; static struct bt_data ad_non_discov[] = { - BT_DATA(BT_DATA_NAME_COMPLETE, "BL602-BLE-DEV-PTS", 17), + BT_DATA(BT_DATA_NAME_COMPLETE, "BL602-BLE-DEV-PTS", 17), }; static u8_t selected_id = BT_ID_DEFAULT; @@ -90,7 +90,7 @@ static void pts_ble_set_smp_flag(char *pcWriteBuffer, int xWriteBufferLen, int a static void pts_ble_clear_smp_flag(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv); static void pts_ble_bondable(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv); static void pts_ble_read_uuid(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv); -static void pts_ble_mread(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv); +static void pts_ble_mread(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv); static void pts_ble_discover_uuid_128(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv); static void pts_ble_read_uuid_128(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv); @@ -119,7 +119,7 @@ const struct cli_command PtsCmdSet[] STATIC_CLI_CMD_ATTRIBUTE = { /*1.The cmd string to type, 2.Cmd description, 3.The function to run, 4.Number of parameters*/ {"pts_ble_address_register", "\r\npts_ble_address_register:\r\n\[Address type, 0:non-rpa, 1:rpa, 2:public adderss]\r\n\ - [Pts_address, e.g.peer_addr]\r\n" , pts_ble_address_register}, + [Pts_address, e.g.peer_addr]\r\n" , pts_ble_address_register}, {"pts_ble_set_flag", "\r\npts_ble_set_flag:[Set flag for different applications]\r\n\[Flag, e.g.0,1]\r\n", pts_ble_set_flag}, {"pts_ble_set_smp_flag", "\r\npts_ble_set_smp_flag:[Set flag for SM test]\r\n\[Flag, e.g.0,1]\r\n", pts_ble_set_smp_flag}, {"pts_ble_clear_smp_flag", "\r\npts_ble_clear_smp_flag:[Clear smp test flag]\r\n\[Flag, e.g.0,1]\r\n", pts_ble_clear_smp_flag}, @@ -192,14 +192,14 @@ const struct cli_command PtsCmdSet[] STATIC_CLI_CMD_ATTRIBUTE = { [Address type,0:ADDR_RAND, 1:ADDR_RPA_OR_PUBLIC,2:ADDR_PUBLIC, 3:ADDR_RPA_OR_RAND]\r\n\ [Address value, e.g.112233AABBCC]\r\n",pts_ble_bt_le_whitelist_add}, #endif//CONFIG_BT_WHITELIST -#endif //CONFIG_BT_CENTRAL +#endif //CONFIG_BT_CENTRAL {"pts_ble_disconnect", "\r\npts_ble_disconnect:[Disconnect remote device]\r\n\ [Address type, 0:ADDR_RAND, 1:ADDR_RPA_OR_PUBLIC,2:ADDR_PUBLIC, 3:ADDR_RPA_OR_RAND]\r\n\ [Address value,e.g.112233AABBCC]\r\n", pts_ble_disconnect}, #endif //CONFIG_BT_CONN - + #if defined(CONFIG_BT_SMP) {"pts_ble_set_mitm", "\r\npts_ble_set_mitm:[set MIMT]\r\n\[State, 0x01:define,0x00:undefine]\r\n", pts_ble_set_mitm}, #endif //CONFIG_BT_SMP @@ -235,480 +235,480 @@ const struct cli_command PtsCmdSet[] STATIC_CLI_CMD_ATTRIBUTE = { #if defined(CONFIG_BT_PERIPHERAL) #if defined(PTS_GAP_SLAVER_CONFIG_READ_CHARC) static u8_t report[]= { - 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, - 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, - 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09 + 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, + 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09, + 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09 }; static ssize_t read_pts_long_value(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + void *buf, u16_t len, u16_t offset) { - const char *lvalue = "PTS-LONG-VALUE0123456789abcdef1122"; + const char *lvalue = "PTS-LONG-VALUE0123456789abcdef1122"; - return bt_gatt_attr_read(conn, attr, buf, len, offset, lvalue, - strlen(lvalue)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, lvalue, + strlen(lvalue)); } static ssize_t read_pts_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + void *buf, u16_t len, u16_t offset) { - const char *name = "PTS_NAME"; + const char *name = "PTS_NAME"; - return bt_gatt_attr_read(conn, attr, buf, len, offset, name,strlen(name)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, name,strlen(name)); } static ssize_t pts_read_report( - struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + struct bt_conn *conn, + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - return bt_gatt_attr_read(conn, attr, buf, len, offset, - attr->user_data, - sizeof(report)/sizeof(u8_t)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, + attr->user_data, + sizeof(report)/sizeof(u8_t)); } #endif /* PTS_GAP_SLAVER_CONFIG_READ_CHARC */ #if defined(PTS_GAP_SLAVER_CONFIG_WRITE_CHARC) -#define TEST_LVAL_MAX 30 -#define TEST_SVAL_MAX 4 +#define TEST_LVAL_MAX 30 +#define TEST_SVAL_MAX 4 static u16_t test_len = 0; //static u16_t test_slen = 0; -static u8_t short_buf[TEST_SVAL_MAX]= +static u8_t short_buf[TEST_SVAL_MAX]= { - 0x01,0x02,0x03,0x04 + 0x01,0x02,0x03,0x04 }; -static u8_t long_buf[TEST_LVAL_MAX] = +static u8_t long_buf[TEST_LVAL_MAX] = { - 0x01,0x02,0x03,0x04, - 0x05,0x06,0x07,0x08, - 0x09,0x0a,0x11,0x12, - 0x13,0x14,0x15,0x16, - 0x17,0x18,0x19,0x1a, - 0x21,0x22,0x23,0x24, - 0x25,0x26,0x27,0x28, - 0x29,0x2a -}; + 0x01,0x02,0x03,0x04, + 0x05,0x06,0x07,0x08, + 0x09,0x0a,0x11,0x12, + 0x13,0x14,0x15,0x16, + 0x17,0x18,0x19,0x1a, + 0x21,0x22,0x23,0x24, + 0x25,0x26,0x27,0x28, + 0x29,0x2a +}; -static ssize_t pts_write_short_value(struct bt_conn *conn,const struct bt_gatt_attr *bt_attr, - void *buf,u16_t len, u16_t offset,u8_t flags) +static ssize_t pts_write_short_value(struct bt_conn *conn,const struct bt_gatt_attr *bt_attr, + void *buf,u16_t len, u16_t offset,u8_t flags) { - u8_t i = 0; - u16_t tlen = len; - u8_t *data = (u8_t*)buf; + u8_t i = 0; + u16_t tlen = len; + u8_t *data = (u8_t*)buf; - for(i=0;i[0x%x]\r\n",i,data[i]); + for(i=0;i[0x%x]\r\n",i,data[i]); - /*The rest of space is enough.*/ - if(TEST_SVAL_MAX >= tlen){ - (void)memcpy(short_buf,data,tlen); - } - else{ - return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); - } - - /*If prepare write, it will return 0 */ - if(flags == BT_GATT_WRITE_FLAG_PREPARE) - tlen = 0; - - return tlen; + /*The rest of space is enough.*/ + if(TEST_SVAL_MAX >= tlen){ + (void)memcpy(short_buf,data,tlen); + } + else{ + return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } + + /*If prepare write, it will return 0 */ + if(flags == BT_GATT_WRITE_FLAG_PREPARE) + tlen = 0; + + return tlen; } static ssize_t pts_read_value(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) -{ - u8_t *data = short_buf; - u16_t data_len = sizeof(short_buf)/sizeof(u8_t); + void *buf, u16_t len, u16_t offset) +{ + u8_t *data = short_buf; + u16_t data_len = sizeof(short_buf)/sizeof(u8_t); - if(/*test_len8*/0) - { - data_len = test_len; - data = long_buf; - test_len = 0; - } - - return bt_gatt_attr_read(conn, attr, buf, len, offset, data,data_len); + if(/*test_len8*/0) + { + data_len = test_len; + data = long_buf; + test_len = 0; + } + + return bt_gatt_attr_read(conn, attr, buf, len, offset, data,data_len); } static ssize_t pts_read_long_value(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + void *buf, u16_t len, u16_t offset) { - u8_t *data = long_buf; - u16_t data_len = sizeof(long_buf)/sizeof(u8_t); + u8_t *data = long_buf; + u16_t data_len = sizeof(long_buf)/sizeof(u8_t); - /*Get new value */ - if(test_len > 0 && test_len <= TEST_LVAL_MAX) - { - data = long_buf; - data_len = test_len; - } - - return bt_gatt_attr_read(conn, attr, buf, len, offset, data,data_len); + /*Get new value */ + if(test_len > 0 && test_len <= TEST_LVAL_MAX) + { + data = long_buf; + data_len = test_len; + } + + return bt_gatt_attr_read(conn, attr, buf, len, offset, data,data_len); } static ssize_t pts_write_long_value( - struct bt_conn *conn, - const struct bt_gatt_attr *bt_attr, - void *buf,u16_t len, u16_t offset,u8_t flags) + struct bt_conn *conn, + const struct bt_gatt_attr *bt_attr, + void *buf,u16_t len, u16_t offset,u8_t flags) { - u16_t tlen = len; - u8_t *data = (u8_t*)buf; - u8_t i = 0; + u16_t tlen = len; + u8_t *data = (u8_t*)buf; + u8_t i = 0; - /*Reset test value */ - if(!offset) - { - test_len = 0; - (void)memset(long_buf,0,TEST_LVAL_MAX); - } - else if(offset > TEST_LVAL_MAX) - { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); - } + /*Reset test value */ + if(!offset) + { + test_len = 0; + (void)memset(long_buf,0,TEST_LVAL_MAX); + } + else if(offset > TEST_LVAL_MAX) + { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); + } - /*The rest of space is enough.*/ - if(TEST_LVAL_MAX - test_len >= tlen) - { - (void)memcpy(&long_buf[test_len],data,tlen); - test_len += tlen; - } - else - { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); - } - - /*If prepare write, it will return 0 */ - if(flags == BT_GATT_WRITE_FLAG_PREPARE) - tlen = 0; - - return tlen; + /*The rest of space is enough.*/ + if(TEST_LVAL_MAX - test_len >= tlen) + { + (void)memcpy(&long_buf[test_len],data,tlen); + test_len += tlen; + } + else + { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } + + /*If prepare write, it will return 0 */ + if(flags == BT_GATT_WRITE_FLAG_PREPARE) + tlen = 0; + + return tlen; } #endif /*PTS_GAP_SLAVER_CONFIG_WRITE_CHARC*/ #if defined(PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC) || defined(PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC) -static bool notify_status = 0; -static u8_t battery_level = 100; +static bool notify_status = 0; +static u8_t battery_level = 100; static void notify(const struct bt_gatt_attr *attr, u16_t value) { - ARG_UNUSED(attr); - - notify_status = (value == BT_GATT_CCC_NOTIFY); + ARG_UNUSED(attr); + + notify_status = (value == BT_GATT_CCC_NOTIFY); } static ssize_t pts_read_value( - struct bt_conn *conn, - const struct bt_gatt_attr *bt_attr, - void *buf,u16_t len, u16_t offset,u8_t flags) + struct bt_conn *conn, + const struct bt_gatt_attr *bt_attr, + void *buf,u16_t len, u16_t offset,u8_t flags) { - const char *data = "PTS_NAME"; - u16_t length = strlen(data); + const char *data = "PTS_NAME"; + u16_t length = strlen(data); - return bt_gatt_attr_read(conn, bt_attr, buf, len, offset, data,length); + return bt_gatt_attr_read(conn, bt_attr, buf, len, offset, data,length); } static ssize_t pts_write_value( - struct bt_conn *conn, - const struct bt_gatt_attr *bt_attr, - void *buf,u16_t len, u16_t offset,u8_t flags) + struct bt_conn *conn, + const struct bt_gatt_attr *bt_attr, + void *buf,u16_t len, u16_t offset,u8_t flags) { - return len; + return len; } #endif /*PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC*/ static ssize_t pts_read_chara_value( - struct bt_conn *conn, - const struct bt_gatt_attr *bt_attr, - void *buf,u16_t len, u16_t offset,u8_t flags) + struct bt_conn *conn, + const struct bt_gatt_attr *bt_attr, + void *buf,u16_t len, u16_t offset,u8_t flags) { - const char *data = "PTS_NAME0123456789abcde"; - u16_t length = strlen(data); + const char *data = "PTS_NAME0123456789abcde"; + u16_t length = strlen(data); - return bt_gatt_attr_read(conn, bt_attr, buf, len, offset, data,length); + return bt_gatt_attr_read(conn, bt_attr, buf, len, offset, data,length); } #if defined(PTS_CHARC_LEN_EQUAL_MTU_SIZE) static ssize_t pts_read_mtu_size( - struct bt_conn *conn, - const struct bt_gatt_attr *bt_attr, - void *buf,u16_t len, u16_t offset,u8_t flags) + struct bt_conn *conn, + const struct bt_gatt_attr *bt_attr, + void *buf,u16_t len, u16_t offset,u8_t flags) { - const char *data = "876543210123456789abcde"; - u16_t length = strlen(data); + const char *data = "876543210123456789abcde"; + u16_t length = strlen(data); - return bt_gatt_attr_read(conn, bt_attr, buf, len, offset, data,length); + return bt_gatt_attr_read(conn, bt_attr, buf, len, offset, data,length); } #endif #if defined(PTS_TEST_CASE_INSUFFICIENT_KEY) static ssize_t pts_read_value_with_key(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset,u8_t flags) -{ - const struct gatt_value *value = attr->user_data; - - if ((attr->perm & (BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_READ_AUTHEN)) && - (value->enc_key_size > bt_conn_enc_key_size(conn))) { - return BT_GATT_ERR(BT_ATT_ERR_ENCRYPTION_KEY_SIZE); - } + void *buf, u16_t len, u16_t offset,u8_t flags) +{ + const struct gatt_value *value = attr->user_data; - return bt_gatt_attr_read(conn, attr, buf, len, offset, value->data,value->len); + if ((attr->perm & (BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_READ_AUTHEN)) && + (value->enc_key_size > bt_conn_enc_key_size(conn))) { + return BT_GATT_ERR(BT_ATT_ERR_ENCRYPTION_KEY_SIZE); + } + + return bt_gatt_attr_read(conn, attr, buf, len, offset, value->data,value->len); } static ssize_t pts_write_value_with_key(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset,u8_t flags) -{ - const struct gatt_value *value = attr->user_data; - - if ((attr->perm & (BT_GATT_PERM_WRITE_ENCRYPT | BT_GATT_PERM_WRITE_AUTHEN )) && - (value->enc_key_size > bt_conn_enc_key_size(conn))) { - return BT_GATT_ERR(BT_ATT_ERR_ENCRYPTION_KEY_SIZE); - } + void *buf, u16_t len, u16_t offset,u8_t flags) +{ + const struct gatt_value *value = attr->user_data; - return len; + if ((attr->perm & (BT_GATT_PERM_WRITE_ENCRYPT | BT_GATT_PERM_WRITE_AUTHEN )) && + (value->enc_key_size > bt_conn_enc_key_size(conn))) { + return BT_GATT_ERR(BT_ATT_ERR_ENCRYPTION_KEY_SIZE); + } + + return len; } #endif static struct bt_gatt_attr pts_attr[] = { - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_AUTH_CHAR, - BT_GATT_CHRC_READ, - BT_GATT_PERM_READ_AUTHEN, - pts_read_chara_value, - NULL, - NULL - ), - - #if defined(PTS_TEST_CASE_INSUFFICIENT_KEY) - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_ENC_KEY, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_READ_ENCRYPT | - BT_GATT_PERM_WRITE | BT_GATT_PERM_WRITE_ENCRYPT | BT_GATT_PERM_PREPARE_WRITE, - pts_read_value_with_key, - pts_write_value_with_key, - &value - ), - #endif - - - #if defined(PTS_GAP_SLAVER_CONFIG_WRITE_CHARC) - - /* Case : GATT/SR/GAR/BV-03-C - * Verify that a Generic Attribute Profile server can support writing a Characteristic - * Value selected by handle - */ - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_WRITE_VALUE, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - pts_read_value, - pts_write_short_value, - NULL - ), - - - /* Case : GATT/SR/GAR/BV-01-C - * Verify that a Generic Attribute Profile server can support a write to a - * characteristic without response - */ BT_GATT_CHARACTERISTIC ( - BT_UUID_PTS_CHAR_WRITE_NORSP, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - pts_read_value, - pts_write_short_value, - NULL - ), - - /* Case : GATT/SR/GAR/BI-03-C, GATT/SR/GAR/BI-12-C - * Verify that a Generic Attribute Profile server can detect and reject a - * Write Characteristic Value Request to a non-writeable Characteristic Value - * and issue a Write Not Permitted Response. - */ - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_WRITE_AUTHEN, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_AUTHEN, - pts_read_long_value, - pts_write_long_value, - NULL - ), - - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_WRITE_AUTHEN, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_AUTHEN, - pts_read_value, - pts_write_long_value, - NULL - ), + BT_UUID_PTS_AUTH_CHAR, + BT_GATT_CHRC_READ, + BT_GATT_PERM_READ_AUTHEN, + pts_read_chara_value, + NULL, + NULL + ), - /* Case : GATT/SR/GAW/BV-05-C */ - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_WRITE_LONGVAL, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - pts_read_long_value, - pts_write_long_value, - NULL - ), - - /* Case : GATT/SR/GAW/BV-10-C */ + #if defined(PTS_TEST_CASE_INSUFFICIENT_KEY) BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_WRITE_2LONGVAL, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - pts_read_long_value, - pts_write_long_value, - NULL - ), + ( + BT_UUID_PTS_ENC_KEY, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_READ_ENCRYPT | + BT_GATT_PERM_WRITE | BT_GATT_PERM_WRITE_ENCRYPT | BT_GATT_PERM_PREPARE_WRITE, + pts_read_value_with_key, + pts_write_value_with_key, + &value + ), + #endif - BT_GATT_DESCRIPTOR - ( - BT_UUID_PTS_CHAR_WRITE_L_DES, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - pts_read_long_value, - pts_write_long_value, - NULL - ), + + #if defined(PTS_GAP_SLAVER_CONFIG_WRITE_CHARC) + + /* Case : GATT/SR/GAR/BV-03-C + * Verify that a Generic Attribute Profile server can support writing a Characteristic + * Value selected by handle + */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_WRITE_VALUE, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + pts_read_value, + pts_write_short_value, + NULL + ), + + + /* Case : GATT/SR/GAR/BV-01-C + * Verify that a Generic Attribute Profile server can support a write to a + * characteristic without response + */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_WRITE_NORSP, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE_WITHOUT_RESP, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + pts_read_value, + pts_write_short_value, + NULL + ), + + /* Case : GATT/SR/GAR/BI-03-C, GATT/SR/GAR/BI-12-C + * Verify that a Generic Attribute Profile server can detect and reject a + * Write Characteristic Value Request to a non-writeable Characteristic Value + * and issue a Write Not Permitted Response. + */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_WRITE_AUTHEN, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_AUTHEN, + pts_read_long_value, + pts_write_long_value, + NULL + ), + + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_WRITE_AUTHEN, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_AUTHEN, + pts_read_value, + pts_write_long_value, + NULL + ), + + /* Case : GATT/SR/GAW/BV-05-C */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_WRITE_LONGVAL, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + pts_read_long_value, + pts_write_long_value, + NULL + ), + + /* Case : GATT/SR/GAW/BV-10-C */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_WRITE_2LONGVAL, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + pts_read_long_value, + pts_write_long_value, + NULL + ), + + BT_GATT_DESCRIPTOR + ( + BT_UUID_PTS_CHAR_WRITE_L_DES, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + pts_read_long_value, + pts_write_long_value, + NULL + ), #endif - #if defined(PTS_GAP_SLAVER_CONFIG_READ_CHARC) - - /* Case : GATT/SR/GAR/BI-04-C - * Using authenticated link-key for read access. handle is 15 - */ - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_READ_AUTHEN, - BT_GATT_CHRC_READ, - BT_GATT_PERM_READ_AUTHEN, - read_pts_name, - NULL, - NULL - ), + #if defined(PTS_GAP_SLAVER_CONFIG_READ_CHARC) - /* Case : GATT/SR/GAR/BI-06-C - * Verify that a Generic Attribute Profile server can detect and reject a Read - * Characteristic by UUID Request to a non-readable Characteristic Value and issue - * a Read Not Permitted Response - */ - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_READ_NOPERM, - BT_GATT_CHRC_READ, - BT_GATT_PERM_NONE, - read_pts_name, - NULL, - NULL - ), + /* Case : GATT/SR/GAR/BI-04-C + * Using authenticated link-key for read access. handle is 15 + */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_READ_AUTHEN, + BT_GATT_CHRC_READ, + BT_GATT_PERM_READ_AUTHEN, + read_pts_name, + NULL, + NULL + ), - /* Case : GATT/SR/GAR/BV-04-C;GATT/SR/GAR/BI-13-C - * Verify that a Generic Attribute Profile server can support reading a - * long Characteristic Value selected by handle. - */ - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_READ_LONGVAL, - BT_GATT_CHRC_READ, - BT_GATT_PERM_READ, - read_pts_long_value, - NULL, - NULL - ), + /* Case : GATT/SR/GAR/BI-06-C + * Verify that a Generic Attribute Profile server can detect and reject a Read + * Characteristic by UUID Request to a non-readable Characteristic Value and issue + * a Read Not Permitted Response + */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_READ_NOPERM, + BT_GATT_CHRC_READ, + BT_GATT_PERM_NONE, + read_pts_name, + NULL, + NULL + ), - /* Case : GATT/SR/GAR/BV-06-C;GATT/SR/GAR/BV-07-C;GATT/SR/GAR/BV-08-C - * Verify that a Generic Attribute Profile server can support reading a Long - * Characteristic Descriptor selected by handle. - */ - BT_GATT_DESCRIPTOR - ( - BT_UUID_PTS_CHAR_READ_LVAL_REF, - BT_GATT_PERM_READ, - pts_read_report, - NULL, - report - ), - - /* Case : GATT/SR/GAR/BI-12-C - * Verify that a Generic Attribute Profile server can detect and reject a Read Long - * Characteristic Value Request to a non-readable Characteristic Value and issue a - * Read Not Permitted Response. - */ - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_READ_L_NOPERM, - BT_GATT_CHRC_READ, - BT_GATT_PERM_NONE, - read_pts_long_value, - NULL, - NULL - ), + /* Case : GATT/SR/GAR/BV-04-C;GATT/SR/GAR/BI-13-C + * Verify that a Generic Attribute Profile server can support reading a + * long Characteristic Value selected by handle. + */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_READ_LONGVAL, + BT_GATT_CHRC_READ, + BT_GATT_PERM_READ, + read_pts_long_value, + NULL, + NULL + ), - #endif /* PTS_GAP_SLAVER_CONFIG_READ_CHARC */ + /* Case : GATT/SR/GAR/BV-06-C;GATT/SR/GAR/BV-07-C;GATT/SR/GAR/BV-08-C + * Verify that a Generic Attribute Profile server can support reading a Long + * Characteristic Descriptor selected by handle. + */ + BT_GATT_DESCRIPTOR + ( + BT_UUID_PTS_CHAR_READ_LVAL_REF, + BT_GATT_PERM_READ, + pts_read_report, + NULL, + report + ), - #if defined(PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC) - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_NOTIFY_CHAR, - BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, - BT_GATT_PERM_READ , - pts_read_value, - NULL, - &battery_level - ), - - BT_GATT_CCC - ( - notify, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE - ), - #endif - - #if defined(PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC) - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_CHAR_INDICATE_CHAR, - BT_GATT_CHRC_READ | BT_GATT_CHRC_INDICATE, - BT_GATT_PERM_READ , - pts_read_value, - NULL, - &battery_level - ), - - BT_GATT_CCC - ( - notify, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE - ), - #endif - #if defined(PTS_CHARC_LEN_EQUAL_MTU_SIZE) - BT_GATT_CHARACTERISTIC - ( - BT_UUID_PTS_READ_MTU_SIZE_CHAR, - BT_GATT_CHRC_READ, - BT_GATT_PERM_READ, - pts_read_mtu_size, - NULL, - NULL - ), - #endif + /* Case : GATT/SR/GAR/BI-12-C + * Verify that a Generic Attribute Profile server can detect and reject a Read Long + * Characteristic Value Request to a non-readable Characteristic Value and issue a + * Read Not Permitted Response. + */ + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_READ_L_NOPERM, + BT_GATT_CHRC_READ, + BT_GATT_PERM_NONE, + read_pts_long_value, + NULL, + NULL + ), + + #endif /* PTS_GAP_SLAVER_CONFIG_READ_CHARC */ + + #if defined(PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC) + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_NOTIFY_CHAR, + BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, + BT_GATT_PERM_READ , + pts_read_value, + NULL, + &battery_level + ), + + BT_GATT_CCC + ( + notify, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE + ), + #endif + + #if defined(PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC) + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_CHAR_INDICATE_CHAR, + BT_GATT_CHRC_READ | BT_GATT_CHRC_INDICATE, + BT_GATT_PERM_READ , + pts_read_value, + NULL, + &battery_level + ), + + BT_GATT_CCC + ( + notify, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE + ), + #endif + #if defined(PTS_CHARC_LEN_EQUAL_MTU_SIZE) + BT_GATT_CHARACTERISTIC + ( + BT_UUID_PTS_READ_MTU_SIZE_CHAR, + BT_GATT_CHRC_READ, + BT_GATT_PERM_READ, + pts_read_mtu_size, + NULL, + NULL + ), + #endif }; @@ -717,86 +717,86 @@ struct bt_gatt_service pts_svc = BT_GATT_SERVICE(pts_attr); #if defined(PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC) static void notify_cb(struct bt_conn *conn, void *user_data) { - vOutputString("%s: Nofication sent to conn %p\r\n",__func__,conn); + vOutputString("%s: Nofication sent to conn %p\r\n",__func__,conn); } static void pts_ble_notify(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_gatt_notify_params params; - u8_t data = 0; - u16_t len = 0; - int err; + struct bt_gatt_notify_params params; + u8_t data = 0; + u16_t len = 0; + int err; - if(!default_conn){ - vOutputString("Not connected\r\n"); - return; - } - - get_uint16_from_string(&argv[1], &len); - get_bytearray_from_string(&argv[2], (u8_t *)&data,len); + if(!default_conn){ + vOutputString("Not connected\r\n"); + return; + } - memset(¶ms, 0, sizeof(params)); + get_uint16_from_string(&argv[1], &len); + get_bytearray_from_string(&argv[2], (u8_t *)&data,len); - params.uuid = pts_attr[1].uuid; - params.attr = &pts_attr[1]; - params.data = &data; - params.len = len; - params.func = notify_cb; + memset(¶ms, 0, sizeof(params)); - vOutputString("len = [0x%x]\r\n",params.len); - - err = bt_gatt_notify_cb(default_conn, ¶ms); - if(err){ - vOutputString("Failed to notifition [%d]\r\n",err); - } + params.uuid = pts_attr[1].uuid; + params.attr = &pts_attr[1]; + params.data = &data; + params.len = len; + params.func = notify_cb; + + vOutputString("len = [0x%x]\r\n",params.len); + + err = bt_gatt_notify_cb(default_conn, ¶ms); + if(err){ + vOutputString("Failed to notifition [%d]\r\n",err); + } } #endif /* PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC */ #if defined(PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC) static void indicate_cb(struct bt_conn *conn, const struct bt_gatt_attr *attr, - u8_t err) + u8_t err) { - if (err != 0U) { - vOutputString("Indication fail"); - } - else { - vOutputString("Indication success"); - } + if (err != 0U) { + vOutputString("Indication fail"); + } + else { + vOutputString("Indication success"); + } } static void pts_ble_indicate(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_gatt_indicate_params params; - u8_t data[16]; - u16_t len = 0; - int err; + struct bt_gatt_indicate_params params; + u8_t data[16]; + u16_t len = 0; + int err; - if(!default_conn){ - vOutputString("Not connected\r\n"); - return; - } - - get_uint16_from_string(&argv[1], &len); - - if(len > 16){ - len = 16; - } - - get_bytearray_from_string(&argv[2], data,len); + if(!default_conn){ + vOutputString("Not connected\r\n"); + return; + } - memset(¶ms, 0, sizeof(params)); + get_uint16_from_string(&argv[1], &len); - params.attr = &pts_attr[1]; - params.data = data; - params.len = len; - params.func = indicate_cb; + if(len > 16){ + len = 16; + } - vOutputString("len = [0x%x] handle(0x%x)\r\n",params.len,params.attr->handle); - - err = bt_gatt_indicate(default_conn, ¶ms); - if(err){ - vOutputString("Failed to indicate [%d]\r\n",err); - } + get_bytearray_from_string(&argv[2], data,len); + + memset(¶ms, 0, sizeof(params)); + + params.attr = &pts_attr[1]; + params.data = data; + params.len = len; + params.func = indicate_cb; + + vOutputString("len = [0x%x] handle(0x%x)\r\n",params.len,params.attr->handle); + + err = bt_gatt_indicate(default_conn, ¶ms); + if(err){ + vOutputString("Failed to indicate [%d]\r\n",err); + } } #endif /* PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC */ #endif /* CONFIG_BT_PERIPHERAL */ @@ -804,29 +804,29 @@ static void pts_ble_indicate(char *pcWriteBuffer, int xWriteBufferLen, int argc, #if defined(CONFIG_BT_OBSERVER) static bool data_cb(struct bt_data *data, void *user_data) { - char *name = user_data; + char *name = user_data; u8_t len; - switch (data->type) { - case BT_DATA_NAME_SHORTENED: - case BT_DATA_NAME_COMPLETE: + switch (data->type) { + case BT_DATA_NAME_SHORTENED: + case BT_DATA_NAME_COMPLETE: len = (data->data_len > NAME_LEN - 1)?(NAME_LEN - 1):(data->data_len); - memcpy(name, data->data, len); - return false; - default: - return true; - } + memcpy(name, data->data, len); + return false; + default: + return true; + } } static bool ad_flag_data_cb(struct bt_data *data, void *user_data) { char *ad_flag = user_data; - + switch(data->type){ case BT_DATA_FLAGS: memcpy(ad_flag, data->data, data->data_len); return false; - + default: return true; } @@ -837,43 +837,43 @@ static char *pts_short_name = "PTS-GAP"; extern bt_addr_le_t pts_addr; static void pts_device_found(const bt_addr_le_t *addr, s8_t rssi, u8_t evtype, - struct net_buf_simple *buf) + struct net_buf_simple *buf) { - char le_addr[BT_ADDR_LE_STR_LEN]; - char name[NAME_LEN]; - u8_t dst_address[6]; - char ad_flag[1]; - struct net_buf_simple abuf; - - (void)memset(ad_flag, 0, sizeof(ad_flag)); - (void)memset(dst_address, 0, sizeof(dst_address)); - memcpy(&abuf,buf,sizeof(struct net_buf_simple)); + char le_addr[BT_ADDR_LE_STR_LEN]; + char name[NAME_LEN]; + u8_t dst_address[6]; + char ad_flag[1]; + struct net_buf_simple abuf; + + (void)memset(ad_flag, 0, sizeof(ad_flag)); + (void)memset(dst_address, 0, sizeof(dst_address)); + memcpy(&abuf,buf,sizeof(struct net_buf_simple)); + + (void)memset(name, 0, sizeof(name)); + bt_data_parse(buf, data_cb, name); + bt_addr_le_to_str(addr, le_addr, sizeof(le_addr)); - (void)memset(name, 0, sizeof(name)); - bt_data_parse(buf, data_cb, name); - bt_addr_le_to_str(addr, le_addr, sizeof(le_addr)); - if(!memcmp(&pts_addr, addr, sizeof(bt_addr_le_t)) || !memcmp(name,pts_cmplt_name, sizeof(*pts_cmplt_name)) || !memcmp(name,pts_short_name, sizeof(*pts_short_name))){ - - if(memcmp(&pts_addr, addr, sizeof(bt_addr_le_t))) - memcpy(&pts_addr, addr, sizeof(pts_addr)); - - vOutputString("[DEVICE]: %s, AD evt type %u, RSSI %i %s \r\n",le_addr, evtype, rssi, name); - - bt_data_parse(&abuf,ad_flag_data_cb,ad_flag); - if(*ad_flag & 0x01){ - vOutputString("Advertising data : 'Limited Discovered Mode' flag is set one\r\n"); - }else - vOutputString("Advertising data : 'Limited Discovered Mode' flag is not set\r\n"); + if(memcmp(&pts_addr, addr, sizeof(bt_addr_le_t))) + memcpy(&pts_addr, addr, sizeof(pts_addr)); - if(*ad_flag & 0x02){ - vOutputString("Advertising data : 'General Discovered Mode' flag is set one\r\n"); + vOutputString("[DEVICE]: %s, AD evt type %u, RSSI %i %s \r\n",le_addr, evtype, rssi, name); + + bt_data_parse(&abuf,ad_flag_data_cb,ad_flag); + + if(*ad_flag & 0x01){ + vOutputString("Advertising data : 'Limited Discovered Mode' flag is set one\r\n"); }else - vOutputString("Advertising data : 'General Discovered Mode' flag is not set\r\n"); - } + vOutputString("Advertising data : 'Limited Discovered Mode' flag is not set\r\n"); + + if(*ad_flag & 0x02){ + vOutputString("Advertising data : 'General Discovered Mode' flag is set one\r\n"); + }else + vOutputString("Advertising data : 'General Discovered Mode' flag is not set\r\n"); + } } static void pts_ble_start_scan(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) @@ -888,14 +888,14 @@ static void pts_ble_start_scan(char *pcWriteBuffer, int xWriteBufferLen, int arg return; } - get_uint8_from_string(&argv[1], &scan_param.type); + get_uint8_from_string(&argv[1], &scan_param.type); get_uint8_from_string(&argv[2], &scan_param.filter_dup); - + get_uint16_from_string(&argv[3], &scan_param.interval); get_uint16_from_string(&argv[4], &scan_param.window); err = bt_le_scan_start(&scan_param, pts_device_found); - + if(err){ vOutputString("Failed to start scan (err %d) \r\n", err); }else{ @@ -905,23 +905,23 @@ static void pts_ble_start_scan(char *pcWriteBuffer, int xWriteBufferLen, int arg static void pts_ble_sc_indicate(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_gatt_indicate_params params; - u8_t data[16]; - u16_t len = 0; - int err; + struct bt_gatt_indicate_params params; + u8_t data[16]; + u16_t len = 0; + int err; - if(!default_conn){ - vOutputString("Not connected\r\n"); - return; - } + if(!default_conn){ + vOutputString("Not connected\r\n"); + return; + } - memset(¶ms, 0, sizeof(params)); - params.func = NULL; - err = service_change_test(¶ms,default_conn); - if(err){ - vOutputString("Failed to sc indicate\r\n"); - return; - } + memset(¶ms, 0, sizeof(params)); + params.func = NULL; + err = service_change_test(¶ms,default_conn); + if(err){ + vOutputString("Failed to sc indicate\r\n"); + return; + } } @@ -954,34 +954,34 @@ static void pts_ble_start_scan_rpa(char *pcWriteBuffer, int xWriteBufferLen, int static void pts_ble_add_peer_irk(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u8_t peer_key[16]; - - memset(peer_key,0,16); - - get_bytearray_from_string(&argv[1], peer_key,16); - reverse_bytearray(peer_key, peer_irk, 16); - vOutputString("peer_irk=[%s]\r\n",bt_hex(peer_irk, 16)); + u8_t peer_key[16]; + + memset(peer_key,0,16); + + get_bytearray_from_string(&argv[1], peer_key,16); + reverse_bytearray(peer_key, peer_irk, 16); + vOutputString("peer_irk=[%s]\r\n",bt_hex(peer_irk, 16)); } static void pts_ble_add_dev_to_resolve_list(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_keys key; - bt_addr_le_t addr; - u8_t type = 0; - u8_t val[6]; + struct bt_keys key; + bt_addr_le_t addr; + u8_t type = 0; + u8_t val[6]; - memset(&key,0,sizeof(struct bt_keys)); - - get_uint8_from_string(&argv[1], &type); - get_bytearray_from_string(&argv[2], val/*(uint8_t *)addr.a.val*/,6); - reverse_bytearray(val, addr.a.val, 6); - if(type == 0) - addr.type = BT_ADDR_LE_PUBLIC; - else if(type == 1) - addr.type = BT_ADDR_LE_RANDOM; + memset(&key,0,sizeof(struct bt_keys)); - memcpy(&key.addr,&addr,sizeof(bt_addr_le_t)); - memcpy(key.irk.val,peer_irk,16); + get_uint8_from_string(&argv[1], &type); + get_bytearray_from_string(&argv[2], val/*(uint8_t *)addr.a.val*/,6); + reverse_bytearray(val, addr.a.val, 6); + if(type == 0) + addr.type = BT_ADDR_LE_PUBLIC; + else if(type == 1) + addr.type = BT_ADDR_LE_RANDOM; + + memcpy(&key.addr,&addr,sizeof(bt_addr_le_t)); + memcpy(key.irk.val,peer_irk,16); bt_id_add(&key); @@ -991,140 +991,140 @@ static void pts_ble_add_dev_to_resolve_list(char *pcWriteBuffer, int xWriteBuffe #if defined(CONFIG_BT_PERIPHERAL) static void pts_ble_register_pts_svc(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; - - err = bt_gatt_service_register(&pts_svc); - if(err){ - vOutputString("Failed to register PTS service\r\n"); - }else{ - vOutputString("Succeed to register PTS service\r\n"); - } + int err; + + err = bt_gatt_service_register(&pts_svc); + if(err){ + vOutputString("Failed to register PTS service\r\n"); + }else{ + vOutputString("Succeed to register PTS service\r\n"); + } } #if defined(PTS_TEST_CASE_INSUFFICIENT_KEY) static int set_attr_enc_key_size(const struct bt_gatt_attr *attr, - u8_t key_size) + u8_t key_size) { - struct gatt_value *value; + struct gatt_value *value; - /* Fail if requested attribute is a service */ - /*if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) || - !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY) || - !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_INCLUDE)) { - return -1; - }*/ + /* Fail if requested attribute is a service */ + /*if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) || + !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY) || + !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_INCLUDE)) { + return -1; + }*/ - /* Fail if permissions are not set */ - /*if (!(attr->perm & ((BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_READ_AUTHEN) | - (BT_GATT_PERM_WRITE_ENCRYPT | BT_GATT_PERM_WRITE_AUTHEN)))) { - - return -1; - }*/ + /* Fail if permissions are not set */ + /*if (!(attr->perm & ((BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_READ_AUTHEN) | + (BT_GATT_PERM_WRITE_ENCRYPT | BT_GATT_PERM_WRITE_AUTHEN)))) { - vOutputString("perm:0x%x\r\n",attr->perm); - vOutputString("handle:0x%04x\r\n",attr->handle); - value = attr->user_data; - value->enc_key_size = key_size; + return -1; + }*/ - return 0; + vOutputString("perm:0x%x\r\n",attr->perm); + vOutputString("handle:0x%04x\r\n",attr->handle); + value = attr->user_data; + value->enc_key_size = key_size; + + return 0; } static void pts_set_enc_key_size(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u8_t key_size; - u8_t index; - int err; - - get_uint8_from_string(&argv[1], &key_size); - get_uint8_from_string(&argv[2], &index); - - if(key_size < 0x07 || key_size > 0x0f) - vOutputString("Invalid key size(%d)\r\n",key_size); - else{ - err = set_attr_enc_key_size(&pts_attr[index],key_size); - if(err){ - vOutputString("Failed to set attr enc key size(%d)\r\n",err); - } - } + u8_t key_size; + u8_t index; + int err; + + get_uint8_from_string(&argv[1], &key_size); + get_uint8_from_string(&argv[2], &index); + + if(key_size < 0x07 || key_size > 0x0f) + vOutputString("Invalid key size(%d)\r\n",key_size); + else{ + err = set_attr_enc_key_size(&pts_attr[index],key_size); + if(err){ + vOutputString("Failed to set attr enc key size(%d)\r\n",err); + } + } } #endif //PTS_TEST_CASE_INSUFFICIENT_KEY #endif #if defined(CONFIG_BT_WHITELIST) static void pts_ble_wl_connect(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; - unsigned char enable = 0U; - struct bt_le_conn_param param = { - .interval_min = BT_GAP_INIT_CONN_INT_MIN, - .interval_max = BT_GAP_INIT_CONN_INT_MAX, - .latency = 0, - .timeout = 400, - }; - /*Auto connect whitelist device, enable : 0x01, disable : 0x02*/ - get_uint8_from_string(&argv[1], &enable); - /*Address type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ - get_uint8_from_string(&argv[2], ¶m.own_address_type); + int err; + unsigned char enable = 0U; + struct bt_le_conn_param param = { + .interval_min = BT_GAP_INIT_CONN_INT_MIN, + .interval_max = BT_GAP_INIT_CONN_INT_MAX, + .latency = 0, + .timeout = 400, + }; + /*Auto connect whitelist device, enable : 0x01, disable : 0x02*/ + get_uint8_from_string(&argv[1], &enable); + /*Address type, 0:ADDR_PUBLIC, 1:ADDR_RAND, 2:ADDR_RPA_OR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ + get_uint8_from_string(&argv[2], ¶m.own_address_type); - if(enable == 0x01){ - err = bt_conn_create_auto_le(¶m); - if(err){ - vOutputString("Auto connect failed (err = [%d])\r\n",err); - return; - }else{ - vOutputString("Auto connection is succeed\r\n"); - } - }else if(enable == 0x02){ - err = bt_conn_create_auto_stop(); - if(err){ - vOutputString("Auto connection stop (err = [%d])\r\n",err); - return ; - } - } + if(enable == 0x01){ + err = bt_conn_create_auto_le(¶m); + if(err){ + vOutputString("Auto connect failed (err = [%d])\r\n",err); + return; + }else{ + vOutputString("Auto connection is succeed\r\n"); + } + }else if(enable == 0x02){ + err = bt_conn_create_auto_stop(); + if(err){ + vOutputString("Auto connection stop (err = [%d])\r\n",err); + return ; + } + } } static void pts_ble_bt_le_whitelist_add(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - bt_addr_le_t waddr; - int err; - u8_t val[6]; - - if(argc != 3){ - vOutputString("Number of Parameters is not correct (argc = [%d])\r\n",argc); - return; - } + bt_addr_le_t waddr; + int err; + u8_t val[6]; - err = bt_le_whitelist_clear(); - if(err){ - vOutputString("Clear white list device failed (err = [%d])\r\n",err); - } + if(argc != 3){ + vOutputString("Number of Parameters is not correct (argc = [%d])\r\n",argc); + return; + } - get_uint8_from_string(&argv[1], &waddr.type); - get_bytearray_from_string(&argv[2], val,6); - - reverse_bytearray(val, waddr.a.val, 6); + err = bt_le_whitelist_clear(); + if(err){ + vOutputString("Clear white list device failed (err = [%d])\r\n",err); + } - err = bt_le_whitelist_add(&waddr); - if(err){ - vOutputString("Failed to add device to whitelist (err = [%d])\r\n",err); - } + get_uint8_from_string(&argv[1], &waddr.type); + get_bytearray_from_string(&argv[2], val,6); + + reverse_bytearray(val, waddr.a.val, 6); + + err = bt_le_whitelist_add(&waddr); + if(err){ + vOutputString("Failed to add device to whitelist (err = [%d])\r\n",err); + } } -#endif +#endif static void pts_ble_start_scan_timeout(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_le_scan_param scan_param; - uint16_t time = 0; + struct bt_le_scan_param scan_param; + uint16_t time = 0; int err; - u8_t addre_type; - + u8_t addre_type; + get_uint8_from_string(&argv[1], &scan_param.type); get_uint8_from_string(&argv[2], &scan_param.filter_dup); get_uint16_from_string(&argv[3], &scan_param.interval); get_uint16_from_string(&argv[4], &scan_param.window); get_uint8_from_string(&argv[5], (uint8_t *)&addre_type); - get_uint16_from_string(&argv[6], (uint16_t *)&time); - + get_uint16_from_string(&argv[6], (uint16_t *)&time); + err = bt_le_pts_scan_start(&scan_param, pts_device_found, addre_type); if(err){ vOutputString("Failed to start scan (err %d) \r\n", err); @@ -1132,76 +1132,76 @@ static void pts_ble_start_scan_timeout(char *pcWriteBuffer, int xWriteBufferLen, vOutputString("Start scan successfully \r\n"); } - k_sleep(time); - bt_le_scan_stop(); - vOutputString("Scan stop \r\n"); + k_sleep(time); + bt_le_scan_stop(); + vOutputString("Scan stop \r\n"); } static void pts_ble_address_register(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - bt_addr_le_t addr; - u8_t type; - char le_addr[BT_ADDR_LE_STR_LEN]; - - get_uint8_from_string(&argv[1], &type); - get_bytearray_from_string(&argv[2], addr.a.val,6); + bt_addr_le_t addr; + u8_t type; + char le_addr[BT_ADDR_LE_STR_LEN]; - if(type == 0){ - addr.type = BT_ADDR_LE_PUBLIC; - }else if(type == 1) - addr.type = BT_ADDR_LE_RANDOM; + get_uint8_from_string(&argv[1], &type); + get_bytearray_from_string(&argv[2], addr.a.val,6); - memcpy(&pts_addr,&addr,sizeof(bt_addr_le_t)); + if(type == 0){ + addr.type = BT_ADDR_LE_PUBLIC; + }else if(type == 1) + addr.type = BT_ADDR_LE_RANDOM; - bt_addr_le_to_str(&pts_addr, le_addr, sizeof(le_addr)); - - memcpy(pts_address,pts_addr.a.val,6); + memcpy(&pts_addr,&addr,sizeof(bt_addr_le_t)); - vOutputString("Pts address %s \r\n",le_addr); + bt_addr_le_to_str(&pts_addr, le_addr, sizeof(le_addr)); + + memcpy(pts_address,pts_addr.a.val,6); + + vOutputString("Pts address %s \r\n",le_addr); } static void pts_ble_set_flag(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u8_t flag; - get_uint8_from_string(&argv[1],&flag); - event_flag = flag; - - vOutputString("Event flag = [0x%x] \r\n",event_flag); + u8_t flag; + get_uint8_from_string(&argv[1],&flag); + event_flag = flag; + + vOutputString("Event flag = [0x%x] \r\n",event_flag); } static void pts_ble_set_smp_flag(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u8_t flag; - - get_uint8_from_string(&argv[1],&flag); - bt_set_smpflag((smp_test_id)flag); + u8_t flag; - vOutputString("Smp flag = [0x%x] \r\n",flag); + get_uint8_from_string(&argv[1],&flag); + bt_set_smpflag((smp_test_id)flag); + + vOutputString("Smp flag = [0x%x] \r\n",flag); } static void pts_ble_clear_smp_flag(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u8_t flag; - - get_uint8_from_string(&argv[1],&flag); - bt_clear_smpflag((smp_test_id)flag); + u8_t flag; - vOutputString("Clear smp flag \r\n"); + get_uint8_from_string(&argv[1],&flag); + bt_clear_smpflag((smp_test_id)flag); + + vOutputString("Clear smp flag \r\n"); } static void pts_ble_bondable(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u8_t bondable; + u8_t bondable; - get_uint8_from_string(&argv[1], &bondable); + get_uint8_from_string(&argv[1], &bondable); - if(bondable == 0x01) - bt_set_bondable(true); - else if(bondable == 0x00) - bt_set_bondable(false); - else - vOutputString("Bondable status is unknow \r\n"); + if(bondable == 0x01) + bt_set_bondable(true); + else if(bondable == 0x00) + bt_set_bondable(false); + else + vOutputString("Bondable status is unknow \r\n"); } #endif //#if defined(CONFIG_BT_OBSERVER) @@ -1211,94 +1211,94 @@ static void pts_ble_bondable(char *pcWriteBuffer, int xWriteBufferLen, int argc, static void pts_ble_start_advertise(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { struct bt_le_adv_param param; - const struct bt_data *ad; - size_t ad_len=0; - int err = 0; + const struct bt_data *ad; + size_t ad_len=0; + int err = 0; uint8_t adv_type, tmp; struct bt_data pts_ad ; - bt_addr_le_t pts; - struct bt_conn *conn; - u8_t adder_type = 0; - u8_t is_ad = 0; - - memset(pts.a.val,0,6); - memset(&pts_ad,0,sizeof(struct bt_data)); + bt_addr_le_t pts; + struct bt_conn *conn; + u8_t adder_type = 0; + u8_t is_ad = 0; + + memset(pts.a.val,0,6); + memset(&pts_ad,0,sizeof(struct bt_data)); if(argc != 4 && argc != 6){ vOutputString("Number of Parameters is not correct\r\n"); return; } - switch(event_flag){ - case ad_type_service_uuid: - pts_ad.type = BT_DATA_UUID128_ALL; - pts_ad.data = service_uuid; - pts_ad.data_len = sizeof(service_uuid); - is_ad = 1; - break; - - case ad_type_local_name: - pts_ad.type = BT_DATA_NAME_COMPLETE; - pts_ad.data = name; - pts_ad.data_len = 13; - is_ad = 1; - break; + switch(event_flag){ + case ad_type_service_uuid: + pts_ad.type = BT_DATA_UUID128_ALL; + pts_ad.data = service_uuid; + pts_ad.data_len = sizeof(service_uuid); + is_ad = 1; + break; - case ad_type_flags: - pts_ad.type = BT_DATA_FLAGS; - pts_ad.data = discover_mode; - pts_ad.data_len = sizeof(discover_mode); - is_ad = 1; - break; + case ad_type_local_name: + pts_ad.type = BT_DATA_NAME_COMPLETE; + pts_ad.data = name; + pts_ad.data_len = 13; + is_ad = 1; + break; + + case ad_type_flags: + pts_ad.type = BT_DATA_FLAGS; + pts_ad.data = discover_mode; + pts_ad.data_len = sizeof(discover_mode); + is_ad = 1; + break; case ad_type_manu_data: - pts_ad.type = BT_DATA_MANUFACTURER_DATA; - pts_ad.data = data_manu; - pts_ad.data_len = sizeof(data_manu); - is_ad = 1; - break; + pts_ad.type = BT_DATA_MANUFACTURER_DATA; + pts_ad.data = data_manu; + pts_ad.data_len = sizeof(data_manu); + is_ad = 1; + break; - case ad_type_tx_power_level: - pts_ad.type = BT_DATA_TX_POWER; - pts_ad.data = tx_power; - pts_ad.data_len = sizeof(tx_power); - is_ad = 1; - break; + case ad_type_tx_power_level: + pts_ad.type = BT_DATA_TX_POWER; + pts_ad.data = tx_power; + pts_ad.data_len = sizeof(tx_power); + is_ad = 1; + break; case ad_type_service_data: - pts_ad.type = BT_DATA_SVC_DATA16; - pts_ad.data = service_data; - pts_ad.data_len = sizeof(service_data); - is_ad = 1; - break; + pts_ad.type = BT_DATA_SVC_DATA16; + pts_ad.data = service_data; + pts_ad.data_len = sizeof(service_data); + is_ad = 1; + break; case ad_type_appearance: - pts_ad.type = BT_DATA_GAP_APPEARANCE; - pts_ad.data = data_appearance; - pts_ad.data_len = sizeof(data_appearance); - is_ad = 1; - break; - - default: - break; - } - + pts_ad.type = BT_DATA_GAP_APPEARANCE; + pts_ad.data = data_appearance; + pts_ad.data_len = sizeof(data_appearance); + is_ad = 1; + break; + + default: + break; + } + param.id = selected_id; param.interval_min = BT_GAP_ADV_FAST_INT_MIN_2; param.interval_max = BT_GAP_ADV_FAST_INT_MAX_2; /*Get adv type, 0:adv_ind, 1:adv_scan_ind, 2:adv_nonconn_ind 3: adv_direct_ind*/ get_uint8_from_string(&argv[1], &adv_type); - + if(adv_type == 0){ param.options = (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_USE_NAME | BT_LE_ADV_OPT_ONE_TIME); }else if(adv_type == 1){ param.options = BT_LE_ADV_OPT_USE_NAME; }else if(adv_type == 2){ param.options = 0; - }else if(adv_type == 3){ - param.options = (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME); + }else if(adv_type == 3){ + param.options = (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME); }else if(adv_type == 4){ - param.options = (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY | BT_LE_ADV_OPT_ONE_TIME); + param.options = (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY | BT_LE_ADV_OPT_ONE_TIME); } else{ vOutputString("Arg1 is invalid\r\n"); @@ -1317,19 +1317,19 @@ static void pts_ble_start_advertise(char *pcWriteBuffer, int xWriteBufferLen, in ad = ad_non_discov; ad_len = 1; } - else if(tmp == 2){ - ad_discov[0].data = &discover_mode[0]; - ad = ad_discov; - ad_len = ARRAY_SIZE(ad_discov); - } - if(is_ad == 1){ - ad = &pts_ad; - ad_len = 1; - }/*else{ - ad = ad_discov; - ad_len = ARRAY_SIZE(ad_discov); - }*/ - + else if(tmp == 2){ + ad_discov[0].data = &discover_mode[0]; + ad = ad_discov; + ad_len = ARRAY_SIZE(ad_discov); + } + if(is_ad == 1){ + ad = &pts_ad; + ad_len = 1; + }/*else{ + ad = ad_discov; + ad_len = ARRAY_SIZE(ad_discov); + }*/ + }else{ vOutputString("Arg2 is invalid\r\n"); return; @@ -1339,53 +1339,53 @@ static void pts_ble_start_advertise(char *pcWriteBuffer, int xWriteBufferLen, in //get_bytearray_from_string(&argv[3], (u8_t *)¶m.addr_type, 1); get_uint8_from_string(&argv[3], (u8_t *)&adder_type); - if(adder_type == 0) - param.addr_type = BT_ADDR_TYPE_NON_RPA; - else if(adder_type == 1) - param.addr_type = BT_ADDR_TYPE_RPA; - else if(adder_type == 2) - param.addr_type = BT_ADDR_LE_PUBLIC; - else - vOutputString("Invaild address type\r\n"); - + if(adder_type == 0) + param.addr_type = BT_ADDR_TYPE_NON_RPA; + else if(adder_type == 1) + param.addr_type = BT_ADDR_TYPE_RPA; + else if(adder_type == 2) + param.addr_type = BT_ADDR_LE_PUBLIC; + else + vOutputString("Invaild address type\r\n"); + if(argc == 6){ get_uint16_from_string(&argv[4], ¶m.interval_min); get_uint16_from_string(&argv[5], ¶m.interval_max); - } + } + + if(adv_type == 3){ + param.interval_min = 0; + param.interval_max = 0; + } - if(adv_type == 3){ - param.interval_min = 0; - param.interval_max = 0; - } - if(adv_type == 1){ - err = bt_le_adv_start(¶m, ad, ad_len, &ad_discov[0], 1); + err = bt_le_adv_start(¶m, ad, ad_len, &ad_discov[0], 1); }else if(adv_type == 3 || adv_type == 4){ - pts.type = BT_ADDR_LE_PUBLIC; - memcpy(pts.a.val,pts_address,6); - conn = bt_conn_create_slave_le(&pts,¶m); - if(!conn){ - err = 1; - } - else{ - bt_conn_unref(conn); - } + pts.type = BT_ADDR_LE_PUBLIC; + memcpy(pts.a.val,pts_address,6); + conn = bt_conn_create_slave_le(&pts,¶m); + if(!conn){ + err = 1; + } + else{ + bt_conn_unref(conn); + } }else{ err = bt_le_adv_start(¶m, ad, ad_len, NULL, 0); } - + if(err){ vOutputString("Failed to start advertising\r\n"); }else{ vOutputString("Advertising started\r\n"); } - if(tmp == 2){ - k_sleep(LIM_ADV_TIME); - bt_le_adv_stop(); - vOutputString("Adv timeout \r\n"); - } + if(tmp == 2){ + k_sleep(LIM_ADV_TIME); + bt_le_adv_stop(); + vOutputString("Adv timeout \r\n"); + } } @@ -1398,38 +1398,38 @@ static void pts_ble_connect_le(char *pcWriteBuffer, int xWriteBufferLen, int arg bt_addr_le_t addr; struct bt_conn *conn; u8_t addr_val[6]; - s8_t type = -1; + s8_t type = -1; - struct bt_le_conn_param param = { - .interval_min = BT_GAP_INIT_CONN_INT_MIN, - .interval_max = BT_GAP_INIT_CONN_INT_MAX, - .latency = 0, - .timeout = 400, - .own_address_type = BT_ADDR_LE_PUBLIC_ID, + struct bt_le_conn_param param = { + .interval_min = BT_GAP_INIT_CONN_INT_MIN, + .interval_max = BT_GAP_INIT_CONN_INT_MAX, + .latency = 0, + .timeout = 400, + .own_address_type = BT_ADDR_LE_PUBLIC_ID, - }; + }; if(argc != 4){ vOutputString("Number of Parameters is not correct\r\n"); return; } - if(event_flag == own_addr_type_random){ - param.own_address_type = BT_ADDR_LE_RANDOM_ID; - } - + if(event_flag == own_addr_type_random){ + param.own_address_type = BT_ADDR_LE_RANDOM_ID; + } + get_uint8_from_string(&argv[1], (u8_t *)&type); - /*Get addr type,0:ADDR_RAND, 1:ADDR_RPA_OR_PUBLIC,2:ADDR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ - if(type == 0) - addr.type = 1; /*ADDR_RAND*/ - else if(type == 1) - addr.type = 2; /*ADDR_RPA_OR_PUBLIC*/ - else if(type == 2) - addr.type = 0; /*ADDR_PUBLIC*/ - else if(type == 3) - addr.type = 3; /*ADDR_RPA_OR_RAND*/ - else - vOutputString("adderss type is unknow [0x%x]\r\n",type); + /*Get addr type,0:ADDR_RAND, 1:ADDR_RPA_OR_PUBLIC,2:ADDR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ + if(type == 0) + addr.type = 1; /*ADDR_RAND*/ + else if(type == 1) + addr.type = 2; /*ADDR_RPA_OR_PUBLIC*/ + else if(type == 2) + addr.type = 0; /*ADDR_PUBLIC*/ + else if(type == 3) + addr.type = 3; /*ADDR_RPA_OR_RAND*/ + else + vOutputString("adderss type is unknow [0x%x]\r\n",type); get_bytearray_from_string(&argv[2], addr_val,6); @@ -1438,16 +1438,16 @@ static void pts_ble_connect_le(char *pcWriteBuffer, int xWriteBufferLen, int arg get_uint8_from_string(&argv[3], (u8_t *)&type); if(type == 0) - param.own_address_type = 1; /*ADDR_RAND*/ - else if(type == 1) - param.own_address_type = 2; /*ADDR_RPA_OR_PUBLIC*/ - else if(type == 2) - param.own_address_type = 0; /*ADDR_PUBLIC*/ - else if(type == 3) - param.own_address_type = 3; /*ADDR_RPA_OR_RAND*/ - else - vOutputString("adderss type is unknow [0x%x]\r\n",type); - + param.own_address_type = 1; /*ADDR_RAND*/ + else if(type == 1) + param.own_address_type = 2; /*ADDR_RPA_OR_PUBLIC*/ + else if(type == 2) + param.own_address_type = 0; /*ADDR_PUBLIC*/ + else if(type == 3) + param.own_address_type = 3; /*ADDR_RPA_OR_RAND*/ + else + vOutputString("adderss type is unknow [0x%x]\r\n",type); + conn = bt_conn_create_le(&addr, /*BT_LE_CONN_PARAM_DEFAULT*/¶m); if(!conn){ @@ -1464,8 +1464,8 @@ static void pts_ble_disconnect(char *pcWriteBuffer, int xWriteBufferLen, int arg bt_addr_le_t addr; u8_t addr_val[6]; struct bt_conn *conn; - s8_t type = -1; - + s8_t type = -1; + if(argc != 3){ vOutputString("Number of Parameters is not correct\r\n"); return; @@ -1474,17 +1474,17 @@ static void pts_ble_disconnect(char *pcWriteBuffer, int xWriteBufferLen, int arg get_bytearray_from_string(&argv[2], addr_val,6); reverse_bytearray(addr_val, addr.a.val, 6); - /*Get addr type,0:ADDR_RAND, 1:ADDR_RPA_OR_PUBLIC,2:ADDR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ - if(type == 0) - addr.type = 1; /*ADDR_RAND*/ - else if(type == 1) - addr.type = 2; /*ADDR_RPA_OR_PUBLIC*/ - else if(type == 2) - addr.type = 0; /*ADDR_PUBLIC*/ - else if(type == 3) - addr.type = 3; /*ADDR_RPA_OR_RAND*/ - else - vOutputString("adderss type is unknow\r\n"); + /*Get addr type,0:ADDR_RAND, 1:ADDR_RPA_OR_PUBLIC,2:ADDR_PUBLIC, 3:ADDR_RPA_OR_RAND*/ + if(type == 0) + addr.type = 1; /*ADDR_RAND*/ + else if(type == 1) + addr.type = 2; /*ADDR_RPA_OR_PUBLIC*/ + else if(type == 2) + addr.type = 0; /*ADDR_PUBLIC*/ + else if(type == 3) + addr.type = 3; /*ADDR_RPA_OR_RAND*/ + else + vOutputString("adderss type is unknow\r\n"); conn = bt_conn_lookup_addr_le(selected_id, &addr); @@ -1503,49 +1503,49 @@ static void pts_ble_disconnect(char *pcWriteBuffer, int xWriteBufferLen, int arg static void pts_ble_conn_update(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - struct bt_le_conn_param param; - int err; + struct bt_le_conn_param param; + int err; if(argc != 5){ vOutputString("Number of Parameters is not correct\r\n"); return; } - if(default_conn == NULL){ - vOutputString("Connection is NULL\r\n"); + if(default_conn == NULL){ + vOutputString("Connection is NULL\r\n"); return; - } - memset(¶m,0,sizeof(struct bt_le_conn_param)); + } + memset(¶m,0,sizeof(struct bt_le_conn_param)); get_uint16_from_string(&argv[1], ¶m.interval_min); get_uint16_from_string(&argv[2], ¶m.interval_max); get_uint16_from_string(&argv[3], ¶m.latency); - get_uint16_from_string(&argv[4], ¶m.timeout); + get_uint16_from_string(&argv[4], ¶m.timeout); - if(event_flag == dir_connect_req) - err = bt_conn_le_param_update(default_conn, ¶m); - else - err = pts_bt_conn_le_param_update(default_conn, ¶m); + if(event_flag == dir_connect_req) + err = bt_conn_le_param_update(default_conn, ¶m); + else + err = pts_bt_conn_le_param_update(default_conn, ¶m); - if (err) { - vOutputString("conn update failed (err %d)\r\n", err); - } else { - vOutputString("conn update initiated\r\n"); - } + if (err) { + vOutputString("conn update failed (err %d)\r\n", err); + } else { + vOutputString("conn update initiated\r\n"); + } } #endif //#if defined(CONFIG_BT_CONN) #if defined(CONFIG_BT_SMP) static void pts_ble_set_mitm(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - u8_t enable = 0; + u8_t enable = 0; - get_uint8_from_string(&argv[1],&enable); + get_uint8_from_string(&argv[1],&enable); - if(enable == 0x01) - bt_set_mitm(true); - else if(enable == 0x00) - bt_set_mitm(false); - else - vOutputString("Inviad parameter\r\n"); + if(enable == 0x01) + bt_set_mitm(true); + else if(enable == 0x00) + bt_set_mitm(false); + else + vOutputString("Inviad parameter\r\n"); } #endif //#if defined(CONFIG_BT_SMP) @@ -1558,20 +1558,20 @@ static struct bt_uuid_128 uuid_128 = BT_UUID_INIT_128(0); extern u8_t discover_func(struct bt_conn *conn, const struct bt_gatt_attr *attr, struct bt_gatt_discover_params *params); static void pts_ble_discover_uuid_128(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; + int err; u8_t disc_type; - u8_t val[16]; + u8_t val[16]; - (void)memset(val,0x0,16); - - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } - - discover_params.func = discover_func; - discover_params.start_handle = 0x0001; - discover_params.end_handle = 0xffff; + (void)memset(val,0x0,16); + + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } + + discover_params.func = discover_func; + discover_params.start_handle = 0x0001; + discover_params.end_handle = 0xffff; get_uint8_from_string(&argv[1], &disc_type); if(disc_type == 0){ @@ -1588,27 +1588,27 @@ static void pts_ble_discover_uuid_128(char *pcWriteBuffer, int xWriteBufferLen, vOutputString("Invalid discovery type\r\n"); return; } - get_bytearray_from_string(&argv[2], val,16); + get_bytearray_from_string(&argv[2], val,16); + + reverse_bytearray(val, uuid_128.val,16); + + /*Set array value to 0 */ + (void)memset(val, 0x0, 16); + + if(!memcmp(uuid_128.val, val, 16)) + discover_params.uuid = NULL; + else + discover_params.uuid = &uuid_128.uuid; - reverse_bytearray(val, uuid_128.val,16); - - /*Set array value to 0 */ - (void)memset(val, 0x0, 16); - - if(!memcmp(uuid_128.val, val, 16)) - discover_params.uuid = NULL; - else - discover_params.uuid = &uuid_128.uuid; - get_uint16_from_string(&argv[3], &discover_params.start_handle); get_uint16_from_string(&argv[4], &discover_params.end_handle); - err = bt_gatt_discover(default_conn, &discover_params); - if (err) { - vOutputString("Discover failed (err %d)\r\n", err); - } else { - vOutputString("Discover pending\r\n"); - } + err = bt_gatt_discover(default_conn, &discover_params); + if (err) { + vOutputString("Discover failed (err %d)\r\n", err); + } else { + vOutputString("Discover pending\r\n"); + } } @@ -1616,143 +1616,143 @@ static struct bt_gatt_read_params read_params; static u8_t read_func(struct bt_conn *conn, u8_t err, struct bt_gatt_read_params *params, const void *data, u16_t length) { - vOutputString("Read complete: err %u length %u \r\n", err, length); + vOutputString("Read complete: err %u length %u \r\n", err, length); - char str[22]; - u8_t *buf = (u8_t *)data; + char str[22]; + u8_t *buf = (u8_t *)data; - memset(str,0,15); - - if(length > 0 && length <= sizeof(str)){ - memcpy(str,buf,length); - vOutputString("device name : %s \r\n",str); - - u8_t i = 0; - for(i=0;i 0 && length <= sizeof(str)){ + memcpy(str,buf,length); + vOutputString("device name : %s \r\n",str); - return BT_GATT_ITER_CONTINUE; + u8_t i = 0; + for(i=0;i ARRAY_SIZE(h)){ - vOutputString("Enter max %lu handle items to read\r\n",ARRAY_SIZE(h)); - return; - } + if((argc-1) > ARRAY_SIZE(h)){ + vOutputString("Enter max %lu handle items to read\r\n",ARRAY_SIZE(h)); + return; + } - for (i = 0; i < argc - 1; i++) { - get_uint16_from_string(&argv[i + 1],&h[i]); - } + for (i = 0; i < argc - 1; i++) { + get_uint16_from_string(&argv[i + 1],&h[i]); + } - read_params.func = read_func; - read_params.handle_count = i; - read_params.handles = h; /* not used in read func */ + read_params.func = read_func; + read_params.handle_count = i; + read_params.handles = h; /* not used in read func */ - vOutputString("i = [%d]\r\n",i); - - err = bt_gatt_read(default_conn, &read_params); - if (err) { - vOutputString("Read failed (err %d)\r\n", err); - } else { - vOutputString("Read pending\r\n"); - } + vOutputString("i = [%d]\r\n",i); + + err = bt_gatt_read(default_conn, &read_params); + if (err) { + vOutputString("Read failed (err %d)\r\n", err); + } else { + vOutputString("Read pending\r\n"); + } } @@ -1760,50 +1760,50 @@ static struct bt_gatt_write_params write_params; static u8_t gatt_write_buf[CHAR_SIZE_MAX]; static void write_func(struct bt_conn *conn, u8_t err, - struct bt_gatt_write_params *params) + struct bt_gatt_write_params *params) { - vOutputString("Write complete: err %u \r\n", err); + vOutputString("Write complete: err %u \r\n", err); - (void)memset(&write_params, 0, sizeof(write_params)); + (void)memset(&write_params, 0, sizeof(write_params)); } static void pts_ble_prepare_write(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv) { - int err; + int err; uint16_t data_len; if(argc != 5){ vOutputString("Number of Parameters is not correct\r\n"); return; } - - if (!default_conn) { - vOutputString("Not connected\r\n"); - return; - } - if (write_params.func) { - vOutputString("Write ongoing\r\n"); - return; - } + if (!default_conn) { + vOutputString("Not connected\r\n"); + return; + } + + if (write_params.func) { + vOutputString("Write ongoing\r\n"); + return; + } get_uint16_from_string(&argv[1], &write_params.handle); get_uint16_from_string(&argv[2], &write_params.offset); get_uint16_from_string(&argv[3], &write_params.length); data_len = write_params.length > sizeof(gatt_write_buf)? (sizeof(gatt_write_buf)):(write_params.length); get_bytearray_from_string(&argv[4], gatt_write_buf,data_len); - - write_params.data = gatt_write_buf; - write_params.length = data_len; - write_params.func = write_func; - - err = bt_gatt_prepare_write(default_conn, &write_params); - if (err) { - vOutputString("Prepare write failed (err %d)\r\n", err); - } else { - vOutputString("Prepare write pending\r\n"); - } + write_params.data = gatt_write_buf; + write_params.length = data_len; + write_params.func = write_func; + + err = bt_gatt_prepare_write(default_conn, &write_params); + + if (err) { + vOutputString("Prepare write failed (err %d)\r\n", err); + } else { + vOutputString("Prepare write pending\r\n"); + } } diff --git a/components/network/ble/blestack/src/common/atomic_c.c b/components/network/ble/blestack/src/common/atomic_c.c index 591e27b9..3d103b06 100644 --- a/components/network/ble/blestack/src/common/atomic_c.c +++ b/components/network/ble/blestack/src/common/atomic_c.c @@ -44,21 +44,21 @@ * @return Returns 1 if is written, 0 otherwise. */ int atomic_cas(atomic_t *target, atomic_val_t old_value, - atomic_val_t new_value) + atomic_val_t new_value) { - unsigned int key; - int ret = 0; + unsigned int key; + int ret = 0; - key = irq_lock(); + key = irq_lock(); - if (*target == old_value) { - *target = new_value; - ret = 1; - } + if (*target == old_value) { + *target = new_value; + ret = 1; + } - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -76,17 +76,17 @@ int atomic_cas(atomic_t *target, atomic_val_t old_value, */ atomic_val_t atomic_add(atomic_t *target, atomic_val_t value) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target += value; + ret = *target; + *target += value; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -104,17 +104,17 @@ atomic_val_t atomic_add(atomic_t *target, atomic_val_t value) */ atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target -= value; + ret = *target; + *target -= value; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -130,17 +130,17 @@ atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value) */ atomic_val_t atomic_inc(atomic_t *target) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - (*target)++; + ret = *target; + (*target)++; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -156,17 +156,17 @@ atomic_val_t atomic_inc(atomic_t *target) */ atomic_val_t atomic_dec(atomic_t *target) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - (*target)--; + ret = *target; + (*target)--; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -183,7 +183,7 @@ atomic_val_t atomic_dec(atomic_t *target) */ atomic_val_t atomic_get(const atomic_t *target) { - return *target; + return *target; } /** @@ -200,17 +200,17 @@ atomic_val_t atomic_get(const atomic_t *target) */ atomic_val_t atomic_set(atomic_t *target, atomic_val_t value) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target = value; + ret = *target; + *target = value; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -227,17 +227,17 @@ atomic_val_t atomic_set(atomic_t *target, atomic_val_t value) */ atomic_val_t atomic_clear(atomic_t *target) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target = 0; + ret = *target; + *target = 0; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -255,17 +255,17 @@ atomic_val_t atomic_clear(atomic_t *target) */ atomic_val_t atomic_or(atomic_t *target, atomic_val_t value) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target |= value; + ret = *target; + *target |= value; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -283,17 +283,17 @@ atomic_val_t atomic_or(atomic_t *target, atomic_val_t value) */ atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target ^= value; + ret = *target; + *target ^= value; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -311,17 +311,17 @@ atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value) */ atomic_val_t atomic_and(atomic_t *target, atomic_val_t value) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target &= value; + ret = *target; + *target &= value; - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } /** @@ -339,15 +339,15 @@ atomic_val_t atomic_and(atomic_t *target, atomic_val_t value) */ atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value) { - unsigned int key; - atomic_val_t ret; + unsigned int key; + atomic_val_t ret; - key = irq_lock(); + key = irq_lock(); - ret = *target; - *target = ~(*target & value); + ret = *target; + *target = ~(*target & value); - irq_unlock(key); + irq_unlock(key); - return ret; + return ret; } diff --git a/components/network/ble/blestack/src/common/buf.c b/components/network/ble/blestack/src/common/buf.c index 70099357..00ade95f 100644 --- a/components/network/ble/blestack/src/common/buf.c +++ b/components/network/ble/blestack/src/common/buf.c @@ -24,13 +24,13 @@ #if defined(CONFIG_NET_BUF_LOG) #define NET_BUF_DBG(fmt, ...) LOG_DBG("(%p) " fmt, k_current_get(), \ - ##__VA_ARGS__) + ##__VA_ARGS__) #define NET_BUF_ERR(fmt, ...) LOG_ERR(fmt, ##__VA_ARGS__) #define NET_BUF_WARN(fmt, ...) LOG_WRN(fmt, ##__VA_ARGS__) #define NET_BUF_INFO(fmt, ...) LOG_INF(fmt, ##__VA_ARGS__) -#define NET_BUF_ASSERT(cond) do { if (!(cond)) { \ - NET_BUF_ERR("assert: '" #cond "' failed"); \ - } } while (0) +#define NET_BUF_ASSERT(cond) do { if (!(cond)) { \ + NET_BUF_ERR("assert: '" #cond "' failed"); \ + } } while (0) #else #define NET_BUF_DBG(fmt, ...) @@ -66,7 +66,7 @@ struct net_buf_pool *net_buf_pool_get(int id) #if defined(BFLB_BLE_DISABLE_STATIC_BUF) return _net_buf_pool_list[id]; #else - return &_net_buf_pool_list[id]; + return &_net_buf_pool_list[id]; #endif } @@ -83,453 +83,453 @@ static int pool_id(struct net_buf_pool *pool) NET_BUF_ASSERT(index < (sizeof(_net_buf_pool_list) / 4)); return index; #else - return pool - _net_buf_pool_list; + return pool - _net_buf_pool_list; #endif } int net_buf_id(struct net_buf *buf) { - struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); + struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); - return buf - pool->__bufs; + return buf - pool->__bufs; } static inline struct net_buf *pool_get_uninit(struct net_buf_pool *pool, - u16_t uninit_count) + u16_t uninit_count) { - struct net_buf *buf; + struct net_buf *buf; - buf = &pool->__bufs[pool->buf_count - uninit_count]; + buf = &pool->__bufs[pool->buf_count - uninit_count]; - buf->pool_id = pool_id(pool); + buf->pool_id = pool_id(pool); - return buf; + return buf; } void net_buf_reset(struct net_buf *buf) { - NET_BUF_ASSERT(buf->flags == 0U); - NET_BUF_ASSERT(buf->frags == NULL); + NET_BUF_ASSERT(buf->flags == 0U); + NET_BUF_ASSERT(buf->frags == NULL); - net_buf_simple_reset(&buf->b); + net_buf_simple_reset(&buf->b); } #if !defined(BFLB_BLE) static u8_t *generic_data_ref(struct net_buf *buf, u8_t *data) { - u8_t *ref_count; + u8_t *ref_count; - ref_count = data - 1; - (*ref_count)++; + ref_count = data - 1; + (*ref_count)++; - return data; + return data; } static u8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size, - s32_t timeout) + s32_t timeout) { - struct net_buf_pool *buf_pool = net_buf_pool_get(buf->pool_id); - struct k_mem_pool *pool = buf_pool->alloc->alloc_data; - struct k_mem_block block; - u8_t *ref_count; + struct net_buf_pool *buf_pool = net_buf_pool_get(buf->pool_id); + struct k_mem_pool *pool = buf_pool->alloc->alloc_data; + struct k_mem_block block; + u8_t *ref_count; - /* Reserve extra space for k_mem_block_id and ref-count (u8_t) */ - if (k_mem_pool_alloc(pool, &block, - sizeof(struct k_mem_block_id) + 1 + *size, - timeout)) { - return NULL; - } + /* Reserve extra space for k_mem_block_id and ref-count (u8_t) */ + if (k_mem_pool_alloc(pool, &block, + sizeof(struct k_mem_block_id) + 1 + *size, + timeout)) { + return NULL; + } - /* save the block descriptor info at the start of the actual block */ - memcpy(block.data, &block.id, sizeof(block.id)); + /* save the block descriptor info at the start of the actual block */ + memcpy(block.data, &block.id, sizeof(block.id)); - ref_count = (u8_t *)block.data + sizeof(block.id); - *ref_count = 1U; + ref_count = (u8_t *)block.data + sizeof(block.id); + *ref_count = 1U; - /* Return pointer to the byte following the ref count */ - return ref_count + 1; + /* Return pointer to the byte following the ref count */ + return ref_count + 1; } static void mem_pool_data_unref(struct net_buf *buf, u8_t *data) { - struct k_mem_block_id id; - u8_t *ref_count; + struct k_mem_block_id id; + u8_t *ref_count; - ref_count = data - 1; - if (--(*ref_count)) { - return; - } + ref_count = data - 1; + if (--(*ref_count)) { + return; + } - /* Need to copy to local variable due to alignment */ - memcpy(&id, ref_count - sizeof(id), sizeof(id)); - k_mem_pool_free_id(&id); + /* Need to copy to local variable due to alignment */ + memcpy(&id, ref_count - sizeof(id), sizeof(id)); + k_mem_pool_free_id(&id); } const struct net_buf_data_cb net_buf_var_cb = { - .alloc = mem_pool_data_alloc, - .ref = generic_data_ref, - .unref = mem_pool_data_unref, + .alloc = mem_pool_data_alloc, + .ref = generic_data_ref, + .unref = mem_pool_data_unref, }; #endif static u8_t *fixed_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) { - struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); - const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; + struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); + const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; - *size = MIN(fixed->data_size, *size); + *size = MIN(fixed->data_size, *size); - return fixed->data_pool + fixed->data_size * net_buf_id(buf); + return fixed->data_pool + fixed->data_size * net_buf_id(buf); } static void fixed_data_unref(struct net_buf *buf, u8_t *data) { - /* Nothing needed for fixed-size data pools */ + /* Nothing needed for fixed-size data pools */ } const struct net_buf_data_cb net_buf_fixed_cb = { - .alloc = fixed_data_alloc, - .unref = fixed_data_unref, + .alloc = fixed_data_alloc, + .unref = fixed_data_unref, }; #if (CONFIG_HEAP_MEM_POOL_SIZE > 0) static u8_t *heap_data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) { - u8_t *ref_count; + u8_t *ref_count; - ref_count = k_malloc(1 + *size); - if (!ref_count) { - return NULL; - } + ref_count = k_malloc(1 + *size); + if (!ref_count) { + return NULL; + } - *ref_count = 1U; + *ref_count = 1U; - return ref_count + 1; + return ref_count + 1; } static void heap_data_unref(struct net_buf *buf, u8_t *data) { - u8_t *ref_count; + u8_t *ref_count; - ref_count = data - 1; - if (--(*ref_count)) { - return; - } + ref_count = data - 1; + if (--(*ref_count)) { + return; + } - k_free(ref_count); + k_free(ref_count); } static const struct net_buf_data_cb net_buf_heap_cb = { - .alloc = heap_data_alloc, - .ref = generic_data_ref, - .unref = heap_data_unref, + .alloc = heap_data_alloc, + .ref = generic_data_ref, + .unref = heap_data_unref, }; const struct net_buf_data_alloc net_buf_heap_alloc = { - .cb = &net_buf_heap_cb, + .cb = &net_buf_heap_cb, }; #endif /* CONFIG_HEAP_MEM_POOL_SIZE > 0 */ static u8_t *data_alloc(struct net_buf *buf, size_t *size, s32_t timeout) { - struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); + struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); - return pool->alloc->cb->alloc(buf, size, timeout); + return pool->alloc->cb->alloc(buf, size, timeout); } static u8_t *data_ref(struct net_buf *buf, u8_t *data) { - struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); + struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); - return pool->alloc->cb->ref(buf, data); + return pool->alloc->cb->ref(buf, data); } static void data_unref(struct net_buf *buf, u8_t *data) { - struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); + struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); - if (buf->flags & NET_BUF_EXTERNAL_DATA) { - return; - } + if (buf->flags & NET_BUF_EXTERNAL_DATA) { + return; + } - pool->alloc->cb->unref(buf, data); + pool->alloc->cb->unref(buf, data); } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size, - s32_t timeout, const char *func, - int line) + s32_t timeout, const char *func, + int line) #else struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size, - s32_t timeout) + s32_t timeout) #endif { - u32_t alloc_start = k_uptime_get_32(); - struct net_buf *buf; - unsigned int key; + u32_t alloc_start = k_uptime_get_32(); + struct net_buf *buf; + unsigned int key; - NET_BUF_ASSERT(pool); + NET_BUF_ASSERT(pool); - NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool, - size, timeout); + NET_BUF_DBG("%s():%d: pool %p size %zu timeout %d", func, line, pool, + size, timeout); - /* We need to lock interrupts temporarily to prevent race conditions - * when accessing pool->uninit_count. - */ - key = irq_lock(); + /* We need to lock interrupts temporarily to prevent race conditions + * when accessing pool->uninit_count. + */ + key = irq_lock(); - /* If there are uninitialized buffers we're guaranteed to succeed - * with the allocation one way or another. - */ - if (pool->uninit_count) { - u16_t uninit_count; + /* If there are uninitialized buffers we're guaranteed to succeed + * with the allocation one way or another. + */ + if (pool->uninit_count) { + u16_t uninit_count; - /* If this is not the first access to the pool, we can - * be opportunistic and try to fetch a previously used - * buffer from the LIFO with K_NO_WAIT. - */ - if (pool->uninit_count < pool->buf_count) { - buf = k_lifo_get(&pool->free, K_NO_WAIT); - if (buf) { - irq_unlock(key); - goto success; - } - } + /* If this is not the first access to the pool, we can + * be opportunistic and try to fetch a previously used + * buffer from the LIFO with K_NO_WAIT. + */ + if (pool->uninit_count < pool->buf_count) { + buf = k_lifo_get(&pool->free, K_NO_WAIT); + if (buf) { + irq_unlock(key); + goto success; + } + } - uninit_count = pool->uninit_count--; - irq_unlock(key); + uninit_count = pool->uninit_count--; + irq_unlock(key); - buf = pool_get_uninit(pool, uninit_count); - goto success; - } + buf = pool_get_uninit(pool, uninit_count); + goto success; + } - irq_unlock(key); + irq_unlock(key); #if defined(CONFIG_NET_BUF_LOG) && (CONFIG_NET_BUF_LOG_LEVEL >= LOG_LEVEL_WRN) - if (timeout == K_FOREVER) { - u32_t ref = k_uptime_get_32(); - buf = k_lifo_get(&pool->free, K_NO_WAIT); - while (!buf) { + if (timeout == K_FOREVER) { + u32_t ref = k_uptime_get_32(); + buf = k_lifo_get(&pool->free, K_NO_WAIT); + while (!buf) { #if defined(CONFIG_NET_BUF_POOL_USAGE) - NET_BUF_WARN("%s():%d: Pool %s low on buffers.", - func, line, pool->name); + NET_BUF_WARN("%s():%d: Pool %s low on buffers.", + func, line, pool->name); #else - NET_BUF_WARN("%s():%d: Pool %p low on buffers.", - func, line, pool); + NET_BUF_WARN("%s():%d: Pool %p low on buffers.", + func, line, pool); #endif - buf = k_lifo_get(&pool->free, WARN_ALLOC_INTERVAL); + buf = k_lifo_get(&pool->free, WARN_ALLOC_INTERVAL); #if defined(CONFIG_NET_BUF_POOL_USAGE) - NET_BUF_WARN("%s():%d: Pool %s blocked for %u secs", - func, line, pool->name, - (k_uptime_get_32() - ref) / MSEC_PER_SEC); + NET_BUF_WARN("%s():%d: Pool %s blocked for %u secs", + func, line, pool->name, + (k_uptime_get_32() - ref) / MSEC_PER_SEC); #else - NET_BUF_WARN("%s():%d: Pool %p blocked for %u secs", - func, line, pool, - (k_uptime_get_32() - ref) / MSEC_PER_SEC); + NET_BUF_WARN("%s():%d: Pool %p blocked for %u secs", + func, line, pool, + (k_uptime_get_32() - ref) / MSEC_PER_SEC); #endif - } - } else { - buf = k_lifo_get(&pool->free, timeout); - } + } + } else { + buf = k_lifo_get(&pool->free, timeout); + } #else - buf = k_lifo_get(&pool->free, timeout); + buf = k_lifo_get(&pool->free, timeout); #endif - if (!buf) { - NET_BUF_ERR("%s():%d: Failed to get free buffer", func, line); - return NULL; - } + if (!buf) { + NET_BUF_ERR("%s():%d: Failed to get free buffer", func, line); + return NULL; + } success: - NET_BUF_DBG("allocated buf %p", buf); + NET_BUF_DBG("allocated buf %p", buf); - if (size) { - if (timeout != K_NO_WAIT && timeout != K_FOREVER) { - u32_t diff = k_uptime_get_32() - alloc_start; + if (size) { + if (timeout != K_NO_WAIT && timeout != K_FOREVER) { + u32_t diff = k_uptime_get_32() - alloc_start; - timeout -= MIN(timeout, diff); - } + timeout -= MIN(timeout, diff); + } - buf->__buf = data_alloc(buf, &size, timeout); - if (!buf->__buf) { - NET_BUF_ERR("%s():%d: Failed to allocate data", - func, line); - net_buf_destroy(buf); - return NULL; - } - } else { - buf->__buf = NULL; - } + buf->__buf = data_alloc(buf, &size, timeout); + if (!buf->__buf) { + NET_BUF_ERR("%s():%d: Failed to allocate data", + func, line); + net_buf_destroy(buf); + return NULL; + } + } else { + buf->__buf = NULL; + } - buf->ref = 1U; - buf->flags = 0U; - buf->frags = NULL; - buf->size = size; - net_buf_reset(buf); + buf->ref = 1U; + buf->flags = 0U; + buf->frags = NULL; + buf->size = size; + net_buf_reset(buf); #if defined(CONFIG_NET_BUF_POOL_USAGE) - pool->avail_count--; - NET_BUF_ASSERT(pool->avail_count >= 0); + pool->avail_count--; + NET_BUF_ASSERT(pool->avail_count >= 0); #endif - return buf; + return buf; } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool, - s32_t timeout, const char *func, - int line) + s32_t timeout, const char *func, + int line) { - const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; + const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; - return net_buf_alloc_len_debug(pool, fixed->data_size, timeout, func, - line); + return net_buf_alloc_len_debug(pool, fixed->data_size, timeout, func, + line); } #else struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout) { - const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; + const struct net_buf_pool_fixed *fixed = pool->alloc->alloc_data; - return net_buf_alloc_len(pool, fixed->data_size, timeout); + return net_buf_alloc_len(pool, fixed->data_size, timeout); } #endif #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_with_data_debug(struct net_buf_pool *pool, - void *data, size_t size, - s32_t timeout, const char *func, - int line) + void *data, size_t size, + s32_t timeout, const char *func, + int line) #else struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool, - void *data, size_t size, - s32_t timeout) + void *data, size_t size, + s32_t timeout) #endif { - struct net_buf *buf; + struct net_buf *buf; #if defined(CONFIG_NET_BUF_LOG) - buf = net_buf_alloc_len_debug(pool, 0, timeout, func, line); + buf = net_buf_alloc_len_debug(pool, 0, timeout, func, line); #else - buf = net_buf_alloc_len(pool, 0, timeout); + buf = net_buf_alloc_len(pool, 0, timeout); #endif - if (!buf) { - return NULL; - } + if (!buf) { + return NULL; + } - buf->__buf = data; - buf->data = data; - buf->size = size; - buf->len = size; - buf->flags = NET_BUF_EXTERNAL_DATA; + buf->__buf = data; + buf->data = data; + buf->size = size; + buf->len = size; + buf->flags = NET_BUF_EXTERNAL_DATA; - return buf; + return buf; } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_get_debug(struct k_fifo *fifo, s32_t timeout, - const char *func, int line) + const char *func, int line) #else struct net_buf *net_buf_get(struct k_fifo *fifo, s32_t timeout) #endif { - struct net_buf *buf, *frag; + struct net_buf *buf, *frag; - NET_BUF_DBG("%s():%d: fifo %p timeout %d", func, line, fifo, timeout); + NET_BUF_DBG("%s():%d: fifo %p timeout %d", func, line, fifo, timeout); - buf = k_fifo_get(fifo, timeout); - if (!buf) { - return NULL; - } + buf = k_fifo_get(fifo, timeout); + if (!buf) { + return NULL; + } - NET_BUF_DBG("%s():%d: buf %p fifo %p", func, line, buf, fifo); + NET_BUF_DBG("%s():%d: buf %p fifo %p", func, line, buf, fifo); - /* Get any fragments belonging to this buffer */ - for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) { - frag->frags = k_fifo_get(fifo, K_NO_WAIT); - NET_BUF_ASSERT(frag->frags); + /* Get any fragments belonging to this buffer */ + for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) { + frag->frags = k_fifo_get(fifo, K_NO_WAIT); + NET_BUF_ASSERT(frag->frags); - /* The fragments flag is only for FIFO-internal usage */ - frag->flags &= ~NET_BUF_FRAGS; - } + /* The fragments flag is only for FIFO-internal usage */ + frag->flags &= ~NET_BUF_FRAGS; + } - /* Mark the end of the fragment list */ - frag->frags = NULL; + /* Mark the end of the fragment list */ + frag->frags = NULL; - return buf; + return buf; } void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve) { - NET_BUF_ASSERT(buf); - NET_BUF_ASSERT(buf->len == 0U); - NET_BUF_DBG("buf %p reserve %zu", buf, reserve); + NET_BUF_ASSERT(buf); + NET_BUF_ASSERT(buf->len == 0U); + NET_BUF_DBG("buf %p reserve %zu", buf, reserve); - buf->data = buf->__buf + reserve; + buf->data = buf->__buf + reserve; } void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf) { - struct net_buf *tail; - unsigned int key; + struct net_buf *tail; + unsigned int key; - NET_BUF_ASSERT(list); - NET_BUF_ASSERT(buf); + NET_BUF_ASSERT(list); + NET_BUF_ASSERT(buf); - for (tail = buf; tail->frags; tail = tail->frags) { - tail->flags |= NET_BUF_FRAGS; - } + for (tail = buf; tail->frags; tail = tail->frags) { + tail->flags |= NET_BUF_FRAGS; + } - key = irq_lock(); - sys_slist_append_list(list, &buf->node, &tail->node); - irq_unlock(key); + key = irq_lock(); + sys_slist_append_list(list, &buf->node, &tail->node); + irq_unlock(key); } struct net_buf *net_buf_slist_get(sys_slist_t *list) { - struct net_buf *buf, *frag; - unsigned int key; + struct net_buf *buf, *frag; + unsigned int key; - NET_BUF_ASSERT(list); + NET_BUF_ASSERT(list); - key = irq_lock(); - buf = (void *)sys_slist_get(list); - irq_unlock(key); + key = irq_lock(); + buf = (void *)sys_slist_get(list); + irq_unlock(key); - if (!buf) { - return NULL; - } + if (!buf) { + return NULL; + } - /* Get any fragments belonging to this buffer */ - for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) { - key = irq_lock(); - frag->frags = (void *)sys_slist_get(list); - irq_unlock(key); + /* Get any fragments belonging to this buffer */ + for (frag = buf; (frag->flags & NET_BUF_FRAGS); frag = frag->frags) { + key = irq_lock(); + frag->frags = (void *)sys_slist_get(list); + irq_unlock(key); - NET_BUF_ASSERT(frag->frags); + NET_BUF_ASSERT(frag->frags); - /* The fragments flag is only for list-internal usage */ - frag->flags &= ~NET_BUF_FRAGS; - } + /* The fragments flag is only for list-internal usage */ + frag->flags &= ~NET_BUF_FRAGS; + } - /* Mark the end of the fragment list */ - frag->frags = NULL; + /* Mark the end of the fragment list */ + frag->frags = NULL; - return buf; + return buf; } void net_buf_put(struct k_fifo *fifo, struct net_buf *buf) { - struct net_buf *tail; + struct net_buf *tail; - NET_BUF_ASSERT(fifo); - NET_BUF_ASSERT(buf); + NET_BUF_ASSERT(fifo); + NET_BUF_ASSERT(buf); - for (tail = buf; tail->frags; tail = tail->frags) { - tail->flags |= NET_BUF_FRAGS; - } + for (tail = buf; tail->frags; tail = tail->frags) { + tail->flags |= NET_BUF_FRAGS; + } - k_fifo_put_list(fifo, buf, tail); + k_fifo_put_list(fifo, buf, tail); } #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) @@ -543,215 +543,215 @@ void net_buf_unref_debug(struct net_buf *buf, const char *func, int line) void net_buf_unref(struct net_buf *buf) #endif { - NET_BUF_ASSERT(buf); + NET_BUF_ASSERT(buf); - while (buf) { - struct net_buf *frags = buf->frags; - struct net_buf_pool *pool; + while (buf) { + struct net_buf *frags = buf->frags; + struct net_buf_pool *pool; #if defined(CONFIG_NET_BUF_LOG) - if (!buf->ref) { - NET_BUF_ERR("%s():%d: buf %p double free", func, line, - buf); - return; - } + if (!buf->ref) { + NET_BUF_ERR("%s():%d: buf %p double free", func, line, + buf); + return; + } #endif - NET_BUF_DBG("buf %p ref %u pool_id %u frags %p", buf, buf->ref, - buf->pool_id, buf->frags); + NET_BUF_DBG("buf %p ref %u pool_id %u frags %p", buf, buf->ref, + buf->pool_id, buf->frags); - if (--buf->ref > 0) { - return; - } + if (--buf->ref > 0) { + return; + } - if (buf->__buf) { - data_unref(buf, buf->__buf); - buf->__buf = NULL; - } + if (buf->__buf) { + data_unref(buf, buf->__buf); + buf->__buf = NULL; + } - buf->data = NULL; - buf->frags = NULL; + buf->data = NULL; + buf->frags = NULL; - pool = net_buf_pool_get(buf->pool_id); + pool = net_buf_pool_get(buf->pool_id); #if defined(CONFIG_NET_BUF_POOL_USAGE) - pool->avail_count++; - NET_BUF_ASSERT(pool->avail_count <= pool->buf_count); + pool->avail_count++; + NET_BUF_ASSERT(pool->avail_count <= pool->buf_count); #endif - if (pool->destroy) { - pool->destroy(buf); - } else { - net_buf_destroy(buf); - } + if (pool->destroy) { + pool->destroy(buf); + } else { + net_buf_destroy(buf); + } - buf = frags; + buf = frags; #if defined(OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER) if(pool == &hci_rx_pool){ bl_handle_queued_msg(); return; } - #endif - } + #endif + } } struct net_buf *net_buf_ref(struct net_buf *buf) { - NET_BUF_ASSERT(buf); + NET_BUF_ASSERT(buf); - NET_BUF_DBG("buf %p (old) ref %u pool_id %u", - buf, buf->ref, buf->pool_id); - buf->ref++; - return buf; + NET_BUF_DBG("buf %p (old) ref %u pool_id %u", + buf, buf->ref, buf->pool_id); + buf->ref++; + return buf; } struct net_buf *net_buf_clone(struct net_buf *buf, s32_t timeout) { - u32_t alloc_start = k_uptime_get_32(); - struct net_buf_pool *pool; - struct net_buf *clone; + u32_t alloc_start = k_uptime_get_32(); + struct net_buf_pool *pool; + struct net_buf *clone; - NET_BUF_ASSERT(buf); + NET_BUF_ASSERT(buf); - pool = net_buf_pool_get(buf->pool_id); + pool = net_buf_pool_get(buf->pool_id); - clone = net_buf_alloc_len(pool, 0, timeout); - if (!clone) { - return NULL; - } + clone = net_buf_alloc_len(pool, 0, timeout); + if (!clone) { + return NULL; + } - /* If the pool supports data referencing use that. Otherwise - * we need to allocate new data and make a copy. - */ - if (pool->alloc->cb->ref && !(buf->flags & NET_BUF_EXTERNAL_DATA)) { - clone->__buf = data_ref(buf, buf->__buf); - clone->data = buf->data; - clone->len = buf->len; - clone->size = buf->size; - } else { - size_t size = buf->size; + /* If the pool supports data referencing use that. Otherwise + * we need to allocate new data and make a copy. + */ + if (pool->alloc->cb->ref && !(buf->flags & NET_BUF_EXTERNAL_DATA)) { + clone->__buf = data_ref(buf, buf->__buf); + clone->data = buf->data; + clone->len = buf->len; + clone->size = buf->size; + } else { + size_t size = buf->size; - if (timeout != K_NO_WAIT && timeout != K_FOREVER) { - u32_t diff = k_uptime_get_32() - alloc_start; + if (timeout != K_NO_WAIT && timeout != K_FOREVER) { + u32_t diff = k_uptime_get_32() - alloc_start; - timeout -= MIN(timeout, diff); - } + timeout -= MIN(timeout, diff); + } - clone->__buf = data_alloc(clone, &size, timeout); - if (!clone->__buf || size < buf->size) { - net_buf_destroy(clone); - return NULL; - } + clone->__buf = data_alloc(clone, &size, timeout); + if (!clone->__buf || size < buf->size) { + net_buf_destroy(clone); + return NULL; + } - clone->size = size; - clone->data = clone->__buf + net_buf_headroom(buf); - net_buf_add_mem(clone, buf->data, buf->len); - } + clone->size = size; + clone->data = clone->__buf + net_buf_headroom(buf); + net_buf_add_mem(clone, buf->data, buf->len); + } - return clone; + return clone; } struct net_buf *net_buf_frag_last(struct net_buf *buf) { - NET_BUF_ASSERT(buf); + NET_BUF_ASSERT(buf); - while (buf->frags) { - buf = buf->frags; - } + while (buf->frags) { + buf = buf->frags; + } - return buf; + return buf; } void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag) { - NET_BUF_ASSERT(parent); - NET_BUF_ASSERT(frag); + NET_BUF_ASSERT(parent); + NET_BUF_ASSERT(frag); - if (parent->frags) { - net_buf_frag_last(frag)->frags = parent->frags; - } - /* Take ownership of the fragment reference */ - parent->frags = frag; + if (parent->frags) { + net_buf_frag_last(frag)->frags = parent->frags; + } + /* Take ownership of the fragment reference */ + parent->frags = frag; } struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag) { - NET_BUF_ASSERT(frag); + NET_BUF_ASSERT(frag); - if (!head) { - return net_buf_ref(frag); - } + if (!head) { + return net_buf_ref(frag); + } - net_buf_frag_insert(net_buf_frag_last(head), frag); + net_buf_frag_insert(net_buf_frag_last(head), frag); - return head; + return head; } #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_frag_del_debug(struct net_buf *parent, - struct net_buf *frag, - const char *func, int line) + struct net_buf *frag, + const char *func, int line) #else struct net_buf *net_buf_frag_del(struct net_buf *parent, struct net_buf *frag) #endif { - struct net_buf *next_frag; + struct net_buf *next_frag; - NET_BUF_ASSERT(frag); + NET_BUF_ASSERT(frag); - if (parent) { - NET_BUF_ASSERT(parent->frags); - NET_BUF_ASSERT(parent->frags == frag); - parent->frags = frag->frags; - } + if (parent) { + NET_BUF_ASSERT(parent->frags); + NET_BUF_ASSERT(parent->frags == frag); + parent->frags = frag->frags; + } - next_frag = frag->frags; + next_frag = frag->frags; - frag->frags = NULL; + frag->frags = NULL; #if defined(CONFIG_NET_BUF_LOG) - net_buf_unref_debug(frag, func, line); + net_buf_unref_debug(frag, func, line); #else - net_buf_unref(frag); + net_buf_unref(frag); #endif - return next_frag; + return next_frag; } size_t net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src, - size_t offset, size_t len) + size_t offset, size_t len) { - struct net_buf *frag; - size_t to_copy; - size_t copied; + struct net_buf *frag; + size_t to_copy; + size_t copied; - len = MIN(len, dst_len); + len = MIN(len, dst_len); - frag = src; + frag = src; - /* find the right fragment to start copying from */ - while (frag && offset >= frag->len) { - offset -= frag->len; - frag = frag->frags; - } + /* find the right fragment to start copying from */ + while (frag && offset >= frag->len) { + offset -= frag->len; + frag = frag->frags; + } - /* traverse the fragment chain until len bytes are copied */ - copied = 0; - while (frag && len > 0) { - to_copy = MIN(len, frag->len - offset); - memcpy((u8_t *)dst + copied, frag->data + offset, to_copy); + /* traverse the fragment chain until len bytes are copied */ + copied = 0; + while (frag && len > 0) { + to_copy = MIN(len, frag->len - offset); + memcpy((u8_t *)dst + copied, frag->data + offset, to_copy); - copied += to_copy; + copied += to_copy; - /* to_copy is always <= len */ - len -= to_copy; - frag = frag->frags; + /* to_copy is always <= len */ + len -= to_copy; + frag = frag->frags; - /* after the first iteration, this value will be 0 */ - offset = 0; - } + /* after the first iteration, this value will be 0 */ + offset = 0; + } - return copied; + return copied; } /* This helper routine will append multiple bytes, if there is no place for @@ -759,35 +759,35 @@ size_t net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src, * the buffer. It assumes that the buffer has at least one fragment. */ size_t net_buf_append_bytes(struct net_buf *buf, size_t len, - const void *value, s32_t timeout, - net_buf_allocator_cb allocate_cb, void *user_data) + const void *value, s32_t timeout, + net_buf_allocator_cb allocate_cb, void *user_data) { - struct net_buf *frag = net_buf_frag_last(buf); - size_t added_len = 0; - const u8_t *value8 = value; + struct net_buf *frag = net_buf_frag_last(buf); + size_t added_len = 0; + const u8_t *value8 = value; - do { - u16_t count = MIN(len, net_buf_tailroom(frag)); + do { + u16_t count = MIN(len, net_buf_tailroom(frag)); - net_buf_add_mem(frag, value8, count); - len -= count; - added_len += count; - value8 += count; + net_buf_add_mem(frag, value8, count); + len -= count; + added_len += count; + value8 += count; - if (len == 0) { - return added_len; - } + if (len == 0) { + return added_len; + } - frag = allocate_cb(timeout, user_data); - if (!frag) { - return added_len; - } + frag = allocate_cb(timeout, user_data); + if (!frag) { + return added_len; + } - net_buf_frag_add(buf, frag); - } while (1); + net_buf_frag_add(buf, frag); + } while (1); - /* Unreachable */ - return 0; + /* Unreachable */ + return 0; } #if defined(CONFIG_NET_BUF_SIMPLE_LOG) @@ -805,183 +805,183 @@ size_t net_buf_append_bytes(struct net_buf *buf, size_t len, #endif /* CONFIG_NET_BUF_SIMPLE_LOG */ void net_buf_simple_clone(const struct net_buf_simple *original, - struct net_buf_simple *clone) + struct net_buf_simple *clone) { - memcpy(clone, original, sizeof(struct net_buf_simple)); + memcpy(clone, original, sizeof(struct net_buf_simple)); } void *net_buf_simple_add(struct net_buf_simple *buf, size_t len) { - u8_t *tail = net_buf_simple_tail(buf); + u8_t *tail = net_buf_simple_tail(buf); - NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); + NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); - NET_BUF_SIMPLE_ASSERT(net_buf_simple_tailroom(buf) >= len); + NET_BUF_SIMPLE_ASSERT(net_buf_simple_tailroom(buf) >= len); - buf->len += len; - return tail; + buf->len += len; + return tail; } void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem, - size_t len) + size_t len) { - NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); + NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); - return memcpy(net_buf_simple_add(buf, len), mem, len); + return memcpy(net_buf_simple_add(buf, len), mem, len); } u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val) { - u8_t *u8; + u8_t *u8; - NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val); + NET_BUF_SIMPLE_DBG("buf %p val 0x%02x", buf, val); - u8 = net_buf_simple_add(buf, 1); - *u8 = val; + u8 = net_buf_simple_add(buf, 1); + *u8 = val; - return u8; + return u8; } void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val) { - NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); + NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); - sys_put_le16(val, net_buf_simple_add(buf, sizeof(val))); + sys_put_le16(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val) { - NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); + NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); - sys_put_be16(val, net_buf_simple_add(buf, sizeof(val))); + sys_put_be16(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_le32(struct net_buf_simple *buf, u32_t val) { - NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); + NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); - sys_put_le32(val, net_buf_simple_add(buf, sizeof(val))); + sys_put_le32(val, net_buf_simple_add(buf, sizeof(val))); } void net_buf_simple_add_be32(struct net_buf_simple *buf, u32_t val) { - NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); + NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); - sys_put_be32(val, net_buf_simple_add(buf, sizeof(val))); + sys_put_be32(val, net_buf_simple_add(buf, sizeof(val))); } void *net_buf_simple_push(struct net_buf_simple *buf, size_t len) { - NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); + NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); - NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len); + NET_BUF_SIMPLE_ASSERT(net_buf_simple_headroom(buf) >= len); - buf->data -= len; - buf->len += len; - return buf->data; + buf->data -= len; + buf->len += len; + return buf->data; } void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val) { - NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); + NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); - sys_put_le16(val, net_buf_simple_push(buf, sizeof(val))); + sys_put_le16(val, net_buf_simple_push(buf, sizeof(val))); } void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val) { - NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); + NET_BUF_SIMPLE_DBG("buf %p val %u", buf, val); - sys_put_be16(val, net_buf_simple_push(buf, sizeof(val))); + sys_put_be16(val, net_buf_simple_push(buf, sizeof(val))); } void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val) { - u8_t *data = net_buf_simple_push(buf, 1); + u8_t *data = net_buf_simple_push(buf, 1); - *data = val; + *data = val; } void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len) { - NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); + NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); - NET_BUF_SIMPLE_ASSERT(buf->len >= len); + NET_BUF_SIMPLE_ASSERT(buf->len >= len); - buf->len -= len; - return buf->data += len; + buf->len -= len; + return buf->data += len; } void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len) { - void *data = buf->data; + void *data = buf->data; - NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); + NET_BUF_SIMPLE_DBG("buf %p len %zu", buf, len); - NET_BUF_SIMPLE_ASSERT(buf->len >= len); + NET_BUF_SIMPLE_ASSERT(buf->len >= len); - buf->len -= len; - buf->data += len; + buf->len -= len; + buf->data += len; - return data; + return data; } u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf) { - u8_t val; + u8_t val; - val = buf->data[0]; - net_buf_simple_pull(buf, 1); + val = buf->data[0]; + net_buf_simple_pull(buf, 1); - return val; + return val; } u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf) { - u16_t val; + u16_t val; - val = UNALIGNED_GET((u16_t *)buf->data); - net_buf_simple_pull(buf, sizeof(val)); + val = UNALIGNED_GET((u16_t *)buf->data); + net_buf_simple_pull(buf, sizeof(val)); - return sys_le16_to_cpu(val); + return sys_le16_to_cpu(val); } u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf) { - u16_t val; + u16_t val; - val = UNALIGNED_GET((u16_t *)buf->data); - net_buf_simple_pull(buf, sizeof(val)); + val = UNALIGNED_GET((u16_t *)buf->data); + net_buf_simple_pull(buf, sizeof(val)); - return sys_be16_to_cpu(val); + return sys_be16_to_cpu(val); } u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf) { - u32_t val; + u32_t val; - val = UNALIGNED_GET((u32_t *)buf->data); - net_buf_simple_pull(buf, sizeof(val)); + val = UNALIGNED_GET((u32_t *)buf->data); + net_buf_simple_pull(buf, sizeof(val)); - return sys_le32_to_cpu(val); + return sys_le32_to_cpu(val); } u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf) { - u32_t val; + u32_t val; - val = UNALIGNED_GET((u32_t *)buf->data); - net_buf_simple_pull(buf, sizeof(val)); + val = UNALIGNED_GET((u32_t *)buf->data); + net_buf_simple_pull(buf, sizeof(val)); - return sys_be32_to_cpu(val); + return sys_be32_to_cpu(val); } size_t net_buf_simple_headroom(struct net_buf_simple *buf) { - return buf->data - buf->__buf; + return buf->data - buf->__buf; } size_t net_buf_simple_tailroom(struct net_buf_simple *buf) { - return buf->size - net_buf_simple_headroom(buf) - buf->len; + return buf->size - net_buf_simple_headroom(buf) - buf->len; } diff --git a/components/network/ble/blestack/src/common/dec.c b/components/network/ble/blestack/src/common/dec.c index 4827b0a7..e6f8cf1c 100644 --- a/components/network/ble/blestack/src/common/dec.c +++ b/components/network/ble/blestack/src/common/dec.c @@ -8,27 +8,27 @@ u8_t u8_to_dec(char *buf, u8_t buflen, u8_t value) { - u8_t divisor = 100; - u8_t num_digits = 0; - u8_t digit; + u8_t divisor = 100; + u8_t num_digits = 0; + u8_t digit; - while (buflen > 0 && divisor > 0) { - digit = value / divisor; - if (digit != 0 || divisor == 1 || num_digits != 0) { - *buf = (char)digit + '0'; - buf++; - buflen--; - num_digits++; - } + while (buflen > 0 && divisor > 0) { + digit = value / divisor; + if (digit != 0 || divisor == 1 || num_digits != 0) { + *buf = (char)digit + '0'; + buf++; + buflen--; + num_digits++; + } - value -= digit * divisor; - divisor /= 10; - } + value -= digit * divisor; + divisor /= 10; + } - if (buflen) { - *buf = '\0'; - } + if (buflen) { + *buf = '\0'; + } - return num_digits; + return num_digits; } diff --git a/components/network/ble/blestack/src/common/dummy.c b/components/network/ble/blestack/src/common/dummy.c index a06d28bf..19070942 100644 --- a/components/network/ble/blestack/src/common/dummy.c +++ b/components/network/ble/blestack/src/common/dummy.c @@ -34,7 +34,7 @@ BUILD_ASSERT(CONFIG_BT_CTLR_RX_PRIO < CONFIG_BT_HCI_TX_PRIO); * interrupts disabled. */ #if !defined(CONFIG_TEST) && !defined(CONFIG_ARCH_POSIX) && \ - (defined(CONFIG_BT_LL_SW_SPLIT) || defined(CONFIG_BT_LL_SW_LEGACY)) + (defined(CONFIG_BT_LL_SW_SPLIT) || defined(CONFIG_BT_LL_SW_LEGACY)) BUILD_ASSERT_MSG(!IS_ENABLED(CONFIG_LOG_IMMEDIATE), "Immediate logging not " - "supported with the software Link Layer"); + "supported with the software Link Layer"); #endif diff --git a/components/network/ble/blestack/src/common/hex.c b/components/network/ble/blestack/src/common/hex.c index e9f46f8a..2cf74459 100644 --- a/components/network/ble/blestack/src/common/hex.c +++ b/components/network/ble/blestack/src/common/hex.c @@ -11,81 +11,81 @@ int char2hex(char c, u8_t *x) { - if (c >= '0' && c <= '9') { - *x = c - '0'; - } else if (c >= 'a' && c <= 'f') { - *x = c - 'a' + 10; - } else if (c >= 'A' && c <= 'F') { - *x = c - 'A' + 10; - } else { - return -EINVAL; - } + if (c >= '0' && c <= '9') { + *x = c - '0'; + } else if (c >= 'a' && c <= 'f') { + *x = c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') { + *x = c - 'A' + 10; + } else { + return -EINVAL; + } - return 0; + return 0; } int hex2char(u8_t x, char *c) { - if (x <= 9) { - *c = x + '0'; - } else if (x >= 10 && x <= 15) { - *c = x - 10 + 'a'; - } else { - return -EINVAL; - } + if (x <= 9) { + *c = x + '0'; + } else if (x >= 10 && x <= 15) { + *c = x - 10 + 'a'; + } else { + return -EINVAL; + } - return 0; + return 0; } size_t bin2hex(const u8_t *buf, size_t buflen, char *hex, size_t hexlen) { - if ((hexlen + 1) < buflen * 2) { - return 0; - } + if ((hexlen + 1) < buflen * 2) { + return 0; + } - for (size_t i = 0; i < buflen; i++) { - if (hex2char(buf[i] >> 4, &hex[2 * i]) < 0) { - return 0; - } - if (hex2char(buf[i] & 0xf, &hex[2 * i + 1]) < 0) { - return 0; - } - } + for (size_t i = 0; i < buflen; i++) { + if (hex2char(buf[i] >> 4, &hex[2 * i]) < 0) { + return 0; + } + if (hex2char(buf[i] & 0xf, &hex[2 * i + 1]) < 0) { + return 0; + } + } - hex[2 * buflen] = '\0'; - return 2 * buflen; + hex[2 * buflen] = '\0'; + return 2 * buflen; } size_t hex2bin(const char *hex, size_t hexlen, u8_t *buf, size_t buflen) { - u8_t dec; + u8_t dec; - if (buflen < hexlen / 2 + hexlen % 2) { - return 0; - } + if (buflen < hexlen / 2 + hexlen % 2) { + return 0; + } - /* if hexlen is uneven, insert leading zero nibble */ - if (hexlen % 2) { - if (char2hex(hex[0], &dec) < 0) { - return 0; - } - buf[0] = dec; - hex++; - buf++; - } + /* if hexlen is uneven, insert leading zero nibble */ + if (hexlen % 2) { + if (char2hex(hex[0], &dec) < 0) { + return 0; + } + buf[0] = dec; + hex++; + buf++; + } - /* regular hex conversion */ - for (size_t i = 0; i < hexlen / 2; i++) { - if (char2hex(hex[2 * i], &dec) < 0) { - return 0; - } - buf[i] = dec << 4; + /* regular hex conversion */ + for (size_t i = 0; i < hexlen / 2; i++) { + if (char2hex(hex[2 * i], &dec) < 0) { + return 0; + } + buf[i] = dec << 4; - if (char2hex(hex[2 * i + 1], &dec) < 0) { - return 0; - } - buf[i] += dec; - } + if (char2hex(hex[2 * i + 1], &dec) < 0) { + return 0; + } + buf[i] += dec; + } - return hexlen / 2 + hexlen % 2; + return hexlen / 2 + hexlen % 2; } diff --git a/components/network/ble/blestack/src/common/include/atomic.h b/components/network/ble/blestack/src/common/include/atomic.h index e0d6c122..f776a067 100644 --- a/components/network/ble/blestack/src/common/include/atomic.h +++ b/components/network/ble/blestack/src/common/include/atomic.h @@ -39,15 +39,15 @@ typedef atomic_t atomic_val_t; */ #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline int atomic_cas(atomic_t *target, atomic_val_t old_value, - atomic_val_t new_value) + atomic_val_t new_value) { - return __atomic_compare_exchange_n(target, &old_value, new_value, - 0, __ATOMIC_SEQ_CST, - __ATOMIC_SEQ_CST); + return __atomic_compare_exchange_n(target, &old_value, new_value, + 0, __ATOMIC_SEQ_CST, + __ATOMIC_SEQ_CST); } #else extern int atomic_cas(atomic_t *target, atomic_val_t old_value, - atomic_val_t new_value); + atomic_val_t new_value); #endif /** @@ -64,7 +64,7 @@ extern int atomic_cas(atomic_t *target, atomic_val_t old_value, #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_add(atomic_t *target, atomic_val_t value) { - return __atomic_fetch_add(target, value, __ATOMIC_SEQ_CST); + return __atomic_fetch_add(target, value, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_add(atomic_t *target, atomic_val_t value); @@ -84,7 +84,7 @@ extern atomic_val_t atomic_add(atomic_t *target, atomic_val_t value); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value) { - return __atomic_fetch_sub(target, value, __ATOMIC_SEQ_CST); + return __atomic_fetch_sub(target, value, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value); @@ -103,7 +103,7 @@ extern atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_inc(atomic_t *target) { - return atomic_add(target, 1); + return atomic_add(target, 1); } #else extern atomic_val_t atomic_inc(atomic_t *target); @@ -122,7 +122,7 @@ extern atomic_val_t atomic_inc(atomic_t *target); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_dec(atomic_t *target) { - return atomic_sub(target, 1); + return atomic_sub(target, 1); } #else extern atomic_val_t atomic_dec(atomic_t *target); @@ -141,7 +141,7 @@ extern atomic_val_t atomic_dec(atomic_t *target); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_get(const atomic_t *target) { - return __atomic_load_n(target, __ATOMIC_SEQ_CST); + return __atomic_load_n(target, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_get(const atomic_t *target); @@ -162,11 +162,11 @@ extern atomic_val_t atomic_get(const atomic_t *target); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_set(atomic_t *target, atomic_val_t value) { - /* This builtin, as described by Intel, is not a traditional - * test-and-set operation, but rather an atomic exchange operation. It - * writes value into *ptr, and returns the previous contents of *ptr. - */ - return __atomic_exchange_n(target, value, __ATOMIC_SEQ_CST); + /* This builtin, as described by Intel, is not a traditional + * test-and-set operation, but rather an atomic exchange operation. It + * writes value into *ptr, and returns the previous contents of *ptr. + */ + return __atomic_exchange_n(target, value, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_set(atomic_t *target, atomic_val_t value); @@ -186,7 +186,7 @@ extern atomic_val_t atomic_set(atomic_t *target, atomic_val_t value); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_clear(atomic_t *target) { - return atomic_set(target, 0); + return atomic_set(target, 0); } #else extern atomic_val_t atomic_clear(atomic_t *target); @@ -207,7 +207,7 @@ extern atomic_val_t atomic_clear(atomic_t *target); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_or(atomic_t *target, atomic_val_t value) { - return __atomic_fetch_or(target, value, __ATOMIC_SEQ_CST); + return __atomic_fetch_or(target, value, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_or(atomic_t *target, atomic_val_t value); @@ -228,7 +228,7 @@ extern atomic_val_t atomic_or(atomic_t *target, atomic_val_t value); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value) { - return __atomic_fetch_xor(target, value, __ATOMIC_SEQ_CST); + return __atomic_fetch_xor(target, value, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value); @@ -249,7 +249,7 @@ extern atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_and(atomic_t *target, atomic_val_t value) { - return __atomic_fetch_and(target, value, __ATOMIC_SEQ_CST); + return __atomic_fetch_and(target, value, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_and(atomic_t *target, atomic_val_t value); @@ -270,7 +270,7 @@ extern atomic_val_t atomic_and(atomic_t *target, atomic_val_t value); #ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN static inline atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value) { - return __atomic_fetch_nand(target, value, __ATOMIC_SEQ_CST); + return __atomic_fetch_nand(target, value, __ATOMIC_SEQ_CST); } #else extern atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value); @@ -313,7 +313,7 @@ extern atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value); * @param num_bits Number of bits needed. */ #define ATOMIC_DEFINE(name, num_bits) \ - atomic_t name[1 + ((num_bits) - 1) / ATOMIC_BITS] + atomic_t name[1 + ((num_bits) - 1) / ATOMIC_BITS] /** * @brief Atomically test a bit. @@ -328,9 +328,9 @@ extern atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value); */ static inline int atomic_test_bit(const atomic_t *target, int bit) { - atomic_val_t val = atomic_get(ATOMIC_ELEM(target, bit)); + atomic_val_t val = atomic_get(ATOMIC_ELEM(target, bit)); - return (1 & (val >> (bit & (ATOMIC_BITS - 1)))); + return (1 & (val >> (bit & (ATOMIC_BITS - 1)))); } /** @@ -346,12 +346,12 @@ static inline int atomic_test_bit(const atomic_t *target, int bit) */ static inline int atomic_test_and_clear_bit(atomic_t *target, int bit) { - atomic_val_t mask = ATOMIC_MASK(bit); - atomic_val_t old; + atomic_val_t mask = ATOMIC_MASK(bit); + atomic_val_t old; - old = atomic_and(ATOMIC_ELEM(target, bit), ~mask); + old = atomic_and(ATOMIC_ELEM(target, bit), ~mask); - return (old & mask) != 0; + return (old & mask) != 0; } /** @@ -367,12 +367,12 @@ static inline int atomic_test_and_clear_bit(atomic_t *target, int bit) */ static inline int atomic_test_and_set_bit(atomic_t *target, int bit) { - atomic_val_t mask = ATOMIC_MASK(bit); - atomic_val_t old; + atomic_val_t mask = ATOMIC_MASK(bit); + atomic_val_t old; - old = atomic_or(ATOMIC_ELEM(target, bit), mask); + old = atomic_or(ATOMIC_ELEM(target, bit), mask); - return (old & mask) != 0; + return (old & mask) != 0; } /** @@ -388,9 +388,9 @@ static inline int atomic_test_and_set_bit(atomic_t *target, int bit) */ static inline void atomic_clear_bit(atomic_t *target, int bit) { - atomic_val_t mask = ATOMIC_MASK(bit); + atomic_val_t mask = ATOMIC_MASK(bit); - atomic_and(ATOMIC_ELEM(target, bit), ~mask); + atomic_and(ATOMIC_ELEM(target, bit), ~mask); } /** @@ -406,9 +406,9 @@ static inline void atomic_clear_bit(atomic_t *target, int bit) */ static inline void atomic_set_bit(atomic_t *target, int bit) { - atomic_val_t mask = ATOMIC_MASK(bit); + atomic_val_t mask = ATOMIC_MASK(bit); - atomic_or(ATOMIC_ELEM(target, bit), mask); + atomic_or(ATOMIC_ELEM(target, bit), mask); } /** @@ -425,13 +425,13 @@ static inline void atomic_set_bit(atomic_t *target, int bit) */ static inline void atomic_set_bit_to(atomic_t *target, int bit, bool val) { - atomic_val_t mask = ATOMIC_MASK(bit); + atomic_val_t mask = ATOMIC_MASK(bit); - if (val) { - (void)atomic_or(ATOMIC_ELEM(target, bit), mask); - } else { - (void)atomic_and(ATOMIC_ELEM(target, bit), ~mask); - } + if (val) { + (void)atomic_or(ATOMIC_ELEM(target, bit), mask); + } else { + (void)atomic_and(ATOMIC_ELEM(target, bit), ~mask); + } } /** diff --git a/components/network/ble/blestack/src/common/include/errno.h b/components/network/ble/blestack/src/common/include/errno.h index 6acf9bdd..8d1d4ea3 100644 --- a/components/network/ble/blestack/src/common/include/errno.h +++ b/components/network/ble/blestack/src/common/include/errno.h @@ -11,7 +11,7 @@ * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. * - * @(#)errno.h 7.1 (Berkeley) 6/4/86 + * @(#)errno.h 7.1 (Berkeley) 6/4/86 */ #ifndef __INCerrnoh @@ -29,24 +29,24 @@ extern int *__errno(void); * POSIX Error codes */ -#define EPERM 1 /* Not owner */ -#define ENOENT 2 /* No such file or directory */ -#define ESRCH 3 /* No such context */ -#define EINTR 4 /* Interrupted system call */ -#define EIO 5 /* I/O error */ -#define ENXIO 6 /* No such device or address */ -#define E2BIG 7 /* Arg list too long */ +#define EPERM 1 /* Not owner */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such context */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* I/O error */ +#define ENXIO 6 /* No such device or address */ +#define E2BIG 7 /* Arg list too long */ #define ENOEXEC 8 /* Exec format error */ -#define EBADF 9 /* Bad file number */ +#define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No children */ #define EAGAIN 11 /* No more contexts */ #define ENOMEM 12 /* Not enough core */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTEMPTY 15 /* Directory not empty */ -#define EBUSY 16 /* Mount device busy */ +#define EBUSY 16 /* Mount device busy */ #define EEXIST 17 /* File exists */ -#define EXDEV 18 /* Cross-device link */ +#define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ @@ -55,12 +55,12 @@ extern int *__errno(void); #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ENAMETOOLONG 26 /* File name too long */ -#define EFBIG 27 /* File too large */ +#define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ -#define EROFS 30 /* Read-only file system */ +#define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ -#define EPIPE 32 /* Broken pipe */ +#define EPIPE 32 /* Broken pipe */ #define EDEADLK 33 /* Resource deadlock avoided */ #define ENOLCK 34 /* No locks available */ #define ENOTSUP 35 /* Unsupported value */ @@ -83,7 +83,7 @@ extern int *__errno(void); #define EAFNOSUPPORT 47 /* Addr family not supported */ #define EADDRINUSE 48 /* Address already in use */ #define EADDRNOTAVAIL 49 /* Can't assign requested address */ -#define ENOTSOCK 50 /* Socket operation on non-socket */ +#define ENOTSOCK 50 /* Socket operation on non-socket */ /* operational errors */ #define ENETUNREACH 51 /* Network is unreachable */ @@ -99,7 +99,7 @@ extern int *__errno(void); #define ECONNREFUSED 61 /* Connection refused */ #define ENETDOWN 62 /* Network is down */ #define ETXTBSY 63 /* Text file busy */ -#define ELOOP 64 /* Too many levels of symbolic links */ +#define ELOOP 64 /* Too many levels of symbolic links */ #define EHOSTUNREACH 65 /* No route to host */ #define ENOTBLK 66 /* Block device required */ #define EHOSTDOWN 67 /* Host is down */ diff --git a/components/network/ble/blestack/src/common/include/misc/__assert.h b/components/network/ble/blestack/src/common/include/misc/__assert.h index 48e1d326..b6ef5804 100644 --- a/components/network/ble/blestack/src/common/include/misc/__assert.h +++ b/components/network/ble/blestack/src/common/include/misc/__assert.h @@ -43,7 +43,7 @@ * This type of situation can be resolved using the __ASSERT_EVAL() macro. * * __ASSERT_EVAL ((void) foo(), - * int x = foo(), + * int x = foo(), * x != 0, * "foo() returned zero!"); * @@ -75,37 +75,37 @@ #if __ASSERT_ON #include #define __ASSERT(test, fmt, ...) \ - do { \ - if (!(test)) { \ - printk("ASSERTION FAIL [%s] @ %s:%d:\n\t", \ - _STRINGIFY(test), \ - __FILE__, \ - __LINE__); \ - printk(fmt, ##__VA_ARGS__); \ - for (;;) \ - ; /* spin thread */ \ - } \ - } while ((0)) + do { \ + if (!(test)) { \ + printk("ASSERTION FAIL [%s] @ %s:%d:\n\t", \ + _STRINGIFY(test), \ + __FILE__, \ + __LINE__); \ + printk(fmt, ##__VA_ARGS__); \ + for (;;) \ + ; /* spin thread */ \ + } \ + } while ((0)) #define __ASSERT_EVAL(expr1, expr2, test, fmt, ...) \ - do { \ - expr2; \ - __ASSERT(test, fmt, ##__VA_ARGS__); \ - } while (0) + do { \ + expr2; \ + __ASSERT(test, fmt, ##__VA_ARGS__); \ + } while (0) #if (__ASSERT_ON == 1) #warning "__ASSERT() statements are ENABLED" #endif #else #define __ASSERT(test, fmt, ...) \ - do {/* nothing */ \ - } while ((0)) + do {/* nothing */ \ + } while ((0)) #define __ASSERT_EVAL(expr1, expr2, test, fmt, ...) expr1 #endif #else #define __ASSERT(test, fmt, ...) \ - do {/* nothing */ \ - } while ((0)) + do {/* nothing */ \ + } while ((0)) #define __ASSERT_EVAL(expr1, expr2, test, fmt, ...) expr1 #endif diff --git a/components/network/ble/blestack/src/common/include/misc/byteorder.h b/components/network/ble/blestack/src/common/include/misc/byteorder.h index f1693a7c..24ecb38a 100644 --- a/components/network/ble/blestack/src/common/include/misc/byteorder.h +++ b/components/network/ble/blestack/src/common/include/misc/byteorder.h @@ -23,17 +23,17 @@ /* Internal helpers only used by the sys_* APIs further below */ #define __bswap_16(x) ((u16_t) ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))) #define __bswap_32(x) ((u32_t) ((((x) >> 24) & 0xff) | \ - (((x) >> 8) & 0xff00) | \ - (((x) & 0xff00) << 8) | \ - (((x) & 0xff) << 24))) + (((x) >> 8) & 0xff00) | \ + (((x) & 0xff00) << 8) | \ + (((x) & 0xff) << 24))) #define __bswap_64(x) ((u64_t) ((((x) >> 56) & 0xff) | \ - (((x) >> 40) & 0xff00) | \ - (((x) >> 24) & 0xff0000) | \ - (((x) >> 8) & 0xff000000) | \ - (((x) & 0xff000000) << 8) | \ - (((x) & 0xff0000) << 24) | \ - (((x) & 0xff00) << 40) | \ - (((x) & 0xff) << 56))) + (((x) >> 40) & 0xff00) | \ + (((x) >> 24) & 0xff0000) | \ + (((x) >> 8) & 0xff000000) | \ + (((x) & 0xff000000) << 8) | \ + (((x) & 0xff0000) << 24) | \ + (((x) & 0xff00) << 40) | \ + (((x) & 0xff) << 56))) /** @def sys_le16_to_cpu * @brief Convert 16-bit integer from little-endian to host endianness. @@ -156,8 +156,8 @@ */ static inline void sys_put_be16(u16_t val, u8_t dst[2]) { - dst[0] = val >> 8; - dst[1] = val; + dst[0] = val >> 8; + dst[1] = val; } /** @@ -171,8 +171,8 @@ static inline void sys_put_be16(u16_t val, u8_t dst[2]) */ static inline void sys_put_be32(u32_t val, u8_t dst[4]) { - sys_put_be16(val >> 16, dst); - sys_put_be16(val, &dst[2]); + sys_put_be16(val >> 16, dst); + sys_put_be16(val, &dst[2]); } /** @@ -186,8 +186,8 @@ static inline void sys_put_be32(u32_t val, u8_t dst[4]) */ static inline void sys_put_le16(u16_t val, u8_t dst[2]) { - dst[0] = val; - dst[1] = val >> 8; + dst[0] = val; + dst[1] = val >> 8; } /** @@ -201,8 +201,8 @@ static inline void sys_put_le16(u16_t val, u8_t dst[2]) */ static inline void sys_put_le32(u32_t val, u8_t dst[4]) { - sys_put_le16(val, dst); - sys_put_le16(val >> 16, &dst[2]); + sys_put_le16(val, dst); + sys_put_le16(val >> 16, &dst[2]); } /** @@ -216,8 +216,8 @@ static inline void sys_put_le32(u32_t val, u8_t dst[4]) */ static inline void sys_put_le64(u64_t val, u8_t dst[8]) { - sys_put_le32(val, dst); - sys_put_le32(val >> 32, &dst[4]); + sys_put_le32(val, dst); + sys_put_le32(val >> 32, &dst[4]); } /** @@ -232,7 +232,7 @@ static inline void sys_put_le64(u64_t val, u8_t dst[8]) */ static inline u16_t sys_get_be16(const u8_t src[2]) { - return ((u16_t)src[0] << 8) | src[1]; + return ((u16_t)src[0] << 8) | src[1]; } /** @@ -247,7 +247,7 @@ static inline u16_t sys_get_be16(const u8_t src[2]) */ static inline u32_t sys_get_be32(const u8_t src[4]) { - return ((u32_t)sys_get_be16(&src[0]) << 16) | sys_get_be16(&src[2]); + return ((u32_t)sys_get_be16(&src[0]) << 16) | sys_get_be16(&src[2]); } /** @@ -262,7 +262,7 @@ static inline u32_t sys_get_be32(const u8_t src[4]) */ static inline u16_t sys_get_le16(const u8_t src[2]) { - return ((u16_t)src[1] << 8) | src[0]; + return ((u16_t)src[1] << 8) | src[0]; } /** @@ -277,7 +277,7 @@ static inline u16_t sys_get_le16(const u8_t src[2]) */ static inline u32_t sys_get_le32(const u8_t src[4]) { - return ((u32_t)sys_get_le16(&src[2]) << 16) | sys_get_le16(&src[0]); + return ((u32_t)sys_get_le16(&src[2]) << 16) | sys_get_le16(&src[0]); } /** @@ -292,7 +292,7 @@ static inline u32_t sys_get_le32(const u8_t src[4]) */ static inline u64_t sys_get_le64(const u8_t src[8]) { - return ((u64_t)sys_get_le32(&src[4]) << 32) | sys_get_le32(&src[0]); + return ((u64_t)sys_get_le32(&src[4]) << 32) | sys_get_le32(&src[0]); } /** @@ -310,15 +310,15 @@ static inline u64_t sys_get_le64(const u8_t src[8]) */ static inline void sys_memcpy_swap(void *dst, const void *src, size_t length) { - __ASSERT(((src < dst && (src + length) <= dst) || - (src > dst && (dst + length) <= src)), - "Source and destination buffers must not overlap"); + __ASSERT(((src < dst && (src + length) <= dst) || + (src > dst && (dst + length) <= src)), + "Source and destination buffers must not overlap"); - src += length - 1; + src += length - 1; - for (; length > 0; length--) { - *((u8_t *)dst++) = *((u8_t *)src--); - } + for (; length > 0; length--) { + *((u8_t *)dst++) = *((u8_t *)src--); + } } /** @@ -333,14 +333,14 @@ static inline void sys_memcpy_swap(void *dst, const void *src, size_t length) */ static inline void sys_mem_swap(void *buf, size_t length) { - size_t i; + size_t i; - for (i = 0; i < (length/2); i++) { - u8_t tmp = ((u8_t *)buf)[i]; + for (i = 0; i < (length/2); i++) { + u8_t tmp = ((u8_t *)buf)[i]; - ((u8_t *)buf)[i] = ((u8_t *)buf)[length - 1 - i]; - ((u8_t *)buf)[length - 1 - i] = tmp; - } + ((u8_t *)buf)[i] = ((u8_t *)buf)[length - 1 - i]; + ((u8_t *)buf)[length - 1 - i] = tmp; + } } #endif /* __BYTEORDER_H__ */ diff --git a/components/network/ble/blestack/src/common/include/misc/dlist.h b/components/network/ble/blestack/src/common/include/misc/dlist.h index 5df9bd99..6e99de69 100644 --- a/components/network/ble/blestack/src/common/include/misc/dlist.h +++ b/components/network/ble/blestack/src/common/include/misc/dlist.h @@ -27,14 +27,14 @@ extern "C" { #endif struct _dnode { - union { - struct _dnode *head; /* ptr to head of list (sys_dlist_t) */ - struct _dnode *next; /* ptr to next node (sys_dnode_t) */ - }; - union { - struct _dnode *tail; /* ptr to tail of list (sys_dlist_t) */ - struct _dnode *prev; /* ptr to previous node (sys_dnode_t) */ - }; + union { + struct _dnode *head; /* ptr to head of list (sys_dlist_t) */ + struct _dnode *next; /* ptr to next node (sys_dnode_t) */ + }; + union { + struct _dnode *tail; /* ptr to tail of list (sys_dlist_t) */ + struct _dnode *prev; /* ptr to previous node (sys_dnode_t) */ + }; }; typedef struct _dnode sys_dlist_t; @@ -55,9 +55,9 @@ typedef struct _dnode sys_dnode_t; * @param __dl A pointer on a sys_dlist_t to iterate on * @param __dn A sys_dnode_t pointer to peek each node of the list */ -#define SYS_DLIST_FOR_EACH_NODE(__dl, __dn) \ - for (__dn = sys_dlist_peek_head(__dl); __dn; \ - __dn = sys_dlist_peek_next(__dl, __dn)) +#define SYS_DLIST_FOR_EACH_NODE(__dl, __dn) \ + for (__dn = sys_dlist_peek_head(__dl); __dn; \ + __dn = sys_dlist_peek_next(__dl, __dn)) /** * @brief Provide the primitive to iterate on a list, from a node in the list @@ -80,10 +80,10 @@ typedef struct _dnode sys_dnode_t; * it contains the starting node, or NULL to start from the head */ #define SYS_DLIST_ITERATE_FROM_NODE(__dl, __dn) \ - for (__dn = __dn ? sys_dlist_peek_next_no_check(__dl, __dn) \ - : sys_dlist_peek_head(__dl); \ - __dn; \ - __dn = sys_dlist_peek_next(__dl, __dn)) + for (__dn = __dn ? sys_dlist_peek_next_no_check(__dl, __dn) \ + : sys_dlist_peek_head(__dl); \ + __dn; \ + __dn = sys_dlist_peek_next(__dl, __dn)) /** * @brief Provide the primitive to safely iterate on a list @@ -101,11 +101,11 @@ typedef struct _dnode sys_dnode_t; * @param __dn A sys_dnode_t pointer to peek each node of the list * @param __dns A sys_dnode_t pointer for the loop to run safely */ -#define SYS_DLIST_FOR_EACH_NODE_SAFE(__dl, __dn, __dns) \ - for (__dn = sys_dlist_peek_head(__dl), \ - __dns = sys_dlist_peek_next(__dl, __dn); \ - __dn; __dn = __dns, \ - __dns = sys_dlist_peek_next(__dl, __dn)) +#define SYS_DLIST_FOR_EACH_NODE_SAFE(__dl, __dn, __dns) \ + for (__dn = sys_dlist_peek_head(__dl), \ + __dns = sys_dlist_peek_next(__dl, __dn); \ + __dn; __dn = __dns, \ + __dns = sys_dlist_peek_next(__dl, __dn)) /* * @brief Provide the primitive to resolve the container of a list node @@ -116,7 +116,7 @@ typedef struct _dnode sys_dnode_t; * @param __n The field name of sys_dnode_t within the container struct */ #define SYS_DLIST_CONTAINER(__dn, __cn, __n) \ - (__dn ? CONTAINER_OF(__dn, __typeof__(*__cn), __n) : NULL) + (__dn ? CONTAINER_OF(__dn, __typeof__(*__cn), __n) : NULL) /* * @brief Provide the primitive to peek container of the list head * @@ -125,7 +125,7 @@ typedef struct _dnode sys_dnode_t; * @param __n The field name of sys_dnode_t within the container struct */ #define SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n) \ - SYS_DLIST_CONTAINER(sys_dlist_peek_head(__dl), __cn, __n) + SYS_DLIST_CONTAINER(sys_dlist_peek_head(__dl), __cn, __n) /* * @brief Provide the primitive to peek the next container @@ -135,8 +135,8 @@ typedef struct _dnode sys_dnode_t; * @param __n The field name of sys_dnode_t within the container struct */ #define SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n) \ - ((__cn) ? SYS_DLIST_CONTAINER(sys_dlist_peek_next(__dl, &(__cn->__n)), \ - __cn, __n) : NULL) + ((__cn) ? SYS_DLIST_CONTAINER(sys_dlist_peek_next(__dl, &(__cn->__n)), \ + __cn, __n) : NULL) /** * @brief Provide the primitive to iterate on a list under a container @@ -152,9 +152,9 @@ typedef struct _dnode sys_dnode_t; * @param __cn A pointer to peek each entry of the list * @param __n The field name of sys_dnode_t within the container struct */ -#define SYS_DLIST_FOR_EACH_CONTAINER(__dl, __cn, __n) \ - for (__cn = SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n); __cn; \ - __cn = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n)) +#define SYS_DLIST_FOR_EACH_CONTAINER(__dl, __cn, __n) \ + for (__cn = SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n); __cn; \ + __cn = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n)) /** * @brief Provide the primitive to safely iterate on a list under a container @@ -171,11 +171,11 @@ typedef struct _dnode sys_dnode_t; * @param __cns A pointer for the loop to run safely * @param __n The field name of sys_dnode_t within the container struct */ -#define SYS_DLIST_FOR_EACH_CONTAINER_SAFE(__dl, __cn, __cns, __n) \ - for (__cn = SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n), \ - __cns = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n); __cn; \ - __cn = __cns, \ - __cns = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n)) +#define SYS_DLIST_FOR_EACH_CONTAINER_SAFE(__dl, __cn, __cns, __n) \ + for (__cn = SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n), \ + __cns = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n); __cn; \ + __cn = __cns, \ + __cns = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n)) /** * @brief initialize list @@ -187,8 +187,8 @@ typedef struct _dnode sys_dnode_t; static inline void sys_dlist_init(sys_dlist_t *list) { - list->head = (sys_dnode_t *)list; - list->tail = (sys_dnode_t *)list; + list->head = (sys_dnode_t *)list; + list->tail = (sys_dnode_t *)list; } #define SYS_DLIST_STATIC_INIT(ptr_to_list) {{(ptr_to_list)}, {(ptr_to_list)}} @@ -204,7 +204,7 @@ static inline void sys_dlist_init(sys_dlist_t *list) static inline int sys_dlist_is_head(sys_dlist_t *list, sys_dnode_t *node) { - return list->head == node; + return list->head == node; } /** @@ -218,7 +218,7 @@ static inline int sys_dlist_is_head(sys_dlist_t *list, sys_dnode_t *node) static inline int sys_dlist_is_tail(sys_dlist_t *list, sys_dnode_t *node) { - return list->tail == node; + return list->tail == node; } /** @@ -231,7 +231,7 @@ static inline int sys_dlist_is_tail(sys_dlist_t *list, sys_dnode_t *node) static inline int sys_dlist_is_empty(sys_dlist_t *list) { - return list->head == list; + return list->head == list; } /** @@ -246,7 +246,7 @@ static inline int sys_dlist_is_empty(sys_dlist_t *list) static inline int sys_dlist_has_multiple_nodes(sys_dlist_t *list) { - return list->head != list->tail; + return list->head != list->tail; } /** @@ -259,7 +259,7 @@ static inline int sys_dlist_has_multiple_nodes(sys_dlist_t *list) static inline sys_dnode_t *sys_dlist_peek_head(sys_dlist_t *list) { - return sys_dlist_is_empty(list) ? NULL : list->head; + return sys_dlist_is_empty(list) ? NULL : list->head; } /** @@ -274,7 +274,7 @@ static inline sys_dnode_t *sys_dlist_peek_head(sys_dlist_t *list) static inline sys_dnode_t *sys_dlist_peek_head_not_empty(sys_dlist_t *list) { - return list->head; + return list->head; } /** @@ -289,9 +289,9 @@ static inline sys_dnode_t *sys_dlist_peek_head_not_empty(sys_dlist_t *list) */ static inline sys_dnode_t *sys_dlist_peek_next_no_check(sys_dlist_t *list, - sys_dnode_t *node) + sys_dnode_t *node) { - return (node == list->tail) ? NULL : node->next; + return (node == list->tail) ? NULL : node->next; } /** @@ -305,9 +305,9 @@ static inline sys_dnode_t *sys_dlist_peek_next_no_check(sys_dlist_t *list, */ static inline sys_dnode_t *sys_dlist_peek_next(sys_dlist_t *list, - sys_dnode_t *node) + sys_dnode_t *node) { - return node ? sys_dlist_peek_next_no_check(list, node) : NULL; + return node ? sys_dlist_peek_next_no_check(list, node) : NULL; } /** @@ -320,7 +320,7 @@ static inline sys_dnode_t *sys_dlist_peek_next(sys_dlist_t *list, static inline sys_dnode_t *sys_dlist_peek_tail(sys_dlist_t *list) { - return sys_dlist_is_empty(list) ? NULL : list->tail; + return sys_dlist_is_empty(list) ? NULL : list->tail; } /** @@ -336,11 +336,11 @@ static inline sys_dnode_t *sys_dlist_peek_tail(sys_dlist_t *list) static inline void sys_dlist_append(sys_dlist_t *list, sys_dnode_t *node) { - node->next = list; - node->prev = list->tail; + node->next = list; + node->prev = list->tail; - list->tail->next = node; - list->tail = node; + list->tail->next = node; + list->tail = node; } /** @@ -356,11 +356,11 @@ static inline void sys_dlist_append(sys_dlist_t *list, sys_dnode_t *node) static inline void sys_dlist_prepend(sys_dlist_t *list, sys_dnode_t *node) { - node->next = list->head; - node->prev = list; + node->next = list->head; + node->prev = list; - list->head->prev = node; - list->head = node; + list->head->prev = node; + list->head = node; } /** @@ -377,16 +377,16 @@ static inline void sys_dlist_prepend(sys_dlist_t *list, sys_dnode_t *node) */ static inline void sys_dlist_insert_after(sys_dlist_t *list, - sys_dnode_t *insert_point, sys_dnode_t *node) + sys_dnode_t *insert_point, sys_dnode_t *node) { - if (!insert_point) { - sys_dlist_prepend(list, node); - } else { - node->next = insert_point->next; - node->prev = insert_point; - insert_point->next->prev = node; - insert_point->next = node; - } + if (!insert_point) { + sys_dlist_prepend(list, node); + } else { + node->next = insert_point->next; + node->prev = insert_point; + insert_point->next->prev = node; + insert_point->next = node; + } } /** @@ -403,16 +403,16 @@ static inline void sys_dlist_insert_after(sys_dlist_t *list, */ static inline void sys_dlist_insert_before(sys_dlist_t *list, - sys_dnode_t *insert_point, sys_dnode_t *node) + sys_dnode_t *insert_point, sys_dnode_t *node) { - if (!insert_point) { - sys_dlist_append(list, node); - } else { - node->prev = insert_point->prev; - node->next = insert_point; - insert_point->prev->next = node; - insert_point->prev = node; - } + if (!insert_point) { + sys_dlist_append(list, node); + } else { + node->prev = insert_point->prev; + node->next = insert_point; + insert_point->prev->next = node; + insert_point->prev = node; + } } /** @@ -433,18 +433,18 @@ static inline void sys_dlist_insert_before(sys_dlist_t *list, */ static inline void sys_dlist_insert_at(sys_dlist_t *list, sys_dnode_t *node, - int (*cond)(sys_dnode_t *, void *), void *data) + int (*cond)(sys_dnode_t *, void *), void *data) { - if (sys_dlist_is_empty(list)) { - sys_dlist_append(list, node); - } else { - sys_dnode_t *pos = sys_dlist_peek_head(list); + if (sys_dlist_is_empty(list)) { + sys_dlist_append(list, node); + } else { + sys_dnode_t *pos = sys_dlist_peek_head(list); - while (pos && !cond(pos, data)) { - pos = sys_dlist_peek_next(list, pos); - } - sys_dlist_insert_before(list, pos, node); - } + while (pos && !cond(pos, data)) { + pos = sys_dlist_peek_next(list, pos); + } + sys_dlist_insert_before(list, pos, node); + } } /** @@ -460,8 +460,8 @@ static inline void sys_dlist_insert_at(sys_dlist_t *list, sys_dnode_t *node, static inline void sys_dlist_remove(sys_dnode_t *node) { - node->prev->next = node->next; - node->next->prev = node->prev; + node->prev->next = node->next; + node->next->prev = node->prev; } /** @@ -476,15 +476,15 @@ static inline void sys_dlist_remove(sys_dnode_t *node) static inline sys_dnode_t *sys_dlist_get(sys_dlist_t *list) { - sys_dnode_t *node; + sys_dnode_t *node; - if (sys_dlist_is_empty(list)) { - return NULL; - } + if (sys_dlist_is_empty(list)) { + return NULL; + } - node = list->head; - sys_dlist_remove(node); - return node; + node = list->head; + sys_dlist_remove(node); + return node; } #ifdef __cplusplus diff --git a/components/network/ble/blestack/src/common/include/misc/slist.h b/components/network/ble/blestack/src/common/include/misc/slist.h index d95a9963..8a858f83 100644 --- a/components/network/ble/blestack/src/common/include/misc/slist.h +++ b/components/network/ble/blestack/src/common/include/misc/slist.h @@ -26,14 +26,14 @@ extern "C" { struct _snode { - struct _snode *next; + struct _snode *next; }; typedef struct _snode sys_snode_t; struct _slist { - sys_snode_t *head; - sys_snode_t *tail; + sys_snode_t *head; + sys_snode_t *tail; }; typedef struct _slist sys_slist_t; @@ -53,9 +53,9 @@ typedef struct _slist sys_slist_t; * @param __sl A pointer on a sys_slist_t to iterate on * @param __sn A sys_snode_t pointer to peek each node of the list */ -#define SYS_SLIST_FOR_EACH_NODE(__sl, __sn) \ - for (__sn = sys_slist_peek_head(__sl); __sn; \ - __sn = sys_slist_peek_next(__sn)) +#define SYS_SLIST_FOR_EACH_NODE(__sl, __sn) \ + for (__sn = sys_slist_peek_head(__sl); __sn; \ + __sn = sys_slist_peek_next(__sn)) /** * @brief Provide the primitive to iterate on a list, from a node in the list @@ -77,11 +77,11 @@ typedef struct _slist sys_slist_t; * @param __sn A sys_snode_t pointer to peek each node of the list * it contains the starting node, or NULL to start from the head */ -#define SYS_SLIST_ITERATE_FROM_NODE(__sl, __sn) \ - for (__sn = __sn ? sys_slist_peek_next_no_check(__sn) \ - : sys_slist_peek_head(__sl); \ - __sn; \ - __sn = sys_slist_peek_next(__sn)) +#define SYS_SLIST_ITERATE_FROM_NODE(__sl, __sn) \ + for (__sn = __sn ? sys_slist_peek_next_no_check(__sn) \ + : sys_slist_peek_head(__sl); \ + __sn; \ + __sn = sys_slist_peek_next(__sn)) /** * @brief Provide the primitive to safely iterate on a list @@ -99,11 +99,11 @@ typedef struct _slist sys_slist_t; * @param __sn A sys_snode_t pointer to peek each node of the list * @param __sns A sys_snode_t pointer for the loop to run safely */ -#define SYS_SLIST_FOR_EACH_NODE_SAFE(__sl, __sn, __sns) \ - for (__sn = sys_slist_peek_head(__sl), \ - __sns = sys_slist_peek_next(__sn); \ - __sn; __sn = __sns, \ - __sns = sys_slist_peek_next(__sn)) +#define SYS_SLIST_FOR_EACH_NODE_SAFE(__sl, __sn, __sns) \ + for (__sn = sys_slist_peek_head(__sl), \ + __sns = sys_slist_peek_next(__sn); \ + __sn; __sn = __sns, \ + __sns = sys_slist_peek_next(__sn)) /* * @brief Provide the primitive to resolve the container of a list node @@ -114,7 +114,7 @@ typedef struct _slist sys_slist_t; * @param __n The field name of sys_node_t within the container struct */ #define SYS_SLIST_CONTAINER(__ln, __cn, __n) \ - ((__ln) ? CONTAINER_OF((__ln), __typeof__(*(__cn)), __n) : NULL) + ((__ln) ? CONTAINER_OF((__ln), __typeof__(*(__cn)), __n) : NULL) /* * @brief Provide the primitive to peek container of the list head * @@ -123,7 +123,7 @@ typedef struct _slist sys_slist_t; * @param __n The field name of sys_node_t within the container struct */ #define SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n) \ - SYS_SLIST_CONTAINER(sys_slist_peek_head(__sl), __cn, __n) + SYS_SLIST_CONTAINER(sys_slist_peek_head(__sl), __cn, __n) /* * @brief Provide the primitive to peek container of the list tail @@ -133,7 +133,7 @@ typedef struct _slist sys_slist_t; * @param __n The field name of sys_node_t within the container struct */ #define SYS_SLIST_PEEK_TAIL_CONTAINER(__sl, __cn, __n) \ - SYS_SLIST_CONTAINER(sys_slist_peek_tail(__sl), __cn, __n) + SYS_SLIST_CONTAINER(sys_slist_peek_tail(__sl), __cn, __n) /* * @brief Provide the primitive to peek the next container @@ -143,8 +143,8 @@ typedef struct _slist sys_slist_t; */ #define SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n) \ - ((__cn) ? SYS_SLIST_CONTAINER(sys_slist_peek_next(&((__cn)->__n)), \ - __cn, __n) : NULL) + ((__cn) ? SYS_SLIST_CONTAINER(sys_slist_peek_next(&((__cn)->__n)), \ + __cn, __n) : NULL) /** * @brief Provide the primitive to iterate on a list under a container @@ -160,9 +160,9 @@ typedef struct _slist sys_slist_t; * @param __cn A pointer to peek each entry of the list * @param __n The field name of sys_node_t within the container struct */ -#define SYS_SLIST_FOR_EACH_CONTAINER(__sl, __cn, __n) \ - for (__cn = SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n); __cn; \ - __cn = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n)) +#define SYS_SLIST_FOR_EACH_CONTAINER(__sl, __cn, __n) \ + for (__cn = SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n); __cn; \ + __cn = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n)) /** * @brief Provide the primitive to safely iterate on a list under a container @@ -179,10 +179,10 @@ typedef struct _slist sys_slist_t; * @param __cns A pointer for the loop to run safely * @param __n The field name of sys_node_t within the container struct */ -#define SYS_SLIST_FOR_EACH_CONTAINER_SAFE(__sl, __cn, __cns, __n) \ - for (__cn = SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n), \ - __cns = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n); __cn; \ - __cn = __cns, __cns = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n)) +#define SYS_SLIST_FOR_EACH_CONTAINER_SAFE(__sl, __cn, __cns, __n) \ + for (__cn = SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n), \ + __cns = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n); __cn; \ + __cn = __cns, __cns = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n)) /** * @brief Initialize a list @@ -191,8 +191,8 @@ typedef struct _slist sys_slist_t; */ static inline void sys_slist_init(sys_slist_t *list) { - list->head = NULL; - list->tail = NULL; + list->head = NULL; + list->tail = NULL; } #define SYS_SLIST_STATIC_INIT(ptr_to_list) {NULL, NULL} @@ -206,7 +206,7 @@ static inline void sys_slist_init(sys_slist_t *list) */ static inline bool sys_slist_is_empty(sys_slist_t *list) { - return (!list->head); + return (!list->head); } /** @@ -218,7 +218,7 @@ static inline bool sys_slist_is_empty(sys_slist_t *list) */ static inline sys_snode_t *sys_slist_peek_head(sys_slist_t *list) { - return list->head; + return list->head; } /** @@ -230,7 +230,7 @@ static inline sys_snode_t *sys_slist_peek_head(sys_slist_t *list) */ static inline sys_snode_t *sys_slist_peek_tail(sys_slist_t *list) { - return list->tail; + return list->tail; } /** @@ -244,7 +244,7 @@ static inline sys_snode_t *sys_slist_peek_tail(sys_slist_t *list) */ static inline sys_snode_t *sys_slist_peek_next_no_check(sys_snode_t *node) { - return node->next; + return node->next; } /** @@ -256,7 +256,7 @@ static inline sys_snode_t *sys_slist_peek_next_no_check(sys_snode_t *node) */ static inline sys_snode_t *sys_slist_peek_next(sys_snode_t *node) { - return node ? sys_slist_peek_next_no_check(node) : NULL; + return node ? sys_slist_peek_next_no_check(node) : NULL; } /** @@ -268,14 +268,14 @@ static inline sys_snode_t *sys_slist_peek_next(sys_snode_t *node) * @param node A pointer on the node to prepend */ static inline void sys_slist_prepend(sys_slist_t *list, - sys_snode_t *node) + sys_snode_t *node) { - node->next = list->head; - list->head = node; + node->next = list->head; + list->head = node; - if (!list->tail) { - list->tail = list->head; - } + if (!list->tail) { + list->tail = list->head; + } } /** @@ -287,17 +287,17 @@ static inline void sys_slist_prepend(sys_slist_t *list, * @param node A pointer on the node to append */ static inline void sys_slist_append(sys_slist_t *list, - sys_snode_t *node) + sys_snode_t *node) { - node->next = NULL; + node->next = NULL; - if (!list->tail) { - list->tail = node; - list->head = node; - } else { - list->tail->next = node; - list->tail = node; - } + if (!list->tail) { + list->tail = node; + list->head = node; + } else { + list->tail->next = node; + list->tail = node; + } } /** @@ -312,15 +312,15 @@ static inline void sys_slist_append(sys_slist_t *list, * @param tail A pointer to the last element of the list to append */ static inline void sys_slist_append_list(sys_slist_t *list, - void *head, void *tail) + void *head, void *tail) { - if (!list->tail) { - list->head = (sys_snode_t *)head; - list->tail = (sys_snode_t *)tail; - } else { - list->tail->next = (sys_snode_t *)head; - list->tail = (sys_snode_t *)tail; - } + if (!list->tail) { + list->head = (sys_snode_t *)head; + list->tail = (sys_snode_t *)tail; + } else { + list->tail->next = (sys_snode_t *)head; + list->tail = (sys_snode_t *)tail; + } } /** @@ -333,11 +333,11 @@ static inline void sys_slist_append_list(sys_slist_t *list, * @param list_to_append A pointer to the list to append. */ static inline void sys_slist_merge_slist(sys_slist_t *list, - sys_slist_t *list_to_append) + sys_slist_t *list_to_append) { - sys_slist_append_list(list, list_to_append->head, - list_to_append->tail); - sys_slist_init(list_to_append); + sys_slist_append_list(list, list_to_append->head, + list_to_append->tail); + sys_slist_init(list_to_append); } /** @@ -350,17 +350,17 @@ static inline void sys_slist_merge_slist(sys_slist_t *list, * @param node A pointer on the node to insert */ static inline void sys_slist_insert(sys_slist_t *list, - sys_snode_t *prev, - sys_snode_t *node) + sys_snode_t *prev, + sys_snode_t *node) { - if (!prev) { - sys_slist_prepend(list, node); - } else if (!prev->next) { - sys_slist_append(list, node); - } else { - node->next = prev->next; - prev->next = node; - } + if (!prev) { + sys_slist_prepend(list, node); + } else if (!prev->next) { + sys_slist_append(list, node); + } else { + node->next = prev->next; + prev->next = node; + } } /** @@ -375,14 +375,14 @@ static inline void sys_slist_insert(sys_slist_t *list, */ static inline sys_snode_t *sys_slist_get_not_empty(sys_slist_t *list) { - sys_snode_t *node = list->head; + sys_snode_t *node = list->head; - list->head = node->next; - if (list->tail == node) { - list->tail = list->head; - } + list->head = node->next; + if (list->tail == node) { + list->tail = list->head; + } - return node; + return node; } /** @@ -396,7 +396,7 @@ static inline sys_snode_t *sys_slist_get_not_empty(sys_slist_t *list) */ static inline sys_snode_t *sys_slist_get(sys_slist_t *list) { - return sys_slist_is_empty(list) ? NULL : sys_slist_get_not_empty(list); + return sys_slist_is_empty(list) ? NULL : sys_slist_get_not_empty(list); } /** @@ -410,26 +410,26 @@ static inline sys_snode_t *sys_slist_get(sys_slist_t *list) * @param node A pointer on the node to remove */ static inline void sys_slist_remove(sys_slist_t *list, - sys_snode_t *prev_node, - sys_snode_t *node) + sys_snode_t *prev_node, + sys_snode_t *node) { - if (!prev_node) { - list->head = node->next; + if (!prev_node) { + list->head = node->next; - /* Was node also the tail? */ - if (list->tail == node) { - list->tail = list->head; - } - } else { - prev_node->next = node->next; + /* Was node also the tail? */ + if (list->tail == node) { + list->tail = list->head; + } + } else { + prev_node->next = node->next; - /* Was node the tail? */ - if (list->tail == node) { - list->tail = prev_node; - } - } + /* Was node the tail? */ + if (list->tail == node) { + list->tail = prev_node; + } + } - node->next = NULL; + node->next = NULL; } /** @@ -443,21 +443,21 @@ static inline void sys_slist_remove(sys_slist_t *list, * @return true if node was removed */ static inline bool sys_slist_find_and_remove(sys_slist_t *list, - sys_snode_t *node) + sys_snode_t *node) { - sys_snode_t *prev = NULL; - sys_snode_t *test; + sys_snode_t *prev = NULL; + sys_snode_t *test; - SYS_SLIST_FOR_EACH_NODE(list, test) { - if (test == node) { - sys_slist_remove(list, prev, node); - return true; - } + SYS_SLIST_FOR_EACH_NODE(list, test) { + if (test == node) { + sys_slist_remove(list, prev, node); + return true; + } - prev = test; - } + prev = test; + } - return false; + return false; } diff --git a/components/network/ble/blestack/src/common/include/misc/stack.h b/components/network/ble/blestack/src/common/include/misc/stack.h index 6a745535..eb539b79 100644 --- a/components/network/ble/blestack/src/common/include/misc/stack.h +++ b/components/network/ble/blestack/src/common/include/misc/stack.h @@ -17,71 +17,71 @@ #if defined(CONFIG_INIT_STACKS) static inline size_t stack_unused_space_get(const char *stack, size_t size) { - size_t unused = 0; - int i; + size_t unused = 0; + int i; #ifdef CONFIG_STACK_SENTINEL - /* First 4 bytes of the stack buffer reserved for the sentinel - * value, it won't be 0xAAAAAAAA for thread stacks. - */ - stack += 4; + /* First 4 bytes of the stack buffer reserved for the sentinel + * value, it won't be 0xAAAAAAAA for thread stacks. + */ + stack += 4; #endif - /* TODO Currently all supported platforms have stack growth down and - * there is no Kconfig option to configure it so this always build - * "else" branch. When support for platform with stack direction up - * (or configurable direction) is added this check should be confirmed - * that correct Kconfig option is used. - */ + /* TODO Currently all supported platforms have stack growth down and + * there is no Kconfig option to configure it so this always build + * "else" branch. When support for platform with stack direction up + * (or configurable direction) is added this check should be confirmed + * that correct Kconfig option is used. + */ #if defined(STACK_GROWS_UP) - for (i = size - 1; i >= 0; i--) { - if ((unsigned char)stack[i] == 0xaa) { - unused++; - } else { - break; - } - } + for (i = size - 1; i >= 0; i--) { + if ((unsigned char)stack[i] == 0xaa) { + unused++; + } else { + break; + } + } #else - for (i = 0; i < size; i++) { - if ((unsigned char)stack[i] == 0xaa) { - unused++; - } else { - break; - } - } + for (i = 0; i < size; i++) { + if ((unsigned char)stack[i] == 0xaa) { + unused++; + } else { + break; + } + } #endif - return unused; + return unused; } #else static inline size_t stack_unused_space_get(const char *stack, size_t size) { - return 0; + return 0; } #endif #if defined(CONFIG_INIT_STACKS) && defined(CONFIG_PRINTK) static inline void stack_analyze(const char *name, const char *stack, - unsigned int size) + unsigned int size) { - unsigned int pcnt, unused = 0; + unsigned int pcnt, unused = 0; - unused = stack_unused_space_get(stack, size); + unused = stack_unused_space_get(stack, size); - /* Calculate the real size reserved for the stack */ - pcnt = ((size - unused) * 100) / size; + /* Calculate the real size reserved for the stack */ + pcnt = ((size - unused) * 100) / size; - printk("%s (real size %u):\tunused %u\tusage %u / %u (%u %%)\n", name, - size, unused, size - unused, size, pcnt); + printk("%s (real size %u):\tunused %u\tusage %u / %u (%u %%)\n", name, + size, unused, size - unused, size, pcnt); } #else static inline void stack_analyze(const char *name, const char *stack, - unsigned int size) + unsigned int size) { } #endif #define STACK_ANALYZE(name, sym) \ - stack_analyze(name, K_THREAD_STACK_BUFFER(sym), \ - K_THREAD_STACK_SIZEOF(sym)) + stack_analyze(name, K_THREAD_STACK_BUFFER(sym), \ + K_THREAD_STACK_SIZEOF(sym)) #endif /* _MISC_STACK_H_ */ diff --git a/components/network/ble/blestack/src/common/include/misc/util.h b/components/network/ble/blestack/src/common/include/misc/util.h index d5142c43..dd211ad5 100644 --- a/components/network/ble/blestack/src/common/include/misc/util.h +++ b/components/network/ble/blestack/src/common/include/misc/util.h @@ -41,34 +41,34 @@ extern "C" { * pointer) */ #define IS_ARRAY(array) \ - ZERO_OR_COMPILE_ERROR( \ - !__builtin_types_compatible_p(__typeof__(array), \ - __typeof__(&(array)[0]))) + ZERO_OR_COMPILE_ERROR( \ + !__builtin_types_compatible_p(__typeof__(array), \ + __typeof__(&(array)[0]))) /* Evaluates to number of elements in an array; compile error if not * an array (e.g. pointer) */ #define ARRAY_SIZE(array) \ - ((unsigned long) (IS_ARRAY(array) + \ - (sizeof(array) / sizeof((array)[0])))) + ((unsigned long) (IS_ARRAY(array) + \ + (sizeof(array) / sizeof((array)[0])))) /* Evaluates to 1 if ptr is part of array, 0 otherwise; compile error if * "array" argument is not an array (e.g. "ptr" and "array" mixed up) */ #define PART_OF_ARRAY(array, ptr) \ - ((ptr) && ((ptr) >= &array[0] && (ptr) < &array[ARRAY_SIZE(array)])) + ((ptr) && ((ptr) >= &array[0] && (ptr) < &array[ARRAY_SIZE(array)])) #define CONTAINER_OF(ptr, type, field) \ - ((type *)(((char *)(ptr)) - offsetof(type, field))) + ((type *)(((char *)(ptr)) - offsetof(type, field))) /* round "x" up/down to next multiple of "align" (which must be a power of 2) */ #define ROUND_UP(x, align) \ - (((unsigned long)(x) + ((unsigned long)align - 1)) & \ - ~((unsigned long)align - 1)) + (((unsigned long)(x) + ((unsigned long)align - 1)) & \ + ~((unsigned long)align - 1)) #define ROUND_DOWN(x, align) ((unsigned long)(x) & ~((unsigned long)align - 1)) #define ceiling_fraction(numerator, divider) \ - (((numerator) + ((divider) - 1)) / (divider)) + (((numerator) + ((divider) - 1)) / (divider)) #ifdef INLINED #define INLINE inline @@ -94,25 +94,25 @@ unsigned int find_lsb_set(uint32_t data); static inline int is_power_of_two(unsigned int x) { - return (x != 0) && !(x & (x - 1)); + return (x != 0) && !(x & (x - 1)); } static inline s64_t arithmetic_shift_right(s64_t value, u8_t shift) { - s64_t sign_ext; + s64_t sign_ext; - if (shift == 0) { - return value; - } + if (shift == 0) { + return value; + } - /* extract sign bit */ - sign_ext = (value >> 63) & 1; + /* extract sign bit */ + sign_ext = (value >> 63) & 1; - /* make all bits of sign_ext be the same as the value's sign bit */ - sign_ext = -sign_ext; + /* make all bits of sign_ext be the same as the value's sign bit */ + sign_ext = -sign_ext; - /* shift value and fill opened bit positions with sign bit */ - return (value >> shift) | (sign_ext << (64 - shift)); + /* shift value and fill opened bit positions with sign bit */ + return (value >> shift) | (sign_ext << (64 - shift)); } #endif /* !_ASMLANGUAGE */ @@ -270,18 +270,18 @@ static inline s64_t arithmetic_shift_right(s64_t value, u8_t shift) #define UTIL_EXPAND(...) __VA_ARGS__ #define UTIL_WHEN(c) UTIL_IF(c)(UTIL_EXPAND, UTIL_EAT) -#define UTIL_REPEAT(count, macro, ...) \ - UTIL_WHEN(count) \ - ( \ - UTIL_OBSTRUCT(UTIL_REPEAT_INDIRECT) () \ - ( \ - UTIL_DEC(count), macro, __VA_ARGS__ \ - ) \ - UTIL_OBSTRUCT(macro) \ - ( \ - UTIL_DEC(count), __VA_ARGS__ \ - ) \ - ) +#define UTIL_REPEAT(count, macro, ...) \ + UTIL_WHEN(count) \ + ( \ + UTIL_OBSTRUCT(UTIL_REPEAT_INDIRECT) () \ + ( \ + UTIL_DEC(count), macro, __VA_ARGS__ \ + ) \ + UTIL_OBSTRUCT(macro) \ + ( \ + UTIL_DEC(count), __VA_ARGS__ \ + ) \ + ) #define UTIL_REPEAT_INDIRECT() UTIL_REPEAT /** diff --git a/components/network/ble/blestack/src/common/include/net/buf.h b/components/network/ble/blestack/src/common/include/net/buf.h index 69cc752e..2ef9862d 100644 --- a/components/network/ble/blestack/src/common/include/net/buf.h +++ b/components/network/ble/blestack/src/common/include/net/buf.h @@ -40,13 +40,13 @@ extern "C" { * @param _size Maximum data storage for the buffer. */ #define NET_BUF_SIMPLE_DEFINE(_name, _size) \ - u8_t net_buf_data_##_name[_size]; \ - struct net_buf_simple _name = { \ - .data = net_buf_data_##_name, \ - .len = 0, \ - .size = _size, \ - .__buf = net_buf_data_##_name, \ - } + u8_t net_buf_data_##_name[_size]; \ + struct net_buf_simple _name = { \ + .data = net_buf_data_##_name, \ + .len = 0, \ + .size = _size, \ + .__buf = net_buf_data_##_name, \ + } /** @def NET_BUF_SIMPLE_DEFINE_STATIC * @brief Define a static net_buf_simple variable. @@ -58,13 +58,13 @@ extern "C" { * @param _size Maximum data storage for the buffer. */ #define NET_BUF_SIMPLE_DEFINE_STATIC(_name, _size) \ - static /*__noinit*/ u8_t net_buf_data_##_name[_size]; \ - static struct net_buf_simple _name = { \ - .data = net_buf_data_##_name, \ - .len = 0, \ - .size = _size, \ - .__buf = net_buf_data_##_name, \ - } + static /*__noinit*/ u8_t net_buf_data_##_name[_size]; \ + static struct net_buf_simple _name = { \ + .data = net_buf_data_##_name, \ + .len = 0, \ + .size = _size, \ + .__buf = net_buf_data_##_name, \ + } /** @brief Simple network buffer representation. * @@ -80,19 +80,19 @@ extern "C" { * */ struct net_buf_simple { - /** Pointer to the start of data in the buffer. */ - u8_t *data; + /** Pointer to the start of data in the buffer. */ + u8_t *data; - /** Length of the data behind the data pointer. */ - u16_t len; + /** Length of the data behind the data pointer. */ + u16_t len; - /** Amount of data that this buffer can store. */ - u16_t size; + /** Amount of data that this buffer can store. */ + u16_t size; - /** Start of the data storage. Not to be accessed directly - * (the data pointer should be used instead). - */ - u8_t *__buf; + /** Start of the data storage. Not to be accessed directly + * (the data pointer should be used instead). + */ + u8_t *__buf; }; /** @def NET_BUF_SIMPLE @@ -111,12 +111,12 @@ struct net_buf_simple { * @return Pointer to stack-allocated net_buf_simple object. */ #define NET_BUF_SIMPLE(_size) \ - ((struct net_buf_simple *)(&(struct { \ - struct net_buf_simple buf; \ - u8_t data[_size] __net_buf_align; \ - }) { \ - .buf.size = _size, \ - })) + ((struct net_buf_simple *)(&(struct { \ + struct net_buf_simple buf; \ + u8_t data[_size] __net_buf_align; \ + }) { \ + .buf.size = _size, \ + })) /** @brief Initialize a net_buf_simple object. * @@ -127,14 +127,14 @@ struct net_buf_simple { * @param reserve_head Headroom to reserve. */ static inline void net_buf_simple_init(struct net_buf_simple *buf, - size_t reserve_head) + size_t reserve_head) { - if (!buf->__buf) { - buf->__buf = (u8_t *)buf + sizeof(*buf); - } + if (!buf->__buf) { + buf->__buf = (u8_t *)buf + sizeof(*buf); + } - buf->data = buf->__buf + reserve_head; - buf->len = 0; + buf->data = buf->__buf + reserve_head; + buf->len = 0; } /** @@ -146,8 +146,8 @@ static inline void net_buf_simple_init(struct net_buf_simple *buf, */ static inline void net_buf_simple_reset(struct net_buf_simple *buf) { - buf->len = 0; - buf->data = buf->__buf; + buf->len = 0; + buf->data = buf->__buf; } /** @@ -176,7 +176,7 @@ void *net_buf_simple_add(struct net_buf_simple *buf, size_t len); * @return The original tail of the buffer. */ void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem, - size_t len); + size_t len); /** * @brief Add (8-bit) byte at the end of the buffer @@ -381,7 +381,7 @@ u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf); */ static inline u8_t *net_buf_simple_tail(struct net_buf_simple *buf) { - return buf->data + buf->len; + return buf->data + buf->len; } /** @@ -414,10 +414,10 @@ size_t net_buf_simple_tailroom(struct net_buf_simple *buf); * control. */ struct net_buf_simple_state { - /** Offset of the data pointer from the beginning of the storage */ - u16_t offset; - /** Length of data */ - u16_t len; + /** Offset of the data pointer from the beginning of the storage */ + u16_t offset; + /** Length of data */ + u16_t len; }; /** @@ -429,10 +429,10 @@ struct net_buf_simple_state { * @param state Storage for the state. */ static inline void net_buf_simple_save(struct net_buf_simple *buf, - struct net_buf_simple_state *state) + struct net_buf_simple_state *state) { - state->offset = net_buf_simple_headroom(buf); - state->len = buf->len; + state->offset = net_buf_simple_headroom(buf); + state->len = buf->len; } /** @@ -445,10 +445,10 @@ static inline void net_buf_simple_save(struct net_buf_simple *buf, * @param state Stored state. */ static inline void net_buf_simple_restore(struct net_buf_simple *buf, - struct net_buf_simple_state *state) + struct net_buf_simple_state *state) { - buf->data = buf->__buf + state->offset; - buf->len = state->len; + buf->data = buf->__buf + state->offset; + buf->len = state->len; } /** Flag indicating that the buffer has associated fragments. Only used @@ -476,116 +476,116 @@ static inline void net_buf_simple_restore(struct net_buf_simple *buf, * using the net_buf_alloc() API. */ struct net_buf { - union { - /** Allow placing the buffer into sys_slist_t */ - sys_snode_t node; + union { + /** Allow placing the buffer into sys_slist_t */ + sys_snode_t node; - /** Fragments associated with this buffer. */ - struct net_buf *frags; - }; + /** Fragments associated with this buffer. */ + struct net_buf *frags; + }; - /** Reference count. */ - u8_t ref; + /** Reference count. */ + u8_t ref; - /** Bit-field of buffer flags. */ - u8_t flags; + /** Bit-field of buffer flags. */ + u8_t flags; - /** Where the buffer should go when freed up. */ - u8_t pool_id; + /** Where the buffer should go when freed up. */ + u8_t pool_id; - /* Union for convenience access to the net_buf_simple members, also - * preserving the old API. - */ - union { - /* The ABI of this struct must match net_buf_simple */ - struct { - /** Pointer to the start of data in the buffer. */ - u8_t *data; + /* Union for convenience access to the net_buf_simple members, also + * preserving the old API. + */ + union { + /* The ABI of this struct must match net_buf_simple */ + struct { + /** Pointer to the start of data in the buffer. */ + u8_t *data; - /** Length of the data behind the data pointer. */ - u16_t len; + /** Length of the data behind the data pointer. */ + u16_t len; - /** Amount of data that this buffer can store. */ - u16_t size; + /** Amount of data that this buffer can store. */ + u16_t size; - /** Start of the data storage. Not to be accessed - * directly (the data pointer should be used - * instead). - */ - u8_t *__buf; - }; + /** Start of the data storage. Not to be accessed + * directly (the data pointer should be used + * instead). + */ + u8_t *__buf; + }; - struct net_buf_simple b; - }; + struct net_buf_simple b; + }; - /** System metadata for this buffer. */ - u8_t user_data[CONFIG_NET_BUF_USER_DATA_SIZE] __net_buf_align; + /** System metadata for this buffer. */ + u8_t user_data[CONFIG_NET_BUF_USER_DATA_SIZE] __net_buf_align; }; struct net_buf_data_cb { - u8_t * (*alloc)(struct net_buf *buf, size_t *size, s32_t timeout); - u8_t * (*ref)(struct net_buf *buf, u8_t *data); - void (*unref)(struct net_buf *buf, u8_t *data); + u8_t * (*alloc)(struct net_buf *buf, size_t *size, s32_t timeout); + u8_t * (*ref)(struct net_buf *buf, u8_t *data); + void (*unref)(struct net_buf *buf, u8_t *data); }; struct net_buf_data_alloc { - const struct net_buf_data_cb *cb; - void *alloc_data; + const struct net_buf_data_cb *cb; + void *alloc_data; }; struct net_buf_pool { - /** LIFO to place the buffer into when free */ - struct k_lifo free; + /** LIFO to place the buffer into when free */ + struct k_lifo free; - /** Number of buffers in pool */ - const u16_t buf_count; + /** Number of buffers in pool */ + const u16_t buf_count; - /** Number of uninitialized buffers */ - u16_t uninit_count; + /** Number of uninitialized buffers */ + u16_t uninit_count; #if defined(CONFIG_NET_BUF_POOL_USAGE) - /** Amount of available buffers in the pool. */ - s16_t avail_count; + /** Amount of available buffers in the pool. */ + s16_t avail_count; - /** Total size of the pool. */ - const u16_t pool_size; + /** Total size of the pool. */ + const u16_t pool_size; - /** Name of the pool. Used when printing pool information. */ - const char *name; + /** Name of the pool. Used when printing pool information. */ + const char *name; #endif /* CONFIG_NET_BUF_POOL_USAGE */ - /** Optional destroy callback when buffer is freed. */ - void (*const destroy)(struct net_buf *buf); + /** Optional destroy callback when buffer is freed. */ + void (*const destroy)(struct net_buf *buf); - /** Data allocation handlers. */ - const struct net_buf_data_alloc *alloc; + /** Data allocation handlers. */ + const struct net_buf_data_alloc *alloc; - /** Start of buffer storage array */ - struct net_buf * const __bufs; + /** Start of buffer storage array */ + struct net_buf * const __bufs; }; #if defined(CONFIG_NET_BUF_POOL_USAGE) #define NET_BUF_POOL_INITIALIZER(_pool, _alloc, _bufs, _count, _destroy) \ - { \ - .alloc = _alloc, \ - .free = _K_LIFO_INITIALIZER(_pool.free), \ - .__bufs = _bufs, \ - .buf_count = _count, \ - .uninit_count = _count, \ - .avail_count = _count, \ - .destroy = _destroy, \ - .name = STRINGIFY(_pool), \ - } + { \ + .alloc = _alloc, \ + .free = _K_LIFO_INITIALIZER(_pool.free), \ + .__bufs = _bufs, \ + .buf_count = _count, \ + .uninit_count = _count, \ + .avail_count = _count, \ + .destroy = _destroy, \ + .name = STRINGIFY(_pool), \ + } #else #define NET_BUF_POOL_INITIALIZER(_pool, _alloc, _bufs, _count, _destroy) \ - { \ - .alloc = _alloc, \ - .free = _K_LIFO_INITIALIZER(_pool.free), \ - .__bufs = _bufs, \ - .buf_count = _count, \ - .uninit_count = _count, \ - .destroy = _destroy, \ - } + { \ + .alloc = _alloc, \ + .free = _K_LIFO_INITIALIZER(_pool.free), \ + .__bufs = _bufs, \ + .buf_count = _count, \ + .uninit_count = _count, \ + .destroy = _destroy, \ + } #endif /* CONFIG_NET_BUF_POOL_USAGE */ extern const struct net_buf_data_alloc net_buf_heap_alloc; @@ -616,15 +616,15 @@ extern const struct net_buf_data_alloc net_buf_heap_alloc; * @param _destroy Optional destroy callback when buffer is freed. */ #define NET_BUF_POOL_HEAP_DEFINE(_name, _count, _destroy) \ - static struct net_buf net_buf_##_name[_count] __noinit; \ - struct net_buf_pool _name __net_buf_align \ - __in_section(_net_buf_pool, static, _name) = \ - NET_BUF_POOL_INITIALIZER(_name, &net_buf_heap_alloc, \ - net_buf_##_name, _count, _destroy) + static struct net_buf net_buf_##_name[_count] __noinit; \ + struct net_buf_pool _name __net_buf_align \ + __in_section(_net_buf_pool, static, _name) = \ + NET_BUF_POOL_INITIALIZER(_name, &net_buf_heap_alloc, \ + net_buf_##_name, _count, _destroy) struct net_buf_pool_fixed { - size_t data_size; - u8_t *data_pool; + size_t data_size; + u8_t *data_pool; }; extern const struct net_buf_data_cb net_buf_fixed_cb; @@ -656,20 +656,20 @@ extern const struct net_buf_data_cb net_buf_fixed_cb; * @param _destroy Optional destroy callback when buffer is freed. */ #define NET_BUF_POOL_FIXED_DEFINE(_name, _count, _data_size, _destroy) \ - static struct net_buf net_buf_##_name[_count]; \ - static u8_t net_buf_data_##_name[_count][_data_size]; \ - static const struct net_buf_pool_fixed net_buf_fixed_##_name = { \ - .data_size = _data_size, \ - .data_pool = (u8_t *)net_buf_data_##_name, \ - }; \ - static const struct net_buf_data_alloc net_buf_fixed_alloc_##_name = {\ - .cb = &net_buf_fixed_cb, \ - .alloc_data = (void *)&net_buf_fixed_##_name, \ - }; \ - struct net_buf_pool _name __net_buf_align \ - __in_section(_net_buf_pool, static, _name) = \ - NET_BUF_POOL_INITIALIZER(_name, &net_buf_fixed_alloc_##_name, \ - net_buf_##_name, _count, _destroy) + static struct net_buf net_buf_##_name[_count]; \ + static u8_t net_buf_data_##_name[_count][_data_size]; \ + static const struct net_buf_pool_fixed net_buf_fixed_##_name = { \ + .data_size = _data_size, \ + .data_pool = (u8_t *)net_buf_data_##_name, \ + }; \ + static const struct net_buf_data_alloc net_buf_fixed_alloc_##_name = {\ + .cb = &net_buf_fixed_cb, \ + .alloc_data = (void *)&net_buf_fixed_##_name, \ + }; \ + struct net_buf_pool _name __net_buf_align \ + __in_section(_net_buf_pool, static, _name) = \ + NET_BUF_POOL_INITIALIZER(_name, &net_buf_fixed_alloc_##_name, \ + net_buf_##_name, _count, _destroy) #if (!BFLB_BLE) extern const struct net_buf_data_cb net_buf_var_cb; @@ -697,16 +697,16 @@ extern const struct net_buf_data_cb net_buf_var_cb; * @param _destroy Optional destroy callback when buffer is freed. */ #define NET_BUF_POOL_VAR_DEFINE(_name, _count, _data_size, _destroy) \ - static struct net_buf _net_buf_##_name[_count] __noinit; \ - K_MEM_POOL_DEFINE(net_buf_mem_pool_##_name, 16, _data_size, 1, 4); \ - static const struct net_buf_data_alloc net_buf_data_alloc_##_name = { \ - .cb = &net_buf_var_cb, \ - .alloc_data = &net_buf_mem_pool_##_name, \ - }; \ - struct net_buf_pool _name __net_buf_align \ - __in_section(_net_buf_pool, static, _name) = \ - NET_BUF_POOL_INITIALIZER(_name, &net_buf_data_alloc_##_name, \ - _net_buf_##_name, _count, _destroy) + static struct net_buf _net_buf_##_name[_count] __noinit; \ + K_MEM_POOL_DEFINE(net_buf_mem_pool_##_name, 16, _data_size, 1, 4); \ + static const struct net_buf_data_alloc net_buf_data_alloc_##_name = { \ + .cb = &net_buf_var_cb, \ + .alloc_data = &net_buf_mem_pool_##_name, \ + }; \ + struct net_buf_pool _name __net_buf_align \ + __in_section(_net_buf_pool, static, _name) = \ + NET_BUF_POOL_INITIALIZER(_name, &net_buf_data_alloc_##_name, \ + _net_buf_##_name, _count, _destroy) #endif /** @def NET_BUF_POOL_DEFINE * @brief Define a new pool for buffers @@ -729,8 +729,8 @@ extern const struct net_buf_data_cb net_buf_var_cb; * @param _destroy Optional destroy callback when buffer is freed. */ #define NET_BUF_POOL_DEFINE(_name, _count, _size, _ud_size, _destroy) \ - BUILD_ASSERT(_ud_size <= CONFIG_NET_BUF_USER_DATA_SIZE); \ - NET_BUF_POOL_FIXED_DEFINE(_name, _count, _size, _destroy) + BUILD_ASSERT(_ud_size <= CONFIG_NET_BUF_USER_DATA_SIZE); \ + NET_BUF_POOL_FIXED_DEFINE(_name, _count, _size, _destroy) /** * @brief Looks up a pool based on its ID. @@ -773,10 +773,10 @@ int net_buf_id(struct net_buf *buf); */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool, - s32_t timeout, const char *func, - int line); + s32_t timeout, const char *func, + int line); #define net_buf_alloc_fixed(_pool, _timeout) \ - net_buf_alloc_fixed_debug(_pool, _timeout, __func__, __LINE__) + net_buf_alloc_fixed_debug(_pool, _timeout, __func__, __LINE__) #else struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout); #endif @@ -802,13 +802,13 @@ struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout); */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size, - s32_t timeout, const char *func, - int line); + s32_t timeout, const char *func, + int line); #define net_buf_alloc_len(_pool, _size, _timeout) \ - net_buf_alloc_len_debug(_pool, _size, _timeout, __func__, __LINE__) + net_buf_alloc_len_debug(_pool, _size, _timeout, __func__, __LINE__) #else struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size, - s32_t timeout); + s32_t timeout); #endif /** @@ -832,16 +832,16 @@ struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size, */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_alloc_with_data_debug(struct net_buf_pool *pool, - void *data, size_t size, - s32_t timeout, const char *func, - int line); -#define net_buf_alloc_with_data(_pool, _data_, _size, _timeout) \ - net_buf_alloc_with_data_debug(_pool, _data_, _size, _timeout, \ - __func__, __LINE__) + void *data, size_t size, + s32_t timeout, const char *func, + int line); +#define net_buf_alloc_with_data(_pool, _data_, _size, _timeout) \ + net_buf_alloc_with_data_debug(_pool, _data_, _size, _timeout, \ + __func__, __LINE__) #else struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool, - void *data, size_t size, - s32_t timeout); + void *data, size_t size, + s32_t timeout); #endif /** @@ -859,9 +859,9 @@ struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool, */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_get_debug(struct k_fifo *fifo, s32_t timeout, - const char *func, int line); -#define net_buf_get(_fifo, _timeout) \ - net_buf_get_debug(_fifo, _timeout, __func__, __LINE__) + const char *func, int line); +#define net_buf_get(_fifo, _timeout) \ + net_buf_get_debug(_fifo, _timeout, __func__, __LINE__) #else struct net_buf *net_buf_get(struct k_fifo *fifo, s32_t timeout); #endif @@ -877,9 +877,9 @@ struct net_buf *net_buf_get(struct k_fifo *fifo, s32_t timeout); */ static inline void net_buf_destroy(struct net_buf *buf) { - struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); + struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); - k_lifo_put(&pool->free, buf); + k_lifo_put(&pool->free, buf); } /** @@ -949,8 +949,8 @@ void net_buf_put(struct k_fifo *fifo, struct net_buf *buf); */ #if defined(CONFIG_NET_BUF_LOG) void net_buf_unref_debug(struct net_buf *buf, const char *func, int line); -#define net_buf_unref(_buf) \ - net_buf_unref_debug(_buf, __func__, __LINE__) +#define net_buf_unref(_buf) \ + net_buf_unref_debug(_buf, __func__, __LINE__) #else void net_buf_unref(struct net_buf *buf); #endif @@ -988,7 +988,7 @@ struct net_buf *net_buf_clone(struct net_buf *buf, s32_t timeout); */ static inline void *net_buf_user_data(const struct net_buf *buf) { - return (void *)buf->user_data; + return (void *)buf->user_data; } /** @def net_buf_reserve @@ -1001,7 +1001,7 @@ static inline void *net_buf_user_data(const struct net_buf *buf) * @param reserve How much headroom to reserve. */ #define net_buf_reserve(buf, reserve) net_buf_simple_reserve(&(buf)->b, \ - reserve) + reserve) /** * @def net_buf_add @@ -1031,7 +1031,7 @@ static inline void *net_buf_user_data(const struct net_buf *buf) * @return The original tail of the buffer. */ #define net_buf_add_mem(buf, mem, len) net_buf_simple_add_mem(&(buf)->b, \ - mem, len) + mem, len) /** * @def net_buf_add_u8 @@ -1320,10 +1320,10 @@ struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag); */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *net_buf_frag_del_debug(struct net_buf *parent, - struct net_buf *frag, - const char *func, int line); + struct net_buf *frag, + const char *func, int line); #define net_buf_frag_del(_parent, _frag) \ - net_buf_frag_del_debug(_parent, _frag, __func__, __LINE__) + net_buf_frag_del_debug(_parent, _frag, __func__, __LINE__) #else struct net_buf *net_buf_frag_del(struct net_buf *parent, struct net_buf *frag); #endif @@ -1382,8 +1382,8 @@ typedef struct net_buf *(*net_buf_allocator_cb)(s32_t timeout, void *user_data); * were no free fragments in a pool to accommodate all data. */ size_t net_buf_append_bytes(struct net_buf *buf, size_t len, - const void *value, s32_t timeout, - net_buf_allocator_cb allocate_cb, void *user_data); + const void *value, s32_t timeout, + net_buf_allocator_cb allocate_cb, void *user_data); /** * @brief Skip N number of bytes in a net_buf @@ -1402,14 +1402,14 @@ size_t net_buf_append_bytes(struct net_buf *buf, size_t len, */ static inline struct net_buf *net_buf_skip(struct net_buf *buf, u16_t len) { - while (buf && len--) { - net_buf_pull_u8(buf); - if (!buf->len) { - buf = net_buf_frag_del(NULL, buf); - } - } + while (buf && len--) { + net_buf_pull_u8(buf); + if (!buf->len) { + buf = net_buf_frag_del(NULL, buf); + } + } - return buf; + return buf; } /** @brief Calculate amount of bytes stored in fragments. @@ -1423,14 +1423,14 @@ static inline struct net_buf *net_buf_skip(struct net_buf *buf, u16_t len) */ static inline size_t net_buf_frags_len(struct net_buf *buf) { - size_t bytes = 0; + size_t bytes = 0; - while (buf) { - bytes += buf->len; - buf = buf->frags; - } + while (buf) { + bytes += buf->len; + buf = buf->frags; + } - return bytes; + return bytes; } /** diff --git a/components/network/ble/blestack/src/common/log.c b/components/network/ble/blestack/src/common/log.c index e0c3d2db..cff65fd6 100644 --- a/components/network/ble/blestack/src/common/log.c +++ b/components/network/ble/blestack/src/common/log.c @@ -21,43 +21,43 @@ const char *bt_hex_real(const void *buf, size_t len) { - static const char hex[] = "0123456789abcdef"; - #ifdef CONFIG_BTSOONP_PRINT - static char str[255]; - #else - static char str[128]; - #endif - const u8_t *b = buf; - int i; + static const char hex[] = "0123456789abcdef"; + #ifdef CONFIG_BTSOONP_PRINT + static char str[255]; + #else + static char str[128]; + #endif + const u8_t *b = buf; + int i; - len = MIN(len, (sizeof(str) - 1) / 2); + len = MIN(len, (sizeof(str) - 1) / 2); - for (i = 0; i < len; i++) { - str[i * 2] = hex[b[i] >> 4]; - str[i * 2 + 1] = hex[b[i] & 0xf]; - } + for (i = 0; i < len; i++) { + str[i * 2] = hex[b[i] >> 4]; + str[i * 2 + 1] = hex[b[i] & 0xf]; + } - str[i * 2] = '\0'; + str[i * 2] = '\0'; - return str; + return str; } const char *bt_addr_str_real(const bt_addr_t *addr) { - static char str[BT_ADDR_STR_LEN]; + static char str[BT_ADDR_STR_LEN]; - bt_addr_to_str(addr, str, sizeof(str)); + bt_addr_to_str(addr, str, sizeof(str)); - return str; + return str; } const char *bt_addr_le_str_real(const bt_addr_le_t *addr) { - static char str[BT_ADDR_LE_STR_LEN]; + static char str[BT_ADDR_LE_STR_LEN]; - bt_addr_le_to_str(addr, str, sizeof(str)); + bt_addr_le_to_str(addr, str, sizeof(str)); - return str; + return str; } diff --git a/components/network/ble/blestack/src/common/log.h b/components/network/ble/blestack/src/common/log.h index a7d92e04..dac985e9 100644 --- a/components/network/ble/blestack/src/common/log.h +++ b/components/network/ble/blestack/src/common/log.h @@ -73,10 +73,10 @@ extern void user_vAssertCalled(void); #define BT_ASSERT(cond) if( ( cond ) == 0 ) user_vAssertCalled() #else #define BT_ASSERT(cond) if (!(cond)) { \ - BT_ASSERT_PRINT("assert: '" #cond \ - "' failed\n"); \ - BT_ASSERT_DIE(); \ - } + BT_ASSERT_PRINT("assert: '" #cond \ + "' failed\n"); \ + BT_ASSERT_DIE(); \ + } #endif/*BFLB_BLE*/ #else #if defined(BFLB_BLE) @@ -87,12 +87,12 @@ extern void user_vAssertCalled(void); #endif/* CONFIG_BT_ASSERT*/ #define BT_HEXDUMP_DBG(_data, _length, _str) \ - LOG_HEXDUMP_DBG((const u8_t *)_data, _length, _str) + LOG_HEXDUMP_DBG((const u8_t *)_data, _length, _str) #if defined(BFLB_BLE) static inline char *log_strdup(const char *str) { - return (char *)str; + return (char *)str; } #endif diff --git a/components/network/ble/blestack/src/common/poll.c b/components/network/ble/blestack/src/common/poll.c index 8511878c..c686ab19 100644 --- a/components/network/ble/blestack/src/common/poll.c +++ b/components/network/ble/blestack/src/common/poll.c @@ -25,133 +25,133 @@ struct k_sem g_poll_sem; void k_poll_event_init(struct k_poll_event *event, u32_t type, - int mode, void *obj) + int mode, void *obj) { - __ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY, - "only NOTIFY_ONLY mode is supported\n"); - __ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n"); - __ASSERT(obj, "must provide an object\n"); + __ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY, + "only NOTIFY_ONLY mode is supported\n"); + __ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n"); + __ASSERT(obj, "must provide an object\n"); - event->poller = NULL; - /* event->tag is left uninitialized: the user will set it if needed */ - event->type = type; - event->state = K_POLL_STATE_NOT_READY; - event->mode = mode; - event->unused = 0; - event->obj = obj; + event->poller = NULL; + /* event->tag is left uninitialized: the user will set it if needed */ + event->type = type; + event->state = K_POLL_STATE_NOT_READY; + event->mode = mode; + event->unused = 0; + event->obj = obj; } /* must be called with interrupts locked */ static inline int is_condition_met(struct k_poll_event *event, u32_t *state) { - switch (event->type) { - case K_POLL_TYPE_SEM_AVAILABLE: - if (k_sem_count_get(event->sem) > 0) { - *state = K_POLL_STATE_SEM_AVAILABLE; - return 1; - } - break; - case K_POLL_TYPE_DATA_AVAILABLE: - if (!k_queue_is_empty(event->queue)) { - *state = K_POLL_STATE_FIFO_DATA_AVAILABLE; - return 1; - } - break; - case K_POLL_TYPE_SIGNAL: - if (event->signal->signaled) { - *state = K_POLL_STATE_SIGNALED; - return 1; - } - break; - case K_POLL_TYPE_IGNORE: - return 0; - default: - __ASSERT(0, "invalid event type (0x%x)\n", event->type); - break; - } + switch (event->type) { + case K_POLL_TYPE_SEM_AVAILABLE: + if (k_sem_count_get(event->sem) > 0) { + *state = K_POLL_STATE_SEM_AVAILABLE; + return 1; + } + break; + case K_POLL_TYPE_DATA_AVAILABLE: + if (!k_queue_is_empty(event->queue)) { + *state = K_POLL_STATE_FIFO_DATA_AVAILABLE; + return 1; + } + break; + case K_POLL_TYPE_SIGNAL: + if (event->signal->signaled) { + *state = K_POLL_STATE_SIGNALED; + return 1; + } + break; + case K_POLL_TYPE_IGNORE: + return 0; + default: + __ASSERT(0, "invalid event type (0x%x)\n", event->type); + break; + } - return 0; + return 0; } static inline void add_event(sys_dlist_t *events, struct k_poll_event *event, - struct _poller *poller) + struct _poller *poller) { sys_dlist_append(events, &event->_node); } /* must be called with interrupts locked */ static inline int register_event(struct k_poll_event *event, - struct _poller *poller) + struct _poller *poller) { - switch (event->type) { - case K_POLL_TYPE_SEM_AVAILABLE: - __ASSERT(event->sem, "invalid semaphore\n"); - add_event(&event->sem->poll_events, event, poller); - break; - case K_POLL_TYPE_DATA_AVAILABLE: - __ASSERT(event->queue, "invalid queue\n"); - add_event(&event->queue->poll_events, event, poller); - break; - case K_POLL_TYPE_SIGNAL: - __ASSERT(event->signal, "invalid poll signal\n"); - add_event(&event->signal->poll_events, event, poller); - break; - case K_POLL_TYPE_IGNORE: - /* nothing to do */ - break; - default: - __ASSERT(0, "invalid event type\n"); - break; - } + switch (event->type) { + case K_POLL_TYPE_SEM_AVAILABLE: + __ASSERT(event->sem, "invalid semaphore\n"); + add_event(&event->sem->poll_events, event, poller); + break; + case K_POLL_TYPE_DATA_AVAILABLE: + __ASSERT(event->queue, "invalid queue\n"); + add_event(&event->queue->poll_events, event, poller); + break; + case K_POLL_TYPE_SIGNAL: + __ASSERT(event->signal, "invalid poll signal\n"); + add_event(&event->signal->poll_events, event, poller); + break; + case K_POLL_TYPE_IGNORE: + /* nothing to do */ + break; + default: + __ASSERT(0, "invalid event type\n"); + break; + } - event->poller = poller; + event->poller = poller; - return 0; + return 0; } /* must be called with interrupts locked */ static inline void clear_event_registration(struct k_poll_event *event) { - event->poller = NULL; + event->poller = NULL; - switch (event->type) { - case K_POLL_TYPE_SEM_AVAILABLE: - __ASSERT(event->sem, "invalid semaphore\n"); - sys_dlist_remove(&event->_node); - break; - case K_POLL_TYPE_DATA_AVAILABLE: - __ASSERT(event->queue, "invalid queue\n"); - sys_dlist_remove(&event->_node); - break; - case K_POLL_TYPE_SIGNAL: - __ASSERT(event->signal, "invalid poll signal\n"); - sys_dlist_remove(&event->_node); - break; - case K_POLL_TYPE_IGNORE: - /* nothing to do */ - break; - default: - __ASSERT(0, "invalid event type\n"); - break; - } + switch (event->type) { + case K_POLL_TYPE_SEM_AVAILABLE: + __ASSERT(event->sem, "invalid semaphore\n"); + sys_dlist_remove(&event->_node); + break; + case K_POLL_TYPE_DATA_AVAILABLE: + __ASSERT(event->queue, "invalid queue\n"); + sys_dlist_remove(&event->_node); + break; + case K_POLL_TYPE_SIGNAL: + __ASSERT(event->signal, "invalid poll signal\n"); + sys_dlist_remove(&event->_node); + break; + case K_POLL_TYPE_IGNORE: + /* nothing to do */ + break; + default: + __ASSERT(0, "invalid event type\n"); + break; + } } /* must be called with interrupts locked */ static inline void clear_event_registrations(struct k_poll_event *events, - int last_registered, - unsigned int key) + int last_registered, + unsigned int key) { - for (; last_registered >= 0; last_registered--) { - clear_event_registration(&events[last_registered]); - irq_unlock(key); - key = irq_lock(); - } + for (; last_registered >= 0; last_registered--) { + clear_event_registration(&events[last_registered]); + irq_unlock(key); + key = irq_lock(); + } } static inline void set_event_ready(struct k_poll_event *event, u32_t state) { - event->poller = NULL; - event->state |= state; + event->poller = NULL; + event->state |= state; } static bool polling_events(struct k_poll_event *events, int num_events, @@ -182,14 +182,14 @@ static bool polling_events(struct k_poll_event *events, int num_events, int k_poll(struct k_poll_event *events, int num_events, s32_t timeout) { - __ASSERT(events, "NULL events\n"); - __ASSERT(num_events > 0, "zero events\n"); + __ASSERT(events, "NULL events\n"); + __ASSERT(num_events > 0, "zero events\n"); int last_registered = -1; - unsigned int key; + unsigned int key; bool polling = true; - /* find events whose condition is already fulfilled */ + /* find events whose condition is already fulfilled */ polling = polling_events(events, num_events, timeout, &last_registered); if (polling == false) { @@ -209,32 +209,32 @@ exit: /* must be called with interrupts locked */ static int _signal_poll_event(struct k_poll_event *event, u32_t state, - int *must_reschedule) + int *must_reschedule) { - *must_reschedule = 0; - set_event_ready(event, state); - return 0; + *must_reschedule = 0; + set_event_ready(event, state); + return 0; } int k_poll_signal_raise(struct k_poll_signal *signal, int result) { - unsigned int key = irq_lock(); - struct k_poll_event *poll_event; - int must_reschedule; + unsigned int key = irq_lock(); + struct k_poll_event *poll_event; + int must_reschedule; - signal->result = result; - signal->signaled = 1; + signal->result = result; + signal->signaled = 1; - poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events); - if (!poll_event) { - irq_unlock(key); - return 0; - } + poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events); + if (!poll_event) { + irq_unlock(key); + return 0; + } - int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED, - &must_reschedule); + int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED, + &must_reschedule); k_sem_give(&g_poll_sem); irq_unlock(key); - return rc; + return rc; } diff --git a/components/network/ble/blestack/src/common/rpa.c b/components/network/ble/blestack/src/common/rpa.c index 461448cc..8c541696 100644 --- a/components/network/ble/blestack/src/common/rpa.c +++ b/components/network/ble/blestack/src/common/rpa.c @@ -31,74 +31,74 @@ static int ah(const u8_t irk[16], const u8_t r[3], u8_t out[3]) { - u8_t res[16]; - int err; + u8_t res[16]; + int err; - BT_DBG("irk %s", bt_hex(irk, 16)); - BT_DBG("r %s", bt_hex(r, 3)); + BT_DBG("irk %s", bt_hex(irk, 16)); + BT_DBG("r %s", bt_hex(r, 3)); - /* r' = padding || r */ - memcpy(res, r, 3); - (void)memset(res + 3, 0, 13); + /* r' = padding || r */ + memcpy(res, r, 3); + (void)memset(res + 3, 0, 13); - err = bt_encrypt_le(irk, res, res); - if (err) { - return err; - } + err = bt_encrypt_le(irk, res, res); + if (err) { + return err; + } - /* The output of the random address function ah is: - * ah(h, r) = e(k, r') mod 2^24 - * The output of the security function e is then truncated to 24 bits - * by taking the least significant 24 bits of the output of e as the - * result of ah. - */ - memcpy(out, res, 3); + /* The output of the random address function ah is: + * ah(h, r) = e(k, r') mod 2^24 + * The output of the security function e is then truncated to 24 bits + * by taking the least significant 24 bits of the output of e as the + * result of ah. + */ + memcpy(out, res, 3); - return 0; + return 0; } #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_CTLR_PRIVACY) bool bt_rpa_irk_matches(const u8_t irk[16], const bt_addr_t *addr) { - u8_t hash[3]; - int err; + u8_t hash[3]; + int err; - BT_DBG("IRK %s bdaddr %s", bt_hex(irk, 16), bt_addr_str(addr)); + BT_DBG("IRK %s bdaddr %s", bt_hex(irk, 16), bt_addr_str(addr)); - err = ah(irk, addr->val + 3, hash); - if (err) { - return false; - } + err = ah(irk, addr->val + 3, hash); + if (err) { + return false; + } - return !memcmp(addr->val, hash, 3); + return !memcmp(addr->val, hash, 3); } #endif #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_CTLR_PRIVACY) int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) { - int err; + int err; - err = bt_rand(rpa->val + 3, 3); - if (err) { - return err; - } + err = bt_rand(rpa->val + 3, 3); + if (err) { + return err; + } - BT_ADDR_SET_RPA(rpa); + BT_ADDR_SET_RPA(rpa); - err = ah(irk, rpa->val + 3, rpa->val); - if (err) { - return err; - } + err = ah(irk, rpa->val + 3, rpa->val); + if (err) { + return err; + } - BT_DBG("Created RPA %s", bt_addr_str((bt_addr_t *)rpa->val)); + BT_DBG("Created RPA %s", bt_addr_str((bt_addr_t *)rpa->val)); - return 0; + return 0; } #else int bt_rpa_create(const u8_t irk[16], bt_addr_t *rpa) { - return -ENOTSUP; + return -ENOTSUP; } #endif /* CONFIG_BT_PRIVACY */ diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/aes.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/aes.h index b612213a..30f2cf39 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/aes.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/aes.h @@ -62,7 +62,7 @@ extern "C" { #define TC_AES_KEY_SIZE (Nb*Nk) typedef struct tc_aes_key_sched_struct { - unsigned int words[Nb*(Nr+1)]; + unsigned int words[Nb*(Nr+1)]; } *TCAesKeySched_t; /** @@ -90,8 +90,8 @@ int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k); * @param in IN -- a plaintext block to encrypt * @param s IN -- initialized AES key schedule */ -int tc_aes_encrypt(uint8_t *out, const uint8_t *in, - const TCAesKeySched_t s); +int tc_aes_encrypt(uint8_t *out, const uint8_t *in, + const TCAesKeySched_t s); /** * @brief Set the AES-128 decryption key @@ -120,8 +120,8 @@ int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k); * @param in IN -- a plaintext block to encrypt * @param s IN -- initialized AES key schedule */ -int tc_aes_decrypt(uint8_t *out, const uint8_t *in, - const TCAesKeySched_t s); +int tc_aes_decrypt(uint8_t *out, const uint8_t *in, + const TCAesKeySched_t s); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cbc_mode.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cbc_mode.h index a53318ee..c156d8fb 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cbc_mode.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cbc_mode.h @@ -108,8 +108,8 @@ extern "C" { * @param sched IN -- AES key schedule for this encrypt */ int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, - unsigned int inlen, const uint8_t *iv, - const TCAesKeySched_t sched); + unsigned int inlen, const uint8_t *iv, + const TCAesKeySched_t sched); /** * @brief CBC decryption procedure @@ -141,8 +141,8 @@ int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, * */ int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, - unsigned int inlen, const uint8_t *iv, - const TCAesKeySched_t sched); + unsigned int inlen, const uint8_t *iv, + const TCAesKeySched_t sched); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ccm_mode.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ccm_mode.h index c22ac08d..473c094e 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ccm_mode.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ccm_mode.h @@ -89,9 +89,9 @@ extern "C" { /* struct tc_ccm_mode_struct represents the state of a CCM computation */ typedef struct tc_ccm_mode_struct { - TCAesKeySched_t sched; /* AES key schedule */ - uint8_t *nonce; /* nonce required by CCM */ - unsigned int mlen; /* mac length in bytes (parameter t in SP-800 38C) */ + TCAesKeySched_t sched; /* AES key schedule */ + uint8_t *nonce; /* nonce required by CCM */ + unsigned int mlen; /* mac length in bytes (parameter t in SP-800 38C) */ } *TCCcmMode_t; /** @@ -109,7 +109,7 @@ typedef struct tc_ccm_mode_struct { * @param mlen -- mac length in bytes (parameter t in SP-800 38C) */ int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce, - unsigned int nlen, unsigned int mlen); + unsigned int nlen, unsigned int mlen); /** * @brief CCM tag generation and encryption procedure @@ -154,9 +154,9 @@ int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce, * 7: always 0 */ int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, - const uint8_t *associated_data, - unsigned int alen, const uint8_t *payload, - unsigned int plen, TCCcmMode_t c); + const uint8_t *associated_data, + unsigned int alen, const uint8_t *payload, + unsigned int plen, TCCcmMode_t c); /** * @brief CCM decryption and tag verification procedure @@ -200,9 +200,9 @@ int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, * 7: always 0 */ int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen, - const uint8_t *associated_data, - unsigned int alen, const uint8_t *payload, unsigned int plen, - TCCcmMode_t c); + const uint8_t *associated_data, + unsigned int alen, const uint8_t *payload, unsigned int plen, + TCCcmMode_t c); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cmac_mode.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cmac_mode.h index fa14d2aa..989305d5 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cmac_mode.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/cmac_mode.h @@ -111,21 +111,21 @@ extern "C" { /* struct tc_cmac_struct represents the state of a CMAC computation */ typedef struct tc_cmac_struct { /* initialization vector */ - uint8_t iv[TC_AES_BLOCK_SIZE]; + uint8_t iv[TC_AES_BLOCK_SIZE]; /* used if message length is a multiple of block_size bytes */ - uint8_t K1[TC_AES_BLOCK_SIZE]; + uint8_t K1[TC_AES_BLOCK_SIZE]; /* used if message length isn't a multiple block_size bytes */ - uint8_t K2[TC_AES_BLOCK_SIZE]; + uint8_t K2[TC_AES_BLOCK_SIZE]; /* where to put bytes that didn't fill a block */ - uint8_t leftover[TC_AES_BLOCK_SIZE]; + uint8_t leftover[TC_AES_BLOCK_SIZE]; /* identifies the encryption key */ - unsigned int keyid; + unsigned int keyid; /* next available leftover location */ - unsigned int leftover_offset; + unsigned int leftover_offset; /* AES key schedule */ - TCAesKeySched_t sched; + TCAesKeySched_t sched; /* calls to tc_cmac_update left before re-key */ - uint64_t countdown; + uint64_t countdown; } *TCCmacState_t; /** @@ -140,7 +140,7 @@ typedef struct tc_cmac_struct { * @param sched IN -- AES key schedule */ int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, - TCAesKeySched_t sched); + TCAesKeySched_t sched); /** * @brief Erases the CMAC state diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_mode.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_mode.h index e2da5b43..8ab7a5c2 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_mode.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_mode.h @@ -99,7 +99,7 @@ extern "C" { * @param sched IN -- an initialized AES key schedule */ int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, - unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched); + unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_prng.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_prng.h index bff7f972..3a0a98ed 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_prng.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ctr_prng.h @@ -68,14 +68,14 @@ extern "C" { #endif typedef struct { - /* updated each time another BLOCKLEN_BYTES bytes are produced */ - uint8_t V[TC_AES_BLOCK_SIZE]; + /* updated each time another BLOCKLEN_BYTES bytes are produced */ + uint8_t V[TC_AES_BLOCK_SIZE]; - /* updated whenever the PRNG is reseeded */ - struct tc_aes_key_sched_struct key; + /* updated whenever the PRNG is reseeded */ + struct tc_aes_key_sched_struct key; - /* number of requests since initialization/reseeding */ - uint64_t reseedCount; + /* number of requests since initialization/reseeding */ + uint64_t reseedCount; } TCCtrPrng_t; @@ -98,11 +98,11 @@ typedef struct { * @param plen IN -- personalization length in bytes * */ -int tc_ctr_prng_init(TCCtrPrng_t * const ctx, - uint8_t const * const entropy, - unsigned int entropyLen, - uint8_t const * const personalization, - unsigned int pLen); +int tc_ctr_prng_init(TCCtrPrng_t * const ctx, + uint8_t const * const entropy, + unsigned int entropyLen, + uint8_t const * const personalization, + unsigned int pLen); /** * @brief CTR-PRNG reseed procedure @@ -123,11 +123,11 @@ int tc_ctr_prng_init(TCCtrPrng_t * const ctx, * @param additional_input IN -- additional input to the prng (may be null) * @param additionallen IN -- additional input length in bytes */ -int tc_ctr_prng_reseed(TCCtrPrng_t * const ctx, - uint8_t const * const entropy, - unsigned int entropyLen, - uint8_t const * const additional_input, - unsigned int additionallen); +int tc_ctr_prng_reseed(TCCtrPrng_t * const ctx, + uint8_t const * const entropy, + unsigned int entropyLen, + uint8_t const * const additional_input, + unsigned int additionallen); /** * @brief CTR-PRNG generate procedure @@ -146,10 +146,10 @@ int tc_ctr_prng_reseed(TCCtrPrng_t * const ctx, * @param outlen IN -- size of out buffer in bytes */ int tc_ctr_prng_generate(TCCtrPrng_t * const ctx, - uint8_t const * const additional_input, - unsigned int additionallen, - uint8_t * const out, - unsigned int outlen); + uint8_t const * const additional_input, + unsigned int additionallen, + uint8_t * const out, + unsigned int outlen); /** * @brief CTR-PRNG uninstantiate procedure diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc.h index 8abc949c..57ca2474 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc.h @@ -118,7 +118,7 @@ struct uECC_Curve_t { uECC_word_t G[NUM_ECC_WORDS * 2]; uECC_word_t b[NUM_ECC_WORDS]; void (*double_jacobian)(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * Z1, - uECC_Curve curve); + uECC_Curve curve); void (*x_side)(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve); void (*mmod_fast)(uECC_word_t *result, uECC_word_t *product); }; @@ -131,7 +131,7 @@ struct uECC_Curve_t { * @param curve IN -- elliptic curve */ void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1, - uECC_word_t * Z1, uECC_Curve curve); + uECC_word_t * Z1, uECC_Curve curve); /* * @brief Computes x^3 + ax + b. result must not overlap x. @@ -140,7 +140,7 @@ void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1, * @param curve IN -- elliptic curve */ void x_side_default(uECC_word_t *result, const uECC_word_t *x, - uECC_Curve curve); + uECC_Curve curve); /* * @brief Computes result = product % curve_p @@ -154,25 +154,25 @@ void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product); #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a #define BITS_TO_WORDS(num_bits) \ - ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / (uECC_WORD_SIZE * 8)) + ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / (uECC_WORD_SIZE * 8)) #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8) /* definition of curve NIST p-256: */ static const struct uECC_Curve_t curve_secp256r1 = { - NUM_ECC_WORDS, - NUM_ECC_BYTES, - 256, /* num_n_bits */ { - BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), - BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00), - BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00), - BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF) - }, { - BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3), - BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC), - BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), - BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF) - }, { - BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4), + NUM_ECC_WORDS, + NUM_ECC_BYTES, + 256, /* num_n_bits */ { + BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), + BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00), + BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00), + BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF) + }, { + BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3), + BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC), + BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), + BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF) + }, { + BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4), BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77), BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8), BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B), @@ -181,12 +181,12 @@ static const struct uECC_Curve_t curve_secp256r1 = { BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B), BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E), BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F) - }, { - BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B), + }, { + BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B), BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65), BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3), BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A) - }, + }, &double_jacobian_default, &x_side_default, &vli_mmod_fast_secp256r1 @@ -203,7 +203,7 @@ uECC_Curve uECC_secp256r1(void); * @return a random integer in the range 0 < random < top */ int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top, - wordcount_t num_words); + wordcount_t num_words); /* uECC_RNG_Function type @@ -264,7 +264,7 @@ int uECC_curve_public_key_size(uECC_Curve curve); * @return Returns 1 if key was computed successfully, 0 if an error occurred. */ int uECC_compute_public_key(const uint8_t *private_key, - uint8_t *public_key, uECC_Curve curve); + uint8_t *public_key, uECC_Curve curve); /* * @brief Compute public-key. @@ -274,7 +274,7 @@ int uECC_compute_public_key(const uint8_t *private_key, * @param curve IN -- elliptic curve */ uECC_word_t EccPoint_compute_public_key(uECC_word_t *result, - uECC_word_t *private_key, uECC_Curve curve); + uECC_word_t *private_key, uECC_Curve curve); /* * @brief Regularize the bitcount for the private key so that attackers cannot @@ -286,7 +286,7 @@ uECC_word_t EccPoint_compute_public_key(uECC_word_t *result, * @param curve IN -- elliptic curve */ uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t *k0, - uECC_word_t *k1, uECC_Curve curve); + uECC_word_t *k1, uECC_Curve curve); /* * @brief Point multiplication algorithm using Montgomery's ladder with co-Z @@ -300,8 +300,8 @@ uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t *k0, * @param curve IN -- elliptic curve */ void EccPoint_mult(uECC_word_t * result, const uECC_word_t * point, - const uECC_word_t * scalar, const uECC_word_t * initial_Z, - bitcount_t num_bits, uECC_Curve curve); + const uECC_word_t * scalar, const uECC_word_t * initial_Z, + bitcount_t num_bits, uECC_Curve curve); /* * @brief Constant-time comparison to zero - secure way to compare long integers @@ -327,7 +327,7 @@ uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve); * @return the sign of left - right */ cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, - wordcount_t num_words); + wordcount_t num_words); /* * @brief computes sign of left - right, not in constant time. @@ -338,7 +338,7 @@ cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, * @return the sign of left - right */ cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *right, - wordcount_t num_words); + wordcount_t num_words); /* * @brief Computes result = (left - right) % mod. @@ -351,8 +351,8 @@ cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *righ * @param num_words IN -- number of words */ void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, const uECC_word_t *mod, - wordcount_t num_words); + const uECC_word_t *right, const uECC_word_t *mod, + wordcount_t num_words); /* * @brief Computes P' = (x1', y1', Z3), P + Q = (x3, y3, Z3) or @@ -365,7 +365,7 @@ void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left, * @param curve IN -- elliptic curve */ void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, - uECC_word_t * Y2, uECC_Curve curve); + uECC_word_t * Y2, uECC_Curve curve); /* * @brief Computes (x1 * z^2, y1 * z^3) @@ -375,7 +375,7 @@ void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, * @param curve IN -- elliptic curve */ void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z, - uECC_Curve curve); + uECC_Curve curve); /* * @brief Check if bit is set. @@ -396,7 +396,7 @@ uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit); * @warning Currently only designed to work for curve_p or curve_n. */ void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product, - const uECC_word_t *mod, wordcount_t num_words); + const uECC_word_t *mod, wordcount_t num_words); /* * @brief Computes modular product (using curve->mmod_fast) @@ -406,7 +406,7 @@ void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product, * @param curve IN -- elliptic curve */ void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, uECC_Curve curve); + const uECC_word_t *right, uECC_Curve curve); /* * @brief Computes result = left - right. @@ -418,7 +418,7 @@ void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left, * @return borrow */ uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, wordcount_t num_words); + const uECC_word_t *right, wordcount_t num_words); /* * @brief Constant-time comparison function(secure way to compare long ints) @@ -428,7 +428,7 @@ uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left, * @return Returns 0 if left == right, 1 otherwise. */ uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right, - wordcount_t num_words); + wordcount_t num_words); /* * @brief Computes (left * right) % mod @@ -439,8 +439,8 @@ uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right, * @param num_words IN -- number of words */ void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, const uECC_word_t *mod, - wordcount_t num_words); + const uECC_word_t *right, const uECC_word_t *mod, + wordcount_t num_words); /* * @brief Computes (1 / input) % mod @@ -452,7 +452,7 @@ void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left, * @param num_words -- number of words */ void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input, - const uECC_word_t *mod, wordcount_t num_words); + const uECC_word_t *mod, wordcount_t num_words); /* * @brief Sets dest = src. @@ -461,7 +461,7 @@ void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input, * @param num_words IN -- number of words */ void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, - wordcount_t num_words); + wordcount_t num_words); /* * @brief Computes (left + right) % mod. @@ -474,8 +474,8 @@ void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, * @param num_words IN -- number of words */ void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, const uECC_word_t *mod, - wordcount_t num_words); + const uECC_word_t *right, const uECC_word_t *mod, + wordcount_t num_words); /* * @brief Counts the number of bits required to represent vli. @@ -483,8 +483,8 @@ void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left, * @param max_words IN -- number of words * @return number of bits in given vli */ -bitcount_t uECC_vli_numBits(const uECC_word_t *vli, - const wordcount_t max_words); +bitcount_t uECC_vli_numBits(const uECC_word_t *vli, + const wordcount_t max_words); /* * @brief Erases (set to 0) vli @@ -527,7 +527,7 @@ int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve); * @param native IN -- uECC native representation */ void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, - const unsigned int *native); + const unsigned int *native); /* * @brief Converts big-endian bytes to an integer in uECC native format. @@ -536,7 +536,7 @@ void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, * @param num_bytes IN -- number of bytes */ void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes, - int num_bytes); + int num_bytes); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dh.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dh.h index 930e9162..4bfa034e 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dh.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dh.h @@ -102,7 +102,7 @@ int uECC_make_key(uint8_t *p_public_key, uint8_t *p_private_key, uECC_Curve curv * uECC_make_key() function for real applications. */ int uECC_make_key_with_d(uint8_t *p_public_key, uint8_t *p_private_key, - unsigned int *d, uECC_Curve curve); + unsigned int *d, uECC_Curve curve); #endif /** @@ -122,7 +122,7 @@ int uECC_make_key_with_d(uint8_t *p_public_key, uint8_t *p_private_key, * order to produce a cryptographically secure symmetric key. */ int uECC_shared_secret(const uint8_t *p_public_key, const uint8_t *p_private_key, - uint8_t *p_secret, uECC_Curve curve); + uint8_t *p_secret, uECC_Curve curve); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dsa.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dsa.h index 8cb421b7..2dbb3308 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dsa.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/ecc_dsa.h @@ -103,7 +103,7 @@ extern "C" { * attack. */ int uECC_sign(const uint8_t *p_private_key, const uint8_t *p_message_hash, - unsigned p_hash_size, uint8_t *p_signature, uECC_Curve curve); + unsigned p_hash_size, uint8_t *p_signature, uECC_Curve curve); #ifdef ENABLE_TESTS /* @@ -111,14 +111,14 @@ int uECC_sign(const uint8_t *p_private_key, const uint8_t *p_message_hash, * Refer to uECC_sign() function for real applications. */ int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, - unsigned int hash_size, uECC_word_t *k, uint8_t *signature, - uECC_Curve curve); + unsigned int hash_size, uECC_word_t *k, uint8_t *signature, + uECC_Curve curve); #endif /** * @brief Verify an ECDSA signature. * @return returns TC_SUCCESS (1) if the signature is valid - * returns TC_FAIL (0) if the signature is invalid. + * returns TC_FAIL (0) if the signature is invalid. * * @param p_public_key IN -- The signer's public key. * @param p_message_hash IN -- The hash of the signed data. @@ -130,7 +130,7 @@ int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, * the signature values (hash_size and signature). */ int uECC_verify(const uint8_t *p_public_key, const uint8_t *p_message_hash, - unsigned int p_hash_size, const uint8_t *p_signature, uECC_Curve curve); + unsigned int p_hash_size, const uint8_t *p_signature, uECC_Curve curve); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac.h index cfa7d38c..b0e28b69 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac.h @@ -70,10 +70,10 @@ extern "C" { #endif struct tc_hmac_state_struct { - /* the internal state required by h */ - struct tc_sha256_state_struct hash_state; - /* HMAC key schedule */ - uint8_t key[2*TC_SHA256_BLOCK_SIZE]; + /* the internal state required by h */ + struct tc_sha256_state_struct hash_state; + /* HMAC key schedule */ + uint8_t key[2*TC_SHA256_BLOCK_SIZE]; }; typedef struct tc_hmac_state_struct *TCHmacState_t; @@ -90,7 +90,7 @@ typedef struct tc_hmac_state_struct *TCHmacState_t; * @param key_size IN -- the HMAC key size */ int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key, - unsigned int key_size); + unsigned int key_size); /** * @brief HMAC init procedure @@ -112,7 +112,7 @@ int tc_hmac_init(TCHmacState_t ctx); * @param data_length IN -- size of data in bytes */ int tc_hmac_update(TCHmacState_t ctx, const void *data, - unsigned int data_length); + unsigned int data_length); /** * @brief HMAC final procedure diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac_prng.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac_prng.h index 24f417e6..63d9975c 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac_prng.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/hmac_prng.h @@ -78,14 +78,14 @@ extern "C" { #define TC_HMAC_PRNG_RESEED_REQ -1 struct tc_hmac_prng_struct { - /* the HMAC instance for this PRNG */ - struct tc_hmac_state_struct h; - /* the PRNG key */ - uint8_t key[TC_SHA256_DIGEST_SIZE]; - /* PRNG state */ - uint8_t v[TC_SHA256_DIGEST_SIZE]; - /* calls to tc_hmac_prng_generate left before re-seed */ - unsigned int countdown; + /* the HMAC instance for this PRNG */ + struct tc_hmac_state_struct h; + /* the PRNG key */ + uint8_t key[TC_SHA256_DIGEST_SIZE]; + /* PRNG state */ + uint8_t v[TC_SHA256_DIGEST_SIZE]; + /* calls to tc_hmac_prng_generate left before re-seed */ + unsigned int countdown; }; typedef struct tc_hmac_prng_struct *TCHmacPrng_t; @@ -113,14 +113,14 @@ typedef struct tc_hmac_prng_struct *TCHmacPrng_t; * @param plen IN -- personalization length in bytes */ int tc_hmac_prng_init(TCHmacPrng_t prng, - const uint8_t *personalization, - unsigned int plen); + const uint8_t *personalization, + unsigned int plen); /** * @brief HMAC-PRNG reseed procedure * Mixes seed into prng, enables tc_hmac_prng_generate * @return returns TC_CRYPTO_SUCCESS (1) - * returns TC_CRYPTO_FAIL (0) if: + * returns TC_CRYPTO_FAIL (0) if: * prng == NULL, * seed == NULL, * seedlen < MIN_SLEN, @@ -137,8 +137,8 @@ int tc_hmac_prng_init(TCHmacPrng_t prng, * @param additionallen IN -- additional input length in bytes */ int tc_hmac_prng_reseed(TCHmacPrng_t prng, const uint8_t *seed, - unsigned int seedlen, const uint8_t *additional_input, - unsigned int additionallen); + unsigned int seedlen, const uint8_t *additional_input, + unsigned int additionallen); /** * @brief HMAC-PRNG generate procedure diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/sha256.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/sha256.h index af5e8baf..6a572731 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/sha256.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/sha256.h @@ -69,10 +69,10 @@ extern "C" { #define TC_SHA256_STATE_BLOCKS (TC_SHA256_DIGEST_SIZE/4) struct tc_sha256_state_struct { - unsigned int iv[TC_SHA256_STATE_BLOCKS]; - uint64_t bits_hashed; - uint8_t leftover[TC_SHA256_BLOCK_SIZE]; - size_t leftover_offset; + unsigned int iv[TC_SHA256_STATE_BLOCKS]; + uint64_t bits_hashed; + uint8_t leftover[TC_SHA256_BLOCK_SIZE]; + size_t leftover_offset; }; typedef struct tc_sha256_state_struct *TCSha256State_t; diff --git a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/utils.h b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/utils.h index 6b7b0abf..e4a2fac9 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/utils.h +++ b/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt/utils.h @@ -59,7 +59,7 @@ extern "C" { * @param from_len IN -- length of origin buffer */ unsigned int _copy(uint8_t *to, unsigned int to_len, - const uint8_t *from, unsigned int from_len); + const uint8_t *from, unsigned int from_len); /** * @brief Set the value 'val' into the buffer 'to', 'len' times. diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/aes_decrypt.c b/components/network/ble/blestack/src/common/tinycrypt/source/aes_decrypt.c index 19a41c30..356c794d 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/aes_decrypt.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/aes_decrypt.c @@ -35,33 +35,33 @@ #include static const uint8_t inv_sbox[256] = { - 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, - 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, - 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, - 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, - 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, - 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, - 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, - 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, - 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, - 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, - 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, - 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, - 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, - 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, - 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, - 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, - 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, - 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, - 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, - 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, - 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, - 0x55, 0x21, 0x0c, 0x7d + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, + 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, + 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, + 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, + 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, + 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, + 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, + 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, + 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, + 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, + 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, + 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, + 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, + 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, + 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, + 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, + 0x55, 0x21, 0x0c, 0x7d }; int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k) { - return tc_aes128_set_encrypt_key(s, k); + return tc_aes128_set_encrypt_key(s, k); } #define mult8(a)(_double_byte(_double_byte(_double_byte(a)))) @@ -72,42 +72,42 @@ int tc_aes128_set_decrypt_key(TCAesKeySched_t s, const uint8_t *k) static inline void mult_row_column(uint8_t *out, const uint8_t *in) { - out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]); - out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]); - out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]); - out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]); + out[0] = multe(in[0]) ^ multb(in[1]) ^ multd(in[2]) ^ mult9(in[3]); + out[1] = mult9(in[0]) ^ multe(in[1]) ^ multb(in[2]) ^ multd(in[3]); + out[2] = multd(in[0]) ^ mult9(in[1]) ^ multe(in[2]) ^ multb(in[3]); + out[3] = multb(in[0]) ^ multd(in[1]) ^ mult9(in[2]) ^ multe(in[3]); } static inline void inv_mix_columns(uint8_t *s) { - uint8_t t[Nb*Nk]; + uint8_t t[Nb*Nk]; - mult_row_column(t, s); - mult_row_column(&t[Nb], s+Nb); - mult_row_column(&t[2*Nb], s+(2*Nb)); - mult_row_column(&t[3*Nb], s+(3*Nb)); - (void)_copy(s, sizeof(t), t, sizeof(t)); + mult_row_column(t, s); + mult_row_column(&t[Nb], s+Nb); + mult_row_column(&t[2*Nb], s+(2*Nb)); + mult_row_column(&t[3*Nb], s+(3*Nb)); + (void)_copy(s, sizeof(t), t, sizeof(t)); } static inline void add_round_key(uint8_t *s, const unsigned int *k) { - s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); - s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); - s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); - s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); - s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); - s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); - s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); - s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); + s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); + s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); + s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); + s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); + s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); + s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); + s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); + s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); } static inline void inv_sub_bytes(uint8_t *s) { - unsigned int i; + unsigned int i; - for (i = 0; i < (Nb*Nk); ++i) { - s[i] = inv_sbox[s[i]]; - } + for (i = 0; i < (Nb*Nk); ++i) { + s[i] = inv_sbox[s[i]]; + } } /* @@ -117,48 +117,48 @@ static inline void inv_sub_bytes(uint8_t *s) */ static inline void inv_shift_rows(uint8_t *s) { - uint8_t t[Nb*Nk]; + uint8_t t[Nb*Nk]; - t[0] = s[0]; t[1] = s[13]; t[2] = s[10]; t[3] = s[7]; - t[4] = s[4]; t[5] = s[1]; t[6] = s[14]; t[7] = s[11]; - t[8] = s[8]; t[9] = s[5]; t[10] = s[2]; t[11] = s[15]; - t[12] = s[12]; t[13] = s[9]; t[14] = s[6]; t[15] = s[3]; - (void)_copy(s, sizeof(t), t, sizeof(t)); + t[0] = s[0]; t[1] = s[13]; t[2] = s[10]; t[3] = s[7]; + t[4] = s[4]; t[5] = s[1]; t[6] = s[14]; t[7] = s[11]; + t[8] = s[8]; t[9] = s[5]; t[10] = s[2]; t[11] = s[15]; + t[12] = s[12]; t[13] = s[9]; t[14] = s[6]; t[15] = s[3]; + (void)_copy(s, sizeof(t), t, sizeof(t)); } int tc_aes_decrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) { - uint8_t state[Nk*Nb]; - unsigned int i; + uint8_t state[Nk*Nb]; + unsigned int i; - if (out == (uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } else if (in == (const uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } else if (s == (TCAesKeySched_t) 0) { - return TC_CRYPTO_FAIL; - } + if (out == (uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } else if (in == (const uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } else if (s == (TCAesKeySched_t) 0) { + return TC_CRYPTO_FAIL; + } - (void)_copy(state, sizeof(state), in, sizeof(state)); + (void)_copy(state, sizeof(state), in, sizeof(state)); - add_round_key(state, s->words + Nb*Nr); + add_round_key(state, s->words + Nb*Nr); - for (i = Nr - 1; i > 0; --i) { - inv_shift_rows(state); - inv_sub_bytes(state); - add_round_key(state, s->words + Nb*i); - inv_mix_columns(state); - } + for (i = Nr - 1; i > 0; --i) { + inv_shift_rows(state); + inv_sub_bytes(state); + add_round_key(state, s->words + Nb*i); + inv_mix_columns(state); + } - inv_shift_rows(state); - inv_sub_bytes(state); - add_round_key(state, s->words); + inv_shift_rows(state); + inv_sub_bytes(state); + add_round_key(state, s->words); - (void)_copy(out, sizeof(state), state, sizeof(state)); + (void)_copy(out, sizeof(state), state, sizeof(state)); - /*zeroing out the state buffer */ - _set(state, TC_ZERO_BYTE, sizeof(state)); + /*zeroing out the state buffer */ + _set(state, TC_ZERO_BYTE, sizeof(state)); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/aes_encrypt.c b/components/network/ble/blestack/src/common/tinycrypt/source/aes_encrypt.c index aa5fa58b..ab94bc0a 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/aes_encrypt.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/aes_encrypt.c @@ -35,33 +35,33 @@ #include "constants.h" static const uint8_t sbox[256] = { - 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, - 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, - 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, - 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, - 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, - 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, - 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, - 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, - 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, - 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, - 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, - 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, - 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, - 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, - 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, - 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, - 0xb0, 0x54, 0xbb, 0x16 + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, + 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, + 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, + 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, + 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, + 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, + 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, + 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, + 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, + 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, + 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, + 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, + 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, + 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, + 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, + 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, + 0xb0, 0x54, 0xbb, 0x16 }; static inline unsigned int rotword(unsigned int a) { - return (((a) >> 24)|((a) << 8)); + return (((a) >> 24)|((a) << 8)); } #define subbyte(a, o)(sbox[((a) >> (o))&0xff] << (o)) @@ -69,75 +69,75 @@ static inline unsigned int rotword(unsigned int a) int tc_aes128_set_encrypt_key(TCAesKeySched_t s, const uint8_t *k) { - const unsigned int rconst[11] = { - 0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, - 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000 - }; - unsigned int i; - unsigned int t; + const unsigned int rconst[11] = { + 0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, + 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000 + }; + unsigned int i; + unsigned int t; - if (s == (TCAesKeySched_t) 0) { - return TC_CRYPTO_FAIL; - } else if (k == (const uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } + if (s == (TCAesKeySched_t) 0) { + return TC_CRYPTO_FAIL; + } else if (k == (const uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } - for (i = 0; i < Nk; ++i) { - s->words[i] = (k[Nb*i]<<24) | (k[Nb*i+1]<<16) | - (k[Nb*i+2]<<8) | (k[Nb*i+3]); - } + for (i = 0; i < Nk; ++i) { + s->words[i] = (k[Nb*i]<<24) | (k[Nb*i+1]<<16) | + (k[Nb*i+2]<<8) | (k[Nb*i+3]); + } - for (; i < (Nb * (Nr + 1)); ++i) { - t = s->words[i-1]; - if ((i % Nk) == 0) { - t = subword(rotword(t)) ^ rconst[i/Nk]; - } - s->words[i] = s->words[i-Nk] ^ t; - } + for (; i < (Nb * (Nr + 1)); ++i) { + t = s->words[i-1]; + if ((i % Nk) == 0) { + t = subword(rotword(t)) ^ rconst[i/Nk]; + } + s->words[i] = s->words[i-Nk] ^ t; + } - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } static inline void add_round_key(uint8_t *s, const unsigned int *k) { - s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); - s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); - s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); - s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); - s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); - s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); - s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); - s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); + s[0] ^= (uint8_t)(k[0] >> 24); s[1] ^= (uint8_t)(k[0] >> 16); + s[2] ^= (uint8_t)(k[0] >> 8); s[3] ^= (uint8_t)(k[0]); + s[4] ^= (uint8_t)(k[1] >> 24); s[5] ^= (uint8_t)(k[1] >> 16); + s[6] ^= (uint8_t)(k[1] >> 8); s[7] ^= (uint8_t)(k[1]); + s[8] ^= (uint8_t)(k[2] >> 24); s[9] ^= (uint8_t)(k[2] >> 16); + s[10] ^= (uint8_t)(k[2] >> 8); s[11] ^= (uint8_t)(k[2]); + s[12] ^= (uint8_t)(k[3] >> 24); s[13] ^= (uint8_t)(k[3] >> 16); + s[14] ^= (uint8_t)(k[3] >> 8); s[15] ^= (uint8_t)(k[3]); } static inline void sub_bytes(uint8_t *s) { - unsigned int i; + unsigned int i; - for (i = 0; i < (Nb * Nk); ++i) { - s[i] = sbox[s[i]]; - } + for (i = 0; i < (Nb * Nk); ++i) { + s[i] = sbox[s[i]]; + } } #define triple(a)(_double_byte(a)^(a)) static inline void mult_row_column(uint8_t *out, const uint8_t *in) { - out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3]; - out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3]; - out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]); - out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]); + out[0] = _double_byte(in[0]) ^ triple(in[1]) ^ in[2] ^ in[3]; + out[1] = in[0] ^ _double_byte(in[1]) ^ triple(in[2]) ^ in[3]; + out[2] = in[0] ^ in[1] ^ _double_byte(in[2]) ^ triple(in[3]); + out[3] = triple(in[0]) ^ in[1] ^ in[2] ^ _double_byte(in[3]); } static inline void mix_columns(uint8_t *s) { - uint8_t t[Nb*Nk]; + uint8_t t[Nb*Nk]; - mult_row_column(t, s); - mult_row_column(&t[Nb], s+Nb); - mult_row_column(&t[2 * Nb], s + (2 * Nb)); - mult_row_column(&t[3 * Nb], s + (3 * Nb)); - (void) _copy(s, sizeof(t), t, sizeof(t)); + mult_row_column(t, s); + mult_row_column(&t[Nb], s+Nb); + mult_row_column(&t[2 * Nb], s + (2 * Nb)); + mult_row_column(&t[3 * Nb], s + (3 * Nb)); + (void) _copy(s, sizeof(t), t, sizeof(t)); } /* @@ -146,46 +146,46 @@ static inline void mix_columns(uint8_t *s) */ static inline void shift_rows(uint8_t *s) { - uint8_t t[Nb * Nk]; + uint8_t t[Nb * Nk]; - t[0] = s[0]; t[1] = s[5]; t[2] = s[10]; t[3] = s[15]; - t[4] = s[4]; t[5] = s[9]; t[6] = s[14]; t[7] = s[3]; - t[8] = s[8]; t[9] = s[13]; t[10] = s[2]; t[11] = s[7]; - t[12] = s[12]; t[13] = s[1]; t[14] = s[6]; t[15] = s[11]; - (void) _copy(s, sizeof(t), t, sizeof(t)); + t[0] = s[0]; t[1] = s[5]; t[2] = s[10]; t[3] = s[15]; + t[4] = s[4]; t[5] = s[9]; t[6] = s[14]; t[7] = s[3]; + t[8] = s[8]; t[9] = s[13]; t[10] = s[2]; t[11] = s[7]; + t[12] = s[12]; t[13] = s[1]; t[14] = s[6]; t[15] = s[11]; + (void) _copy(s, sizeof(t), t, sizeof(t)); } int tc_aes_encrypt(uint8_t *out, const uint8_t *in, const TCAesKeySched_t s) { - uint8_t state[Nk*Nb]; - unsigned int i; + uint8_t state[Nk*Nb]; + unsigned int i; - if (out == (uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } else if (in == (const uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } else if (s == (TCAesKeySched_t) 0) { - return TC_CRYPTO_FAIL; - } + if (out == (uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } else if (in == (const uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } else if (s == (TCAesKeySched_t) 0) { + return TC_CRYPTO_FAIL; + } - (void)_copy(state, sizeof(state), in, sizeof(state)); - add_round_key(state, s->words); + (void)_copy(state, sizeof(state), in, sizeof(state)); + add_round_key(state, s->words); - for (i = 0; i < (Nr - 1); ++i) { - sub_bytes(state); - shift_rows(state); - mix_columns(state); - add_round_key(state, s->words + Nb*(i+1)); - } + for (i = 0; i < (Nr - 1); ++i) { + sub_bytes(state); + shift_rows(state); + mix_columns(state); + add_round_key(state, s->words + Nb*(i+1)); + } - sub_bytes(state); - shift_rows(state); - add_round_key(state, s->words + Nb*(i+1)); + sub_bytes(state); + shift_rows(state); + add_round_key(state, s->words + Nb*(i+1)); - (void)_copy(out, sizeof(state), state, sizeof(state)); + (void)_copy(out, sizeof(state), state, sizeof(state)); - /* zeroing out the state buffer */ - _set(state, TC_ZERO_BYTE, sizeof(state)); + /* zeroing out the state buffer */ + _set(state, TC_ZERO_BYTE, sizeof(state)); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/cbc_mode.c b/components/network/ble/blestack/src/common/tinycrypt/source/cbc_mode.c index 5b6fd82c..72406097 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/cbc_mode.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/cbc_mode.c @@ -35,80 +35,80 @@ #include "utils.h" int tc_cbc_mode_encrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, - unsigned int inlen, const uint8_t *iv, - const TCAesKeySched_t sched) + unsigned int inlen, const uint8_t *iv, + const TCAesKeySched_t sched) { - uint8_t buffer[TC_AES_BLOCK_SIZE]; - unsigned int n, m; + uint8_t buffer[TC_AES_BLOCK_SIZE]; + unsigned int n, m; - /* input sanity check: */ - if (out == (uint8_t *) 0 || - in == (const uint8_t *) 0 || - sched == (TCAesKeySched_t) 0 || - inlen == 0 || - outlen == 0 || - (inlen % TC_AES_BLOCK_SIZE) != 0 || - (outlen % TC_AES_BLOCK_SIZE) != 0 || - outlen != inlen + TC_AES_BLOCK_SIZE) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (out == (uint8_t *) 0 || + in == (const uint8_t *) 0 || + sched == (TCAesKeySched_t) 0 || + inlen == 0 || + outlen == 0 || + (inlen % TC_AES_BLOCK_SIZE) != 0 || + (outlen % TC_AES_BLOCK_SIZE) != 0 || + outlen != inlen + TC_AES_BLOCK_SIZE) { + return TC_CRYPTO_FAIL; + } - /* copy iv to the buffer */ - (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); - /* copy iv to the output buffer */ - (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); - out += TC_AES_BLOCK_SIZE; + /* copy iv to the buffer */ + (void)_copy(buffer, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); + /* copy iv to the output buffer */ + (void)_copy(out, TC_AES_BLOCK_SIZE, iv, TC_AES_BLOCK_SIZE); + out += TC_AES_BLOCK_SIZE; - for (n = m = 0; n < inlen; ++n) { - buffer[m++] ^= *in++; - if (m == TC_AES_BLOCK_SIZE) { - (void)tc_aes_encrypt(buffer, buffer, sched); - (void)_copy(out, TC_AES_BLOCK_SIZE, - buffer, TC_AES_BLOCK_SIZE); - out += TC_AES_BLOCK_SIZE; - m = 0; - } - } + for (n = m = 0; n < inlen; ++n) { + buffer[m++] ^= *in++; + if (m == TC_AES_BLOCK_SIZE) { + (void)tc_aes_encrypt(buffer, buffer, sched); + (void)_copy(out, TC_AES_BLOCK_SIZE, + buffer, TC_AES_BLOCK_SIZE); + out += TC_AES_BLOCK_SIZE; + m = 0; + } + } - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_cbc_mode_decrypt(uint8_t *out, unsigned int outlen, const uint8_t *in, - unsigned int inlen, const uint8_t *iv, - const TCAesKeySched_t sched) + unsigned int inlen, const uint8_t *iv, + const TCAesKeySched_t sched) { - uint8_t buffer[TC_AES_BLOCK_SIZE]; - const uint8_t *p; - unsigned int n, m; + uint8_t buffer[TC_AES_BLOCK_SIZE]; + const uint8_t *p; + unsigned int n, m; - /* sanity check the inputs */ - if (out == (uint8_t *) 0 || - in == (const uint8_t *) 0 || - sched == (TCAesKeySched_t) 0 || - inlen == 0 || - outlen == 0 || - (inlen % TC_AES_BLOCK_SIZE) != 0 || - (outlen % TC_AES_BLOCK_SIZE) != 0 || - outlen != inlen) { - return TC_CRYPTO_FAIL; - } + /* sanity check the inputs */ + if (out == (uint8_t *) 0 || + in == (const uint8_t *) 0 || + sched == (TCAesKeySched_t) 0 || + inlen == 0 || + outlen == 0 || + (inlen % TC_AES_BLOCK_SIZE) != 0 || + (outlen % TC_AES_BLOCK_SIZE) != 0 || + outlen != inlen) { + return TC_CRYPTO_FAIL; + } - /* - * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are - * contiguous. This allows for a very efficient decryption algorithm - * that would not otherwise be possible. - */ - p = iv; - for (n = m = 0; n < outlen; ++n) { - if ((n % TC_AES_BLOCK_SIZE) == 0) { - (void)tc_aes_decrypt(buffer, in, sched); - in += TC_AES_BLOCK_SIZE; - m = 0; - } - *out++ = buffer[m++] ^ *p++; - } + /* + * Note that in == iv + ciphertext, i.e. the iv and the ciphertext are + * contiguous. This allows for a very efficient decryption algorithm + * that would not otherwise be possible. + */ + p = iv; + for (n = m = 0; n < outlen; ++n) { + if ((n % TC_AES_BLOCK_SIZE) == 0) { + (void)tc_aes_decrypt(buffer, in, sched); + in += TC_AES_BLOCK_SIZE; + m = 0; + } + *out++ = buffer[m++] ^ *p++; + } - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/ccm_mode.c b/components/network/ble/blestack/src/common/tinycrypt/source/ccm_mode.c index 9b19994a..98310ec9 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/ccm_mode.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/ccm_mode.c @@ -37,50 +37,50 @@ #include int tc_ccm_config(TCCcmMode_t c, TCAesKeySched_t sched, uint8_t *nonce, - unsigned int nlen, unsigned int mlen) + unsigned int nlen, unsigned int mlen) { - /* input sanity check: */ - if (c == (TCCcmMode_t) 0 || - sched == (TCAesKeySched_t) 0 || - nonce == (uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } else if (nlen != 13) { - return TC_CRYPTO_FAIL; /* The allowed nonce size is: 13. See documentation.*/ - } else if ((mlen < 4) || (mlen > 16) || (mlen & 1)) { - return TC_CRYPTO_FAIL; /* The allowed mac sizes are: 4, 6, 8, 10, 12, 14, 16.*/ - } + /* input sanity check: */ + if (c == (TCCcmMode_t) 0 || + sched == (TCAesKeySched_t) 0 || + nonce == (uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } else if (nlen != 13) { + return TC_CRYPTO_FAIL; /* The allowed nonce size is: 13. See documentation.*/ + } else if ((mlen < 4) || (mlen > 16) || (mlen & 1)) { + return TC_CRYPTO_FAIL; /* The allowed mac sizes are: 4, 6, 8, 10, 12, 14, 16.*/ + } - c->mlen = mlen; - c->sched = sched; - c->nonce = nonce; + c->mlen = mlen; + c->sched = sched; + c->nonce = nonce; - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } /** * Variation of CBC-MAC mode used in CCM. */ static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen, - unsigned int flag, TCAesKeySched_t sched) + unsigned int flag, TCAesKeySched_t sched) { - unsigned int i; + unsigned int i; - if (flag > 0) { - T[0] ^= (uint8_t)(dlen >> 8); - T[1] ^= (uint8_t)(dlen); - dlen += 2; i = 2; - } else { - i = 0; - } + if (flag > 0) { + T[0] ^= (uint8_t)(dlen >> 8); + T[1] ^= (uint8_t)(dlen); + dlen += 2; i = 2; + } else { + i = 0; + } - while (i < dlen) { - T[i++ % (Nb * Nk)] ^= *data++; - if (((i % (Nb * Nk)) == 0) || dlen == i) { - (void) tc_aes_encrypt(T, T, sched); - } - } + while (i < dlen) { + T[i++ % (Nb * Nk)] ^= *data++; + if (((i % (Nb * Nk)) == 0) || dlen == i) { + (void) tc_aes_encrypt(T, T, sched); + } + } } /** @@ -91,176 +91,176 @@ static void ccm_cbc_mac(uint8_t *T, const uint8_t *data, unsigned int dlen, * 2 bytes of the nonce. */ static int ccm_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, - unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) + unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) { - uint8_t buffer[TC_AES_BLOCK_SIZE]; - uint8_t nonce[TC_AES_BLOCK_SIZE]; - uint16_t block_num; - unsigned int i; + uint8_t buffer[TC_AES_BLOCK_SIZE]; + uint8_t nonce[TC_AES_BLOCK_SIZE]; + uint16_t block_num; + unsigned int i; - /* input sanity check: */ - if (out == (uint8_t *) 0 || - in == (uint8_t *) 0 || - ctr == (uint8_t *) 0 || - sched == (TCAesKeySched_t) 0 || - inlen == 0 || - outlen == 0 || - outlen != inlen) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (out == (uint8_t *) 0 || + in == (uint8_t *) 0 || + ctr == (uint8_t *) 0 || + sched == (TCAesKeySched_t) 0 || + inlen == 0 || + outlen == 0 || + outlen != inlen) { + return TC_CRYPTO_FAIL; + } - /* copy the counter to the nonce */ - (void) _copy(nonce, sizeof(nonce), ctr, sizeof(nonce)); + /* copy the counter to the nonce */ + (void) _copy(nonce, sizeof(nonce), ctr, sizeof(nonce)); - /* select the last 2 bytes of the nonce to be incremented */ - block_num = (uint16_t) ((nonce[14] << 8)|(nonce[15])); - for (i = 0; i < inlen; ++i) { - if ((i % (TC_AES_BLOCK_SIZE)) == 0) { - block_num++; - nonce[14] = (uint8_t)(block_num >> 8); - nonce[15] = (uint8_t)(block_num); - if (!tc_aes_encrypt(buffer, nonce, sched)) { - return TC_CRYPTO_FAIL; - } - } - /* update the output */ - *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++; - } + /* select the last 2 bytes of the nonce to be incremented */ + block_num = (uint16_t) ((nonce[14] << 8)|(nonce[15])); + for (i = 0; i < inlen; ++i) { + if ((i % (TC_AES_BLOCK_SIZE)) == 0) { + block_num++; + nonce[14] = (uint8_t)(block_num >> 8); + nonce[15] = (uint8_t)(block_num); + if (!tc_aes_encrypt(buffer, nonce, sched)) { + return TC_CRYPTO_FAIL; + } + } + /* update the output */ + *out++ = buffer[i % (TC_AES_BLOCK_SIZE)] ^ *in++; + } - /* update the counter */ - ctr[14] = nonce[14]; ctr[15] = nonce[15]; + /* update the counter */ + ctr[14] = nonce[14]; ctr[15] = nonce[15]; - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_ccm_generation_encryption(uint8_t *out, unsigned int olen, - const uint8_t *associated_data, - unsigned int alen, const uint8_t *payload, - unsigned int plen, TCCcmMode_t c) + const uint8_t *associated_data, + unsigned int alen, const uint8_t *payload, + unsigned int plen, TCCcmMode_t c) { - /* input sanity check: */ - if ((out == (uint8_t *) 0) || - (c == (TCCcmMode_t) 0) || - ((plen > 0) && (payload == (uint8_t *) 0)) || - ((alen > 0) && (associated_data == (uint8_t *) 0)) || - (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ - (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ - (olen < (plen + c->mlen))) { /* invalid output buffer size */ - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if ((out == (uint8_t *) 0) || + (c == (TCCcmMode_t) 0) || + ((plen > 0) && (payload == (uint8_t *) 0)) || + ((alen > 0) && (associated_data == (uint8_t *) 0)) || + (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ + (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ + (olen < (plen + c->mlen))) { /* invalid output buffer size */ + return TC_CRYPTO_FAIL; + } - uint8_t b[Nb * Nk]; - uint8_t tag[Nb * Nk]; - unsigned int i; + uint8_t b[Nb * Nk]; + uint8_t tag[Nb * Nk]; + unsigned int i; - /* GENERATING THE AUTHENTICATION TAG: */ + /* GENERATING THE AUTHENTICATION TAG: */ - /* formatting the sequence b for authentication: */ - b[0] = ((alen > 0) ? 0x40:0) | (((c->mlen - 2) / 2 << 3)) | (1); - for (i = 1; i <= 13; ++i) { - b[i] = c->nonce[i - 1]; - } - b[14] = (uint8_t)(plen >> 8); - b[15] = (uint8_t)(plen); + /* formatting the sequence b for authentication: */ + b[0] = ((alen > 0) ? 0x40:0) | (((c->mlen - 2) / 2 << 3)) | (1); + for (i = 1; i <= 13; ++i) { + b[i] = c->nonce[i - 1]; + } + b[14] = (uint8_t)(plen >> 8); + b[15] = (uint8_t)(plen); - /* computing the authentication tag using cbc-mac: */ - (void) tc_aes_encrypt(tag, b, c->sched); - if (alen > 0) { - ccm_cbc_mac(tag, associated_data, alen, 1, c->sched); - } - if (plen > 0) { - ccm_cbc_mac(tag, payload, plen, 0, c->sched); - } + /* computing the authentication tag using cbc-mac: */ + (void) tc_aes_encrypt(tag, b, c->sched); + if (alen > 0) { + ccm_cbc_mac(tag, associated_data, alen, 1, c->sched); + } + if (plen > 0) { + ccm_cbc_mac(tag, payload, plen, 0, c->sched); + } - /* ENCRYPTION: */ + /* ENCRYPTION: */ - /* formatting the sequence b for encryption: */ - b[0] = 1; /* q - 1 = 2 - 1 = 1 */ - b[14] = b[15] = TC_ZERO_BYTE; + /* formatting the sequence b for encryption: */ + b[0] = 1; /* q - 1 = 2 - 1 = 1 */ + b[14] = b[15] = TC_ZERO_BYTE; - /* encrypting payload using ctr mode: */ - ccm_ctr_mode(out, plen, payload, plen, b, c->sched); + /* encrypting payload using ctr mode: */ + ccm_ctr_mode(out, plen, payload, plen, b, c->sched); - b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter for ctr_mode (0):*/ + b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter for ctr_mode (0):*/ - /* encrypting b and adding the tag to the output: */ - (void) tc_aes_encrypt(b, b, c->sched); - out += plen; - for (i = 0; i < c->mlen; ++i) { - *out++ = tag[i] ^ b[i]; - } + /* encrypting b and adding the tag to the output: */ + (void) tc_aes_encrypt(b, b, c->sched); + out += plen; + for (i = 0; i < c->mlen; ++i) { + *out++ = tag[i] ^ b[i]; + } - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_ccm_decryption_verification(uint8_t *out, unsigned int olen, - const uint8_t *associated_data, - unsigned int alen, const uint8_t *payload, - unsigned int plen, TCCcmMode_t c) + const uint8_t *associated_data, + unsigned int alen, const uint8_t *payload, + unsigned int plen, TCCcmMode_t c) { - /* input sanity check: */ - if ((out == (uint8_t *) 0) || - (c == (TCCcmMode_t) 0) || - ((plen > 0) && (payload == (uint8_t *) 0)) || - ((alen > 0) && (associated_data == (uint8_t *) 0)) || - (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ - (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ - (olen < plen - c->mlen)) { /* invalid output buffer size */ - return TC_CRYPTO_FAIL; + /* input sanity check: */ + if ((out == (uint8_t *) 0) || + (c == (TCCcmMode_t) 0) || + ((plen > 0) && (payload == (uint8_t *) 0)) || + ((alen > 0) && (associated_data == (uint8_t *) 0)) || + (alen >= TC_CCM_AAD_MAX_BYTES) || /* associated data size unsupported */ + (plen >= TC_CCM_PAYLOAD_MAX_BYTES) || /* payload size unsupported */ + (olen < plen - c->mlen)) { /* invalid output buffer size */ + return TC_CRYPTO_FAIL; } - uint8_t b[Nb * Nk]; - uint8_t tag[Nb * Nk]; - unsigned int i; + uint8_t b[Nb * Nk]; + uint8_t tag[Nb * Nk]; + unsigned int i; - /* DECRYPTION: */ + /* DECRYPTION: */ - /* formatting the sequence b for decryption: */ - b[0] = 1; /* q - 1 = 2 - 1 = 1 */ - for (i = 1; i < 14; ++i) { - b[i] = c->nonce[i - 1]; - } - b[14] = b[15] = TC_ZERO_BYTE; /* initial counter value is 0 */ + /* formatting the sequence b for decryption: */ + b[0] = 1; /* q - 1 = 2 - 1 = 1 */ + for (i = 1; i < 14; ++i) { + b[i] = c->nonce[i - 1]; + } + b[14] = b[15] = TC_ZERO_BYTE; /* initial counter value is 0 */ - /* decrypting payload using ctr mode: */ - ccm_ctr_mode(out, plen - c->mlen, payload, plen - c->mlen, b, c->sched); + /* decrypting payload using ctr mode: */ + ccm_ctr_mode(out, plen - c->mlen, payload, plen - c->mlen, b, c->sched); - b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter value (0) */ + b[14] = b[15] = TC_ZERO_BYTE; /* restoring initial counter value (0) */ - /* encrypting b and restoring the tag from input: */ - (void) tc_aes_encrypt(b, b, c->sched); - for (i = 0; i < c->mlen; ++i) { - tag[i] = *(payload + plen - c->mlen + i) ^ b[i]; - } + /* encrypting b and restoring the tag from input: */ + (void) tc_aes_encrypt(b, b, c->sched); + for (i = 0; i < c->mlen; ++i) { + tag[i] = *(payload + plen - c->mlen + i) ^ b[i]; + } - /* VERIFYING THE AUTHENTICATION TAG: */ + /* VERIFYING THE AUTHENTICATION TAG: */ - /* formatting the sequence b for authentication: */ - b[0] = ((alen > 0) ? 0x40:0)|(((c->mlen - 2) / 2 << 3)) | (1); - for (i = 1; i < 14; ++i) { - b[i] = c->nonce[i - 1]; - } - b[14] = (uint8_t)((plen - c->mlen) >> 8); - b[15] = (uint8_t)(plen - c->mlen); + /* formatting the sequence b for authentication: */ + b[0] = ((alen > 0) ? 0x40:0)|(((c->mlen - 2) / 2 << 3)) | (1); + for (i = 1; i < 14; ++i) { + b[i] = c->nonce[i - 1]; + } + b[14] = (uint8_t)((plen - c->mlen) >> 8); + b[15] = (uint8_t)(plen - c->mlen); - /* computing the authentication tag using cbc-mac: */ - (void) tc_aes_encrypt(b, b, c->sched); - if (alen > 0) { - ccm_cbc_mac(b, associated_data, alen, 1, c->sched); - } - if (plen > 0) { - ccm_cbc_mac(b, out, plen - c->mlen, 0, c->sched); - } + /* computing the authentication tag using cbc-mac: */ + (void) tc_aes_encrypt(b, b, c->sched); + if (alen > 0) { + ccm_cbc_mac(b, associated_data, alen, 1, c->sched); + } + if (plen > 0) { + ccm_cbc_mac(b, out, plen - c->mlen, 0, c->sched); + } - /* comparing the received tag and the computed one: */ - if (_compare(b, tag, c->mlen) == 0) { - return TC_CRYPTO_SUCCESS; - } else { - /* erase the decrypted buffer in case of mac validation failure: */ - _set(out, 0, plen - c->mlen); - return TC_CRYPTO_FAIL; - } + /* comparing the received tag and the computed one: */ + if (_compare(b, tag, c->mlen) == 0) { + return TC_CRYPTO_SUCCESS; + } else { + /* erase the decrypted buffer in case of mac validation failure: */ + _set(out, 0, plen - c->mlen); + return TC_CRYPTO_FAIL; + } } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/cmac_mode.c b/components/network/ble/blestack/src/common/tinycrypt/source/cmac_mode.c index 6b96e247..f1dfd1cf 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/cmac_mode.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/cmac_mode.c @@ -78,177 +78,177 @@ const unsigned char gf_wrap = 0x87; void gf_double(uint8_t *out, uint8_t *in) { - /* start with low order byte */ - uint8_t *x = in + (TC_AES_BLOCK_SIZE - 1); + /* start with low order byte */ + uint8_t *x = in + (TC_AES_BLOCK_SIZE - 1); - /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */ - uint8_t carry = (in[0] >> 7) ? gf_wrap : 0; + /* if msb == 1, we need to add the gf_wrap value, otherwise add 0 */ + uint8_t carry = (in[0] >> 7) ? gf_wrap : 0; - out += (TC_AES_BLOCK_SIZE - 1); - for (;;) { - *out-- = (*x << 1) ^ carry; - if (x == in) { - break; - } - carry = *x-- >> 7; - } + out += (TC_AES_BLOCK_SIZE - 1); + for (;;) { + *out-- = (*x << 1) ^ carry; + if (x == in) { + break; + } + carry = *x-- >> 7; + } } int tc_cmac_setup(TCCmacState_t s, const uint8_t *key, TCAesKeySched_t sched) { - /* input sanity check: */ - if (s == (TCCmacState_t) 0 || - key == (const uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (s == (TCCmacState_t) 0 || + key == (const uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } - /* put s into a known state */ - _set(s, 0, sizeof(*s)); - s->sched = sched; + /* put s into a known state */ + _set(s, 0, sizeof(*s)); + s->sched = sched; - /* configure the encryption key used by the underlying block cipher */ - tc_aes128_set_encrypt_key(s->sched, key); + /* configure the encryption key used by the underlying block cipher */ + tc_aes128_set_encrypt_key(s->sched, key); - /* compute s->K1 and s->K2 from s->iv using s->keyid */ - _set(s->iv, 0, TC_AES_BLOCK_SIZE); - tc_aes_encrypt(s->iv, s->iv, s->sched); - gf_double (s->K1, s->iv); - gf_double (s->K2, s->K1); + /* compute s->K1 and s->K2 from s->iv using s->keyid */ + _set(s->iv, 0, TC_AES_BLOCK_SIZE); + tc_aes_encrypt(s->iv, s->iv, s->sched); + gf_double (s->K1, s->iv); + gf_double (s->K2, s->K1); - /* reset s->iv to 0 in case someone wants to compute now */ - tc_cmac_init(s); + /* reset s->iv to 0 in case someone wants to compute now */ + tc_cmac_init(s); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_cmac_erase(TCCmacState_t s) { - if (s == (TCCmacState_t) 0) { - return TC_CRYPTO_FAIL; - } + if (s == (TCCmacState_t) 0) { + return TC_CRYPTO_FAIL; + } - /* destroy the current state */ - _set(s, 0, sizeof(*s)); + /* destroy the current state */ + _set(s, 0, sizeof(*s)); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_cmac_init(TCCmacState_t s) { - /* input sanity check: */ - if (s == (TCCmacState_t) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (s == (TCCmacState_t) 0) { + return TC_CRYPTO_FAIL; + } - /* CMAC starts with an all zero initialization vector */ - _set(s->iv, 0, TC_AES_BLOCK_SIZE); + /* CMAC starts with an all zero initialization vector */ + _set(s->iv, 0, TC_AES_BLOCK_SIZE); - /* and the leftover buffer is empty */ - _set(s->leftover, 0, TC_AES_BLOCK_SIZE); - s->leftover_offset = 0; + /* and the leftover buffer is empty */ + _set(s->leftover, 0, TC_AES_BLOCK_SIZE); + s->leftover_offset = 0; - /* Set countdown to max number of calls allowed before re-keying: */ - s->countdown = MAX_CALLS; + /* Set countdown to max number of calls allowed before re-keying: */ + s->countdown = MAX_CALLS; - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_cmac_update(TCCmacState_t s, const uint8_t *data, size_t data_length) { - unsigned int i; + unsigned int i; - /* input sanity check: */ - if (s == (TCCmacState_t) 0) { - return TC_CRYPTO_FAIL; - } - if (data_length == 0) { - return TC_CRYPTO_SUCCESS; - } - if (data == (const uint8_t *) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (s == (TCCmacState_t) 0) { + return TC_CRYPTO_FAIL; + } + if (data_length == 0) { + return TC_CRYPTO_SUCCESS; + } + if (data == (const uint8_t *) 0) { + return TC_CRYPTO_FAIL; + } - if (s->countdown == 0) { - return TC_CRYPTO_FAIL; - } + if (s->countdown == 0) { + return TC_CRYPTO_FAIL; + } - s->countdown--; + s->countdown--; - if (s->leftover_offset > 0) { - /* last data added to s didn't end on a TC_AES_BLOCK_SIZE byte boundary */ - size_t remaining_space = TC_AES_BLOCK_SIZE - s->leftover_offset; + if (s->leftover_offset > 0) { + /* last data added to s didn't end on a TC_AES_BLOCK_SIZE byte boundary */ + size_t remaining_space = TC_AES_BLOCK_SIZE - s->leftover_offset; - if (data_length < remaining_space) { - /* still not enough data to encrypt this time either */ - _copy(&s->leftover[s->leftover_offset], data_length, data, data_length); - s->leftover_offset += data_length; - return TC_CRYPTO_SUCCESS; - } - /* leftover block is now full; encrypt it first */ - _copy(&s->leftover[s->leftover_offset], - remaining_space, - data, - remaining_space); - data_length -= remaining_space; - data += remaining_space; - s->leftover_offset = 0; + if (data_length < remaining_space) { + /* still not enough data to encrypt this time either */ + _copy(&s->leftover[s->leftover_offset], data_length, data, data_length); + s->leftover_offset += data_length; + return TC_CRYPTO_SUCCESS; + } + /* leftover block is now full; encrypt it first */ + _copy(&s->leftover[s->leftover_offset], + remaining_space, + data, + remaining_space); + data_length -= remaining_space; + data += remaining_space; + s->leftover_offset = 0; - for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { - s->iv[i] ^= s->leftover[i]; - } - tc_aes_encrypt(s->iv, s->iv, s->sched); - } + for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { + s->iv[i] ^= s->leftover[i]; + } + tc_aes_encrypt(s->iv, s->iv, s->sched); + } - /* CBC encrypt each (except the last) of the data blocks */ - while (data_length > TC_AES_BLOCK_SIZE) { - for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { - s->iv[i] ^= data[i]; - } - tc_aes_encrypt(s->iv, s->iv, s->sched); - data += TC_AES_BLOCK_SIZE; - data_length -= TC_AES_BLOCK_SIZE; - } + /* CBC encrypt each (except the last) of the data blocks */ + while (data_length > TC_AES_BLOCK_SIZE) { + for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { + s->iv[i] ^= data[i]; + } + tc_aes_encrypt(s->iv, s->iv, s->sched); + data += TC_AES_BLOCK_SIZE; + data_length -= TC_AES_BLOCK_SIZE; + } - if (data_length > 0) { - /* save leftover data for next time */ - _copy(s->leftover, data_length, data, data_length); - s->leftover_offset = data_length; - } + if (data_length > 0) { + /* save leftover data for next time */ + _copy(s->leftover, data_length, data, data_length); + s->leftover_offset = data_length; + } - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_cmac_final(uint8_t *tag, TCCmacState_t s) { - uint8_t *k; - unsigned int i; + uint8_t *k; + unsigned int i; - /* input sanity check: */ - if (tag == (uint8_t *) 0 || - s == (TCCmacState_t) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (tag == (uint8_t *) 0 || + s == (TCCmacState_t) 0) { + return TC_CRYPTO_FAIL; + } - if (s->leftover_offset == TC_AES_BLOCK_SIZE) { - /* the last message block is a full-sized block */ - k = (uint8_t *) s->K1; - } else { - /* the final message block is not a full-sized block */ - size_t remaining = TC_AES_BLOCK_SIZE - s->leftover_offset; + if (s->leftover_offset == TC_AES_BLOCK_SIZE) { + /* the last message block is a full-sized block */ + k = (uint8_t *) s->K1; + } else { + /* the final message block is not a full-sized block */ + size_t remaining = TC_AES_BLOCK_SIZE - s->leftover_offset; - _set(&s->leftover[s->leftover_offset], 0, remaining); - s->leftover[s->leftover_offset] = TC_CMAC_PADDING; - k = (uint8_t *) s->K2; - } - for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { - s->iv[i] ^= s->leftover[i] ^ k[i]; - } + _set(&s->leftover[s->leftover_offset], 0, remaining); + s->leftover[s->leftover_offset] = TC_CMAC_PADDING; + k = (uint8_t *) s->K2; + } + for (i = 0; i < TC_AES_BLOCK_SIZE; ++i) { + s->iv[i] ^= s->leftover[i] ^ k[i]; + } - tc_aes_encrypt(tag, s->iv, s->sched); + tc_aes_encrypt(tag, s->iv, s->sched); - /* erasing state: */ - tc_cmac_erase(s); + /* erasing state: */ + tc_cmac_erase(s); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/ctr_mode.c b/components/network/ble/blestack/src/common/tinycrypt/source/ctr_mode.c index f642e983..f6fd3b44 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/ctr_mode.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/ctr_mode.c @@ -35,51 +35,51 @@ #include "utils.h" int tc_ctr_mode(uint8_t *out, unsigned int outlen, const uint8_t *in, - unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) + unsigned int inlen, uint8_t *ctr, const TCAesKeySched_t sched) { - uint8_t buffer[TC_AES_BLOCK_SIZE]; - uint8_t nonce[TC_AES_BLOCK_SIZE]; - unsigned int block_num; - unsigned int i; + uint8_t buffer[TC_AES_BLOCK_SIZE]; + uint8_t nonce[TC_AES_BLOCK_SIZE]; + unsigned int block_num; + unsigned int i; - /* input sanity check: */ - if (out == (uint8_t *) 0 || - in == (uint8_t *) 0 || - ctr == (uint8_t *) 0 || - sched == (TCAesKeySched_t) 0 || - inlen == 0 || - outlen == 0 || - outlen != inlen) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (out == (uint8_t *) 0 || + in == (uint8_t *) 0 || + ctr == (uint8_t *) 0 || + sched == (TCAesKeySched_t) 0 || + inlen == 0 || + outlen == 0 || + outlen != inlen) { + return TC_CRYPTO_FAIL; + } - /* copy the ctr to the nonce */ - (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce)); + /* copy the ctr to the nonce */ + (void)_copy(nonce, sizeof(nonce), ctr, sizeof(nonce)); - /* select the last 4 bytes of the nonce to be incremented */ - block_num = (nonce[12] << 24) | (nonce[13] << 16) | - (nonce[14] << 8) | (nonce[15]); - for (i = 0; i < inlen; ++i) { - if ((i % (TC_AES_BLOCK_SIZE)) == 0) { - /* encrypt data using the current nonce */ - if (tc_aes_encrypt(buffer, nonce, sched)) { - block_num++; - nonce[12] = (uint8_t)(block_num >> 24); - nonce[13] = (uint8_t)(block_num >> 16); - nonce[14] = (uint8_t)(block_num >> 8); - nonce[15] = (uint8_t)(block_num); - } else { - return TC_CRYPTO_FAIL; - } - } - /* update the output */ - *out++ = buffer[i%(TC_AES_BLOCK_SIZE)] ^ *in++; - } + /* select the last 4 bytes of the nonce to be incremented */ + block_num = (nonce[12] << 24) | (nonce[13] << 16) | + (nonce[14] << 8) | (nonce[15]); + for (i = 0; i < inlen; ++i) { + if ((i % (TC_AES_BLOCK_SIZE)) == 0) { + /* encrypt data using the current nonce */ + if (tc_aes_encrypt(buffer, nonce, sched)) { + block_num++; + nonce[12] = (uint8_t)(block_num >> 24); + nonce[13] = (uint8_t)(block_num >> 16); + nonce[14] = (uint8_t)(block_num >> 8); + nonce[15] = (uint8_t)(block_num); + } else { + return TC_CRYPTO_FAIL; + } + } + /* update the output */ + *out++ = buffer[i%(TC_AES_BLOCK_SIZE)] ^ *in++; + } - /* update the counter */ - ctr[12] = nonce[12]; ctr[13] = nonce[13]; - ctr[14] = nonce[14]; ctr[15] = nonce[15]; + /* update the counter */ + ctr[12] = nonce[12]; ctr[13] = nonce[13]; + ctr[14] = nonce[14]; ctr[15] = nonce[15]; - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/ctr_prng.c b/components/network/ble/blestack/src/common/tinycrypt/source/ctr_prng.c index 59909600..6af69671 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/ctr_prng.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/ctr_prng.c @@ -52,14 +52,14 @@ */ static void arrInc(uint8_t arr[], unsigned int len) { - unsigned int i; - if (0 != arr) { - for (i = len; i > 0U; i--) { - if (++arr[i-1] != 0U) { - break; - } - } - } + unsigned int i; + if (0 != arr) { + for (i = len; i > 0U; i--) { + if (++arr[i-1] != 0U) { + break; + } + } + } } /** @@ -73,209 +73,209 @@ static void arrInc(uint8_t arr[], unsigned int len) */ static void tc_ctr_prng_update(TCCtrPrng_t * const ctx, uint8_t const * const providedData) { - if (0 != ctx) { - /* 10.2.1.2 step 1 */ - uint8_t temp[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; - unsigned int len = 0U; + if (0 != ctx) { + /* 10.2.1.2 step 1 */ + uint8_t temp[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; + unsigned int len = 0U; - /* 10.2.1.2 step 2 */ - while (len < sizeof temp) { - unsigned int blocklen = sizeof(temp) - len; - uint8_t output_block[TC_AES_BLOCK_SIZE]; + /* 10.2.1.2 step 2 */ + while (len < sizeof temp) { + unsigned int blocklen = sizeof(temp) - len; + uint8_t output_block[TC_AES_BLOCK_SIZE]; - /* 10.2.1.2 step 2.1 */ - arrInc(ctx->V, sizeof ctx->V); + /* 10.2.1.2 step 2.1 */ + arrInc(ctx->V, sizeof ctx->V); - /* 10.2.1.2 step 2.2 */ - if (blocklen > TC_AES_BLOCK_SIZE) { - blocklen = TC_AES_BLOCK_SIZE; - } - (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key); + /* 10.2.1.2 step 2.2 */ + if (blocklen > TC_AES_BLOCK_SIZE) { + blocklen = TC_AES_BLOCK_SIZE; + } + (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key); - /* 10.2.1.2 step 2.3/step 3 */ - memcpy(&(temp[len]), output_block, blocklen); + /* 10.2.1.2 step 2.3/step 3 */ + memcpy(&(temp[len]), output_block, blocklen); - len += blocklen; - } + len += blocklen; + } - /* 10.2.1.2 step 4 */ - if (0 != providedData) { - unsigned int i; - for (i = 0U; i < sizeof temp; i++) { - temp[i] ^= providedData[i]; - } - } + /* 10.2.1.2 step 4 */ + if (0 != providedData) { + unsigned int i; + for (i = 0U; i < sizeof temp; i++) { + temp[i] ^= providedData[i]; + } + } - /* 10.2.1.2 step 5 */ - (void)tc_aes128_set_encrypt_key(&ctx->key, temp); - - /* 10.2.1.2 step 6 */ - memcpy(ctx->V, &(temp[TC_AES_KEY_SIZE]), TC_AES_BLOCK_SIZE); - } + /* 10.2.1.2 step 5 */ + (void)tc_aes128_set_encrypt_key(&ctx->key, temp); + + /* 10.2.1.2 step 6 */ + memcpy(ctx->V, &(temp[TC_AES_KEY_SIZE]), TC_AES_BLOCK_SIZE); + } } -int tc_ctr_prng_init(TCCtrPrng_t * const ctx, - uint8_t const * const entropy, - unsigned int entropyLen, - uint8_t const * const personalization, - unsigned int pLen) +int tc_ctr_prng_init(TCCtrPrng_t * const ctx, + uint8_t const * const entropy, + unsigned int entropyLen, + uint8_t const * const personalization, + unsigned int pLen) { - int result = TC_CRYPTO_FAIL; - unsigned int i; - uint8_t personalization_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; - uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; - uint8_t zeroArr[TC_AES_BLOCK_SIZE] = {0U}; - - if (0 != personalization) { - /* 10.2.1.3.1 step 1 */ - unsigned int len = pLen; - if (len > sizeof personalization_buf) { - len = sizeof personalization_buf; - } + int result = TC_CRYPTO_FAIL; + unsigned int i; + uint8_t personalization_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; + uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; + uint8_t zeroArr[TC_AES_BLOCK_SIZE] = {0U}; - /* 10.2.1.3.1 step 2 */ - memcpy(personalization_buf, personalization, len); - } + if (0 != personalization) { + /* 10.2.1.3.1 step 1 */ + unsigned int len = pLen; + if (len > sizeof personalization_buf) { + len = sizeof personalization_buf; + } - if ((0 != ctx) && (0 != entropy) && (entropyLen >= sizeof seed_material)) { - /* 10.2.1.3.1 step 3 */ - memcpy(seed_material, entropy, sizeof seed_material); - for (i = 0U; i < sizeof seed_material; i++) { - seed_material[i] ^= personalization_buf[i]; - } + /* 10.2.1.3.1 step 2 */ + memcpy(personalization_buf, personalization, len); + } - /* 10.2.1.3.1 step 4 */ - (void)tc_aes128_set_encrypt_key(&ctx->key, zeroArr); + if ((0 != ctx) && (0 != entropy) && (entropyLen >= sizeof seed_material)) { + /* 10.2.1.3.1 step 3 */ + memcpy(seed_material, entropy, sizeof seed_material); + for (i = 0U; i < sizeof seed_material; i++) { + seed_material[i] ^= personalization_buf[i]; + } - /* 10.2.1.3.1 step 5 */ - memset(ctx->V, 0x00, sizeof ctx->V); - - /* 10.2.1.3.1 step 6 */ - tc_ctr_prng_update(ctx, seed_material); + /* 10.2.1.3.1 step 4 */ + (void)tc_aes128_set_encrypt_key(&ctx->key, zeroArr); - /* 10.2.1.3.1 step 7 */ - ctx->reseedCount = 1U; + /* 10.2.1.3.1 step 5 */ + memset(ctx->V, 0x00, sizeof ctx->V); - result = TC_CRYPTO_SUCCESS; - } - return result; + /* 10.2.1.3.1 step 6 */ + tc_ctr_prng_update(ctx, seed_material); + + /* 10.2.1.3.1 step 7 */ + ctx->reseedCount = 1U; + + result = TC_CRYPTO_SUCCESS; + } + return result; } -int tc_ctr_prng_reseed(TCCtrPrng_t * const ctx, - uint8_t const * const entropy, - unsigned int entropyLen, - uint8_t const * const additional_input, - unsigned int additionallen) +int tc_ctr_prng_reseed(TCCtrPrng_t * const ctx, + uint8_t const * const entropy, + unsigned int entropyLen, + uint8_t const * const additional_input, + unsigned int additionallen) { - unsigned int i; - int result = TC_CRYPTO_FAIL; - uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; - uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; + unsigned int i; + int result = TC_CRYPTO_FAIL; + uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; + uint8_t seed_material[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE]; - if (0 != additional_input) { - /* 10.2.1.4.1 step 1 */ - unsigned int len = additionallen; - if (len > sizeof additional_input_buf) { - len = sizeof additional_input_buf; - } + if (0 != additional_input) { + /* 10.2.1.4.1 step 1 */ + unsigned int len = additionallen; + if (len > sizeof additional_input_buf) { + len = sizeof additional_input_buf; + } - /* 10.2.1.4.1 step 2 */ - memcpy(additional_input_buf, additional_input, len); - } - - unsigned int seedlen = (unsigned int)TC_AES_KEY_SIZE + (unsigned int)TC_AES_BLOCK_SIZE; - if ((0 != ctx) && (entropyLen >= seedlen)) { - /* 10.2.1.4.1 step 3 */ - memcpy(seed_material, entropy, sizeof seed_material); - for (i = 0U; i < sizeof seed_material; i++) { - seed_material[i] ^= additional_input_buf[i]; - } + /* 10.2.1.4.1 step 2 */ + memcpy(additional_input_buf, additional_input, len); + } - /* 10.2.1.4.1 step 4 */ - tc_ctr_prng_update(ctx, seed_material); + unsigned int seedlen = (unsigned int)TC_AES_KEY_SIZE + (unsigned int)TC_AES_BLOCK_SIZE; + if ((0 != ctx) && (entropyLen >= seedlen)) { + /* 10.2.1.4.1 step 3 */ + memcpy(seed_material, entropy, sizeof seed_material); + for (i = 0U; i < sizeof seed_material; i++) { + seed_material[i] ^= additional_input_buf[i]; + } - /* 10.2.1.4.1 step 5 */ - ctx->reseedCount = 1U; + /* 10.2.1.4.1 step 4 */ + tc_ctr_prng_update(ctx, seed_material); - result = TC_CRYPTO_SUCCESS; - } - return result; + /* 10.2.1.4.1 step 5 */ + ctx->reseedCount = 1U; + + result = TC_CRYPTO_SUCCESS; + } + return result; } int tc_ctr_prng_generate(TCCtrPrng_t * const ctx, - uint8_t const * const additional_input, - unsigned int additionallen, - uint8_t * const out, - unsigned int outlen) + uint8_t const * const additional_input, + unsigned int additionallen, + uint8_t * const out, + unsigned int outlen) { - /* 2^48 - see section 10.2.1 */ - static const uint64_t MAX_REQS_BEFORE_RESEED = 0x1000000000000ULL; + /* 2^48 - see section 10.2.1 */ + static const uint64_t MAX_REQS_BEFORE_RESEED = 0x1000000000000ULL; - /* 2^19 bits - see section 10.2.1 */ - static const unsigned int MAX_BYTES_PER_REQ = 65536U; + /* 2^19 bits - see section 10.2.1 */ + static const unsigned int MAX_BYTES_PER_REQ = 65536U; - unsigned int result = TC_CRYPTO_FAIL; + unsigned int result = TC_CRYPTO_FAIL; - if ((0 != ctx) && (0 != out) && (outlen < MAX_BYTES_PER_REQ)) { - /* 10.2.1.5.1 step 1 */ - if (ctx->reseedCount > MAX_REQS_BEFORE_RESEED) { - result = TC_CTR_PRNG_RESEED_REQ; - } else { - uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; - if (0 != additional_input) { - /* 10.2.1.5.1 step 2 */ - unsigned int len = additionallen; - if (len > sizeof additional_input_buf) { - len = sizeof additional_input_buf; - } - memcpy(additional_input_buf, additional_input, len); - tc_ctr_prng_update(ctx, additional_input_buf); - } - - /* 10.2.1.5.1 step 3 - implicit */ + if ((0 != ctx) && (0 != out) && (outlen < MAX_BYTES_PER_REQ)) { + /* 10.2.1.5.1 step 1 */ + if (ctx->reseedCount > MAX_REQS_BEFORE_RESEED) { + result = TC_CTR_PRNG_RESEED_REQ; + } else { + uint8_t additional_input_buf[TC_AES_KEY_SIZE + TC_AES_BLOCK_SIZE] = {0U}; + if (0 != additional_input) { + /* 10.2.1.5.1 step 2 */ + unsigned int len = additionallen; + if (len > sizeof additional_input_buf) { + len = sizeof additional_input_buf; + } + memcpy(additional_input_buf, additional_input, len); + tc_ctr_prng_update(ctx, additional_input_buf); + } - /* 10.2.1.5.1 step 4 */ - unsigned int len = 0U; - while (len < outlen) { - unsigned int blocklen = outlen - len; - uint8_t output_block[TC_AES_BLOCK_SIZE]; + /* 10.2.1.5.1 step 3 - implicit */ - /* 10.2.1.5.1 step 4.1 */ - arrInc(ctx->V, sizeof ctx->V); + /* 10.2.1.5.1 step 4 */ + unsigned int len = 0U; + while (len < outlen) { + unsigned int blocklen = outlen - len; + uint8_t output_block[TC_AES_BLOCK_SIZE]; - /* 10.2.1.5.1 step 4.2 */ - (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key); - - /* 10.2.1.5.1 step 4.3/step 5 */ - if (blocklen > TC_AES_BLOCK_SIZE) { - blocklen = TC_AES_BLOCK_SIZE; - } - memcpy(&(out[len]), output_block, blocklen); + /* 10.2.1.5.1 step 4.1 */ + arrInc(ctx->V, sizeof ctx->V); - len += blocklen; - } - - /* 10.2.1.5.1 step 6 */ - tc_ctr_prng_update(ctx, additional_input_buf); + /* 10.2.1.5.1 step 4.2 */ + (void)tc_aes_encrypt(output_block, ctx->V, &ctx->key); - /* 10.2.1.5.1 step 7 */ - ctx->reseedCount++; + /* 10.2.1.5.1 step 4.3/step 5 */ + if (blocklen > TC_AES_BLOCK_SIZE) { + blocklen = TC_AES_BLOCK_SIZE; + } + memcpy(&(out[len]), output_block, blocklen); - /* 10.2.1.5.1 step 8 */ - result = TC_CRYPTO_SUCCESS; - } - } + len += blocklen; + } - return result; + /* 10.2.1.5.1 step 6 */ + tc_ctr_prng_update(ctx, additional_input_buf); + + /* 10.2.1.5.1 step 7 */ + ctx->reseedCount++; + + /* 10.2.1.5.1 step 8 */ + result = TC_CRYPTO_SUCCESS; + } + } + + return result; } void tc_ctr_prng_uninstantiate(TCCtrPrng_t * const ctx) { - if (0 != ctx) { - memset(ctx->key.words, 0x00, sizeof ctx->key.words); - memset(ctx->V, 0x00, sizeof ctx->V); - ctx->reseedCount = 0U; - } + if (0 != ctx) { + memset(ctx->key.words, 0x00, sizeof ctx->key.words); + memset(ctx->V, 0x00, sizeof ctx->V); + ctx->reseedCount = 0U; + } } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/ecc.c b/components/network/ble/blestack/src/common/tinycrypt/source/ecc.c index baf8e4eb..834968fe 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/ecc.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/ecc.c @@ -66,622 +66,622 @@ static uECC_RNG_Function g_rng_function = 0; void uECC_set_rng(uECC_RNG_Function rng_function) { - g_rng_function = rng_function; + g_rng_function = rng_function; } uECC_RNG_Function uECC_get_rng(void) { - return g_rng_function; + return g_rng_function; } int uECC_curve_private_key_size(uECC_Curve curve) { - return BITS_TO_BYTES(curve->num_n_bits); + return BITS_TO_BYTES(curve->num_n_bits); } int uECC_curve_public_key_size(uECC_Curve curve) { - return 2 * curve->num_bytes; + return 2 * curve->num_bytes; } void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words) { - wordcount_t i; - for (i = 0; i < num_words; ++i) { - vli[i] = 0; - } + wordcount_t i; + for (i = 0; i < num_words; ++i) { + vli[i] = 0; + } } uECC_word_t uECC_vli_isZero(const uECC_word_t *vli, wordcount_t num_words) { - uECC_word_t bits = 0; - wordcount_t i; - for (i = 0; i < num_words; ++i) { - bits |= vli[i]; - } - return (bits == 0); + uECC_word_t bits = 0; + wordcount_t i; + for (i = 0; i < num_words; ++i) { + bits |= vli[i]; + } + return (bits == 0); } uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit) { - return (vli[bit >> uECC_WORD_BITS_SHIFT] & - ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK))); + return (vli[bit >> uECC_WORD_BITS_SHIFT] & + ((uECC_word_t)1 << (bit & uECC_WORD_BITS_MASK))); } /* Counts the number of words in vli. */ static wordcount_t vli_numDigits(const uECC_word_t *vli, - const wordcount_t max_words) + const wordcount_t max_words) { - wordcount_t i; - /* Search from the end until we find a non-zero digit. We do it in reverse - * because we expect that most digits will be nonzero. */ - for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) { - } + wordcount_t i; + /* Search from the end until we find a non-zero digit. We do it in reverse + * because we expect that most digits will be nonzero. */ + for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) { + } - return (i + 1); + return (i + 1); } bitcount_t uECC_vli_numBits(const uECC_word_t *vli, - const wordcount_t max_words) + const wordcount_t max_words) { - uECC_word_t i; - uECC_word_t digit; + uECC_word_t i; + uECC_word_t digit; - wordcount_t num_digits = vli_numDigits(vli, max_words); - if (num_digits == 0) { - return 0; - } + wordcount_t num_digits = vli_numDigits(vli, max_words); + if (num_digits == 0) { + return 0; + } - digit = vli[num_digits - 1]; - for (i = 0; digit; ++i) { - digit >>= 1; - } + digit = vli[num_digits - 1]; + for (i = 0; digit; ++i) { + digit >>= 1; + } - return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i); + return (((bitcount_t)(num_digits - 1) << uECC_WORD_BITS_SHIFT) + i); } void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src, - wordcount_t num_words) + wordcount_t num_words) { - wordcount_t i; + wordcount_t i; - for (i = 0; i < num_words; ++i) { - dest[i] = src[i]; - } + for (i = 0; i < num_words; ++i) { + dest[i] = src[i]; + } } cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, - const uECC_word_t *right, - wordcount_t num_words) + const uECC_word_t *right, + wordcount_t num_words) { - wordcount_t i; + wordcount_t i; - for (i = num_words - 1; i >= 0; --i) { - if (left[i] > right[i]) { - return 1; - } else if (left[i] < right[i]) { - return -1; - } - } - return 0; + for (i = num_words - 1; i >= 0; --i) { + if (left[i] > right[i]) { + return 1; + } else if (left[i] < right[i]) { + return -1; + } + } + return 0; } uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right, - wordcount_t num_words) + wordcount_t num_words) { - uECC_word_t diff = 0; - wordcount_t i; + uECC_word_t diff = 0; + wordcount_t i; - for (i = num_words - 1; i >= 0; --i) { - diff |= (left[i] ^ right[i]); - } - return !(diff == 0); + for (i = num_words - 1; i >= 0; --i) { + diff |= (left[i] ^ right[i]); + } + return !(diff == 0); } uECC_word_t cond_set(uECC_word_t p_true, uECC_word_t p_false, unsigned int cond) { - return (p_true*(cond)) | (p_false*(!cond)); + return (p_true*(cond)) | (p_false*(!cond)); } /* Computes result = left - right, returning borrow, in constant time. * Can modify in place. */ uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, wordcount_t num_words) + const uECC_word_t *right, wordcount_t num_words) { - uECC_word_t borrow = 0; - wordcount_t i; - for (i = 0; i < num_words; ++i) { - uECC_word_t diff = left[i] - right[i] - borrow; - uECC_word_t val = (diff > left[i]); - borrow = cond_set(val, borrow, (diff != left[i])); + uECC_word_t borrow = 0; + wordcount_t i; + for (i = 0; i < num_words; ++i) { + uECC_word_t diff = left[i] - right[i] - borrow; + uECC_word_t val = (diff > left[i]); + borrow = cond_set(val, borrow, (diff != left[i])); - result[i] = diff; - } - return borrow; + result[i] = diff; + } + return borrow; } /* Computes result = left + right, returning carry, in constant time. * Can modify in place. */ static uECC_word_t uECC_vli_add(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, wordcount_t num_words) + const uECC_word_t *right, wordcount_t num_words) { - uECC_word_t carry = 0; - wordcount_t i; - for (i = 0; i < num_words; ++i) { - uECC_word_t sum = left[i] + right[i] + carry; - uECC_word_t val = (sum < left[i]); - carry = cond_set(val, carry, (sum != left[i])); - result[i] = sum; - } - return carry; + uECC_word_t carry = 0; + wordcount_t i; + for (i = 0; i < num_words; ++i) { + uECC_word_t sum = left[i] + right[i] + carry; + uECC_word_t val = (sum < left[i]); + carry = cond_set(val, carry, (sum != left[i])); + result[i] = sum; + } + return carry; } cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right, - wordcount_t num_words) + wordcount_t num_words) { - uECC_word_t tmp[NUM_ECC_WORDS]; - uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words); - uECC_word_t equal = uECC_vli_isZero(tmp, num_words); - return (!equal - 2 * neg); + uECC_word_t tmp[NUM_ECC_WORDS]; + uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words); + uECC_word_t equal = uECC_vli_isZero(tmp, num_words); + return (!equal - 2 * neg); } /* Computes vli = vli >> 1. */ static void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words) { - uECC_word_t *end = vli; - uECC_word_t carry = 0; + uECC_word_t *end = vli; + uECC_word_t carry = 0; - vli += num_words; - while (vli-- > end) { - uECC_word_t temp = *vli; - *vli = (temp >> 1) | carry; - carry = temp << (uECC_WORD_BITS - 1); - } + vli += num_words; + while (vli-- > end) { + uECC_word_t temp = *vli; + *vli = (temp >> 1) | carry; + carry = temp << (uECC_WORD_BITS - 1); + } } static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0, - uECC_word_t *r1, uECC_word_t *r2) + uECC_word_t *r1, uECC_word_t *r2) { - uECC_dword_t p = (uECC_dword_t)a * b; - uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0; - r01 += p; - *r2 += (r01 < p); - *r1 = r01 >> uECC_WORD_BITS; - *r0 = (uECC_word_t)r01; + uECC_dword_t p = (uECC_dword_t)a * b; + uECC_dword_t r01 = ((uECC_dword_t)(*r1) << uECC_WORD_BITS) | *r0; + r01 += p; + *r2 += (r01 < p); + *r1 = r01 >> uECC_WORD_BITS; + *r0 = (uECC_word_t)r01; } /* Computes result = left * right. Result must be 2 * num_words long. */ static void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, wordcount_t num_words) + const uECC_word_t *right, wordcount_t num_words) { - uECC_word_t r0 = 0; - uECC_word_t r1 = 0; - uECC_word_t r2 = 0; - wordcount_t i, k; + uECC_word_t r0 = 0; + uECC_word_t r1 = 0; + uECC_word_t r2 = 0; + wordcount_t i, k; - /* Compute each digit of result in sequence, maintaining the carries. */ - for (k = 0; k < num_words; ++k) { + /* Compute each digit of result in sequence, maintaining the carries. */ + for (k = 0; k < num_words; ++k) { - for (i = 0; i <= k; ++i) { - muladd(left[i], right[k - i], &r0, &r1, &r2); - } + for (i = 0; i <= k; ++i) { + muladd(left[i], right[k - i], &r0, &r1, &r2); + } - result[k] = r0; - r0 = r1; - r1 = r2; - r2 = 0; - } + result[k] = r0; + r0 = r1; + r1 = r2; + r2 = 0; + } - for (k = num_words; k < num_words * 2 - 1; ++k) { + for (k = num_words; k < num_words * 2 - 1; ++k) { - for (i = (k + 1) - num_words; i < num_words; ++i) { - muladd(left[i], right[k - i], &r0, &r1, &r2); - } - result[k] = r0; - r0 = r1; - r1 = r2; - r2 = 0; - } - result[num_words * 2 - 1] = r0; + for (i = (k + 1) - num_words; i < num_words; ++i) { + muladd(left[i], right[k - i], &r0, &r1, &r2); + } + result[k] = r0; + r0 = r1; + r1 = r2; + r2 = 0; + } + result[num_words * 2 - 1] = r0; } void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, const uECC_word_t *mod, - wordcount_t num_words) + const uECC_word_t *right, const uECC_word_t *mod, + wordcount_t num_words) { - uECC_word_t carry = uECC_vli_add(result, left, right, num_words); - if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) { - /* result > mod (result = mod + remainder), so subtract mod to get - * remainder. */ - uECC_vli_sub(result, result, mod, num_words); - } + uECC_word_t carry = uECC_vli_add(result, left, right, num_words); + if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) { + /* result > mod (result = mod + remainder), so subtract mod to get + * remainder. */ + uECC_vli_sub(result, result, mod, num_words); + } } void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, const uECC_word_t *mod, - wordcount_t num_words) + const uECC_word_t *right, const uECC_word_t *mod, + wordcount_t num_words) { - uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words); - if (l_borrow) { - /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x, - * we can get the correct result from result + mod (with overflow). */ - uECC_vli_add(result, result, mod, num_words); - } + uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words); + if (l_borrow) { + /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x, + * we can get the correct result from result + mod (with overflow). */ + uECC_vli_add(result, result, mod, num_words); + } } /* Computes result = product % mod, where product is 2N words long. */ /* Currently only designed to work for curve_p or curve_n. */ void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product, - const uECC_word_t *mod, wordcount_t num_words) + const uECC_word_t *mod, wordcount_t num_words) { - uECC_word_t mod_multiple[2 * NUM_ECC_WORDS]; - uECC_word_t tmp[2 * NUM_ECC_WORDS]; - uECC_word_t *v[2] = {tmp, product}; - uECC_word_t index; + uECC_word_t mod_multiple[2 * NUM_ECC_WORDS]; + uECC_word_t tmp[2 * NUM_ECC_WORDS]; + uECC_word_t *v[2] = {tmp, product}; + uECC_word_t index; - /* Shift mod so its highest set bit is at the maximum position. */ - bitcount_t shift = (num_words * 2 * uECC_WORD_BITS) - - uECC_vli_numBits(mod, num_words); - wordcount_t word_shift = shift / uECC_WORD_BITS; - wordcount_t bit_shift = shift % uECC_WORD_BITS; - uECC_word_t carry = 0; - uECC_vli_clear(mod_multiple, word_shift); - if (bit_shift > 0) { - for(index = 0; index < (uECC_word_t)num_words; ++index) { - mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry; - carry = mod[index] >> (uECC_WORD_BITS - bit_shift); - } - } else { - uECC_vli_set(mod_multiple + word_shift, mod, num_words); - } + /* Shift mod so its highest set bit is at the maximum position. */ + bitcount_t shift = (num_words * 2 * uECC_WORD_BITS) - + uECC_vli_numBits(mod, num_words); + wordcount_t word_shift = shift / uECC_WORD_BITS; + wordcount_t bit_shift = shift % uECC_WORD_BITS; + uECC_word_t carry = 0; + uECC_vli_clear(mod_multiple, word_shift); + if (bit_shift > 0) { + for(index = 0; index < (uECC_word_t)num_words; ++index) { + mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry; + carry = mod[index] >> (uECC_WORD_BITS - bit_shift); + } + } else { + uECC_vli_set(mod_multiple + word_shift, mod, num_words); + } - for (index = 1; shift >= 0; --shift) { - uECC_word_t borrow = 0; - wordcount_t i; - for (i = 0; i < num_words * 2; ++i) { - uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow; - if (diff != v[index][i]) { - borrow = (diff > v[index][i]); - } - v[1 - index][i] = diff; - } - /* Swap the index if there was no borrow */ - index = !(index ^ borrow); - uECC_vli_rshift1(mod_multiple, num_words); - mod_multiple[num_words - 1] |= mod_multiple[num_words] << - (uECC_WORD_BITS - 1); - uECC_vli_rshift1(mod_multiple + num_words, num_words); - } - uECC_vli_set(result, v[index], num_words); + for (index = 1; shift >= 0; --shift) { + uECC_word_t borrow = 0; + wordcount_t i; + for (i = 0; i < num_words * 2; ++i) { + uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow; + if (diff != v[index][i]) { + borrow = (diff > v[index][i]); + } + v[1 - index][i] = diff; + } + /* Swap the index if there was no borrow */ + index = !(index ^ borrow); + uECC_vli_rshift1(mod_multiple, num_words); + mod_multiple[num_words - 1] |= mod_multiple[num_words] << + (uECC_WORD_BITS - 1); + uECC_vli_rshift1(mod_multiple + num_words, num_words); + } + uECC_vli_set(result, v[index], num_words); } void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, const uECC_word_t *mod, - wordcount_t num_words) + const uECC_word_t *right, const uECC_word_t *mod, + wordcount_t num_words) { - uECC_word_t product[2 * NUM_ECC_WORDS]; - uECC_vli_mult(product, left, right, num_words); - uECC_vli_mmod(result, product, mod, num_words); + uECC_word_t product[2 * NUM_ECC_WORDS]; + uECC_vli_mult(product, left, right, num_words); + uECC_vli_mmod(result, product, mod, num_words); } void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left, - const uECC_word_t *right, uECC_Curve curve) + const uECC_word_t *right, uECC_Curve curve) { - uECC_word_t product[2 * NUM_ECC_WORDS]; - uECC_vli_mult(product, left, right, curve->num_words); + uECC_word_t product[2 * NUM_ECC_WORDS]; + uECC_vli_mult(product, left, right, curve->num_words); - curve->mmod_fast(result, product); + curve->mmod_fast(result, product); } static void uECC_vli_modSquare_fast(uECC_word_t *result, - const uECC_word_t *left, - uECC_Curve curve) + const uECC_word_t *left, + uECC_Curve curve) { - uECC_vli_modMult_fast(result, left, left, curve); + uECC_vli_modMult_fast(result, left, left, curve); } #define EVEN(vli) (!(vli[0] & 1)) static void vli_modInv_update(uECC_word_t *uv, - const uECC_word_t *mod, - wordcount_t num_words) + const uECC_word_t *mod, + wordcount_t num_words) { - uECC_word_t carry = 0; + uECC_word_t carry = 0; - if (!EVEN(uv)) { - carry = uECC_vli_add(uv, uv, mod, num_words); - } - uECC_vli_rshift1(uv, num_words); - if (carry) { - uv[num_words - 1] |= HIGH_BIT_SET; - } + if (!EVEN(uv)) { + carry = uECC_vli_add(uv, uv, mod, num_words); + } + uECC_vli_rshift1(uv, num_words); + if (carry) { + uv[num_words - 1] |= HIGH_BIT_SET; + } } void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input, - const uECC_word_t *mod, wordcount_t num_words) + const uECC_word_t *mod, wordcount_t num_words) { - uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS]; - uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS]; - cmpresult_t cmpResult; + uECC_word_t a[NUM_ECC_WORDS], b[NUM_ECC_WORDS]; + uECC_word_t u[NUM_ECC_WORDS], v[NUM_ECC_WORDS]; + cmpresult_t cmpResult; - if (uECC_vli_isZero(input, num_words)) { - uECC_vli_clear(result, num_words); - return; - } + if (uECC_vli_isZero(input, num_words)) { + uECC_vli_clear(result, num_words); + return; + } - uECC_vli_set(a, input, num_words); - uECC_vli_set(b, mod, num_words); - uECC_vli_clear(u, num_words); - u[0] = 1; - uECC_vli_clear(v, num_words); - while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) { - if (EVEN(a)) { - uECC_vli_rshift1(a, num_words); - vli_modInv_update(u, mod, num_words); - } else if (EVEN(b)) { - uECC_vli_rshift1(b, num_words); - vli_modInv_update(v, mod, num_words); - } else if (cmpResult > 0) { - uECC_vli_sub(a, a, b, num_words); - uECC_vli_rshift1(a, num_words); - if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) { - uECC_vli_add(u, u, mod, num_words); - } - uECC_vli_sub(u, u, v, num_words); - vli_modInv_update(u, mod, num_words); - } else { - uECC_vli_sub(b, b, a, num_words); - uECC_vli_rshift1(b, num_words); - if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) { - uECC_vli_add(v, v, mod, num_words); - } - uECC_vli_sub(v, v, u, num_words); - vli_modInv_update(v, mod, num_words); - } - } - uECC_vli_set(result, u, num_words); + uECC_vli_set(a, input, num_words); + uECC_vli_set(b, mod, num_words); + uECC_vli_clear(u, num_words); + u[0] = 1; + uECC_vli_clear(v, num_words); + while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) { + if (EVEN(a)) { + uECC_vli_rshift1(a, num_words); + vli_modInv_update(u, mod, num_words); + } else if (EVEN(b)) { + uECC_vli_rshift1(b, num_words); + vli_modInv_update(v, mod, num_words); + } else if (cmpResult > 0) { + uECC_vli_sub(a, a, b, num_words); + uECC_vli_rshift1(a, num_words); + if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) { + uECC_vli_add(u, u, mod, num_words); + } + uECC_vli_sub(u, u, v, num_words); + vli_modInv_update(u, mod, num_words); + } else { + uECC_vli_sub(b, b, a, num_words); + uECC_vli_rshift1(b, num_words); + if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) { + uECC_vli_add(v, v, mod, num_words); + } + uECC_vli_sub(v, v, u, num_words); + vli_modInv_update(v, mod, num_words); + } + } + uECC_vli_set(result, u, num_words); } /* ------ Point operations ------ */ void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1, - uECC_word_t * Z1, uECC_Curve curve) + uECC_word_t * Z1, uECC_Curve curve) { - /* t1 = X, t2 = Y, t3 = Z */ - uECC_word_t t4[NUM_ECC_WORDS]; - uECC_word_t t5[NUM_ECC_WORDS]; - wordcount_t num_words = curve->num_words; + /* t1 = X, t2 = Y, t3 = Z */ + uECC_word_t t4[NUM_ECC_WORDS]; + uECC_word_t t5[NUM_ECC_WORDS]; + wordcount_t num_words = curve->num_words; - if (uECC_vli_isZero(Z1, num_words)) { - return; - } + if (uECC_vli_isZero(Z1, num_words)) { + return; + } - uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */ - uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */ - uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */ - uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */ - uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */ + uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */ + uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */ + uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */ + uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */ + uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */ - uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */ - uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */ - uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */ - uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */ + uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */ + uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */ + uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */ + uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */ - uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */ - uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */ - if (uECC_vli_testBit(X1, 0)) { - uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words); - uECC_vli_rshift1(X1, num_words); - X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1); - } else { - uECC_vli_rshift1(X1, num_words); - } + uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */ + uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */ + if (uECC_vli_testBit(X1, 0)) { + uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words); + uECC_vli_rshift1(X1, num_words); + X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1); + } else { + uECC_vli_rshift1(X1, num_words); + } - /* t1 = 3/2*(x1^2 - z1^4) = B */ - uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */ - uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */ - uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */ - uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */ - uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */ - /* t4 = B * (A - x3) - y1^4 = y3: */ - uECC_vli_modSub(t4, X1, t4, curve->p, num_words); + /* t1 = 3/2*(x1^2 - z1^4) = B */ + uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */ + uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */ + uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */ + uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */ + uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */ + /* t4 = B * (A - x3) - y1^4 = y3: */ + uECC_vli_modSub(t4, X1, t4, curve->p, num_words); - uECC_vli_set(X1, Z1, num_words); - uECC_vli_set(Z1, Y1, num_words); - uECC_vli_set(Y1, t4, num_words); + uECC_vli_set(X1, Z1, num_words); + uECC_vli_set(Z1, Y1, num_words); + uECC_vli_set(Y1, t4, num_words); } void x_side_default(uECC_word_t *result, - const uECC_word_t *x, - uECC_Curve curve) + const uECC_word_t *x, + uECC_Curve curve) { - uECC_word_t _3[NUM_ECC_WORDS] = {3}; /* -a = 3 */ - wordcount_t num_words = curve->num_words; + uECC_word_t _3[NUM_ECC_WORDS] = {3}; /* -a = 3 */ + wordcount_t num_words = curve->num_words; - uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */ - uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */ - uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */ - /* r = x^3 - 3x + b: */ - uECC_vli_modAdd(result, result, curve->b, curve->p, num_words); + uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */ + uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */ + uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */ + /* r = x^3 - 3x + b: */ + uECC_vli_modAdd(result, result, curve->b, curve->p, num_words); } uECC_Curve uECC_secp256r1(void) { - return &curve_secp256r1; + return &curve_secp256r1; } void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int*product) { - unsigned int tmp[NUM_ECC_WORDS]; - int carry; + unsigned int tmp[NUM_ECC_WORDS]; + int carry; - /* t */ - uECC_vli_set(result, product, NUM_ECC_WORDS); + /* t */ + uECC_vli_set(result, product, NUM_ECC_WORDS); - /* s1 */ - tmp[0] = tmp[1] = tmp[2] = 0; - tmp[3] = product[11]; - tmp[4] = product[12]; - tmp[5] = product[13]; - tmp[6] = product[14]; - tmp[7] = product[15]; - carry = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS); - carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); + /* s1 */ + tmp[0] = tmp[1] = tmp[2] = 0; + tmp[3] = product[11]; + tmp[4] = product[12]; + tmp[5] = product[13]; + tmp[6] = product[14]; + tmp[7] = product[15]; + carry = uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS); + carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); - /* s2 */ - tmp[3] = product[12]; - tmp[4] = product[13]; - tmp[5] = product[14]; - tmp[6] = product[15]; - tmp[7] = 0; - carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS); - carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); + /* s2 */ + tmp[3] = product[12]; + tmp[4] = product[13]; + tmp[5] = product[14]; + tmp[6] = product[15]; + tmp[7] = 0; + carry += uECC_vli_add(tmp, tmp, tmp, NUM_ECC_WORDS); + carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); - /* s3 */ - tmp[0] = product[8]; - tmp[1] = product[9]; - tmp[2] = product[10]; - tmp[3] = tmp[4] = tmp[5] = 0; - tmp[6] = product[14]; - tmp[7] = product[15]; - carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); + /* s3 */ + tmp[0] = product[8]; + tmp[1] = product[9]; + tmp[2] = product[10]; + tmp[3] = tmp[4] = tmp[5] = 0; + tmp[6] = product[14]; + tmp[7] = product[15]; + carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); - /* s4 */ - tmp[0] = product[9]; - tmp[1] = product[10]; - tmp[2] = product[11]; - tmp[3] = product[13]; - tmp[4] = product[14]; - tmp[5] = product[15]; - tmp[6] = product[13]; - tmp[7] = product[8]; - carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); + /* s4 */ + tmp[0] = product[9]; + tmp[1] = product[10]; + tmp[2] = product[11]; + tmp[3] = product[13]; + tmp[4] = product[14]; + tmp[5] = product[15]; + tmp[6] = product[13]; + tmp[7] = product[8]; + carry += uECC_vli_add(result, result, tmp, NUM_ECC_WORDS); - /* d1 */ - tmp[0] = product[11]; - tmp[1] = product[12]; - tmp[2] = product[13]; - tmp[3] = tmp[4] = tmp[5] = 0; - tmp[6] = product[8]; - tmp[7] = product[10]; - carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); + /* d1 */ + tmp[0] = product[11]; + tmp[1] = product[12]; + tmp[2] = product[13]; + tmp[3] = tmp[4] = tmp[5] = 0; + tmp[6] = product[8]; + tmp[7] = product[10]; + carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); - /* d2 */ - tmp[0] = product[12]; - tmp[1] = product[13]; - tmp[2] = product[14]; - tmp[3] = product[15]; - tmp[4] = tmp[5] = 0; - tmp[6] = product[9]; - tmp[7] = product[11]; - carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); + /* d2 */ + tmp[0] = product[12]; + tmp[1] = product[13]; + tmp[2] = product[14]; + tmp[3] = product[15]; + tmp[4] = tmp[5] = 0; + tmp[6] = product[9]; + tmp[7] = product[11]; + carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); - /* d3 */ - tmp[0] = product[13]; - tmp[1] = product[14]; - tmp[2] = product[15]; - tmp[3] = product[8]; - tmp[4] = product[9]; - tmp[5] = product[10]; - tmp[6] = 0; - tmp[7] = product[12]; - carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); + /* d3 */ + tmp[0] = product[13]; + tmp[1] = product[14]; + tmp[2] = product[15]; + tmp[3] = product[8]; + tmp[4] = product[9]; + tmp[5] = product[10]; + tmp[6] = 0; + tmp[7] = product[12]; + carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); - /* d4 */ - tmp[0] = product[14]; - tmp[1] = product[15]; - tmp[2] = 0; - tmp[3] = product[9]; - tmp[4] = product[10]; - tmp[5] = product[11]; - tmp[6] = 0; - tmp[7] = product[13]; - carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); + /* d4 */ + tmp[0] = product[14]; + tmp[1] = product[15]; + tmp[2] = 0; + tmp[3] = product[9]; + tmp[4] = product[10]; + tmp[5] = product[11]; + tmp[6] = 0; + tmp[7] = product[13]; + carry -= uECC_vli_sub(result, result, tmp, NUM_ECC_WORDS); - if (carry < 0) { - do { - carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS); - } - while (carry < 0); - } else { - while (carry || - uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) { - carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS); - } - } + if (carry < 0) { + do { + carry += uECC_vli_add(result, result, curve_secp256r1.p, NUM_ECC_WORDS); + } + while (carry < 0); + } else { + while (carry || + uECC_vli_cmp_unsafe(curve_secp256r1.p, result, NUM_ECC_WORDS) != 1) { + carry -= uECC_vli_sub(result, result, curve_secp256r1.p, NUM_ECC_WORDS); + } + } } uECC_word_t EccPoint_isZero(const uECC_word_t *point, uECC_Curve curve) { - return uECC_vli_isZero(point, curve->num_words * 2); + return uECC_vli_isZero(point, curve->num_words * 2); } void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z, - uECC_Curve curve) + uECC_Curve curve) { - uECC_word_t t1[NUM_ECC_WORDS]; + uECC_word_t t1[NUM_ECC_WORDS]; - uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */ - uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */ - uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */ - uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */ + uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */ + uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */ + uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */ + uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */ } /* P = (x1, y1) => 2P, (x2, y2) => P' */ static void XYcZ_initial_double(uECC_word_t * X1, uECC_word_t * Y1, - uECC_word_t * X2, uECC_word_t * Y2, - const uECC_word_t * const initial_Z, - uECC_Curve curve) + uECC_word_t * X2, uECC_word_t * Y2, + const uECC_word_t * const initial_Z, + uECC_Curve curve) { - uECC_word_t z[NUM_ECC_WORDS]; - wordcount_t num_words = curve->num_words; - if (initial_Z) { - uECC_vli_set(z, initial_Z, num_words); - } else { - uECC_vli_clear(z, num_words); - z[0] = 1; - } + uECC_word_t z[NUM_ECC_WORDS]; + wordcount_t num_words = curve->num_words; + if (initial_Z) { + uECC_vli_set(z, initial_Z, num_words); + } else { + uECC_vli_clear(z, num_words); + z[0] = 1; + } - uECC_vli_set(X2, X1, num_words); - uECC_vli_set(Y2, Y1, num_words); + uECC_vli_set(X2, X1, num_words); + uECC_vli_set(Y2, Y1, num_words); - apply_z(X1, Y1, z, curve); - curve->double_jacobian(X1, Y1, z, curve); - apply_z(X2, Y2, z, curve); + apply_z(X1, Y1, z, curve); + curve->double_jacobian(X1, Y1, z, curve); + apply_z(X2, Y2, z, curve); } void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, - uECC_word_t * X2, uECC_word_t * Y2, - uECC_Curve curve) + uECC_word_t * X2, uECC_word_t * Y2, + uECC_Curve curve) { - /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ - uECC_word_t t5[NUM_ECC_WORDS]; - wordcount_t num_words = curve->num_words; + /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ + uECC_word_t t5[NUM_ECC_WORDS]; + wordcount_t num_words = curve->num_words; - uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ - uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ - uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ - uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ - uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ - uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */ + uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ + uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ + uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ + uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ + uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ + uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */ - uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */ - uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */ - uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */ - uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */ - uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */ - uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */ - uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */ + uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */ + uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */ + uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */ + uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */ + uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */ + uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */ + uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */ - uECC_vli_set(X2, t5, num_words); + uECC_vli_set(X2, t5, num_words); } /* Input P = (x1, y1, Z), Q = (x2, y2, Z) @@ -689,253 +689,253 @@ void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, or P => P - Q, Q => P + Q */ static void XYcZ_addC(uECC_word_t * X1, uECC_word_t * Y1, - uECC_word_t * X2, uECC_word_t * Y2, - uECC_Curve curve) + uECC_word_t * X2, uECC_word_t * Y2, + uECC_Curve curve) { - /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ - uECC_word_t t5[NUM_ECC_WORDS]; - uECC_word_t t6[NUM_ECC_WORDS]; - uECC_word_t t7[NUM_ECC_WORDS]; - wordcount_t num_words = curve->num_words; + /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ + uECC_word_t t5[NUM_ECC_WORDS]; + uECC_word_t t6[NUM_ECC_WORDS]; + uECC_word_t t7[NUM_ECC_WORDS]; + wordcount_t num_words = curve->num_words; - uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ - uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ - uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ - uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ - uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */ - uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ + uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ + uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ + uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ + uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ + uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */ + uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ - uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */ - uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */ - uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */ - uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */ - uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */ + uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */ + uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */ + uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */ + uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */ + uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */ - uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */ - uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */ - /* t4 = (y2 - y1)*(B - x3) - E = y3: */ - uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); + uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */ + uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */ + /* t4 = (y2 - y1)*(B - x3) - E = y3: */ + uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); - uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */ - uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */ - uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */ - uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */ - /* t2 = (y2+y1)*(x3' - B) - E = y3': */ - uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words); + uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */ + uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */ + uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */ + uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */ + /* t2 = (y2+y1)*(x3' - B) - E = y3': */ + uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words); - uECC_vli_set(X1, t7, num_words); + uECC_vli_set(X1, t7, num_words); } void EccPoint_mult(uECC_word_t * result, const uECC_word_t * point, - const uECC_word_t * scalar, - const uECC_word_t * initial_Z, - bitcount_t num_bits, uECC_Curve curve) + const uECC_word_t * scalar, + const uECC_word_t * initial_Z, + bitcount_t num_bits, uECC_Curve curve) { - /* R0 and R1 */ - uECC_word_t Rx[2][NUM_ECC_WORDS]; - uECC_word_t Ry[2][NUM_ECC_WORDS]; - uECC_word_t z[NUM_ECC_WORDS]; - bitcount_t i; - uECC_word_t nb; - wordcount_t num_words = curve->num_words; + /* R0 and R1 */ + uECC_word_t Rx[2][NUM_ECC_WORDS]; + uECC_word_t Ry[2][NUM_ECC_WORDS]; + uECC_word_t z[NUM_ECC_WORDS]; + bitcount_t i; + uECC_word_t nb; + wordcount_t num_words = curve->num_words; - uECC_vli_set(Rx[1], point, num_words); - uECC_vli_set(Ry[1], point + num_words, num_words); + uECC_vli_set(Rx[1], point, num_words); + uECC_vli_set(Ry[1], point + num_words, num_words); - XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve); + XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve); - for (i = num_bits - 2; i > 0; --i) { - nb = !uECC_vli_testBit(scalar, i); - XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); - XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); - } + for (i = num_bits - 2; i > 0; --i) { + nb = !uECC_vli_testBit(scalar, i); + XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); + XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); + } - nb = !uECC_vli_testBit(scalar, 0); - XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); + nb = !uECC_vli_testBit(scalar, 0); + XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); - /* Find final 1/Z value. */ - uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */ - uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */ - uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */ - uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0))*/ - /* yP / (xP * Yb * (X1 - X0)) */ - uECC_vli_modMult_fast(z, z, point + num_words, curve); - /* Xb * yP / (xP * Yb * (X1 - X0)) */ - uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve); - /* End 1/Z calculation */ + /* Find final 1/Z value. */ + uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */ + uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */ + uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */ + uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0))*/ + /* yP / (xP * Yb * (X1 - X0)) */ + uECC_vli_modMult_fast(z, z, point + num_words, curve); + /* Xb * yP / (xP * Yb * (X1 - X0)) */ + uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve); + /* End 1/Z calculation */ - XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); - apply_z(Rx[0], Ry[0], z, curve); + XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); + apply_z(Rx[0], Ry[0], z, curve); - uECC_vli_set(result, Rx[0], num_words); - uECC_vli_set(result + num_words, Ry[0], num_words); + uECC_vli_set(result, Rx[0], num_words); + uECC_vli_set(result + num_words, Ry[0], num_words); } uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t *k0, - uECC_word_t *k1, uECC_Curve curve) + uECC_word_t *k1, uECC_Curve curve) { - wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); + wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); - bitcount_t num_n_bits = curve->num_n_bits; + bitcount_t num_n_bits = curve->num_n_bits; - uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) || - (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) && - uECC_vli_testBit(k0, num_n_bits)); + uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) || + (num_n_bits < ((bitcount_t)num_n_words * uECC_WORD_SIZE * 8) && + uECC_vli_testBit(k0, num_n_bits)); - uECC_vli_add(k1, k0, curve->n, num_n_words); + uECC_vli_add(k1, k0, curve->n, num_n_words); - return carry; + return carry; } uECC_word_t EccPoint_compute_public_key(uECC_word_t *result, - uECC_word_t *private_key, - uECC_Curve curve) + uECC_word_t *private_key, + uECC_Curve curve) { - uECC_word_t tmp1[NUM_ECC_WORDS]; - uECC_word_t tmp2[NUM_ECC_WORDS]; - uECC_word_t *p2[2] = {tmp1, tmp2}; - uECC_word_t carry; + uECC_word_t tmp1[NUM_ECC_WORDS]; + uECC_word_t tmp2[NUM_ECC_WORDS]; + uECC_word_t *p2[2] = {tmp1, tmp2}; + uECC_word_t carry; - /* Regularize the bitcount for the private key so that attackers cannot - * use a side channel attack to learn the number of leading zeros. */ - carry = regularize_k(private_key, tmp1, tmp2, curve); + /* Regularize the bitcount for the private key so that attackers cannot + * use a side channel attack to learn the number of leading zeros. */ + carry = regularize_k(private_key, tmp1, tmp2, curve); - EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve); + EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve); - if (EccPoint_isZero(result, curve)) { - return 0; - } - return 1; + if (EccPoint_isZero(result, curve)) { + return 0; + } + return 1; } /* Converts an integer in uECC native format to big-endian bytes. */ void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes, - const unsigned int *native) + const unsigned int *native) { - wordcount_t i; - for (i = 0; i < num_bytes; ++i) { - unsigned b = num_bytes - 1 - i; - bytes[i] = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE)); - } + wordcount_t i; + for (i = 0; i < num_bytes; ++i) { + unsigned b = num_bytes - 1 - i; + bytes[i] = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE)); + } } /* Converts big-endian bytes to an integer in uECC native format. */ void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes, - int num_bytes) + int num_bytes) { - wordcount_t i; - uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE); - for (i = 0; i < num_bytes; ++i) { - unsigned b = num_bytes - 1 - i; - native[b / uECC_WORD_SIZE] |= - (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE)); - } + wordcount_t i; + uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE); + for (i = 0; i < num_bytes; ++i) { + unsigned b = num_bytes - 1 - i; + native[b / uECC_WORD_SIZE] |= + (uECC_word_t)bytes[i] << (8 * (b % uECC_WORD_SIZE)); + } } int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top, - wordcount_t num_words) + wordcount_t num_words) { - uECC_word_t mask = (uECC_word_t)-1; - uECC_word_t tries; - bitcount_t num_bits = uECC_vli_numBits(top, num_words); + uECC_word_t mask = (uECC_word_t)-1; + uECC_word_t tries; + bitcount_t num_bits = uECC_vli_numBits(top, num_words); - if (!g_rng_function) { - return 0; - } + if (!g_rng_function) { + return 0; + } - for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { - if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) { - return 0; - } - random[num_words - 1] &= - mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits)); - if (!uECC_vli_isZero(random, num_words) && - uECC_vli_cmp(top, random, num_words) == 1) { - return 1; - } - } - return 0; + for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { + if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) { + return 0; + } + random[num_words - 1] &= + mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits)); + if (!uECC_vli_isZero(random, num_words) && + uECC_vli_cmp(top, random, num_words) == 1) { + return 1; + } + } + return 0; } int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) { - uECC_word_t tmp1[NUM_ECC_WORDS]; - uECC_word_t tmp2[NUM_ECC_WORDS]; - wordcount_t num_words = curve->num_words; + uECC_word_t tmp1[NUM_ECC_WORDS]; + uECC_word_t tmp2[NUM_ECC_WORDS]; + wordcount_t num_words = curve->num_words; - /* The point at infinity is invalid. */ - if (EccPoint_isZero(point, curve)) { - return -1; - } + /* The point at infinity is invalid. */ + if (EccPoint_isZero(point, curve)) { + return -1; + } - /* x and y must be smaller than p. */ - if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 || - uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) { - return -2; - } + /* x and y must be smaller than p. */ + if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 || + uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) { + return -2; + } - uECC_vli_modSquare_fast(tmp1, point + num_words, curve); - curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */ + uECC_vli_modSquare_fast(tmp1, point + num_words, curve); + curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */ - /* Make sure that y^2 == x^3 + ax + b */ - if (uECC_vli_equal(tmp1, tmp2, num_words) != 0) - return -3; + /* Make sure that y^2 == x^3 + ax + b */ + if (uECC_vli_equal(tmp1, tmp2, num_words) != 0) + return -3; - return 0; + return 0; } int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve) { - uECC_word_t _public[NUM_ECC_WORDS * 2]; + uECC_word_t _public[NUM_ECC_WORDS * 2]; - uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); - uECC_vli_bytesToNative( - _public + curve->num_words, - public_key + curve->num_bytes, - curve->num_bytes); + uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); + uECC_vli_bytesToNative( + _public + curve->num_words, + public_key + curve->num_bytes, + curve->num_bytes); - if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) { - return -4; - } + if (uECC_vli_cmp_unsafe(_public, curve->G, NUM_ECC_WORDS * 2) == 0) { + return -4; + } - return uECC_valid_point(_public, curve); + return uECC_valid_point(_public, curve); } int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key, - uECC_Curve curve) + uECC_Curve curve) { - uECC_word_t _private[NUM_ECC_WORDS]; - uECC_word_t _public[NUM_ECC_WORDS * 2]; + uECC_word_t _private[NUM_ECC_WORDS]; + uECC_word_t _public[NUM_ECC_WORDS * 2]; - uECC_vli_bytesToNative( - _private, - private_key, - BITS_TO_BYTES(curve->num_n_bits)); + uECC_vli_bytesToNative( + _private, + private_key, + BITS_TO_BYTES(curve->num_n_bits)); - /* Make sure the private key is in the range [1, n-1]. */ - if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) { - return 0; - } + /* Make sure the private key is in the range [1, n-1]. */ + if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) { + return 0; + } - if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) { - return 0; - } + if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) { + return 0; + } - /* Compute public key. */ - if (!EccPoint_compute_public_key(_public, _private, curve)) { - return 0; - } + /* Compute public key. */ + if (!EccPoint_compute_public_key(_public, _private, curve)) { + return 0; + } - uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); - uECC_vli_nativeToBytes( - public_key + - curve->num_bytes, curve->num_bytes, _public + curve->num_words); - return 1; + uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); + uECC_vli_nativeToBytes( + public_key + + curve->num_bytes, curve->num_bytes, _public + curve->num_words); + return 1; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dh.c b/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dh.c index c42e77df..288c0999 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dh.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dh.c @@ -1,6 +1,6 @@ /* ec_dh.c - TinyCrypt implementation of EC-DH */ -/* +/* * Copyright (c) 2014, Kenneth MacKay * All rights reserved. * @@ -69,132 +69,132 @@ static uECC_RNG_Function g_rng_function = 0; #endif int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key, - unsigned int *d, uECC_Curve curve) + unsigned int *d, uECC_Curve curve) { - uECC_word_t _private[NUM_ECC_WORDS]; - uECC_word_t _public[NUM_ECC_WORDS * 2]; + uECC_word_t _private[NUM_ECC_WORDS]; + uECC_word_t _public[NUM_ECC_WORDS * 2]; - /* This function is designed for test purposes-only (such as validating NIST - * test vectors) as it uses a provided value for d instead of generating - * it uniformly at random. */ - memcpy (_private, d, NUM_ECC_BYTES); + /* This function is designed for test purposes-only (such as validating NIST + * test vectors) as it uses a provided value for d instead of generating + * it uniformly at random. */ + memcpy (_private, d, NUM_ECC_BYTES); - /* Computing public-key from private: */ - if (EccPoint_compute_public_key(_public, _private, curve)) { + /* Computing public-key from private: */ + if (EccPoint_compute_public_key(_public, _private, curve)) { - /* Converting buffers to correct bit order: */ - uECC_vli_nativeToBytes(private_key, - BITS_TO_BYTES(curve->num_n_bits), - _private); - uECC_vli_nativeToBytes(public_key, - curve->num_bytes, - _public); - uECC_vli_nativeToBytes(public_key + curve->num_bytes, - curve->num_bytes, - _public + curve->num_words); + /* Converting buffers to correct bit order: */ + uECC_vli_nativeToBytes(private_key, + BITS_TO_BYTES(curve->num_n_bits), + _private); + uECC_vli_nativeToBytes(public_key, + curve->num_bytes, + _public); + uECC_vli_nativeToBytes(public_key + curve->num_bytes, + curve->num_bytes, + _public + curve->num_words); - /* erasing temporary buffer used to store secret: */ - _set_secure(_private, 0, NUM_ECC_BYTES); + /* erasing temporary buffer used to store secret: */ + _set_secure(_private, 0, NUM_ECC_BYTES); - return 1; - } - return 0; + return 1; + } + return 0; } int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve) { - uECC_word_t _random[NUM_ECC_WORDS * 2]; - uECC_word_t _private[NUM_ECC_WORDS]; - uECC_word_t _public[NUM_ECC_WORDS * 2]; - uECC_word_t tries; + uECC_word_t _random[NUM_ECC_WORDS * 2]; + uECC_word_t _private[NUM_ECC_WORDS]; + uECC_word_t _public[NUM_ECC_WORDS * 2]; + uECC_word_t tries; - for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { - /* Generating _private uniformly at random: */ - uECC_RNG_Function rng_function = uECC_get_rng(); - if (!rng_function || - !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS*uECC_WORD_SIZE)) { - return 0; - } + for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { + /* Generating _private uniformly at random: */ + uECC_RNG_Function rng_function = uECC_get_rng(); + if (!rng_function || + !rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS*uECC_WORD_SIZE)) { + return 0; + } - /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */ - uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits)); + /* computing modular reduction of _random (see FIPS 186.4 B.4.1): */ + uECC_vli_mmod(_private, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits)); - /* Computing public-key from private: */ - if (EccPoint_compute_public_key(_public, _private, curve)) { + /* Computing public-key from private: */ + if (EccPoint_compute_public_key(_public, _private, curve)) { - /* Converting buffers to correct bit order: */ - uECC_vli_nativeToBytes(private_key, - BITS_TO_BYTES(curve->num_n_bits), - _private); - uECC_vli_nativeToBytes(public_key, - curve->num_bytes, - _public); - uECC_vli_nativeToBytes(public_key + curve->num_bytes, - curve->num_bytes, - _public + curve->num_words); + /* Converting buffers to correct bit order: */ + uECC_vli_nativeToBytes(private_key, + BITS_TO_BYTES(curve->num_n_bits), + _private); + uECC_vli_nativeToBytes(public_key, + curve->num_bytes, + _public); + uECC_vli_nativeToBytes(public_key + curve->num_bytes, + curve->num_bytes, + _public + curve->num_words); - /* erasing temporary buffer that stored secret: */ - _set_secure(_private, 0, NUM_ECC_BYTES); + /* erasing temporary buffer that stored secret: */ + _set_secure(_private, 0, NUM_ECC_BYTES); - return 1; - } - } - return 0; + return 1; + } + } + return 0; } int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key, - uint8_t *secret, uECC_Curve curve) + uint8_t *secret, uECC_Curve curve) { - uECC_word_t _public[NUM_ECC_WORDS * 2]; - uECC_word_t _private[NUM_ECC_WORDS]; + uECC_word_t _public[NUM_ECC_WORDS * 2]; + uECC_word_t _private[NUM_ECC_WORDS]; - uECC_word_t tmp[NUM_ECC_WORDS]; - uECC_word_t *p2[2] = {_private, tmp}; - uECC_word_t *initial_Z = 0; - uECC_word_t carry; - wordcount_t num_words = curve->num_words; - wordcount_t num_bytes = curve->num_bytes; - int r; + uECC_word_t tmp[NUM_ECC_WORDS]; + uECC_word_t *p2[2] = {_private, tmp}; + uECC_word_t *initial_Z = 0; + uECC_word_t carry; + wordcount_t num_words = curve->num_words; + wordcount_t num_bytes = curve->num_bytes; + int r; - /* Converting buffers to correct bit order: */ - uECC_vli_bytesToNative(_private, - private_key, - BITS_TO_BYTES(curve->num_n_bits)); - uECC_vli_bytesToNative(_public, - public_key, - num_bytes); - uECC_vli_bytesToNative(_public + num_words, - public_key + num_bytes, - num_bytes); + /* Converting buffers to correct bit order: */ + uECC_vli_bytesToNative(_private, + private_key, + BITS_TO_BYTES(curve->num_n_bits)); + uECC_vli_bytesToNative(_public, + public_key, + num_bytes); + uECC_vli_bytesToNative(_public + num_words, + public_key + num_bytes, + num_bytes); - /* Regularize the bitcount for the private key so that attackers cannot use a - * side channel attack to learn the number of leading zeros. */ - carry = regularize_k(_private, _private, tmp, curve); + /* Regularize the bitcount for the private key so that attackers cannot use a + * side channel attack to learn the number of leading zeros. */ + carry = regularize_k(_private, _private, tmp, curve); - /* If an RNG function was specified, try to get a random initial Z value to - * improve protection against side-channel attacks. */ - if (g_rng_function) { - if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) { - r = 0; - goto clear_and_out; - } - initial_Z = p2[carry]; - } + /* If an RNG function was specified, try to get a random initial Z value to + * improve protection against side-channel attacks. */ + if (g_rng_function) { + if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) { + r = 0; + goto clear_and_out; + } + initial_Z = p2[carry]; + } - EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, - curve); + EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, + curve); - uECC_vli_nativeToBytes(secret, num_bytes, _public); - r = !EccPoint_isZero(_public, curve); + uECC_vli_nativeToBytes(secret, num_bytes, _public); + r = !EccPoint_isZero(_public, curve); clear_and_out: - /* erasing temporary buffer used to store secret: */ - _set_secure(p2, 0, sizeof(p2)); - _set_secure(tmp, 0, sizeof(tmp)); - _set_secure(_private, 0, sizeof(_private)); + /* erasing temporary buffer used to store secret: */ + _set_secure(p2, 0, sizeof(p2)); + _set_secure(tmp, 0, sizeof(tmp)); + _set_secure(_private, 0, sizeof(_private)); - return r; + return r; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dsa.c b/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dsa.c index 421c7149..b9569e8f 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dsa.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/ecc_dsa.c @@ -64,232 +64,232 @@ static uECC_RNG_Function g_rng_function = 0; #endif static void bits2int(uECC_word_t *native, const uint8_t *bits, - unsigned bits_size, uECC_Curve curve) + unsigned bits_size, uECC_Curve curve) { - unsigned num_n_bytes = BITS_TO_BYTES(curve->num_n_bits); - unsigned num_n_words = BITS_TO_WORDS(curve->num_n_bits); - int shift; - uECC_word_t carry; - uECC_word_t *ptr; + unsigned num_n_bytes = BITS_TO_BYTES(curve->num_n_bits); + unsigned num_n_words = BITS_TO_WORDS(curve->num_n_bits); + int shift; + uECC_word_t carry; + uECC_word_t *ptr; - if (bits_size > num_n_bytes) { - bits_size = num_n_bytes; - } + if (bits_size > num_n_bytes) { + bits_size = num_n_bytes; + } - uECC_vli_clear(native, num_n_words); - uECC_vli_bytesToNative(native, bits, bits_size); - if (bits_size * 8 <= (unsigned)curve->num_n_bits) { - return; - } - shift = bits_size * 8 - curve->num_n_bits; - carry = 0; - ptr = native + num_n_words; - while (ptr-- > native) { - uECC_word_t temp = *ptr; - *ptr = (temp >> shift) | carry; - carry = temp << (uECC_WORD_BITS - shift); - } + uECC_vli_clear(native, num_n_words); + uECC_vli_bytesToNative(native, bits, bits_size); + if (bits_size * 8 <= (unsigned)curve->num_n_bits) { + return; + } + shift = bits_size * 8 - curve->num_n_bits; + carry = 0; + ptr = native + num_n_words; + while (ptr-- > native) { + uECC_word_t temp = *ptr; + *ptr = (temp >> shift) | carry; + carry = temp << (uECC_WORD_BITS - shift); + } - /* Reduce mod curve_n */ - if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) { - uECC_vli_sub(native, native, curve->n, num_n_words); - } + /* Reduce mod curve_n */ + if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) { + uECC_vli_sub(native, native, curve->n, num_n_words); + } } int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash, - unsigned hash_size, uECC_word_t *k, uint8_t *signature, - uECC_Curve curve) + unsigned hash_size, uECC_word_t *k, uint8_t *signature, + uECC_Curve curve) { - uECC_word_t tmp[NUM_ECC_WORDS]; - uECC_word_t s[NUM_ECC_WORDS]; - uECC_word_t *k2[2] = {tmp, s}; - uECC_word_t p[NUM_ECC_WORDS * 2]; - uECC_word_t carry; - wordcount_t num_words = curve->num_words; - wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); - bitcount_t num_n_bits = curve->num_n_bits; + uECC_word_t tmp[NUM_ECC_WORDS]; + uECC_word_t s[NUM_ECC_WORDS]; + uECC_word_t *k2[2] = {tmp, s}; + uECC_word_t p[NUM_ECC_WORDS * 2]; + uECC_word_t carry; + wordcount_t num_words = curve->num_words; + wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); + bitcount_t num_n_bits = curve->num_n_bits; - /* Make sure 0 < k < curve_n */ - if (uECC_vli_isZero(k, num_words) || - uECC_vli_cmp(curve->n, k, num_n_words) != 1) { - return 0; - } + /* Make sure 0 < k < curve_n */ + if (uECC_vli_isZero(k, num_words) || + uECC_vli_cmp(curve->n, k, num_n_words) != 1) { + return 0; + } - carry = regularize_k(k, tmp, s, curve); - EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve); - if (uECC_vli_isZero(p, num_words)) { - return 0; - } + carry = regularize_k(k, tmp, s, curve); + EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve); + if (uECC_vli_isZero(p, num_words)) { + return 0; + } - /* If an RNG function was specified, get a random number - to prevent side channel analysis of k. */ - if (!g_rng_function) { - uECC_vli_clear(tmp, num_n_words); - tmp[0] = 1; - } - else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) { - return 0; - } + /* If an RNG function was specified, get a random number + to prevent side channel analysis of k. */ + if (!g_rng_function) { + uECC_vli_clear(tmp, num_n_words); + tmp[0] = 1; + } + else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) { + return 0; + } - /* Prevent side channel analysis of uECC_vli_modInv() to determine - bits of k / the private key by premultiplying by a random number */ - uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */ - uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */ - uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */ + /* Prevent side channel analysis of uECC_vli_modInv() to determine + bits of k / the private key by premultiplying by a random number */ + uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */ + uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */ + uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */ - uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */ + uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */ - /* tmp = d: */ - uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); + /* tmp = d: */ + uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); - s[num_n_words - 1] = 0; - uECC_vli_set(s, p, num_words); - uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */ + s[num_n_words - 1] = 0; + uECC_vli_set(s, p, num_words); + uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */ - bits2int(tmp, message_hash, hash_size, curve); - uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */ - uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */ - if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) { - return 0; - } + bits2int(tmp, message_hash, hash_size, curve); + uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */ + uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */ + if (uECC_vli_numBits(s, num_n_words) > (bitcount_t)curve->num_bytes * 8) { + return 0; + } - uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s); - return 1; + uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s); + return 1; } int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash, - unsigned hash_size, uint8_t *signature, uECC_Curve curve) + unsigned hash_size, uint8_t *signature, uECC_Curve curve) { - uECC_word_t _random[2*NUM_ECC_WORDS]; - uECC_word_t k[NUM_ECC_WORDS]; - uECC_word_t tries; + uECC_word_t _random[2*NUM_ECC_WORDS]; + uECC_word_t k[NUM_ECC_WORDS]; + uECC_word_t tries; - for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { - /* Generating _random uniformly at random: */ - uECC_RNG_Function rng_function = uECC_get_rng(); - if (!rng_function || - !rng_function((uint8_t *)_random, 2*NUM_ECC_WORDS*uECC_WORD_SIZE)) { - return 0; - } + for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) { + /* Generating _random uniformly at random: */ + uECC_RNG_Function rng_function = uECC_get_rng(); + if (!rng_function || + !rng_function((uint8_t *)_random, 2*NUM_ECC_WORDS*uECC_WORD_SIZE)) { + return 0; + } - // computing k as modular reduction of _random (see FIPS 186.4 B.5.1): - uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits)); + // computing k as modular reduction of _random (see FIPS 186.4 B.5.1): + uECC_vli_mmod(k, _random, curve->n, BITS_TO_WORDS(curve->num_n_bits)); - if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature, - curve)) { - return 1; - } - } - return 0; + if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature, + curve)) { + return 1; + } + } + return 0; } static bitcount_t smax(bitcount_t a, bitcount_t b) { - return (a > b ? a : b); + return (a > b ? a : b); } int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash, - unsigned hash_size, const uint8_t *signature, - uECC_Curve curve) + unsigned hash_size, const uint8_t *signature, + uECC_Curve curve) { - uECC_word_t u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS]; - uECC_word_t z[NUM_ECC_WORDS]; - uECC_word_t sum[NUM_ECC_WORDS * 2]; - uECC_word_t rx[NUM_ECC_WORDS]; - uECC_word_t ry[NUM_ECC_WORDS]; - uECC_word_t tx[NUM_ECC_WORDS]; - uECC_word_t ty[NUM_ECC_WORDS]; - uECC_word_t tz[NUM_ECC_WORDS]; - const uECC_word_t *points[4]; - const uECC_word_t *point; - bitcount_t num_bits; - bitcount_t i; + uECC_word_t u1[NUM_ECC_WORDS], u2[NUM_ECC_WORDS]; + uECC_word_t z[NUM_ECC_WORDS]; + uECC_word_t sum[NUM_ECC_WORDS * 2]; + uECC_word_t rx[NUM_ECC_WORDS]; + uECC_word_t ry[NUM_ECC_WORDS]; + uECC_word_t tx[NUM_ECC_WORDS]; + uECC_word_t ty[NUM_ECC_WORDS]; + uECC_word_t tz[NUM_ECC_WORDS]; + const uECC_word_t *points[4]; + const uECC_word_t *point; + bitcount_t num_bits; + bitcount_t i; - uECC_word_t _public[NUM_ECC_WORDS * 2]; - uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS]; - wordcount_t num_words = curve->num_words; - wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); + uECC_word_t _public[NUM_ECC_WORDS * 2]; + uECC_word_t r[NUM_ECC_WORDS], s[NUM_ECC_WORDS]; + wordcount_t num_words = curve->num_words; + wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); - rx[num_n_words - 1] = 0; - r[num_n_words - 1] = 0; - s[num_n_words - 1] = 0; + rx[num_n_words - 1] = 0; + r[num_n_words - 1] = 0; + s[num_n_words - 1] = 0; - uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); - uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes, - curve->num_bytes); - uECC_vli_bytesToNative(r, signature, curve->num_bytes); - uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes); + uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); + uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes, + curve->num_bytes); + uECC_vli_bytesToNative(r, signature, curve->num_bytes); + uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes); - /* r, s must not be 0. */ - if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) { - return 0; - } + /* r, s must not be 0. */ + if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) { + return 0; + } - /* r, s must be < n. */ - if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 || - uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) { - return 0; - } + /* r, s must be < n. */ + if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 || + uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) { + return 0; + } - /* Calculate u1 and u2. */ - uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */ - u1[num_n_words - 1] = 0; - bits2int(u1, message_hash, hash_size, curve); - uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */ - uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */ + /* Calculate u1 and u2. */ + uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */ + u1[num_n_words - 1] = 0; + bits2int(u1, message_hash, hash_size, curve); + uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */ + uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */ - /* Calculate sum = G + Q. */ - uECC_vli_set(sum, _public, num_words); - uECC_vli_set(sum + num_words, _public + num_words, num_words); - uECC_vli_set(tx, curve->G, num_words); - uECC_vli_set(ty, curve->G + num_words, num_words); - uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */ - XYcZ_add(tx, ty, sum, sum + num_words, curve); - uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */ - apply_z(sum, sum + num_words, z, curve); + /* Calculate sum = G + Q. */ + uECC_vli_set(sum, _public, num_words); + uECC_vli_set(sum + num_words, _public + num_words, num_words); + uECC_vli_set(tx, curve->G, num_words); + uECC_vli_set(ty, curve->G + num_words, num_words); + uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */ + XYcZ_add(tx, ty, sum, sum + num_words, curve); + uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */ + apply_z(sum, sum + num_words, z, curve); - /* Use Shamir's trick to calculate u1*G + u2*Q */ - points[0] = 0; - points[1] = curve->G; - points[2] = _public; - points[3] = sum; - num_bits = smax(uECC_vli_numBits(u1, num_n_words), - uECC_vli_numBits(u2, num_n_words)); + /* Use Shamir's trick to calculate u1*G + u2*Q */ + points[0] = 0; + points[1] = curve->G; + points[2] = _public; + points[3] = sum; + num_bits = smax(uECC_vli_numBits(u1, num_n_words), + uECC_vli_numBits(u2, num_n_words)); - point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) | + point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) | ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)]; - uECC_vli_set(rx, point, num_words); - uECC_vli_set(ry, point + num_words, num_words); - uECC_vli_clear(z, num_words); - z[0] = 1; + uECC_vli_set(rx, point, num_words); + uECC_vli_set(ry, point + num_words, num_words); + uECC_vli_clear(z, num_words); + z[0] = 1; - for (i = num_bits - 2; i >= 0; --i) { - uECC_word_t index; - curve->double_jacobian(rx, ry, z, curve); + for (i = num_bits - 2; i >= 0; --i) { + uECC_word_t index; + curve->double_jacobian(rx, ry, z, curve); - index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1); - point = points[index]; - if (point) { - uECC_vli_set(tx, point, num_words); - uECC_vli_set(ty, point + num_words, num_words); - apply_z(tx, ty, z, curve); - uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */ - XYcZ_add(tx, ty, rx, ry, curve); - uECC_vli_modMult_fast(z, z, tz, curve); - } - } + index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1); + point = points[index]; + if (point) { + uECC_vli_set(tx, point, num_words); + uECC_vli_set(ty, point + num_words, num_words); + apply_z(tx, ty, z, curve); + uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */ + XYcZ_add(tx, ty, rx, ry, curve); + uECC_vli_modMult_fast(z, z, tz, curve); + } + } - uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */ - apply_z(rx, ry, z, curve); + uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */ + apply_z(rx, ry, z, curve); - /* v = x1 (mod n) */ - if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) { - uECC_vli_sub(rx, rx, curve->n, num_n_words); - } + /* v = x1 (mod n) */ + if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) { + uECC_vli_sub(rx, rx, curve->n, num_n_words); + } - /* Accept only if v == r. */ - return (int)(uECC_vli_equal(rx, r, num_words) == 0); + /* Accept only if v == r. */ + return (int)(uECC_vli_equal(rx, r, num_words) == 0); } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/hmac.c b/components/network/ble/blestack/src/common/tinycrypt/source/hmac.c index 2965aa80..b7135539 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/hmac.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/hmac.c @@ -36,112 +36,112 @@ static void rekey(uint8_t *key, const uint8_t *new_key, unsigned int key_size) { - const uint8_t inner_pad = (uint8_t) 0x36; - const uint8_t outer_pad = (uint8_t) 0x5c; - unsigned int i; + const uint8_t inner_pad = (uint8_t) 0x36; + const uint8_t outer_pad = (uint8_t) 0x5c; + unsigned int i; - for (i = 0; i < key_size; ++i) { - key[i] = inner_pad ^ new_key[i]; - key[i + TC_SHA256_BLOCK_SIZE] = outer_pad ^ new_key[i]; - } - for (; i < TC_SHA256_BLOCK_SIZE; ++i) { - key[i] = inner_pad; key[i + TC_SHA256_BLOCK_SIZE] = outer_pad; - } + for (i = 0; i < key_size; ++i) { + key[i] = inner_pad ^ new_key[i]; + key[i + TC_SHA256_BLOCK_SIZE] = outer_pad ^ new_key[i]; + } + for (; i < TC_SHA256_BLOCK_SIZE; ++i) { + key[i] = inner_pad; key[i + TC_SHA256_BLOCK_SIZE] = outer_pad; + } } int tc_hmac_set_key(TCHmacState_t ctx, const uint8_t *key, - unsigned int key_size) + unsigned int key_size) { - /* Input sanity check */ - if (ctx == (TCHmacState_t) 0 || - key == (const uint8_t *) 0 || - key_size == 0) { - return TC_CRYPTO_FAIL; - } + /* Input sanity check */ + if (ctx == (TCHmacState_t) 0 || + key == (const uint8_t *) 0 || + key_size == 0) { + return TC_CRYPTO_FAIL; + } - const uint8_t dummy_key[TC_SHA256_BLOCK_SIZE]; - struct tc_hmac_state_struct dummy_state; + const uint8_t dummy_key[TC_SHA256_BLOCK_SIZE]; + struct tc_hmac_state_struct dummy_state; - if (key_size <= TC_SHA256_BLOCK_SIZE) { - /* - * The next three calls are dummy calls just to avoid - * certain timing attacks. Without these dummy calls, - * adversaries would be able to learn whether the key_size is - * greater than TC_SHA256_BLOCK_SIZE by measuring the time - * consumed in this process. - */ - (void)tc_sha256_init(&dummy_state.hash_state); - (void)tc_sha256_update(&dummy_state.hash_state, - dummy_key, - key_size); - (void)tc_sha256_final(&dummy_state.key[TC_SHA256_DIGEST_SIZE], - &dummy_state.hash_state); + if (key_size <= TC_SHA256_BLOCK_SIZE) { + /* + * The next three calls are dummy calls just to avoid + * certain timing attacks. Without these dummy calls, + * adversaries would be able to learn whether the key_size is + * greater than TC_SHA256_BLOCK_SIZE by measuring the time + * consumed in this process. + */ + (void)tc_sha256_init(&dummy_state.hash_state); + (void)tc_sha256_update(&dummy_state.hash_state, + dummy_key, + key_size); + (void)tc_sha256_final(&dummy_state.key[TC_SHA256_DIGEST_SIZE], + &dummy_state.hash_state); - /* Actual code for when key_size <= TC_SHA256_BLOCK_SIZE: */ - rekey(ctx->key, key, key_size); - } else { - (void)tc_sha256_init(&ctx->hash_state); - (void)tc_sha256_update(&ctx->hash_state, key, key_size); - (void)tc_sha256_final(&ctx->key[TC_SHA256_DIGEST_SIZE], - &ctx->hash_state); - rekey(ctx->key, - &ctx->key[TC_SHA256_DIGEST_SIZE], - TC_SHA256_DIGEST_SIZE); - } + /* Actual code for when key_size <= TC_SHA256_BLOCK_SIZE: */ + rekey(ctx->key, key, key_size); + } else { + (void)tc_sha256_init(&ctx->hash_state); + (void)tc_sha256_update(&ctx->hash_state, key, key_size); + (void)tc_sha256_final(&ctx->key[TC_SHA256_DIGEST_SIZE], + &ctx->hash_state); + rekey(ctx->key, + &ctx->key[TC_SHA256_DIGEST_SIZE], + TC_SHA256_DIGEST_SIZE); + } - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_hmac_init(TCHmacState_t ctx) { - /* input sanity check: */ - if (ctx == (TCHmacState_t) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (ctx == (TCHmacState_t) 0) { + return TC_CRYPTO_FAIL; + } (void) tc_sha256_init(&ctx->hash_state); (void) tc_sha256_update(&ctx->hash_state, ctx->key, TC_SHA256_BLOCK_SIZE); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_hmac_update(TCHmacState_t ctx, - const void *data, - unsigned int data_length) + const void *data, + unsigned int data_length) { - /* input sanity check: */ - if (ctx == (TCHmacState_t) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (ctx == (TCHmacState_t) 0) { + return TC_CRYPTO_FAIL; + } - (void)tc_sha256_update(&ctx->hash_state, data, data_length); + (void)tc_sha256_update(&ctx->hash_state, data, data_length); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_hmac_final(uint8_t *tag, unsigned int taglen, TCHmacState_t ctx) { - /* input sanity check: */ - if (tag == (uint8_t *) 0 || - taglen != TC_SHA256_DIGEST_SIZE || - ctx == (TCHmacState_t) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (tag == (uint8_t *) 0 || + taglen != TC_SHA256_DIGEST_SIZE || + ctx == (TCHmacState_t) 0) { + return TC_CRYPTO_FAIL; + } - (void) tc_sha256_final(tag, &ctx->hash_state); + (void) tc_sha256_final(tag, &ctx->hash_state); - (void)tc_sha256_init(&ctx->hash_state); - (void)tc_sha256_update(&ctx->hash_state, - &ctx->key[TC_SHA256_BLOCK_SIZE], - TC_SHA256_BLOCK_SIZE); - (void)tc_sha256_update(&ctx->hash_state, tag, TC_SHA256_DIGEST_SIZE); - (void)tc_sha256_final(tag, &ctx->hash_state); + (void)tc_sha256_init(&ctx->hash_state); + (void)tc_sha256_update(&ctx->hash_state, + &ctx->key[TC_SHA256_BLOCK_SIZE], + TC_SHA256_BLOCK_SIZE); + (void)tc_sha256_update(&ctx->hash_state, tag, TC_SHA256_DIGEST_SIZE); + (void)tc_sha256_final(tag, &ctx->hash_state); - /* destroy the current state */ - _set(ctx, 0, sizeof(*ctx)); + /* destroy the current state */ + _set(ctx, 0, sizeof(*ctx)); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/hmac_prng.c b/components/network/ble/blestack/src/common/tinycrypt/source/hmac_prng.c index 9664839a..54834336 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/hmac_prng.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/hmac_prng.c @@ -77,154 +77,154 @@ static const unsigned int MAX_OUT = (1 << 19); */ static void update(TCHmacPrng_t prng, const uint8_t *data, unsigned int datalen, const uint8_t *additional_data, unsigned int additional_datalen) { - const uint8_t separator0 = 0x00; - const uint8_t separator1 = 0x01; + const uint8_t separator0 = 0x00; + const uint8_t separator1 = 0x01; - /* configure the new prng key into the prng's instance of hmac */ - tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); + /* configure the new prng key into the prng's instance of hmac */ + tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); - /* use current state, e and separator 0 to compute a new prng key: */ - (void)tc_hmac_init(&prng->h); - (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); - (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0)); + /* use current state, e and separator 0 to compute a new prng key: */ + (void)tc_hmac_init(&prng->h); + (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); + (void)tc_hmac_update(&prng->h, &separator0, sizeof(separator0)); - if (data && datalen) - (void)tc_hmac_update(&prng->h, data, datalen); - if (additional_data && additional_datalen) - (void)tc_hmac_update(&prng->h, additional_data, additional_datalen); + if (data && datalen) + (void)tc_hmac_update(&prng->h, data, datalen); + if (additional_data && additional_datalen) + (void)tc_hmac_update(&prng->h, additional_data, additional_datalen); - (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); + (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); - /* configure the new prng key into the prng's instance of hmac */ - (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); + /* configure the new prng key into the prng's instance of hmac */ + (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); - /* use the new key to compute a new state variable v */ - (void)tc_hmac_init(&prng->h); - (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); - (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); + /* use the new key to compute a new state variable v */ + (void)tc_hmac_init(&prng->h); + (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); + (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); - if (data == 0 || datalen == 0) - return; + if (data == 0 || datalen == 0) + return; - /* configure the new prng key into the prng's instance of hmac */ - tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); + /* configure the new prng key into the prng's instance of hmac */ + tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); - /* use current state, e and separator 1 to compute a new prng key: */ - (void)tc_hmac_init(&prng->h); - (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); - (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1)); - (void)tc_hmac_update(&prng->h, data, datalen); - if (additional_data && additional_datalen) - (void)tc_hmac_update(&prng->h, additional_data, additional_datalen); - (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); + /* use current state, e and separator 1 to compute a new prng key: */ + (void)tc_hmac_init(&prng->h); + (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); + (void)tc_hmac_update(&prng->h, &separator1, sizeof(separator1)); + (void)tc_hmac_update(&prng->h, data, datalen); + if (additional_data && additional_datalen) + (void)tc_hmac_update(&prng->h, additional_data, additional_datalen); + (void)tc_hmac_final(prng->key, sizeof(prng->key), &prng->h); - /* configure the new prng key into the prng's instance of hmac */ - (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); + /* configure the new prng key into the prng's instance of hmac */ + (void)tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); - /* use the new key to compute a new state variable v */ - (void)tc_hmac_init(&prng->h); - (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); - (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); + /* use the new key to compute a new state variable v */ + (void)tc_hmac_init(&prng->h); + (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); + (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); } int tc_hmac_prng_init(TCHmacPrng_t prng, - const uint8_t *personalization, - unsigned int plen) + const uint8_t *personalization, + unsigned int plen) { - /* input sanity check: */ - if (prng == (TCHmacPrng_t) 0 || - personalization == (uint8_t *) 0 || - plen > MAX_PLEN) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (prng == (TCHmacPrng_t) 0 || + personalization == (uint8_t *) 0 || + plen > MAX_PLEN) { + return TC_CRYPTO_FAIL; + } - /* put the generator into a known state: */ - _set(prng->key, 0x00, sizeof(prng->key)); - _set(prng->v, 0x01, sizeof(prng->v)); + /* put the generator into a known state: */ + _set(prng->key, 0x00, sizeof(prng->key)); + _set(prng->v, 0x01, sizeof(prng->v)); - update(prng, personalization, plen, 0, 0); + update(prng, personalization, plen, 0, 0); - /* force a reseed before allowing tc_hmac_prng_generate to succeed: */ - prng->countdown = 0; + /* force a reseed before allowing tc_hmac_prng_generate to succeed: */ + prng->countdown = 0; - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_hmac_prng_reseed(TCHmacPrng_t prng, - const uint8_t *seed, - unsigned int seedlen, - const uint8_t *additional_input, - unsigned int additionallen) + const uint8_t *seed, + unsigned int seedlen, + const uint8_t *additional_input, + unsigned int additionallen) { - /* input sanity check: */ - if (prng == (TCHmacPrng_t) 0 || - seed == (const uint8_t *) 0 || - seedlen < MIN_SLEN || - seedlen > MAX_SLEN) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (prng == (TCHmacPrng_t) 0 || + seed == (const uint8_t *) 0 || + seedlen < MIN_SLEN || + seedlen > MAX_SLEN) { + return TC_CRYPTO_FAIL; + } - if (additional_input != (const uint8_t *) 0) { - /* - * Abort if additional_input is provided but has inappropriate - * length - */ - if (additionallen == 0 || - additionallen > MAX_ALEN) { - return TC_CRYPTO_FAIL; - } else { - /* call update for the seed and additional_input */ - update(prng, seed, seedlen, additional_input, additionallen); - } - } else { - /* call update only for the seed */ - update(prng, seed, seedlen, 0, 0); - } + if (additional_input != (const uint8_t *) 0) { + /* + * Abort if additional_input is provided but has inappropriate + * length + */ + if (additionallen == 0 || + additionallen > MAX_ALEN) { + return TC_CRYPTO_FAIL; + } else { + /* call update for the seed and additional_input */ + update(prng, seed, seedlen, additional_input, additionallen); + } + } else { + /* call update only for the seed */ + update(prng, seed, seedlen, 0, 0); + } - /* ... and enable hmac_prng_generate */ - prng->countdown = MAX_GENS; + /* ... and enable hmac_prng_generate */ + prng->countdown = MAX_GENS; - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_hmac_prng_generate(uint8_t *out, unsigned int outlen, TCHmacPrng_t prng) { - unsigned int bufferlen; + unsigned int bufferlen; - /* input sanity check: */ - if (out == (uint8_t *) 0 || - prng == (TCHmacPrng_t) 0 || - outlen == 0 || - outlen > MAX_OUT) { - return TC_CRYPTO_FAIL; - } else if (prng->countdown == 0) { - return TC_HMAC_PRNG_RESEED_REQ; - } + /* input sanity check: */ + if (out == (uint8_t *) 0 || + prng == (TCHmacPrng_t) 0 || + outlen == 0 || + outlen > MAX_OUT) { + return TC_CRYPTO_FAIL; + } else if (prng->countdown == 0) { + return TC_HMAC_PRNG_RESEED_REQ; + } - prng->countdown--; + prng->countdown--; - while (outlen != 0) { - /* configure the new prng key into the prng's instance of hmac */ - tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); + while (outlen != 0) { + /* configure the new prng key into the prng's instance of hmac */ + tc_hmac_set_key(&prng->h, prng->key, sizeof(prng->key)); - /* operate HMAC in OFB mode to create "random" outputs */ - (void)tc_hmac_init(&prng->h); - (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); - (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); + /* operate HMAC in OFB mode to create "random" outputs */ + (void)tc_hmac_init(&prng->h); + (void)tc_hmac_update(&prng->h, prng->v, sizeof(prng->v)); + (void)tc_hmac_final(prng->v, sizeof(prng->v), &prng->h); - bufferlen = (TC_SHA256_DIGEST_SIZE > outlen) ? - outlen : TC_SHA256_DIGEST_SIZE; - (void)_copy(out, bufferlen, prng->v, bufferlen); + bufferlen = (TC_SHA256_DIGEST_SIZE > outlen) ? + outlen : TC_SHA256_DIGEST_SIZE; + (void)_copy(out, bufferlen, prng->v, bufferlen); - out += bufferlen; - outlen = (outlen > TC_SHA256_DIGEST_SIZE) ? - (outlen - TC_SHA256_DIGEST_SIZE) : 0; - } + out += bufferlen; + outlen = (outlen > TC_SHA256_DIGEST_SIZE) ? + (outlen - TC_SHA256_DIGEST_SIZE) : 0; + } - /* block future PRNG compromises from revealing past state */ - update(prng, 0, 0, 0, 0); + /* block future PRNG compromises from revealing past state */ + update(prng, 0, 0, 0, 0); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/sha256.c b/components/network/ble/blestack/src/common/tinycrypt/source/sha256.c index 97045df7..b781aebc 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/sha256.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/sha256.c @@ -38,101 +38,101 @@ static void compress(unsigned int *iv, const uint8_t *data); int tc_sha256_init(TCSha256State_t s) { - /* input sanity check: */ - if (s == (TCSha256State_t) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (s == (TCSha256State_t) 0) { + return TC_CRYPTO_FAIL; + } - /* - * Setting the initial state values. - * These values correspond to the first 32 bits of the fractional parts - * of the square roots of the first 8 primes: 2, 3, 5, 7, 11, 13, 17 - * and 19. - */ - _set((uint8_t *) s, 0x00, sizeof(*s)); - s->iv[0] = 0x6a09e667; - s->iv[1] = 0xbb67ae85; - s->iv[2] = 0x3c6ef372; - s->iv[3] = 0xa54ff53a; - s->iv[4] = 0x510e527f; - s->iv[5] = 0x9b05688c; - s->iv[6] = 0x1f83d9ab; - s->iv[7] = 0x5be0cd19; + /* + * Setting the initial state values. + * These values correspond to the first 32 bits of the fractional parts + * of the square roots of the first 8 primes: 2, 3, 5, 7, 11, 13, 17 + * and 19. + */ + _set((uint8_t *) s, 0x00, sizeof(*s)); + s->iv[0] = 0x6a09e667; + s->iv[1] = 0xbb67ae85; + s->iv[2] = 0x3c6ef372; + s->iv[3] = 0xa54ff53a; + s->iv[4] = 0x510e527f; + s->iv[5] = 0x9b05688c; + s->iv[6] = 0x1f83d9ab; + s->iv[7] = 0x5be0cd19; - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_sha256_update(TCSha256State_t s, const uint8_t *data, size_t datalen) { - /* input sanity check: */ - if (s == (TCSha256State_t) 0 || - data == (void *) 0) { - return TC_CRYPTO_FAIL; - } else if (datalen == 0) { - return TC_CRYPTO_SUCCESS; - } + /* input sanity check: */ + if (s == (TCSha256State_t) 0 || + data == (void *) 0) { + return TC_CRYPTO_FAIL; + } else if (datalen == 0) { + return TC_CRYPTO_SUCCESS; + } - while (datalen-- > 0) { - s->leftover[s->leftover_offset++] = *(data++); - if (s->leftover_offset >= TC_SHA256_BLOCK_SIZE) { - compress(s->iv, s->leftover); - s->leftover_offset = 0; - s->bits_hashed += (TC_SHA256_BLOCK_SIZE << 3); - } - } + while (datalen-- > 0) { + s->leftover[s->leftover_offset++] = *(data++); + if (s->leftover_offset >= TC_SHA256_BLOCK_SIZE) { + compress(s->iv, s->leftover); + s->leftover_offset = 0; + s->bits_hashed += (TC_SHA256_BLOCK_SIZE << 3); + } + } - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } int tc_sha256_final(uint8_t *digest, TCSha256State_t s) { - unsigned int i; + unsigned int i; - /* input sanity check: */ - if (digest == (uint8_t *) 0 || - s == (TCSha256State_t) 0) { - return TC_CRYPTO_FAIL; - } + /* input sanity check: */ + if (digest == (uint8_t *) 0 || + s == (TCSha256State_t) 0) { + return TC_CRYPTO_FAIL; + } - s->bits_hashed += (s->leftover_offset << 3); + s->bits_hashed += (s->leftover_offset << 3); - s->leftover[s->leftover_offset++] = 0x80; /* always room for one byte */ - if (s->leftover_offset > (sizeof(s->leftover) - 8)) { - /* there is not room for all the padding in this block */ - _set(s->leftover + s->leftover_offset, 0x00, - sizeof(s->leftover) - s->leftover_offset); - compress(s->iv, s->leftover); - s->leftover_offset = 0; - } + s->leftover[s->leftover_offset++] = 0x80; /* always room for one byte */ + if (s->leftover_offset > (sizeof(s->leftover) - 8)) { + /* there is not room for all the padding in this block */ + _set(s->leftover + s->leftover_offset, 0x00, + sizeof(s->leftover) - s->leftover_offset); + compress(s->iv, s->leftover); + s->leftover_offset = 0; + } - /* add the padding and the length in big-Endian format */ - _set(s->leftover + s->leftover_offset, 0x00, - sizeof(s->leftover) - 8 - s->leftover_offset); - s->leftover[sizeof(s->leftover) - 1] = (uint8_t)(s->bits_hashed); - s->leftover[sizeof(s->leftover) - 2] = (uint8_t)(s->bits_hashed >> 8); - s->leftover[sizeof(s->leftover) - 3] = (uint8_t)(s->bits_hashed >> 16); - s->leftover[sizeof(s->leftover) - 4] = (uint8_t)(s->bits_hashed >> 24); - s->leftover[sizeof(s->leftover) - 5] = (uint8_t)(s->bits_hashed >> 32); - s->leftover[sizeof(s->leftover) - 6] = (uint8_t)(s->bits_hashed >> 40); - s->leftover[sizeof(s->leftover) - 7] = (uint8_t)(s->bits_hashed >> 48); - s->leftover[sizeof(s->leftover) - 8] = (uint8_t)(s->bits_hashed >> 56); + /* add the padding and the length in big-Endian format */ + _set(s->leftover + s->leftover_offset, 0x00, + sizeof(s->leftover) - 8 - s->leftover_offset); + s->leftover[sizeof(s->leftover) - 1] = (uint8_t)(s->bits_hashed); + s->leftover[sizeof(s->leftover) - 2] = (uint8_t)(s->bits_hashed >> 8); + s->leftover[sizeof(s->leftover) - 3] = (uint8_t)(s->bits_hashed >> 16); + s->leftover[sizeof(s->leftover) - 4] = (uint8_t)(s->bits_hashed >> 24); + s->leftover[sizeof(s->leftover) - 5] = (uint8_t)(s->bits_hashed >> 32); + s->leftover[sizeof(s->leftover) - 6] = (uint8_t)(s->bits_hashed >> 40); + s->leftover[sizeof(s->leftover) - 7] = (uint8_t)(s->bits_hashed >> 48); + s->leftover[sizeof(s->leftover) - 8] = (uint8_t)(s->bits_hashed >> 56); - /* hash the padding and length */ - compress(s->iv, s->leftover); + /* hash the padding and length */ + compress(s->iv, s->leftover); - /* copy the iv out to digest */ - for (i = 0; i < TC_SHA256_STATE_BLOCKS; ++i) { - unsigned int t = *((unsigned int *) &s->iv[i]); - *digest++ = (uint8_t)(t >> 24); - *digest++ = (uint8_t)(t >> 16); - *digest++ = (uint8_t)(t >> 8); - *digest++ = (uint8_t)(t); - } + /* copy the iv out to digest */ + for (i = 0; i < TC_SHA256_STATE_BLOCKS; ++i) { + unsigned int t = *((unsigned int *) &s->iv[i]); + *digest++ = (uint8_t)(t >> 24); + *digest++ = (uint8_t)(t >> 16); + *digest++ = (uint8_t)(t >> 8); + *digest++ = (uint8_t)(t); + } - /* destroy the current state */ - _set(s, 0, sizeof(*s)); + /* destroy the current state */ + _set(s, 0, sizeof(*s)); - return TC_CRYPTO_SUCCESS; + return TC_CRYPTO_SUCCESS; } /* @@ -141,22 +141,22 @@ int tc_sha256_final(uint8_t *digest, TCSha256State_t s) * cube roots of the first 64 primes between 2 and 311. */ static const unsigned int k256[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, - 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, - 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, - 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, - 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, - 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, + 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, + 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, + 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, + 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; static inline unsigned int ROTR(unsigned int a, unsigned int n) { - return (((a) >> n) | ((a) << (32 - n))); + return (((a) >> n) | ((a) << (32 - n))); } #define Sigma0(a)(ROTR((a), 2) ^ ROTR((a), 13) ^ ROTR((a), 22)) @@ -169,49 +169,49 @@ static inline unsigned int ROTR(unsigned int a, unsigned int n) static inline unsigned int BigEndian(const uint8_t **c) { - unsigned int n = 0; + unsigned int n = 0; - n = (((unsigned int)(*((*c)++))) << 24); - n |= ((unsigned int)(*((*c)++)) << 16); - n |= ((unsigned int)(*((*c)++)) << 8); - n |= ((unsigned int)(*((*c)++))); - return n; + n = (((unsigned int)(*((*c)++))) << 24); + n |= ((unsigned int)(*((*c)++)) << 16); + n |= ((unsigned int)(*((*c)++)) << 8); + n |= ((unsigned int)(*((*c)++))); + return n; } static void compress(unsigned int *iv, const uint8_t *data) { - unsigned int a, b, c, d, e, f, g, h; - unsigned int s0, s1; - unsigned int t1, t2; - unsigned int work_space[16]; - unsigned int n; - unsigned int i; + unsigned int a, b, c, d, e, f, g, h; + unsigned int s0, s1; + unsigned int t1, t2; + unsigned int work_space[16]; + unsigned int n; + unsigned int i; - a = iv[0]; b = iv[1]; c = iv[2]; d = iv[3]; - e = iv[4]; f = iv[5]; g = iv[6]; h = iv[7]; + a = iv[0]; b = iv[1]; c = iv[2]; d = iv[3]; + e = iv[4]; f = iv[5]; g = iv[6]; h = iv[7]; - for (i = 0; i < 16; ++i) { - n = BigEndian(&data); - t1 = work_space[i] = n; - t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i]; - t2 = Sigma0(a) + Maj(a, b, c); - h = g; g = f; f = e; e = d + t1; - d = c; c = b; b = a; a = t1 + t2; - } + for (i = 0; i < 16; ++i) { + n = BigEndian(&data); + t1 = work_space[i] = n; + t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i]; + t2 = Sigma0(a) + Maj(a, b, c); + h = g; g = f; f = e; e = d + t1; + d = c; c = b; b = a; a = t1 + t2; + } - for ( ; i < 64; ++i) { - s0 = work_space[(i+1)&0x0f]; - s0 = sigma0(s0); - s1 = work_space[(i+14)&0x0f]; - s1 = sigma1(s1); + for ( ; i < 64; ++i) { + s0 = work_space[(i+1)&0x0f]; + s0 = sigma0(s0); + s1 = work_space[(i+14)&0x0f]; + s1 = sigma1(s1); - t1 = work_space[i&0xf] += s0 + s1 + work_space[(i+9)&0xf]; - t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i]; - t2 = Sigma0(a) + Maj(a, b, c); - h = g; g = f; f = e; e = d + t1; - d = c; c = b; b = a; a = t1 + t2; - } + t1 = work_space[i&0xf] += s0 + s1 + work_space[(i+9)&0xf]; + t1 += h + Sigma1(e) + Ch(e, f, g) + k256[i]; + t2 = Sigma0(a) + Maj(a, b, c); + h = g; g = f; f = e; e = d + t1; + d = c; c = b; b = a; a = t1 + t2; + } - iv[0] += a; iv[1] += b; iv[2] += c; iv[3] += d; - iv[4] += e; iv[5] += f; iv[6] += g; iv[7] += h; + iv[0] += a; iv[1] += b; iv[2] += c; iv[3] += d; + iv[4] += e; iv[5] += f; iv[6] += g; iv[7] += h; } diff --git a/components/network/ble/blestack/src/common/tinycrypt/source/utils.c b/components/network/ble/blestack/src/common/tinycrypt/source/utils.c index 61a567bf..ea988008 100644 --- a/components/network/ble/blestack/src/common/tinycrypt/source/utils.c +++ b/components/network/ble/blestack/src/common/tinycrypt/source/utils.c @@ -38,19 +38,19 @@ #define MASK_TWENTY_SEVEN 0x1b unsigned int _copy(uint8_t *to, unsigned int to_len, - const uint8_t *from, unsigned int from_len) + const uint8_t *from, unsigned int from_len) { - if (from_len <= to_len) { - (void)memcpy(to, from, from_len); - return from_len; - } else { - return TC_CRYPTO_FAIL; - } + if (from_len <= to_len) { + (void)memcpy(to, from, from_len); + return from_len; + } else { + return TC_CRYPTO_FAIL; + } } void _set(void *to, uint8_t val, unsigned int len) { - (void)memset(to, val, len); + (void)memset(to, val, len); } /* @@ -58,17 +58,17 @@ void _set(void *to, uint8_t val, unsigned int len) */ uint8_t _double_byte(uint8_t a) { - return ((a<<1) ^ ((a>>7) * MASK_TWENTY_SEVEN)); + return ((a<<1) ^ ((a>>7) * MASK_TWENTY_SEVEN)); } int _compare(const uint8_t *a, const uint8_t *b, size_t size) { - const uint8_t *tempa = a; - const uint8_t *tempb = b; - uint8_t result = 0; + const uint8_t *tempa = a; + const uint8_t *tempb = b; + uint8_t result = 0; - for (unsigned int i = 0; i < size; i++) { - result |= tempa[i] ^ tempb[i]; - } - return result; + for (unsigned int i = 0; i < size; i++) { + result |= tempa[i] ^ tempb[i]; + } + return result; } diff --git a/components/network/ble/blestack/src/common/work_q.c b/components/network/ble/blestack/src/common/work_q.c index 1f60b23c..10daa306 100644 --- a/components/network/ble/blestack/src/common/work_q.c +++ b/components/network/ble/blestack/src/common/work_q.c @@ -41,7 +41,7 @@ static void work_queue_main(void *p1) { struct k_work *work; UNUSED(p1); - + while (1) { work = k_fifo_get(&g_work_queue_main.fifo, K_FOREVER); @@ -81,7 +81,7 @@ static void work_timeout(void *timer) timer_rec_d *rec = get_timer_record(timer); BT_ASSERT(rec != NULL); struct k_delayed_work *w = rec->delay_work; - + /* submit work to workqueue */ k_timer_stop(&w->timer); k_work_submit_to_queue(w->work_q, &w->work); @@ -148,8 +148,8 @@ int k_delayed_work_submit(struct k_delayed_work *work, uint32_t delay) int k_delayed_work_submit_periodic(struct k_delayed_work *work, s32_t period) { - // TODO - return 0; + // TODO + return 0; } int k_delayed_work_cancel(struct k_delayed_work *work) @@ -188,7 +188,7 @@ s32_t k_delayed_work_remaining_get(struct k_delayed_work *work) } timer = &work->timer; - remain = timer->timeout - (k_now_ms() - timer->start_ms); + remain = timer->timeout - (k_now_ms() - timer->start_ms); if (remain < 0) { remain = 0; } @@ -199,16 +199,16 @@ void k_delayed_work_del_timer(struct k_delayed_work *work) { if(NULL == work || NULL == work->timer.timer.hdl) return; - + k_timer_delete(&work->timer); work->timer.timer.hdl = NULL; } int k_delayed_work_free(struct k_delayed_work *work) { - remv_timer_record(work); - k_delayed_work_del_timer(work); - return 0; + remv_timer_record(work); + k_delayed_work_del_timer(work); + return 0; } @@ -240,7 +240,7 @@ int add_timer_record(struct k_delayed_work *delay_work) for(int i = 0; i < ARRAY_SIZE(timer_records); i++) { if(timer_records[i].timer.hdl == delay_work->timer.timer.hdl) - return 0; + return 0; } return alloc_timer_record(delay_work); @@ -256,8 +256,8 @@ int remv_timer_record(struct k_delayed_work *delay_work) break; } } - - return 0; + + return 0; } timer_rec_d *get_timer_record(void *hdl) @@ -266,137 +266,137 @@ timer_rec_d *get_timer_record(void *hdl) if(hdl == timer_records[i].timer.hdl) return &timer_records[i]; } - + return NULL; } #else static void work_q_main(void *work_q_ptr, void *p2, void *p3) { - struct k_work_q *work_q = work_q_ptr; + struct k_work_q *work_q = work_q_ptr; - ARG_UNUSED(p2); - ARG_UNUSED(p3); + ARG_UNUSED(p2); + ARG_UNUSED(p3); - while (1) { - struct k_work *work; - k_work_handler_t handler; + while (1) { + struct k_work *work; + k_work_handler_t handler; - work = k_queue_get(&work_q->queue, K_FOREVER); - if (!work) { - continue; - } + work = k_queue_get(&work_q->queue, K_FOREVER); + if (!work) { + continue; + } - handler = work->handler; + handler = work->handler; - /* Reset pending state so it can be resubmitted by handler */ - if (atomic_test_and_clear_bit(work->flags, - K_WORK_STATE_PENDING)) { - handler(work); - } + /* Reset pending state so it can be resubmitted by handler */ + if (atomic_test_and_clear_bit(work->flags, + K_WORK_STATE_PENDING)) { + handler(work); + } - /* Make sure we don't hog up the CPU if the FIFO never (or - * very rarely) gets empty. - */ - k_yield(); - } + /* Make sure we don't hog up the CPU if the FIFO never (or + * very rarely) gets empty. + */ + k_yield(); + } } void k_work_q_start(struct k_work_q *work_q, k_thread_stack_t *stack, - size_t stack_size, int prio) + size_t stack_size, int prio) { - k_queue_init(&work_q->queue, 20); - k_thread_create(&work_q->thread, stack, stack_size, work_q_main, - work_q, 0, 0, prio, 0, 0); - _k_object_init(work_q); + k_queue_init(&work_q->queue, 20); + k_thread_create(&work_q->thread, stack, stack_size, work_q_main, + work_q, 0, 0, prio, 0, 0); + _k_object_init(work_q); } #ifdef CONFIG_SYS_CLOCK_EXISTS static void work_timeout(struct _timeout *t) { - struct k_delayed_work *w = CONTAINER_OF(t, struct k_delayed_work, - timeout); + struct k_delayed_work *w = CONTAINER_OF(t, struct k_delayed_work, + timeout); - /* submit work to workqueue */ - k_work_submit_to_queue(w->work_q, &w->work); + /* submit work to workqueue */ + k_work_submit_to_queue(w->work_q, &w->work); } void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler) { - k_work_init(&work->work, handler); - _init_timeout(&work->timeout, work_timeout); - work->work_q = NULL; + k_work_init(&work->work, handler); + _init_timeout(&work->timeout, work_timeout); + work->work_q = NULL; - _k_object_init(work); + _k_object_init(work); } int k_delayed_work_submit_to_queue(struct k_work_q *work_q, - struct k_delayed_work *work, - s32_t delay) + struct k_delayed_work *work, + s32_t delay) { - unsigned int key = irq_lock(); - int err; + unsigned int key = irq_lock(); + int err; - /* Work cannot be active in multiple queues */ - if (work->work_q && work->work_q != work_q) { - err = -EADDRINUSE; - goto done; - } + /* Work cannot be active in multiple queues */ + if (work->work_q && work->work_q != work_q) { + err = -EADDRINUSE; + goto done; + } - /* Cancel if work has been submitted */ - if (work->work_q == work_q) { - err = k_delayed_work_cancel(work); - if (err < 0) { - goto done; - } - } + /* Cancel if work has been submitted */ + if (work->work_q == work_q) { + err = k_delayed_work_cancel(work); + if (err < 0) { + goto done; + } + } - /* Attach workqueue so the timeout callback can submit it */ - work->work_q = work_q; + /* Attach workqueue so the timeout callback can submit it */ + work->work_q = work_q; - if (!delay) { - /* Submit work if no ticks is 0 */ - k_work_submit_to_queue(work_q, &work->work); - } else { - /* Add timeout */ - _add_timeout(NULL, &work->timeout, NULL, - _TICK_ALIGN + _ms_to_ticks(delay)); - } + if (!delay) { + /* Submit work if no ticks is 0 */ + k_work_submit_to_queue(work_q, &work->work); + } else { + /* Add timeout */ + _add_timeout(NULL, &work->timeout, NULL, + _TICK_ALIGN + _ms_to_ticks(delay)); + } - err = 0; + err = 0; done: - irq_unlock(key); + irq_unlock(key); - return err; + return err; } int k_delayed_work_cancel(struct k_delayed_work *work) { - unsigned int key = irq_lock(); + unsigned int key = irq_lock(); - if (!work->work_q) { - irq_unlock(key); - return -EINVAL; - } + if (!work->work_q) { + irq_unlock(key); + return -EINVAL; + } - if (k_work_pending(&work->work)) { - /* Remove from the queue if already submitted */ - if (!k_queue_remove(&work->work_q->queue, &work->work)) { - irq_unlock(key); - return -EINVAL; - } - } else { - _abort_timeout(&work->timeout); - } + if (k_work_pending(&work->work)) { + /* Remove from the queue if already submitted */ + if (!k_queue_remove(&work->work_q->queue, &work->work)) { + irq_unlock(key); + return -EINVAL; + } + } else { + _abort_timeout(&work->timeout); + } - /* Detach from workqueue */ - work->work_q = NULL; + /* Detach from workqueue */ + work->work_q = NULL; - atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING); - irq_unlock(key); + atomic_clear_bit(work->work.flags, K_WORK_STATE_PENDING); + irq_unlock(key); - return 0; + return 0; } #endif /* CONFIG_SYS_CLOCK_EXISTS */ #endif /* BFLB_BLE */ \ No newline at end of file diff --git a/components/network/ble/blestack/src/hci_onchip/hci_driver.c b/components/network/ble/blestack/src/hci_onchip/hci_driver.c index bb12859e..16f19760 100644 --- a/components/network/ble/blestack/src/hci_onchip/hci_driver.c +++ b/components/network/ble/blestack/src/hci_onchip/hci_driver.c @@ -44,7 +44,7 @@ #endif #define NODE_RX(_node) CONTAINER_OF(_node, struct radio_pdu_node_rx, \ - hdr.onion.node) + hdr.onion.node) #if !defined(BFLB_BLE) static K_SEM_DEFINE(sem_prio_recv, 0, BT_UINT_MAX); @@ -59,7 +59,7 @@ static int recv_fifo_count = 0; #if !defined(BFLB_BLE) struct k_thread prio_recv_thread_data; static BT_STACK_NOINIT(prio_recv_thread_stack, - CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE); + CONFIG_BT_CTLR_RX_PRIO_STACK_SIZE); #endif struct k_thread recv_thread_data; @@ -74,7 +74,7 @@ static u32_t rx_ts; #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) static struct k_poll_signal hbuf_signal = - K_POLL_SIGNAL_INITIALIZER(hbuf_signal); + K_POLL_SIGNAL_INITIALIZER(hbuf_signal); static sys_slist_t hbuf_pend; static s32_t hbuf_count; #endif @@ -82,211 +82,211 @@ static s32_t hbuf_count; #if !defined(BFLB_BLE) static void prio_recv_thread(void *p1, void *p2, void *p3) { - while (1) { - struct radio_pdu_node_rx *node_rx; - u8_t num_cmplt; - u16_t handle; + while (1) { + struct radio_pdu_node_rx *node_rx; + u8_t num_cmplt; + u16_t handle; - while ((num_cmplt = radio_rx_get(&node_rx, &handle))) { + while ((num_cmplt = radio_rx_get(&node_rx, &handle))) { #if defined(CONFIG_BT_CONN) - struct net_buf *buf; + struct net_buf *buf; - buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); - hci_num_cmplt_encode(buf, handle, num_cmplt); - BT_DBG("Num Complete: 0x%04x:%u", handle, num_cmplt); - bt_recv_prio(buf); - k_yield(); + buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); + hci_num_cmplt_encode(buf, handle, num_cmplt); + BT_DBG("Num Complete: 0x%04x:%u", handle, num_cmplt); + bt_recv_prio(buf); + k_yield(); #endif - } + } - if (node_rx) { + if (node_rx) { - radio_rx_dequeue(); + radio_rx_dequeue(); - BT_DBG("RX node enqueue"); - k_fifo_put(&recv_fifo, node_rx); + BT_DBG("RX node enqueue"); + k_fifo_put(&recv_fifo, node_rx); - continue; - } + continue; + } - BT_DBG("sem take..."); - k_sem_take(&sem_prio_recv, K_FOREVER); - BT_DBG("sem taken"); + BT_DBG("sem take..."); + k_sem_take(&sem_prio_recv, K_FOREVER); + BT_DBG("sem taken"); #if defined(CONFIG_INIT_STACKS) - if (k_uptime_get_32() - prio_ts > K_SECONDS(5)) { - STACK_ANALYZE("prio recv thread stack", - prio_recv_thread_stack); - prio_ts = k_uptime_get_32(); - } + if (k_uptime_get_32() - prio_ts > K_SECONDS(5)) { + STACK_ANALYZE("prio recv thread stack", + prio_recv_thread_stack); + prio_ts = k_uptime_get_32(); + } #endif - } + } } static inline struct net_buf *encode_node(struct radio_pdu_node_rx *node_rx, - s8_t class) + s8_t class) { - struct net_buf *buf = NULL; + struct net_buf *buf = NULL; - /* Check if we need to generate an HCI event or ACL data */ - switch (class) { - case HCI_CLASS_EVT_DISCARDABLE: - case HCI_CLASS_EVT_REQUIRED: - case HCI_CLASS_EVT_CONNECTION: - if (class == HCI_CLASS_EVT_DISCARDABLE) { - buf = bt_buf_get_rx(BT_BUF_EVT, K_NO_WAIT); - } else { - buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); - } - if (buf) { - hci_evt_encode(node_rx, buf); - } - break; + /* Check if we need to generate an HCI event or ACL data */ + switch (class) { + case HCI_CLASS_EVT_DISCARDABLE: + case HCI_CLASS_EVT_REQUIRED: + case HCI_CLASS_EVT_CONNECTION: + if (class == HCI_CLASS_EVT_DISCARDABLE) { + buf = bt_buf_get_rx(BT_BUF_EVT, K_NO_WAIT); + } else { + buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); + } + if (buf) { + hci_evt_encode(node_rx, buf); + } + break; #if defined(CONFIG_BT_CONN) - case HCI_CLASS_ACL_DATA: - /* generate ACL data */ - buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER); - hci_acl_encode(node_rx, buf); - break; + case HCI_CLASS_ACL_DATA: + /* generate ACL data */ + buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER); + hci_acl_encode(node_rx, buf); + break; #endif - default: - LL_ASSERT(0); - break; - } + default: + LL_ASSERT(0); + break; + } - radio_rx_fc_set(node_rx->hdr.handle, 0); - node_rx->hdr.onion.next = 0; - radio_rx_mem_release(&node_rx); + radio_rx_fc_set(node_rx->hdr.handle, 0); + node_rx->hdr.onion.next = 0; + radio_rx_mem_release(&node_rx); - return buf; + return buf; } static inline struct net_buf *process_node(struct radio_pdu_node_rx *node_rx) { - s8_t class = hci_get_class(node_rx); - struct net_buf *buf = NULL; + s8_t class = hci_get_class(node_rx); + struct net_buf *buf = NULL; #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) - if (hbuf_count != -1) { - bool pend = !sys_slist_is_empty(&hbuf_pend); + if (hbuf_count != -1) { + bool pend = !sys_slist_is_empty(&hbuf_pend); - /* controller to host flow control enabled */ - switch (class) { - case HCI_CLASS_EVT_DISCARDABLE: - case HCI_CLASS_EVT_REQUIRED: - break; - case HCI_CLASS_EVT_CONNECTION: - /* for conn-related events, only pend is relevant */ - hbuf_count = 1; - /* fallthrough */ - case HCI_CLASS_ACL_DATA: - if (pend || !hbuf_count) { - sys_slist_append(&hbuf_pend, - &node_rx->hdr.onion.node); - BT_DBG("FC: Queuing item: %d", class); - return NULL; - } - break; - default: - LL_ASSERT(0); - break; - } - } + /* controller to host flow control enabled */ + switch (class) { + case HCI_CLASS_EVT_DISCARDABLE: + case HCI_CLASS_EVT_REQUIRED: + break; + case HCI_CLASS_EVT_CONNECTION: + /* for conn-related events, only pend is relevant */ + hbuf_count = 1; + /* fallthrough */ + case HCI_CLASS_ACL_DATA: + if (pend || !hbuf_count) { + sys_slist_append(&hbuf_pend, + &node_rx->hdr.onion.node); + BT_DBG("FC: Queuing item: %d", class); + return NULL; + } + break; + default: + LL_ASSERT(0); + break; + } + } #endif - /* process regular node from radio */ - buf = encode_node(node_rx, class); + /* process regular node from radio */ + buf = encode_node(node_rx, class); - return buf; + return buf; } #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) static inline struct net_buf *process_hbuf(struct radio_pdu_node_rx *n) { - /* shadow total count in case of preemption */ - struct radio_pdu_node_rx *node_rx = NULL; - s32_t hbuf_total = hci_hbuf_total; - struct net_buf *buf = NULL; - sys_snode_t *node = NULL; - s8_t class; - int reset; + /* shadow total count in case of preemption */ + struct radio_pdu_node_rx *node_rx = NULL; + s32_t hbuf_total = hci_hbuf_total; + struct net_buf *buf = NULL; + sys_snode_t *node = NULL; + s8_t class; + int reset; - reset = atomic_test_and_clear_bit(&hci_state_mask, HCI_STATE_BIT_RESET); - if (reset) { - /* flush queue, no need to free, the LL has already done it */ - sys_slist_init(&hbuf_pend); - } + reset = atomic_test_and_clear_bit(&hci_state_mask, HCI_STATE_BIT_RESET); + if (reset) { + /* flush queue, no need to free, the LL has already done it */ + sys_slist_init(&hbuf_pend); + } - if (hbuf_total <= 0) { - hbuf_count = -1; - return NULL; - } + if (hbuf_total <= 0) { + hbuf_count = -1; + return NULL; + } - /* available host buffers */ - hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked); + /* available host buffers */ + hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked); - /* host acked ACL packets, try to dequeue from hbuf */ - node = sys_slist_peek_head(&hbuf_pend); - if (!node) { - return NULL; - } + /* host acked ACL packets, try to dequeue from hbuf */ + node = sys_slist_peek_head(&hbuf_pend); + if (!node) { + return NULL; + } - /* Return early if this iteration already has a node to process */ - node_rx = NODE_RX(node); - class = hci_get_class(node_rx); - if (n) { - if (class == HCI_CLASS_EVT_CONNECTION || - (class == HCI_CLASS_ACL_DATA && hbuf_count)) { - /* node to process later, schedule an iteration */ - BT_DBG("FC: signalling"); - k_poll_signal_raise(&hbuf_signal, 0x0); - } - return NULL; - } + /* Return early if this iteration already has a node to process */ + node_rx = NODE_RX(node); + class = hci_get_class(node_rx); + if (n) { + if (class == HCI_CLASS_EVT_CONNECTION || + (class == HCI_CLASS_ACL_DATA && hbuf_count)) { + /* node to process later, schedule an iteration */ + BT_DBG("FC: signalling"); + k_poll_signal_raise(&hbuf_signal, 0x0); + } + return NULL; + } - switch (class) { - case HCI_CLASS_EVT_CONNECTION: - BT_DBG("FC: dequeueing event"); - (void) sys_slist_get(&hbuf_pend); - break; - case HCI_CLASS_ACL_DATA: - if (hbuf_count) { - BT_DBG("FC: dequeueing ACL data"); - (void) sys_slist_get(&hbuf_pend); - } else { - /* no buffers, HCI will signal */ - node = NULL; - } - break; - case HCI_CLASS_EVT_DISCARDABLE: - case HCI_CLASS_EVT_REQUIRED: - default: - LL_ASSERT(0); - break; - } + switch (class) { + case HCI_CLASS_EVT_CONNECTION: + BT_DBG("FC: dequeueing event"); + (void) sys_slist_get(&hbuf_pend); + break; + case HCI_CLASS_ACL_DATA: + if (hbuf_count) { + BT_DBG("FC: dequeueing ACL data"); + (void) sys_slist_get(&hbuf_pend); + } else { + /* no buffers, HCI will signal */ + node = NULL; + } + break; + case HCI_CLASS_EVT_DISCARDABLE: + case HCI_CLASS_EVT_REQUIRED: + default: + LL_ASSERT(0); + break; + } - if (node) { - buf = encode_node(node_rx, class); - /* Update host buffers after encoding */ - hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked); - /* next node */ - node = sys_slist_peek_head(&hbuf_pend); - if (node) { - node_rx = NODE_RX(node); - class = hci_get_class(node_rx); + if (node) { + buf = encode_node(node_rx, class); + /* Update host buffers after encoding */ + hbuf_count = hbuf_total - (hci_hbuf_sent - hci_hbuf_acked); + /* next node */ + node = sys_slist_peek_head(&hbuf_pend); + if (node) { + node_rx = NODE_RX(node); + class = hci_get_class(node_rx); - if (class == HCI_CLASS_EVT_CONNECTION || - (class == HCI_CLASS_ACL_DATA && hbuf_count)) { - /* more to process, schedule an - * iteration - */ - BT_DBG("FC: signalling"); - k_poll_signal_raise(&hbuf_signal, 0x0); - } - } - } + if (class == HCI_CLASS_EVT_CONNECTION || + (class == HCI_CLASS_ACL_DATA && hbuf_count)) { + /* more to process, schedule an + * iteration + */ + BT_DBG("FC: signalling"); + k_poll_signal_raise(&hbuf_signal, 0x0); + } + } + } - return buf; + return buf; } #endif #endif @@ -295,31 +295,31 @@ static inline struct net_buf *process_hbuf(struct radio_pdu_node_rx *n) #if (BFLB_BLE_CO_THREAD) void co_rx_thread() { - struct net_buf *buf = NULL; - buf = net_buf_get(&recv_fifo, K_NO_WAIT); - if(buf){ - BT_DBG("Calling bt_recv(%p)", buf); - bt_recv(buf); - } + struct net_buf *buf = NULL; + buf = net_buf_get(&recv_fifo, K_NO_WAIT); + if(buf){ + BT_DBG("Calling bt_recv(%p)", buf); + bt_recv(buf); + } } void co_tx_rx_thread(void *p1) { - UNUSED(p1); - BT_DBG("using %s\n", __func__); - while (1) { - if (k_sem_count_get(&g_poll_sem) > 0) { - co_tx_thread(); - } + UNUSED(p1); + BT_DBG("using %s\n", __func__); + while (1) { + if (k_sem_count_get(&g_poll_sem) > 0) { + co_tx_thread(); + } - if (recv_fifo_count > 0) { - recv_fifo_count--; - co_rx_thread(); - } + if (recv_fifo_count > 0) { + recv_fifo_count--; + co_rx_thread(); + } - k_sleep(portTICK_PERIOD_MS); - k_yield(); - } + k_sleep(portTICK_PERIOD_MS); + k_yield(); + } } #else @@ -327,18 +327,18 @@ static void recv_thread(void *p1) { UNUSED(p1); #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) - /* @todo: check if the events structure really needs to be static */ - static struct k_poll_event events[2] = { - K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SIGNAL, - K_POLL_MODE_NOTIFY_ONLY, - &hbuf_signal, 0), - K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, - K_POLL_MODE_NOTIFY_ONLY, - &recv_fifo, 0), - }; + /* @todo: check if the events structure really needs to be static */ + static struct k_poll_event events[2] = { + K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SIGNAL, + K_POLL_MODE_NOTIFY_ONLY, + &hbuf_signal, 0), + K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, + K_POLL_MODE_NOTIFY_ONLY, + &recv_fifo, 0), + }; #endif - while (1) { + while (1) { #if defined(BFLB_BLE) struct net_buf *buf = NULL; buf = net_buf_get(&recv_fifo, K_FOREVER); @@ -347,57 +347,57 @@ static void recv_thread(void *p1) bt_recv(buf); } #else - struct radio_pdu_node_rx *node_rx = NULL; - struct net_buf *buf = NULL; + struct radio_pdu_node_rx *node_rx = NULL; + struct net_buf *buf = NULL; - BT_DBG("blocking"); + BT_DBG("blocking"); #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) - int err; + int err; - err = k_poll(events, 2, K_FOREVER); - LL_ASSERT(err == 0); - if (events[0].state == K_POLL_STATE_SIGNALED) { - events[0].signal->signaled = 0; - } else if (events[1].state == - K_POLL_STATE_FIFO_DATA_AVAILABLE) { - node_rx = k_fifo_get(events[1].fifo, 0); - } + err = k_poll(events, 2, K_FOREVER); + LL_ASSERT(err == 0); + if (events[0].state == K_POLL_STATE_SIGNALED) { + events[0].signal->signaled = 0; + } else if (events[1].state == + K_POLL_STATE_FIFO_DATA_AVAILABLE) { + node_rx = k_fifo_get(events[1].fifo, 0); + } - events[0].state = K_POLL_STATE_NOT_READY; - events[1].state = K_POLL_STATE_NOT_READY; + events[0].state = K_POLL_STATE_NOT_READY; + events[1].state = K_POLL_STATE_NOT_READY; - /* process host buffers first if any */ - buf = process_hbuf(node_rx); + /* process host buffers first if any */ + buf = process_hbuf(node_rx); #else - node_rx = k_fifo_get(&recv_fifo, K_FOREVER); + node_rx = k_fifo_get(&recv_fifo, K_FOREVER); #endif - BT_DBG("unblocked"); + BT_DBG("unblocked"); - if (node_rx && !buf) { - /* process regular node from radio */ - buf = process_node(node_rx); - } - - if (buf) { - if (buf->len) { - BT_DBG("Packet in: type:%u len:%u", - bt_buf_get_type(buf), buf->len); - bt_recv(buf); - } else { - net_buf_unref(buf); - } - } + if (node_rx && !buf) { + /* process regular node from radio */ + buf = process_node(node_rx); + } + + if (buf) { + if (buf->len) { + BT_DBG("Packet in: type:%u len:%u", + bt_buf_get_type(buf), buf->len); + bt_recv(buf); + } else { + net_buf_unref(buf); + } + } #endif k_yield(); #if defined(CONFIG_INIT_STACKS) - if (k_uptime_get_32() - rx_ts > K_SECONDS(5)) { - STACK_ANALYZE("recv thread stack", recv_thread_stack); - rx_ts = k_uptime_get_32(); - } + if (k_uptime_get_32() - rx_ts > K_SECONDS(5)) { + STACK_ANALYZE("recv thread stack", recv_thread_stack); + rx_ts = k_uptime_get_32(); + } #endif - } + } } #endif #endif @@ -405,28 +405,28 @@ static void recv_thread(void *p1) #if !defined(BFLB_BLE) static int cmd_handle(struct net_buf *buf) { - struct net_buf *evt; + struct net_buf *evt; - evt = hci_cmd_handle(buf); - if (evt) { - BT_DBG("Replying with event of %u bytes", evt->len); - bt_recv_prio(evt); - } + evt = hci_cmd_handle(buf); + if (evt) { + BT_DBG("Replying with event of %u bytes", evt->len); + bt_recv_prio(evt); + } } #if defined(CONFIG_BT_CONN) static int acl_handle(struct net_buf *buf) { - struct net_buf *evt; - int err; + struct net_buf *evt; + int err; - err = hci_acl_handle(buf, &evt); - if (evt) { - BT_DBG("Replying with event of %u bytes", evt->len); - bt_recv_prio(evt); - } + err = hci_acl_handle(buf, &evt); + if (evt) { + BT_DBG("Replying with event of %u bytes", evt->len); + bt_recv_prio(evt); + } - return err; + return err; } #endif /* CONFIG_BT_CONN */ #endif @@ -434,72 +434,72 @@ static int acl_handle(struct net_buf *buf) static int hci_driver_send(struct net_buf *buf) { #if !defined(BFLB_BLE) - u8_t type; + u8_t type; #endif - int err; + int err; - BT_DBG("enter"); + BT_DBG("enter"); - if (!buf->len) { - BT_ERR("Empty HCI packet"); - return -EINVAL; - } + if (!buf->len) { + BT_ERR("Empty HCI packet"); + return -EINVAL; + } #if defined(BFLB_BLE) err = bl_onchiphci_send_2_controller(buf); net_buf_unref(buf); return err; #else - type = bt_buf_get_type(buf); - switch (type) { + type = bt_buf_get_type(buf); + switch (type) { #if defined(CONFIG_BT_CONN) - case BT_BUF_ACL_OUT: - err = acl_handle(buf); - break; + case BT_BUF_ACL_OUT: + err = acl_handle(buf); + break; #endif /* CONFIG_BT_CONN */ - case BT_BUF_CMD: - err = cmd_handle(buf); - - break; - default: - BT_ERR("Unknown HCI type %u", type); - return -EINVAL; - } + case BT_BUF_CMD: + err = cmd_handle(buf); - if (!err) { - - net_buf_unref(buf); - } + break; + default: + BT_ERR("Unknown HCI type %u", type); + return -EINVAL; + } + + if (!err) { + + net_buf_unref(buf); + } else { } - BT_DBG("exit: %d", err); + BT_DBG("exit: %d", err); #endif - return err; + return err; } static int hci_driver_open(void) { -#if !defined(BFLB_BLE) - u32_t err; +#if !defined(BFLB_BLE) + u32_t err; - DEBUG_INIT(); - k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX); + DEBUG_INIT(); + k_sem_init(&sem_prio_recv, 0, BT_UINT_MAX); - err = ll_init(&sem_prio_recv); + err = ll_init(&sem_prio_recv); - if (err) { - BT_ERR("LL initialization failed: %u", err); - return err; - } + if (err) { + BT_ERR("LL initialization failed: %u", err); + return err; + } #endif -#if !defined(BFLB_BLE) +#if !defined(BFLB_BLE) #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) - hci_init(&hbuf_signal); + hci_init(&hbuf_signal); #else - hci_init(NULL); + hci_init(NULL); #endif #endif k_fifo_init(&recv_fifo, 20); @@ -507,25 +507,25 @@ static int hci_driver_open(void) #if defined(BFLB_BLE) #if (BFLB_BLE_CO_THREAD) k_thread_create(&recv_thread_data, "co_tx_rx_thread", - CONFIG_BT_RX_STACK_SIZE, - co_tx_rx_thread, - K_PRIO_COOP(CONFIG_BT_RX_PRIO)); + CONFIG_BT_RX_STACK_SIZE, + co_tx_rx_thread, + K_PRIO_COOP(CONFIG_BT_RX_PRIO)); #else k_thread_create(&recv_thread_data, "recv_thread", - CONFIG_BT_RX_STACK_SIZE/*K_THREAD_STACK_SIZEOF(recv_thread_stack)*/, - recv_thread, - K_PRIO_COOP(CONFIG_BT_RX_PRIO)); + CONFIG_BT_RX_STACK_SIZE/*K_THREAD_STACK_SIZEOF(recv_thread_stack)*/, + recv_thread, + K_PRIO_COOP(CONFIG_BT_RX_PRIO)); #endif #else k_thread_create(&prio_recv_thread_data, prio_recv_thread_stack, - K_THREAD_STACK_SIZEOF(prio_recv_thread_stack), - prio_recv_thread, NULL, NULL, NULL, - K_PRIO_COOP(CONFIG_BT_CTLR_RX_PRIO), 0, K_NO_WAIT); + K_THREAD_STACK_SIZEOF(prio_recv_thread_stack), + prio_recv_thread, NULL, NULL, NULL, + K_PRIO_COOP(CONFIG_BT_CTLR_RX_PRIO), 0, K_NO_WAIT); #endif - BT_DBG("Success."); + BT_DBG("Success."); - return 0; + return 0; } void hci_driver_enque_recvq(struct net_buf *buf) @@ -537,28 +537,28 @@ void hci_driver_enque_recvq(struct net_buf *buf) } static const struct bt_hci_driver drv = { - .name = "Controller", - .bus = BT_HCI_DRIVER_BUS_VIRTUAL, - .open = hci_driver_open, - .send = hci_driver_send, + .name = "Controller", + .bus = BT_HCI_DRIVER_BUS_VIRTUAL, + .open = hci_driver_open, + .send = hci_driver_send, }; #if defined(BFLB_BLE) int hci_driver_init(void) { - bt_hci_driver_register(&drv); + bt_hci_driver_register(&drv); - return 0; + return 0; } #else static int _hci_driver_init(struct device *unused) { - ARG_UNUSED(unused); + ARG_UNUSED(unused); - bt_hci_driver_register(&drv); + bt_hci_driver_register(&drv); - return 0; + return 0; } //SYS_INIT(_hci_driver_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE); #endif diff --git a/components/network/ble/blestack/src/host/att.c b/components/network/ble/blestack/src/host/att.c index 63f27ca9..cc463fda 100644 --- a/components/network/ble/blestack/src/host/att.c +++ b/components/network/ble/blestack/src/host/att.c @@ -33,54 +33,54 @@ #define ATT_CHAN(_ch) CONTAINER_OF(_ch, struct bt_att, chan.chan) #define ATT_REQ(_node) CONTAINER_OF(_node, struct bt_att_req, node) -#define ATT_CMD_MASK 0x40 +#define ATT_CMD_MASK 0x40 -#define ATT_TIMEOUT K_SECONDS(30) +#define ATT_TIMEOUT K_SECONDS(30) typedef enum __packed { - ATT_COMMAND, - ATT_REQUEST, - ATT_RESPONSE, - ATT_NOTIFICATION, - ATT_CONFIRMATION, - ATT_INDICATION, - ATT_UNKNOWN, + ATT_COMMAND, + ATT_REQUEST, + ATT_RESPONSE, + ATT_NOTIFICATION, + ATT_CONFIRMATION, + ATT_INDICATION, + ATT_UNKNOWN, } att_type_t; static att_type_t att_op_get_type(u8_t op); #if CONFIG_BT_ATT_PREPARE_COUNT > 0 struct bt_attr_data { - u16_t handle; - u16_t offset; + u16_t handle; + u16_t offset; }; /* Pool for incoming ATT packets */ NET_BUF_POOL_DEFINE(prep_pool, CONFIG_BT_ATT_PREPARE_COUNT, BT_ATT_MTU, - sizeof(struct bt_attr_data), NULL); + sizeof(struct bt_attr_data), NULL); #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ enum { - ATT_PENDING_RSP, - ATT_PENDING_CFM, - ATT_DISCONNECTED, + ATT_PENDING_RSP, + ATT_PENDING_CFM, + ATT_DISCONNECTED, - /* Total number of flags - must be at the end of the enum */ - ATT_NUM_FLAGS, + /* Total number of flags - must be at the end of the enum */ + ATT_NUM_FLAGS, }; /* ATT channel specific context */ struct bt_att { - /* The channel this context is associated with */ - struct bt_l2cap_le_chan chan; - ATOMIC_DEFINE(flags, ATT_NUM_FLAGS); - struct bt_att_req *req; - sys_slist_t reqs; - struct k_delayed_work timeout_work; - struct k_sem tx_sem; - struct k_fifo tx_queue; + /* The channel this context is associated with */ + struct bt_l2cap_le_chan chan; + ATOMIC_DEFINE(flags, ATT_NUM_FLAGS); + struct bt_att_req *req; + sys_slist_t reqs; + struct k_delayed_work timeout_work; + struct k_sem tx_sem; + struct k_fifo tx_queue; #if CONFIG_BT_ATT_PREPARE_COUNT > 0 - struct k_fifo prep_queue; + struct k_fifo prep_queue; #endif }; @@ -93,1439 +93,1439 @@ static struct bt_att_req cancel; static void att_req_destroy(struct bt_att_req *req) { - BT_DBG("req %p", req); + BT_DBG("req %p", req); - if (req->buf) { - net_buf_unref(req->buf); - } + if (req->buf) { + net_buf_unref(req->buf); + } - if (req->destroy) { - req->destroy(req); - } + if (req->destroy) { + req->destroy(req); + } - (void)memset(req, 0, sizeof(*req)); + (void)memset(req, 0, sizeof(*req)); } static struct bt_att *att_get(struct bt_conn *conn) { - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_ATT); - __ASSERT(chan, "No ATT channel found"); + chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_ATT); + __ASSERT(chan, "No ATT channel found"); - return CONTAINER_OF(chan, struct bt_att, chan); + return CONTAINER_OF(chan, struct bt_att, chan); } static bt_conn_tx_cb_t att_cb(struct net_buf *buf); static int att_send(struct bt_conn *conn, struct net_buf *buf, - bt_conn_tx_cb_t cb, void *user_data) + bt_conn_tx_cb_t cb, void *user_data) { - struct bt_att_hdr *hdr; + struct bt_att_hdr *hdr; - hdr = (void *)buf->data; + hdr = (void *)buf->data; + + BT_DBG("code 0x%02x", hdr->code); - BT_DBG("code 0x%02x", hdr->code); - #if defined(CONFIG_BT_SMP) && defined(CONFIG_BT_SIGNING) - if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) { - int err; + if (hdr->code == BT_ATT_OP_SIGNED_WRITE_CMD) { + int err; - err = bt_smp_sign(conn, buf); - if (err) { - BT_ERR("Error signing data"); - net_buf_unref(buf); - return err; - } - } + err = bt_smp_sign(conn, buf); + if (err) { + BT_ERR("Error signing data"); + net_buf_unref(buf); + return err; + } + } #endif - return bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, - cb ? cb : att_cb(buf), - user_data); + return bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, + cb ? cb : att_cb(buf), + user_data); } void att_pdu_sent(struct bt_conn *conn, void *user_data) { - struct bt_att *att = att_get(conn); - struct net_buf *buf; + struct bt_att *att = att_get(conn); + struct net_buf *buf; - BT_DBG("conn %p att %p", conn, att); + BT_DBG("conn %p att %p", conn, att); - while ((buf = net_buf_get(&att->tx_queue, K_NO_WAIT))) { - /* Check if the queued buf is a request */ - if (att->req && att->req->buf == buf) { - /* Save request state so it can be resent */ - net_buf_simple_save(&att->req->buf->b, - &att->req->state); - } + while ((buf = net_buf_get(&att->tx_queue, K_NO_WAIT))) { + /* Check if the queued buf is a request */ + if (att->req && att->req->buf == buf) { + /* Save request state so it can be resent */ + net_buf_simple_save(&att->req->buf->b, + &att->req->state); + } - if (!att_send(conn, buf, NULL, NULL)) { - return; - } - } + if (!att_send(conn, buf, NULL, NULL)) { + return; + } + } - k_sem_give(&att->tx_sem); + k_sem_give(&att->tx_sem); } void att_cfm_sent(struct bt_conn *conn, void *user_data) { - struct bt_att *att = att_get(conn); + struct bt_att *att = att_get(conn); - BT_DBG("conn %p att %p", conn, att); + BT_DBG("conn %p att %p", conn, att); - if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { - atomic_clear_bit(att->flags, ATT_PENDING_CFM); - } + if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { + atomic_clear_bit(att->flags, ATT_PENDING_CFM); + } - att_pdu_sent(conn, user_data); + att_pdu_sent(conn, user_data); } void att_rsp_sent(struct bt_conn *conn, void *user_data) { - struct bt_att *att = att_get(conn); + struct bt_att *att = att_get(conn); - BT_DBG("conn %p att %p", conn, att); + BT_DBG("conn %p att %p", conn, att); - if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { - atomic_clear_bit(att->flags, ATT_PENDING_RSP); - } + if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { + atomic_clear_bit(att->flags, ATT_PENDING_RSP); + } - att_pdu_sent(conn, user_data); + att_pdu_sent(conn, user_data); } void att_req_sent(struct bt_conn *conn, void *user_data) { - struct bt_att *att = att_get(conn); + struct bt_att *att = att_get(conn); - BT_DBG("conn %p att %p att->req %p", conn, att, att->req); + BT_DBG("conn %p att %p att->req %p", conn, att, att->req); - /* Start timeout work */ - if (att->req) { - k_delayed_work_submit(&att->timeout_work, ATT_TIMEOUT); - } + /* Start timeout work */ + if (att->req) { + k_delayed_work_submit(&att->timeout_work, ATT_TIMEOUT); + } - att_pdu_sent(conn, user_data); + att_pdu_sent(conn, user_data); } static bt_conn_tx_cb_t att_cb(struct net_buf *buf) { - switch (att_op_get_type(buf->data[0])) { - case ATT_RESPONSE: - return att_rsp_sent; - case ATT_CONFIRMATION: - return att_cfm_sent; - case ATT_REQUEST: - case ATT_INDICATION: - return att_req_sent; - default: - return att_pdu_sent; - } + switch (att_op_get_type(buf->data[0])) { + case ATT_RESPONSE: + return att_rsp_sent; + case ATT_CONFIRMATION: + return att_cfm_sent; + case ATT_REQUEST: + case ATT_INDICATION: + return att_req_sent; + default: + return att_pdu_sent; + } } static void send_err_rsp(struct bt_conn *conn, u8_t req, u16_t handle, - u8_t err) + u8_t err) { - struct bt_att_error_rsp *rsp; - struct net_buf *buf; + struct bt_att_error_rsp *rsp; + struct net_buf *buf; - /* Ignore opcode 0x00 */ - if (!req) { - return; - } + /* Ignore opcode 0x00 */ + if (!req) { + return; + } - buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp)); - if (!buf) { - return; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_ERROR_RSP, sizeof(*rsp)); + if (!buf) { + return; + } - rsp = net_buf_add(buf, sizeof(*rsp)); - rsp->request = req; - rsp->handle = sys_cpu_to_le16(handle); - rsp->error = err; + rsp = net_buf_add(buf, sizeof(*rsp)); + rsp->request = req; + rsp->handle = sys_cpu_to_le16(handle); + rsp->error = err; - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL); } static u8_t att_mtu_req(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - struct bt_att_exchange_mtu_req *req; - struct bt_att_exchange_mtu_rsp *rsp; - struct net_buf *pdu; - u16_t mtu_client, mtu_server; + struct bt_conn *conn = att->chan.chan.conn; + struct bt_att_exchange_mtu_req *req; + struct bt_att_exchange_mtu_rsp *rsp; + struct net_buf *pdu; + u16_t mtu_client, mtu_server; - req = (void *)buf->data; + req = (void *)buf->data; - mtu_client = sys_le16_to_cpu(req->mtu); + mtu_client = sys_le16_to_cpu(req->mtu); - BT_DBG("Client MTU %u", mtu_client); + BT_DBG("Client MTU %u", mtu_client); - /* Check if MTU is valid */ - if (mtu_client < BT_ATT_DEFAULT_LE_MTU) { - return BT_ATT_ERR_INVALID_PDU; - } + /* Check if MTU is valid */ + if (mtu_client < BT_ATT_DEFAULT_LE_MTU) { + return BT_ATT_ERR_INVALID_PDU; + } - pdu = bt_att_create_pdu(conn, BT_ATT_OP_MTU_RSP, sizeof(*rsp)); - if (!pdu) { - return BT_ATT_ERR_UNLIKELY; - } + pdu = bt_att_create_pdu(conn, BT_ATT_OP_MTU_RSP, sizeof(*rsp)); + if (!pdu) { + return BT_ATT_ERR_UNLIKELY; + } - mtu_server = BT_ATT_MTU; + mtu_server = BT_ATT_MTU; - BT_DBG("Server MTU %u", mtu_server); + BT_DBG("Server MTU %u", mtu_server); - rsp = net_buf_add(pdu, sizeof(*rsp)); - rsp->mtu = sys_cpu_to_le16(mtu_server); + rsp = net_buf_add(pdu, sizeof(*rsp)); + rsp->mtu = sys_cpu_to_le16(mtu_server); - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, pdu, att_rsp_sent, NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, pdu, att_rsp_sent, NULL); - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484: - * - * A device's Exchange MTU Request shall contain the same MTU as the - * device's Exchange MTU Response (i.e. the MTU shall be symmetric). - */ - att->chan.rx.mtu = MIN(mtu_client, mtu_server); - att->chan.tx.mtu = att->chan.rx.mtu; + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484: + * + * A device's Exchange MTU Request shall contain the same MTU as the + * device's Exchange MTU Response (i.e. the MTU shall be symmetric). + */ + att->chan.rx.mtu = MIN(mtu_client, mtu_server); + att->chan.tx.mtu = att->chan.rx.mtu; - BT_DBG("Negotiated MTU %u", att->chan.rx.mtu); - return 0; + BT_DBG("Negotiated MTU %u", att->chan.rx.mtu); + return 0; } static inline bool att_is_connected(struct bt_att *att) { - return (att->chan.chan.conn->state != BT_CONN_CONNECTED || - !atomic_test_bit(att->flags, ATT_DISCONNECTED)); + return (att->chan.chan.conn->state != BT_CONN_CONNECTED || + !atomic_test_bit(att->flags, ATT_DISCONNECTED)); } static int att_send_req(struct bt_att *att, struct bt_att_req *req) { - int err; + int err; - __ASSERT_NO_MSG(req); - __ASSERT_NO_MSG(req->func); - __ASSERT_NO_MSG(!att->req); + __ASSERT_NO_MSG(req); + __ASSERT_NO_MSG(req->func); + __ASSERT_NO_MSG(!att->req); - BT_DBG("req %p", req); + BT_DBG("req %p", req); - att->req = req; + att->req = req; - if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) { - k_fifo_put(&att->tx_queue, req->buf); - return 0; - } + if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) { + k_fifo_put(&att->tx_queue, req->buf); + return 0; + } - /* Save request state so it can be resent */ - net_buf_simple_save(&req->buf->b, &req->state); + /* Save request state so it can be resent */ + net_buf_simple_save(&req->buf->b, &req->state); - /* Keep a reference for resending in case of an error */ - err = bt_l2cap_send_cb(att->chan.chan.conn, BT_L2CAP_CID_ATT, - net_buf_ref(req->buf), att_cb(req->buf), NULL); - if (err) { - net_buf_unref(req->buf); - req->buf = NULL; - return err; - } + /* Keep a reference for resending in case of an error */ + err = bt_l2cap_send_cb(att->chan.chan.conn, BT_L2CAP_CID_ATT, + net_buf_ref(req->buf), att_cb(req->buf), NULL); + if (err) { + net_buf_unref(req->buf); + req->buf = NULL; + return err; + } - return 0; + return 0; } static void att_process(struct bt_att *att) { - sys_snode_t *node; + sys_snode_t *node; - BT_DBG(""); + BT_DBG(""); - /* Pull next request from the list */ - node = sys_slist_get(&att->reqs); - if (!node) { - return; - } + /* Pull next request from the list */ + node = sys_slist_get(&att->reqs); + if (!node) { + return; + } - att_send_req(att, ATT_REQ(node)); + att_send_req(att, ATT_REQ(node)); } static u8_t att_handle_rsp(struct bt_att *att, void *pdu, u16_t len, u8_t err) { - bt_att_func_t func; + bt_att_func_t func; - BT_DBG("err 0x%02x len %u: %s", err, len, bt_hex(pdu, len)); + BT_DBG("err 0x%02x len %u: %s", err, len, bt_hex(pdu, len)); - /* Cancel timeout if ongoing */ - k_delayed_work_cancel(&att->timeout_work); + /* Cancel timeout if ongoing */ + k_delayed_work_cancel(&att->timeout_work); - if (!att->req) { - BT_WARN("No pending ATT request"); - goto process; - } + if (!att->req) { + BT_WARN("No pending ATT request"); + goto process; + } - /* Check if request has been cancelled */ - if (att->req == &cancel) { - att->req = NULL; - goto process; - } + /* Check if request has been cancelled */ + if (att->req == &cancel) { + att->req = NULL; + goto process; + } - /* Release original buffer */ - if (att->req->buf) { - net_buf_unref(att->req->buf); - att->req->buf = NULL; - } + /* Release original buffer */ + if (att->req->buf) { + net_buf_unref(att->req->buf); + att->req->buf = NULL; + } - /* Reset func so it can be reused by the callback */ - func = att->req->func; - att->req->func = NULL; + /* Reset func so it can be reused by the callback */ + func = att->req->func; + att->req->func = NULL; - func(att->chan.chan.conn, err, pdu, len, att->req); + func(att->chan.chan.conn, err, pdu, len, att->req); - /* Don't destroy if callback had reused the request */ - if (!att->req->func) { - att_req_destroy(att->req); - } + /* Don't destroy if callback had reused the request */ + if (!att->req->func) { + att_req_destroy(att->req); + } - att->req = NULL; + att->req = NULL; process: - /* Process pending requests */ - att_process(att); + /* Process pending requests */ + att_process(att); - return 0; + return 0; } #if defined(CONFIG_BT_GATT_CLIENT) static u8_t att_mtu_rsp(struct bt_att *att, struct net_buf *buf) { - struct bt_att_exchange_mtu_rsp *rsp; - u16_t mtu; + struct bt_att_exchange_mtu_rsp *rsp; + u16_t mtu; - if (!att) { - return 0; - } + if (!att) { + return 0; + } - rsp = (void *)buf->data; + rsp = (void *)buf->data; - mtu = sys_le16_to_cpu(rsp->mtu); + mtu = sys_le16_to_cpu(rsp->mtu); - BT_DBG("Server MTU %u", mtu); + BT_DBG("Server MTU %u", mtu); - /* Check if MTU is valid */ - if (mtu < BT_ATT_DEFAULT_LE_MTU) { - return att_handle_rsp(att, NULL, 0, BT_ATT_ERR_INVALID_PDU); - } + /* Check if MTU is valid */ + if (mtu < BT_ATT_DEFAULT_LE_MTU) { + return att_handle_rsp(att, NULL, 0, BT_ATT_ERR_INVALID_PDU); + } - att->chan.rx.mtu = MIN(mtu, BT_ATT_MTU); + att->chan.rx.mtu = MIN(mtu, BT_ATT_MTU); - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484: - * - * A device's Exchange MTU Request shall contain the same MTU as the - * device's Exchange MTU Response (i.e. the MTU shall be symmetric). - */ - att->chan.tx.mtu = att->chan.rx.mtu; + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 484: + * + * A device's Exchange MTU Request shall contain the same MTU as the + * device's Exchange MTU Response (i.e. the MTU shall be symmetric). + */ + att->chan.tx.mtu = att->chan.rx.mtu; - BT_DBG("Negotiated MTU %u", att->chan.rx.mtu); + BT_DBG("Negotiated MTU %u", att->chan.rx.mtu); - return att_handle_rsp(att, rsp, buf->len, 0); + return att_handle_rsp(att, rsp, buf->len, 0); } #endif /* CONFIG_BT_GATT_CLIENT */ static bool range_is_valid(u16_t start, u16_t end, u16_t *err) { - /* Handle 0 is invalid */ - if (!start || !end) { - if (err) { - *err = 0U; - } - return false; - } + /* Handle 0 is invalid */ + if (!start || !end) { + if (err) { + *err = 0U; + } + return false; + } - /* Check if range is valid */ - if (start > end) { - if (err) { - *err = start; - } - return false; - } + /* Check if range is valid */ + if (start > end) { + if (err) { + *err = start; + } + return false; + } - return true; + return true; } struct find_info_data { - struct bt_att *att; - struct net_buf *buf; - struct bt_att_find_info_rsp *rsp; - union { - struct bt_att_info_16 *info16; - struct bt_att_info_128 *info128; - }; + struct bt_att *att; + struct net_buf *buf; + struct bt_att_find_info_rsp *rsp; + union { + struct bt_att_info_16 *info16; + struct bt_att_info_128 *info128; + }; }; static u8_t find_info_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct find_info_data *data = user_data; - struct bt_att *att = data->att; + struct find_info_data *data = user_data; + struct bt_att *att = data->att; - BT_DBG("handle 0x%04x", attr->handle); + BT_DBG("handle 0x%04x", attr->handle); - /* Initialize rsp at first entry */ - if (!data->rsp) { - data->rsp = net_buf_add(data->buf, sizeof(*data->rsp)); - data->rsp->format = (attr->uuid->type == BT_UUID_TYPE_16) ? - BT_ATT_INFO_16 : BT_ATT_INFO_128; - } + /* Initialize rsp at first entry */ + if (!data->rsp) { + data->rsp = net_buf_add(data->buf, sizeof(*data->rsp)); + data->rsp->format = (attr->uuid->type == BT_UUID_TYPE_16) ? + BT_ATT_INFO_16 : BT_ATT_INFO_128; + } - switch (data->rsp->format) { - case BT_ATT_INFO_16: - if (attr->uuid->type != BT_UUID_TYPE_16) { - return BT_GATT_ITER_STOP; - } + switch (data->rsp->format) { + case BT_ATT_INFO_16: + if (attr->uuid->type != BT_UUID_TYPE_16) { + return BT_GATT_ITER_STOP; + } - /* Fast forward to next item position */ - data->info16 = net_buf_add(data->buf, sizeof(*data->info16)); - data->info16->handle = sys_cpu_to_le16(attr->handle); - data->info16->uuid = sys_cpu_to_le16(BT_UUID_16(attr->uuid)->val); + /* Fast forward to next item position */ + data->info16 = net_buf_add(data->buf, sizeof(*data->info16)); + data->info16->handle = sys_cpu_to_le16(attr->handle); + data->info16->uuid = sys_cpu_to_le16(BT_UUID_16(attr->uuid)->val); - if (att->chan.tx.mtu - data->buf->len > - sizeof(*data->info16)) { - return BT_GATT_ITER_CONTINUE; - } + if (att->chan.tx.mtu - data->buf->len > + sizeof(*data->info16)) { + return BT_GATT_ITER_CONTINUE; + } - break; - case BT_ATT_INFO_128: - if (attr->uuid->type != BT_UUID_TYPE_128) { - return BT_GATT_ITER_STOP; - } + break; + case BT_ATT_INFO_128: + if (attr->uuid->type != BT_UUID_TYPE_128) { + return BT_GATT_ITER_STOP; + } - /* Fast forward to next item position */ - data->info128 = net_buf_add(data->buf, sizeof(*data->info128)); - data->info128->handle = sys_cpu_to_le16(attr->handle); - memcpy(data->info128->uuid, BT_UUID_128(attr->uuid)->val, - sizeof(data->info128->uuid)); + /* Fast forward to next item position */ + data->info128 = net_buf_add(data->buf, sizeof(*data->info128)); + data->info128->handle = sys_cpu_to_le16(attr->handle); + memcpy(data->info128->uuid, BT_UUID_128(attr->uuid)->val, + sizeof(data->info128->uuid)); - if (att->chan.tx.mtu - data->buf->len > - sizeof(*data->info128)) { - return BT_GATT_ITER_CONTINUE; - } - } + if (att->chan.tx.mtu - data->buf->len > + sizeof(*data->info128)) { + return BT_GATT_ITER_CONTINUE; + } + } - return BT_GATT_ITER_STOP; + return BT_GATT_ITER_STOP; } static u8_t att_find_info_rsp(struct bt_att *att, u16_t start_handle, - u16_t end_handle) + u16_t end_handle) { - struct bt_conn *conn = att->chan.chan.conn; - struct find_info_data data; + struct bt_conn *conn = att->chan.chan.conn; + struct find_info_data data; - (void)memset(&data, 0, sizeof(data)); + (void)memset(&data, 0, sizeof(data)); - data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_RSP, 0); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } + data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_RSP, 0); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } - data.att = att; - bt_gatt_foreach_attr(start_handle, end_handle, find_info_cb, &data); + data.att = att; + bt_gatt_foreach_attr(start_handle, end_handle, find_info_cb, &data); - if (!data.rsp) { - net_buf_unref(data.buf); - /* Respond since handle is set */ - send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, start_handle, - BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); - return 0; - } + if (!data.rsp) { + net_buf_unref(data.buf); + /* Respond since handle is set */ + send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, start_handle, + BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); + return 0; + } - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, - NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, + NULL); - return 0; + return 0; } static u8_t att_find_info_req(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - struct bt_att_find_info_req *req; - u16_t start_handle, end_handle, err_handle; + struct bt_conn *conn = att->chan.chan.conn; + struct bt_att_find_info_req *req; + u16_t start_handle, end_handle, err_handle; - req = (void *)buf->data; + req = (void *)buf->data; - start_handle = sys_le16_to_cpu(req->start_handle); - end_handle = sys_le16_to_cpu(req->end_handle); + start_handle = sys_le16_to_cpu(req->start_handle); + end_handle = sys_le16_to_cpu(req->end_handle); - BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, - end_handle); + BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, + end_handle); - if (!range_is_valid(start_handle, end_handle, &err_handle)) { - send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, err_handle, - BT_ATT_ERR_INVALID_HANDLE); - return 0; - } + if (!range_is_valid(start_handle, end_handle, &err_handle)) { + send_err_rsp(conn, BT_ATT_OP_FIND_INFO_REQ, err_handle, + BT_ATT_ERR_INVALID_HANDLE); + return 0; + } - return att_find_info_rsp(att, start_handle, end_handle); + return att_find_info_rsp(att, start_handle, end_handle); } struct find_type_data { - struct bt_att *att; - struct net_buf *buf; - struct bt_att_handle_group *group; - const void *value; - u8_t value_len; - u8_t err; + struct bt_att *att; + struct net_buf *buf; + struct bt_att_handle_group *group; + const void *value; + u8_t value_len; + u8_t err; }; static u8_t find_type_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct find_type_data *data = user_data; - struct bt_att *att = data->att; - struct bt_conn *conn = att->chan.chan.conn; - int read; - u8_t uuid[16]; + struct find_type_data *data = user_data; + struct bt_att *att = data->att; + struct bt_conn *conn = att->chan.chan.conn; + int read; + u8_t uuid[16]; - /* Skip secondary services */ - if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { - goto skip; - } + /* Skip secondary services */ + if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { + goto skip; + } - /* Update group end_handle if not a primary service */ - if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY)) { - if (data->group && - attr->handle > sys_le16_to_cpu(data->group->end_handle)) { - data->group->end_handle = sys_cpu_to_le16(attr->handle); - } - return BT_GATT_ITER_CONTINUE; - } + /* Update group end_handle if not a primary service */ + if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY)) { + if (data->group && + attr->handle > sys_le16_to_cpu(data->group->end_handle)) { + data->group->end_handle = sys_cpu_to_le16(attr->handle); + } + return BT_GATT_ITER_CONTINUE; + } - BT_DBG("handle 0x%04x", attr->handle); + BT_DBG("handle 0x%04x", attr->handle); - /* stop if there is no space left */ - if (att->chan.tx.mtu - data->buf->len < sizeof(*data->group)) { - return BT_GATT_ITER_STOP; - } + /* stop if there is no space left */ + if (att->chan.tx.mtu - data->buf->len < sizeof(*data->group)) { + return BT_GATT_ITER_STOP; + } - /* Read attribute value and store in the buffer */ - read = attr->read(conn, attr, uuid, sizeof(uuid), 0); - if (read < 0) { - /* - * Since we don't know if it is the service with requested UUID, - * we cannot respond with an error to this request. - */ - goto skip; - } + /* Read attribute value and store in the buffer */ + read = attr->read(conn, attr, uuid, sizeof(uuid), 0); + if (read < 0) { + /* + * Since we don't know if it is the service with requested UUID, + * we cannot respond with an error to this request. + */ + goto skip; + } - /* Check if data matches */ - if (read != data->value_len) { - /* Use bt_uuid_cmp() to compare UUIDs of different form. */ - struct bt_uuid_128 ref_uuid; - struct bt_uuid_128 recvd_uuid; + /* Check if data matches */ + if (read != data->value_len) { + /* Use bt_uuid_cmp() to compare UUIDs of different form. */ + struct bt_uuid_128 ref_uuid; + struct bt_uuid_128 recvd_uuid; - if (!bt_uuid_create(&recvd_uuid.uuid, data->value, data->value_len)) { - BT_WARN("Unable to create UUID: size %u", data->value_len); - goto skip; - } - if (!bt_uuid_create(&ref_uuid.uuid, uuid, read)) { - BT_WARN("Unable to create UUID: size %d", read); - goto skip; - } - if (bt_uuid_cmp(&recvd_uuid.uuid, &ref_uuid.uuid)) { - goto skip; - } - } else if (memcmp(data->value, uuid, read)) { - goto skip; - } + if (!bt_uuid_create(&recvd_uuid.uuid, data->value, data->value_len)) { + BT_WARN("Unable to create UUID: size %u", data->value_len); + goto skip; + } + if (!bt_uuid_create(&ref_uuid.uuid, uuid, read)) { + BT_WARN("Unable to create UUID: size %d", read); + goto skip; + } + if (bt_uuid_cmp(&recvd_uuid.uuid, &ref_uuid.uuid)) { + goto skip; + } + } else if (memcmp(data->value, uuid, read)) { + goto skip; + } - /* If service has been found, error should be cleared */ - data->err = 0x00; + /* If service has been found, error should be cleared */ + data->err = 0x00; - /* Fast forward to next item position */ - data->group = net_buf_add(data->buf, sizeof(*data->group)); - data->group->start_handle = sys_cpu_to_le16(attr->handle); - data->group->end_handle = sys_cpu_to_le16(attr->handle); + /* Fast forward to next item position */ + data->group = net_buf_add(data->buf, sizeof(*data->group)); + data->group->start_handle = sys_cpu_to_le16(attr->handle); + data->group->end_handle = sys_cpu_to_le16(attr->handle); - /* continue to find the end_handle */ - return BT_GATT_ITER_CONTINUE; + /* continue to find the end_handle */ + return BT_GATT_ITER_CONTINUE; skip: - data->group = NULL; - return BT_GATT_ITER_CONTINUE; + data->group = NULL; + return BT_GATT_ITER_CONTINUE; } static u8_t att_find_type_rsp(struct bt_att *att, u16_t start_handle, - u16_t end_handle, const void *value, - u8_t value_len) + u16_t end_handle, const void *value, + u8_t value_len) { - struct bt_conn *conn = att->chan.chan.conn; - struct find_type_data data; + struct bt_conn *conn = att->chan.chan.conn; + struct find_type_data data; - (void)memset(&data, 0, sizeof(data)); + (void)memset(&data, 0, sizeof(data)); - data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_RSP, 0); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } + data.buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_RSP, 0); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } - data.att = att; - data.group = NULL; - data.value = value; - data.value_len = value_len; + data.att = att; + data.group = NULL; + data.value = value; + data.value_len = value_len; - /* Pre-set error in case no service will be found */ - data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND; + /* Pre-set error in case no service will be found */ + data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND; - bt_gatt_foreach_attr(start_handle, end_handle, find_type_cb, &data); + bt_gatt_foreach_attr(start_handle, end_handle, find_type_cb, &data); - /* If error has not been cleared, no service has been found */ - if (data.err) { - net_buf_unref(data.buf); - /* Respond since handle is set */ - send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, - data.err); + /* If error has not been cleared, no service has been found */ + if (data.err) { + net_buf_unref(data.buf); + /* Respond since handle is set */ + send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, + data.err); - #if defined(CONFIG_BT_STACK_PTS) - /*PTS sends a request to the iut discover all primary services it contains */ - if(event_flag == att_find_by_type_value_ind){ - BT_PTS("rsp err : [%d] start_handle = [0x%04x]\r\n",data.err,start_handle); - } - #endif - return 0; - } + #if defined(CONFIG_BT_STACK_PTS) + /*PTS sends a request to the iut discover all primary services it contains */ + if(event_flag == att_find_by_type_value_ind){ + BT_PTS("rsp err : [%d] start_handle = [0x%04x]\r\n",data.err,start_handle); + } + #endif + return 0; + } - #if defined(CONFIG_BT_STACK_PTS) - /*when PTS sends a request to the iut discover all primary services it contains, set event flag - * to @att_find_by_type_value_ind make it easy for the user to check whether the messages is correct in the console. - */ - if(event_flag == att_find_by_type_value_ind){ - u8_t i = 0; - u8_t *req_val = (u8_t *)data.value; - u8_t src[20]; - - (void)memcpy(src, req_val, data.value_len); + #if defined(CONFIG_BT_STACK_PTS) + /*when PTS sends a request to the iut discover all primary services it contains, set event flag + * to @att_find_by_type_value_ind make it easy for the user to check whether the messages is correct in the console. + */ + if(event_flag == att_find_by_type_value_ind){ + u8_t i = 0; + u8_t *req_val = (u8_t *)data.value; + u8_t src[20]; + + (void)memcpy(src, req_val, data.value_len); BT_PTS("uuid = ["); for(i=0;idata[1] | data.buf->data[2] << 8, - data.buf->data[3] | data.buf->data[4] << 8); - - } - #endif - - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, - NULL); - return 0; + BT_PTS("start_handle = [0x%04x] end_handle = [0x%04x]\r\n", data.buf->data[1] | data.buf->data[2] << 8, + data.buf->data[3] | data.buf->data[4] << 8); + + } + #endif + + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, + NULL); + + return 0; } static u8_t att_find_type_req(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - struct bt_att_find_type_req *req; - u16_t start_handle, end_handle, err_handle, type; - u8_t *value; + struct bt_conn *conn = att->chan.chan.conn; + struct bt_att_find_type_req *req; + u16_t start_handle, end_handle, err_handle, type; + u8_t *value; - req = net_buf_pull_mem(buf, sizeof(*req)); + req = net_buf_pull_mem(buf, sizeof(*req)); - start_handle = sys_le16_to_cpu(req->start_handle); - end_handle = sys_le16_to_cpu(req->end_handle); - type = sys_le16_to_cpu(req->type); - value = buf->data; + start_handle = sys_le16_to_cpu(req->start_handle); + end_handle = sys_le16_to_cpu(req->end_handle); + type = sys_le16_to_cpu(req->type); + value = buf->data; - BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle, - end_handle, type); + BT_DBG("start_handle 0x%04x end_handle 0x%04x type %u", start_handle, + end_handle, type); - if (!range_is_valid(start_handle, end_handle, &err_handle)) { - send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, err_handle, - BT_ATT_ERR_INVALID_HANDLE); - return 0; - } + if (!range_is_valid(start_handle, end_handle, &err_handle)) { + send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, err_handle, + BT_ATT_ERR_INVALID_HANDLE); + return 0; + } - /* The Attribute Protocol Find By Type Value Request shall be used with - * the Attribute Type parameter set to the UUID for "Primary Service" - * and the Attribute Value set to the 16-bit Bluetooth UUID or 128-bit - * UUID for the specific primary service. - */ - if (bt_uuid_cmp(BT_UUID_DECLARE_16(type), BT_UUID_GATT_PRIMARY)) { - send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, - BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); - return 0; - } + /* The Attribute Protocol Find By Type Value Request shall be used with + * the Attribute Type parameter set to the UUID for "Primary Service" + * and the Attribute Value set to the 16-bit Bluetooth UUID or 128-bit + * UUID for the specific primary service. + */ + if (bt_uuid_cmp(BT_UUID_DECLARE_16(type), BT_UUID_GATT_PRIMARY)) { + send_err_rsp(conn, BT_ATT_OP_FIND_TYPE_REQ, start_handle, + BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); + return 0; + } - return att_find_type_rsp(att, start_handle, end_handle, value, - buf->len); + return att_find_type_rsp(att, start_handle, end_handle, value, + buf->len); } static u8_t err_to_att(int err) { - BT_DBG("%d", err); + BT_DBG("%d", err); - if (err < 0 && err >= -0xff) { - return -err; - } + if (err < 0 && err >= -0xff) { + return -err; + } - return BT_ATT_ERR_UNLIKELY; + return BT_ATT_ERR_UNLIKELY; } struct read_type_data { - struct bt_att *att; - struct bt_uuid *uuid; - struct net_buf *buf; - struct bt_att_read_type_rsp *rsp; - struct bt_att_data *item; - u8_t err; + struct bt_att *att; + struct bt_uuid *uuid; + struct net_buf *buf; + struct bt_att_read_type_rsp *rsp; + struct bt_att_data *item; + u8_t err; }; static u8_t read_type_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct read_type_data *data = user_data; - struct bt_att *att = data->att; - struct bt_conn *conn = att->chan.chan.conn; - int read; + struct read_type_data *data = user_data; + struct bt_att *att = data->att; + struct bt_conn *conn = att->chan.chan.conn; + int read; - /* Skip if doesn't match */ - if (bt_uuid_cmp(attr->uuid, data->uuid)) { - return BT_GATT_ITER_CONTINUE; - } + /* Skip if doesn't match */ + if (bt_uuid_cmp(attr->uuid, data->uuid)) { + return BT_GATT_ITER_CONTINUE; + } - BT_DBG("handle 0x%04x", attr->handle); + BT_DBG("handle 0x%04x", attr->handle); - /* - * If an attribute in the set of requested attributes would cause an - * Error Response then this attribute cannot be included in a - * Read By Type Response and the attributes before this attribute - * shall be returned - * - * If the first attribute in the set of requested attributes would - * cause an Error Response then no other attributes in the requested - * attributes can be considered. - */ - data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK); - if (data->err) { - if (data->rsp->len) { - data->err = 0x00; - } - return BT_GATT_ITER_STOP; - } + /* + * If an attribute in the set of requested attributes would cause an + * Error Response then this attribute cannot be included in a + * Read By Type Response and the attributes before this attribute + * shall be returned + * + * If the first attribute in the set of requested attributes would + * cause an Error Response then no other attributes in the requested + * attributes can be considered. + */ + data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK); + if (data->err) { + if (data->rsp->len) { + data->err = 0x00; + } + return BT_GATT_ITER_STOP; + } - /* - * If any attribute is founded in handle range it means that error - * should be changed from pre-set: attr not found error to no error. - */ - data->err = 0x00; + /* + * If any attribute is founded in handle range it means that error + * should be changed from pre-set: attr not found error to no error. + */ + data->err = 0x00; - /* Fast forward to next item position */ - data->item = net_buf_add(data->buf, sizeof(*data->item)); - data->item->handle = sys_cpu_to_le16(attr->handle); + /* Fast forward to next item position */ + data->item = net_buf_add(data->buf, sizeof(*data->item)); + data->item->handle = sys_cpu_to_le16(attr->handle); - /* Read attribute value and store in the buffer */ - read = attr->read(conn, attr, data->buf->data + data->buf->len, - att->chan.tx.mtu - data->buf->len, 0); - if (read < 0) { - data->err = err_to_att(read); - return BT_GATT_ITER_STOP; - } + /* Read attribute value and store in the buffer */ + read = attr->read(conn, attr, data->buf->data + data->buf->len, + att->chan.tx.mtu - data->buf->len, 0); + if (read < 0) { + data->err = err_to_att(read); + return BT_GATT_ITER_STOP; + } - if (!data->rsp->len) { - /* Set len to be the first item found */ - data->rsp->len = read + sizeof(*data->item); - } else if (data->rsp->len != read + sizeof(*data->item)) { - /* All items should have the same size */ - data->buf->len -= sizeof(*data->item); - return BT_GATT_ITER_STOP; - } + if (!data->rsp->len) { + /* Set len to be the first item found */ + data->rsp->len = read + sizeof(*data->item); + } else if (data->rsp->len != read + sizeof(*data->item)) { + /* All items should have the same size */ + data->buf->len -= sizeof(*data->item); + return BT_GATT_ITER_STOP; + } - net_buf_add(data->buf, read); + net_buf_add(data->buf, read); - /* return true only if there are still space for more items */ - return att->chan.tx.mtu - data->buf->len > data->rsp->len ? - BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP; + /* return true only if there are still space for more items */ + return att->chan.tx.mtu - data->buf->len > data->rsp->len ? + BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP; } static u8_t att_read_type_rsp(struct bt_att *att, struct bt_uuid *uuid, - u16_t start_handle, u16_t end_handle) + u16_t start_handle, u16_t end_handle) { - struct bt_conn *conn = att->chan.chan.conn; - struct read_type_data data; - - (void)memset(&data, 0, sizeof(data)); + struct bt_conn *conn = att->chan.chan.conn; + struct read_type_data data; - data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_RSP, - sizeof(*data.rsp)); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } + (void)memset(&data, 0, sizeof(data)); - data.att = att; - data.uuid = uuid; - data.rsp = net_buf_add(data.buf, sizeof(*data.rsp)); - data.rsp->len = 0U; + data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_RSP, + sizeof(*data.rsp)); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } - /* Pre-set error if no attr will be found in handle */ - data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND; + data.att = att; + data.uuid = uuid; + data.rsp = net_buf_add(data.buf, sizeof(*data.rsp)); + data.rsp->len = 0U; - bt_gatt_foreach_attr(start_handle, end_handle, read_type_cb, &data); + /* Pre-set error if no attr will be found in handle */ + data.err = BT_ATT_ERR_ATTRIBUTE_NOT_FOUND; - if (data.err) { - net_buf_unref(data.buf); - /* Response here since handle is set */ - send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, start_handle, - data.err); - return 0; - } + bt_gatt_foreach_attr(start_handle, end_handle, read_type_cb, &data); - #if defined(CONFIG_BT_STACK_PTS) - if(event_flag == att_read_by_type_ind) - BT_PTS("handle : [0x%04x]\r\n",data.rsp->data->handle); - #endif + if (data.err) { + net_buf_unref(data.buf); + /* Response here since handle is set */ + send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, start_handle, + data.err); + return 0; + } - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, - NULL); + #if defined(CONFIG_BT_STACK_PTS) + if(event_flag == att_read_by_type_ind) + BT_PTS("handle : [0x%04x]\r\n",data.rsp->data->handle); + #endif - return 0; + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, + NULL); + + return 0; } static u8_t att_read_type_req(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - struct bt_att_read_type_req *req; - u16_t start_handle, end_handle, err_handle; - union { - struct bt_uuid uuid; - struct bt_uuid_16 u16; - struct bt_uuid_128 u128; - } u; - u8_t uuid_len = buf->len - sizeof(*req); + struct bt_conn *conn = att->chan.chan.conn; + struct bt_att_read_type_req *req; + u16_t start_handle, end_handle, err_handle; + union { + struct bt_uuid uuid; + struct bt_uuid_16 u16; + struct bt_uuid_128 u128; + } u; + u8_t uuid_len = buf->len - sizeof(*req); - /* Type can only be UUID16 or UUID128 */ - if (uuid_len != 2 && uuid_len != 16) { - return BT_ATT_ERR_INVALID_PDU; - } + /* Type can only be UUID16 or UUID128 */ + if (uuid_len != 2 && uuid_len != 16) { + return BT_ATT_ERR_INVALID_PDU; + } - req = net_buf_pull_mem(buf, sizeof(*req)); + req = net_buf_pull_mem(buf, sizeof(*req)); - start_handle = sys_le16_to_cpu(req->start_handle); - end_handle = sys_le16_to_cpu(req->end_handle); - if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) { - return BT_ATT_ERR_UNLIKELY; - } + start_handle = sys_le16_to_cpu(req->start_handle); + end_handle = sys_le16_to_cpu(req->end_handle); + if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) { + return BT_ATT_ERR_UNLIKELY; + } - BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", - start_handle, end_handle, bt_uuid_str(&u.uuid)); + BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", + start_handle, end_handle, bt_uuid_str(&u.uuid)); - if (!range_is_valid(start_handle, end_handle, &err_handle)) { - send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, err_handle, - BT_ATT_ERR_INVALID_HANDLE); - return 0; - } + if (!range_is_valid(start_handle, end_handle, &err_handle)) { + send_err_rsp(conn, BT_ATT_OP_READ_TYPE_REQ, err_handle, + BT_ATT_ERR_INVALID_HANDLE); + return 0; + } - return att_read_type_rsp(att, &u.uuid, start_handle, end_handle); + return att_read_type_rsp(att, &u.uuid, start_handle, end_handle); } struct read_data { - struct bt_att *att; - u16_t offset; - struct net_buf *buf; - struct bt_att_read_rsp *rsp; - u8_t err; + struct bt_att *att; + u16_t offset; + struct net_buf *buf; + struct bt_att_read_rsp *rsp; + u8_t err; }; static u8_t read_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct read_data *data = user_data; - struct bt_att *att = data->att; - struct bt_conn *conn = att->chan.chan.conn; - int read; + struct read_data *data = user_data; + struct bt_att *att = data->att; + struct bt_conn *conn = att->chan.chan.conn; + int read; - BT_DBG("handle 0x%04x", attr->handle); + BT_DBG("handle 0x%04x", attr->handle); - data->rsp = net_buf_add(data->buf, sizeof(*data->rsp)); + data->rsp = net_buf_add(data->buf, sizeof(*data->rsp)); - /* - * If any attribute is founded in handle range it means that error - * should be changed from pre-set: invalid handle error to no error. - */ - data->err = 0x00; + /* + * If any attribute is founded in handle range it means that error + * should be changed from pre-set: invalid handle error to no error. + */ + data->err = 0x00; - /* Check attribute permissions */ - data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK); - if (data->err) { - return BT_GATT_ITER_STOP; - } + /* Check attribute permissions */ + data->err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_READ_MASK); + if (data->err) { + return BT_GATT_ITER_STOP; + } - /* Read attribute value and store in the buffer */ - read = attr->read(conn, attr, data->buf->data + data->buf->len, - att->chan.tx.mtu - data->buf->len, data->offset); - if (read < 0) { - data->err = err_to_att(read); - return BT_GATT_ITER_STOP; - } + /* Read attribute value and store in the buffer */ + read = attr->read(conn, attr, data->buf->data + data->buf->len, + att->chan.tx.mtu - data->buf->len, data->offset); + if (read < 0) { + data->err = err_to_att(read); + return BT_GATT_ITER_STOP; + } - net_buf_add(data->buf, read); + net_buf_add(data->buf, read); - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static u8_t att_read_rsp(struct bt_att *att, u8_t op, u8_t rsp, u16_t handle, - u16_t offset) + u16_t offset) { - struct bt_conn *conn = att->chan.chan.conn; - struct read_data data; + struct bt_conn *conn = att->chan.chan.conn; + struct read_data data; - if (!bt_gatt_change_aware(conn, true)) { - return BT_ATT_ERR_DB_OUT_OF_SYNC; - } + if (!bt_gatt_change_aware(conn, true)) { + return BT_ATT_ERR_DB_OUT_OF_SYNC; + } - if (!handle) { - return BT_ATT_ERR_INVALID_HANDLE; - } + if (!handle) { + return BT_ATT_ERR_INVALID_HANDLE; + } - (void)memset(&data, 0, sizeof(data)); + (void)memset(&data, 0, sizeof(data)); - data.buf = bt_att_create_pdu(conn, rsp, 0); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } + data.buf = bt_att_create_pdu(conn, rsp, 0); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } - data.att = att; - data.offset = offset; + data.att = att; + data.offset = offset; - /* Pre-set error if no attr will be found in handle */ - data.err = BT_ATT_ERR_INVALID_HANDLE; + /* Pre-set error if no attr will be found in handle */ + data.err = BT_ATT_ERR_INVALID_HANDLE; - bt_gatt_foreach_attr(handle, handle, read_cb, &data); + bt_gatt_foreach_attr(handle, handle, read_cb, &data); - /* In case of error discard data and respond with an error */ - if (data.err) { - net_buf_unref(data.buf); - /* Respond here since handle is set */ - send_err_rsp(conn, op, handle, data.err); - return 0; - } + /* In case of error discard data and respond with an error */ + if (data.err) { + net_buf_unref(data.buf); + /* Respond here since handle is set */ + send_err_rsp(conn, op, handle, data.err); + return 0; + } - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, - NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, + NULL); - return 0; + return 0; } static u8_t att_read_req(struct bt_att *att, struct net_buf *buf) { - struct bt_att_read_req *req; - u16_t handle; + struct bt_att_read_req *req; + u16_t handle; - req = (void *)buf->data; + req = (void *)buf->data; - handle = sys_le16_to_cpu(req->handle); + handle = sys_le16_to_cpu(req->handle); - BT_DBG("handle 0x%04x", handle); + BT_DBG("handle 0x%04x", handle); - return att_read_rsp(att, BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP, - handle, 0); + return att_read_rsp(att, BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP, + handle, 0); } static u8_t att_read_blob_req(struct bt_att *att, struct net_buf *buf) { - struct bt_att_read_blob_req *req; - u16_t handle, offset; + struct bt_att_read_blob_req *req; + u16_t handle, offset; - req = (void *)buf->data; + req = (void *)buf->data; - handle = sys_le16_to_cpu(req->handle); - offset = sys_le16_to_cpu(req->offset); + handle = sys_le16_to_cpu(req->handle); + offset = sys_le16_to_cpu(req->offset); - BT_DBG("handle 0x%04x offset %u", handle, offset); + BT_DBG("handle 0x%04x offset %u", handle, offset); - return att_read_rsp(att, BT_ATT_OP_READ_BLOB_REQ, - BT_ATT_OP_READ_BLOB_RSP, handle, offset); + return att_read_rsp(att, BT_ATT_OP_READ_BLOB_REQ, + BT_ATT_OP_READ_BLOB_RSP, handle, offset); } #if defined(CONFIG_BT_GATT_READ_MULTIPLE) static u8_t att_read_mult_req(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - struct read_data data; - u16_t handle; + struct bt_conn *conn = att->chan.chan.conn; + struct read_data data; + u16_t handle; - (void)memset(&data, 0, sizeof(data)); + (void)memset(&data, 0, sizeof(data)); - data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_RSP, 0); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } + data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_RSP, 0); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } - data.att = att; + data.att = att; - while (buf->len >= sizeof(u16_t)) { - handle = net_buf_pull_le16(buf); + while (buf->len >= sizeof(u16_t)) { + handle = net_buf_pull_le16(buf); - BT_DBG("handle 0x%04x ", handle); + BT_DBG("handle 0x%04x ", handle); - /* An Error Response shall be sent by the server in response to - * the Read Multiple Request [....] if a read operation is not - * permitted on any of the Characteristic Values. - * - * If handle is not valid then return invalid handle error. - * If handle is found error will be cleared by read_cb. - */ - data.err = BT_ATT_ERR_INVALID_HANDLE; + /* An Error Response shall be sent by the server in response to + * the Read Multiple Request [....] if a read operation is not + * permitted on any of the Characteristic Values. + * + * If handle is not valid then return invalid handle error. + * If handle is found error will be cleared by read_cb. + */ + data.err = BT_ATT_ERR_INVALID_HANDLE; - bt_gatt_foreach_attr(handle, handle, read_cb, &data); + bt_gatt_foreach_attr(handle, handle, read_cb, &data); - /* Stop reading in case of error */ - if (data.err) { - net_buf_unref(data.buf); - /* Respond here since handle is set */ - send_err_rsp(conn, BT_ATT_OP_READ_MULT_REQ, handle, - data.err); - return 0; - } - } + /* Stop reading in case of error */ + if (data.err) { + net_buf_unref(data.buf); + /* Respond here since handle is set */ + send_err_rsp(conn, BT_ATT_OP_READ_MULT_REQ, handle, + data.err); + return 0; + } + } - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, - NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, + NULL); - return 0; + return 0; } #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ struct read_group_data { - struct bt_att *att; - struct bt_uuid *uuid; - struct net_buf *buf; - struct bt_att_read_group_rsp *rsp; - struct bt_att_group_data *group; + struct bt_att *att; + struct bt_uuid *uuid; + struct net_buf *buf; + struct bt_att_read_group_rsp *rsp; + struct bt_att_group_data *group; }; static u8_t read_group_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct read_group_data *data = user_data; - struct bt_att *att = data->att; - struct bt_conn *conn = att->chan.chan.conn; - int read; + struct read_group_data *data = user_data; + struct bt_att *att = data->att; + struct bt_conn *conn = att->chan.chan.conn; + int read; - /* Update group end_handle if attribute is not a service */ - if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) && - bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { - if (data->group && - attr->handle > sys_le16_to_cpu(data->group->end_handle)) { - data->group->end_handle = sys_cpu_to_le16(attr->handle); - - } - return BT_GATT_ITER_CONTINUE; - } + /* Update group end_handle if attribute is not a service */ + if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) && + bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { + if (data->group && + attr->handle > sys_le16_to_cpu(data->group->end_handle)) { + data->group->end_handle = sys_cpu_to_le16(attr->handle); - /* If Group Type don't match skip */ - if (bt_uuid_cmp(attr->uuid, data->uuid)) { - data->group = NULL; - return BT_GATT_ITER_CONTINUE; - } + } + return BT_GATT_ITER_CONTINUE; + } - BT_DBG("handle 0x%04x", attr->handle); + /* If Group Type don't match skip */ + if (bt_uuid_cmp(attr->uuid, data->uuid)) { + data->group = NULL; + return BT_GATT_ITER_CONTINUE; + } - /* Stop if there is no space left */ - if (data->rsp->len && - att->chan.tx.mtu - data->buf->len < data->rsp->len) { - return BT_GATT_ITER_STOP; - } + BT_DBG("handle 0x%04x", attr->handle); - /* Fast forward to next group position */ - data->group = net_buf_add(data->buf, sizeof(*data->group)); + /* Stop if there is no space left */ + if (data->rsp->len && + att->chan.tx.mtu - data->buf->len < data->rsp->len) { + return BT_GATT_ITER_STOP; + } - /* Initialize group handle range */ - data->group->start_handle = sys_cpu_to_le16(attr->handle); - data->group->end_handle = sys_cpu_to_le16(attr->handle); + /* Fast forward to next group position */ + data->group = net_buf_add(data->buf, sizeof(*data->group)); - - /* Read attribute value and store in the buffer */ - read = attr->read(conn, attr, data->buf->data + data->buf->len, - att->chan.tx.mtu - data->buf->len, 0); - if (read < 0) { - /* TODO: Handle read errors */ - return BT_GATT_ITER_STOP; - } + /* Initialize group handle range */ + data->group->start_handle = sys_cpu_to_le16(attr->handle); + data->group->end_handle = sys_cpu_to_le16(attr->handle); - if (!data->rsp->len) { - /* Set len to be the first group found */ - data->rsp->len = read + sizeof(*data->group); - } else if (data->rsp->len != read + sizeof(*data->group)) { - /* All groups entries should have the same size */ - data->buf->len -= sizeof(*data->group); - return false; - } - net_buf_add(data->buf, read); + /* Read attribute value and store in the buffer */ + read = attr->read(conn, attr, data->buf->data + data->buf->len, + att->chan.tx.mtu - data->buf->len, 0); + if (read < 0) { + /* TODO: Handle read errors */ + return BT_GATT_ITER_STOP; + } - /* Continue to find the end handle */ - return BT_GATT_ITER_CONTINUE; + if (!data->rsp->len) { + /* Set len to be the first group found */ + data->rsp->len = read + sizeof(*data->group); + } else if (data->rsp->len != read + sizeof(*data->group)) { + /* All groups entries should have the same size */ + data->buf->len -= sizeof(*data->group); + return false; + } + + net_buf_add(data->buf, read); + + /* Continue to find the end handle */ + return BT_GATT_ITER_CONTINUE; } static u8_t att_read_group_rsp(struct bt_att *att, struct bt_uuid *uuid, - u16_t start_handle, u16_t end_handle) + u16_t start_handle, u16_t end_handle) { - struct bt_conn *conn = att->chan.chan.conn; - struct read_group_data data; + struct bt_conn *conn = att->chan.chan.conn; + struct read_group_data data; - (void)memset(&data, 0, sizeof(data)); + (void)memset(&data, 0, sizeof(data)); - data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_RSP, - sizeof(*data.rsp)); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } + data.buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_RSP, + sizeof(*data.rsp)); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } - data.att = att; - data.uuid = uuid; - data.rsp = net_buf_add(data.buf, sizeof(*data.rsp)); - data.rsp->len = 0U; - data.group = NULL; + data.att = att; + data.uuid = uuid; + data.rsp = net_buf_add(data.buf, sizeof(*data.rsp)); + data.rsp->len = 0U; + data.group = NULL; - bt_gatt_foreach_attr(start_handle, end_handle, read_group_cb, &data); + bt_gatt_foreach_attr(start_handle, end_handle, read_group_cb, &data); - - if (!data.rsp->len) { - net_buf_unref(data.buf); - /* Respond here since handle is set */ - send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, - BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); - return 0; - } - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, - NULL); + if (!data.rsp->len) { + net_buf_unref(data.buf); + /* Respond here since handle is set */ + send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, + BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); + return 0; + } - return 0; + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, + NULL); + + return 0; } static u8_t att_read_group_req(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - struct bt_att_read_group_req *req; - u16_t start_handle, end_handle, err_handle; - union { - struct bt_uuid uuid; - struct bt_uuid_16 u16; - struct bt_uuid_128 u128; - } u; - u8_t uuid_len = buf->len - sizeof(*req); + struct bt_conn *conn = att->chan.chan.conn; + struct bt_att_read_group_req *req; + u16_t start_handle, end_handle, err_handle; + union { + struct bt_uuid uuid; + struct bt_uuid_16 u16; + struct bt_uuid_128 u128; + } u; + u8_t uuid_len = buf->len - sizeof(*req); - /* Type can only be UUID16 or UUID128 */ - if (uuid_len != 2 && uuid_len != 16) { - return BT_ATT_ERR_INVALID_PDU; - } + /* Type can only be UUID16 or UUID128 */ + if (uuid_len != 2 && uuid_len != 16) { + return BT_ATT_ERR_INVALID_PDU; + } - req = net_buf_pull_mem(buf, sizeof(*req)); + req = net_buf_pull_mem(buf, sizeof(*req)); - start_handle = sys_le16_to_cpu(req->start_handle); - end_handle = sys_le16_to_cpu(req->end_handle); + start_handle = sys_le16_to_cpu(req->start_handle); + end_handle = sys_le16_to_cpu(req->end_handle); - if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) { - return BT_ATT_ERR_UNLIKELY; - } + if (!bt_uuid_create(&u.uuid, req->uuid, uuid_len)) { + return BT_ATT_ERR_UNLIKELY; + } - BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", - start_handle, end_handle, bt_uuid_str(&u.uuid)); + BT_DBG("start_handle 0x%04x end_handle 0x%04x type %s", + start_handle, end_handle, bt_uuid_str(&u.uuid)); - if (!range_is_valid(start_handle, end_handle, &err_handle)) { - send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, err_handle, - BT_ATT_ERR_INVALID_HANDLE); - return 0; - } + if (!range_is_valid(start_handle, end_handle, &err_handle)) { + send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, err_handle, + BT_ATT_ERR_INVALID_HANDLE); + return 0; + } - /* Core v4.2, Vol 3, sec 2.5.3 Attribute Grouping: - * Not all of the grouping attributes can be used in the ATT - * Read By Group Type Request. The "Primary Service" and "Secondary - * Service" grouping types may be used in the Read By Group Type - * Request. The "Characteristic" grouping type shall not be used in - * the ATT Read By Group Type Request. - */ - if (bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) && - bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY)) { - send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, - BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE); - return 0; - } + /* Core v4.2, Vol 3, sec 2.5.3 Attribute Grouping: + * Not all of the grouping attributes can be used in the ATT + * Read By Group Type Request. The "Primary Service" and "Secondary + * Service" grouping types may be used in the Read By Group Type + * Request. The "Characteristic" grouping type shall not be used in + * the ATT Read By Group Type Request. + */ + if (bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) && + bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY)) { + send_err_rsp(conn, BT_ATT_OP_READ_GROUP_REQ, start_handle, + BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE); + return 0; + } - return att_read_group_rsp(att, &u.uuid, start_handle, end_handle); + return att_read_group_rsp(att, &u.uuid, start_handle, end_handle); } struct write_data { - struct bt_conn *conn; - struct net_buf *buf; - u8_t req; - const void *value; - u16_t len; - u16_t offset; - u8_t err; + struct bt_conn *conn; + struct net_buf *buf; + u8_t req; + const void *value; + u16_t len; + u16_t offset; + u8_t err; }; static u8_t write_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct write_data *data = user_data; - int write; - u8_t flags = 0U; + struct write_data *data = user_data; + int write; + u8_t flags = 0U; - BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset); + BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset); - /* Check attribute permissions */ - data->err = bt_gatt_check_perm(data->conn, attr, - BT_GATT_PERM_WRITE_MASK); - if (data->err) { - return BT_GATT_ITER_STOP; - } + /* Check attribute permissions */ + data->err = bt_gatt_check_perm(data->conn, attr, + BT_GATT_PERM_WRITE_MASK); + if (data->err) { + return BT_GATT_ITER_STOP; + } - /* Set command flag if not a request */ - if (!data->req) { - flags |= BT_GATT_WRITE_FLAG_CMD; - } + /* Set command flag if not a request */ + if (!data->req) { + flags |= BT_GATT_WRITE_FLAG_CMD; + } - /* Write attribute value */ - write = attr->write(data->conn, attr, data->value, data->len, - data->offset, flags); - if (write < 0 || write != data->len) { - data->err = err_to_att(write); - return BT_GATT_ITER_STOP; - } + /* Write attribute value */ + write = attr->write(data->conn, attr, data->value, data->len, + data->offset, flags); + if (write < 0 || write != data->len) { + data->err = err_to_att(write); + return BT_GATT_ITER_STOP; + } - data->err = 0U; + data->err = 0U; - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static u8_t att_write_rsp(struct bt_conn *conn, u8_t req, u8_t rsp, - u16_t handle, u16_t offset, const void *value, - u16_t len) + u16_t handle, u16_t offset, const void *value, + u16_t len) { - struct write_data data; + struct write_data data; - if (!bt_gatt_change_aware(conn, req ? true : false)) { - return BT_ATT_ERR_DB_OUT_OF_SYNC; - } + if (!bt_gatt_change_aware(conn, req ? true : false)) { + return BT_ATT_ERR_DB_OUT_OF_SYNC; + } - if (!handle) { - return BT_ATT_ERR_INVALID_HANDLE; - } + if (!handle) { + return BT_ATT_ERR_INVALID_HANDLE; + } - (void)memset(&data, 0, sizeof(data)); + (void)memset(&data, 0, sizeof(data)); - /* Only allocate buf if required to respond */ - if (rsp) { - data.buf = bt_att_create_pdu(conn, rsp, 0); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } - } + /* Only allocate buf if required to respond */ + if (rsp) { + data.buf = bt_att_create_pdu(conn, rsp, 0); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } + } - data.conn = conn; - data.req = req; - data.offset = offset; - data.value = value; - data.len = len; - data.err = BT_ATT_ERR_INVALID_HANDLE; + data.conn = conn; + data.req = req; + data.offset = offset; + data.value = value; + data.len = len; + data.err = BT_ATT_ERR_INVALID_HANDLE; - bt_gatt_foreach_attr(handle, handle, write_cb, &data); + bt_gatt_foreach_attr(handle, handle, write_cb, &data); - if (data.err) { - /* In case of error discard data and respond with an error */ - if (rsp) { - net_buf_unref(data.buf); - /* Respond here since handle is set */ - send_err_rsp(conn, req, handle, data.err); - } - return req == BT_ATT_OP_EXEC_WRITE_REQ ? data.err : 0; - } + if (data.err) { + /* In case of error discard data and respond with an error */ + if (rsp) { + net_buf_unref(data.buf); + /* Respond here since handle is set */ + send_err_rsp(conn, req, handle, data.err); + } + return req == BT_ATT_OP_EXEC_WRITE_REQ ? data.err : 0; + } - if (data.buf) { - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, - att_rsp_sent, NULL); - } + if (data.buf) { + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, + att_rsp_sent, NULL); + } - return 0; + return 0; } static u8_t att_write_req(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - u16_t handle; + struct bt_conn *conn = att->chan.chan.conn; + u16_t handle; - handle = net_buf_pull_le16(buf); + handle = net_buf_pull_le16(buf); - BT_DBG("handle 0x%04x", handle); + BT_DBG("handle 0x%04x", handle); - return att_write_rsp(conn, BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP, - handle, 0, buf->data, buf->len); + return att_write_rsp(conn, BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP, + handle, 0, buf->data, buf->len); } #if CONFIG_BT_ATT_PREPARE_COUNT > 0 struct prep_data { - struct bt_conn *conn; - struct net_buf *buf; - const void *value; - u16_t len; - u16_t offset; - u8_t err; + struct bt_conn *conn; + struct net_buf *buf; + const void *value; + u16_t len; + u16_t offset; + u8_t err; }; static u8_t prep_write_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct prep_data *data = user_data; - struct bt_attr_data *attr_data; - int write; + struct prep_data *data = user_data; + struct bt_attr_data *attr_data; + int write; - BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset); + BT_DBG("handle 0x%04x offset %u", attr->handle, data->offset); - /* Check attribute permissions */ - data->err = bt_gatt_check_perm(data->conn, attr, - BT_GATT_PERM_WRITE_MASK); - if (data->err) { - return BT_GATT_ITER_STOP; - } + /* Check attribute permissions */ + data->err = bt_gatt_check_perm(data->conn, attr, + BT_GATT_PERM_WRITE_MASK); + if (data->err) { + return BT_GATT_ITER_STOP; + } - /* Check if attribute requires handler to accept the data */ - if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) { - goto append; - } + /* Check if attribute requires handler to accept the data */ + if (!(attr->perm & BT_GATT_PERM_PREPARE_WRITE)) { + goto append; + } - /* Write attribute value to check if device is authorized */ - write = attr->write(data->conn, attr, data->value, data->len, - data->offset, BT_GATT_WRITE_FLAG_PREPARE); - if (write != 0) { - data->err = err_to_att(write); - return BT_GATT_ITER_STOP; - } + /* Write attribute value to check if device is authorized */ + write = attr->write(data->conn, attr, data->value, data->len, + data->offset, BT_GATT_WRITE_FLAG_PREPARE); + if (write != 0) { + data->err = err_to_att(write); + return BT_GATT_ITER_STOP; + } append: - /* Copy data into the outstanding queue */ - data->buf = net_buf_alloc(&prep_pool, K_NO_WAIT); - if (!data->buf) { - data->err = BT_ATT_ERR_PREPARE_QUEUE_FULL; - return BT_GATT_ITER_STOP; - } + /* Copy data into the outstanding queue */ + data->buf = net_buf_alloc(&prep_pool, K_NO_WAIT); + if (!data->buf) { + data->err = BT_ATT_ERR_PREPARE_QUEUE_FULL; + return BT_GATT_ITER_STOP; + } - attr_data = net_buf_user_data(data->buf); - attr_data->handle = attr->handle; - attr_data->offset = data->offset; + attr_data = net_buf_user_data(data->buf); + attr_data->handle = attr->handle; + attr_data->offset = data->offset; - net_buf_add_mem(data->buf, data->value, data->len); + net_buf_add_mem(data->buf, data->value, data->len); - data->err = 0U; + data->err = 0U; - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static u8_t att_prep_write_rsp(struct bt_att *att, u16_t handle, u16_t offset, - const void *value, u16_t len) + const void *value, u16_t len) { - struct bt_conn *conn = att->chan.chan.conn; - struct prep_data data; - struct bt_att_prepare_write_rsp *rsp; + struct bt_conn *conn = att->chan.chan.conn; + struct prep_data data; + struct bt_att_prepare_write_rsp *rsp; - if (!bt_gatt_change_aware(conn, true)) { - return BT_ATT_ERR_DB_OUT_OF_SYNC; - } + if (!bt_gatt_change_aware(conn, true)) { + return BT_ATT_ERR_DB_OUT_OF_SYNC; + } - if (!handle) { - return BT_ATT_ERR_INVALID_HANDLE; - } + if (!handle) { + return BT_ATT_ERR_INVALID_HANDLE; + } - (void)memset(&data, 0, sizeof(data)); + (void)memset(&data, 0, sizeof(data)); - data.conn = conn; - data.offset = offset; - data.value = value; - data.len = len; - data.err = BT_ATT_ERR_INVALID_HANDLE; + data.conn = conn; + data.offset = offset; + data.value = value; + data.len = len; + data.err = BT_ATT_ERR_INVALID_HANDLE; - bt_gatt_foreach_attr(handle, handle, prep_write_cb, &data); + bt_gatt_foreach_attr(handle, handle, prep_write_cb, &data); - if (data.err) { - /* Respond here since handle is set */ - send_err_rsp(conn, BT_ATT_OP_PREPARE_WRITE_REQ, handle, - data.err); - return 0; - } + if (data.err) { + /* Respond here since handle is set */ + send_err_rsp(conn, BT_ATT_OP_PREPARE_WRITE_REQ, handle, + data.err); + return 0; + } - BT_DBG("buf %p handle 0x%04x offset %u", data.buf, handle, offset); + BT_DBG("buf %p handle 0x%04x offset %u", data.buf, handle, offset); - /* Store buffer in the outstanding queue */ - net_buf_put(&att->prep_queue, data.buf); + /* Store buffer in the outstanding queue */ + net_buf_put(&att->prep_queue, data.buf); - /* Generate response */ - data.buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_RSP, 0); - if (!data.buf) { - return BT_ATT_ERR_UNLIKELY; - } + /* Generate response */ + data.buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_RSP, 0); + if (!data.buf) { + return BT_ATT_ERR_UNLIKELY; + } - rsp = net_buf_add(data.buf, sizeof(*rsp)); - rsp->handle = sys_cpu_to_le16(handle); - rsp->offset = sys_cpu_to_le16(offset); - net_buf_add(data.buf, len); - memcpy(rsp->value, value, len); + rsp = net_buf_add(data.buf, sizeof(*rsp)); + rsp->handle = sys_cpu_to_le16(handle); + rsp->offset = sys_cpu_to_le16(offset); + net_buf_add(data.buf, len); + memcpy(rsp->value, value, len); - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, - NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, data.buf, att_rsp_sent, + NULL); - return 0; + return 0; } #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ static u8_t att_prepare_write_req(struct bt_att *att, struct net_buf *buf) { #if CONFIG_BT_ATT_PREPARE_COUNT == 0 - return BT_ATT_ERR_NOT_SUPPORTED; + return BT_ATT_ERR_NOT_SUPPORTED; #else - struct bt_att_prepare_write_req *req; - u16_t handle, offset; + struct bt_att_prepare_write_req *req; + u16_t handle, offset; - req = net_buf_pull_mem(buf, sizeof(*req)); + req = net_buf_pull_mem(buf, sizeof(*req)); - handle = sys_le16_to_cpu(req->handle); - offset = sys_le16_to_cpu(req->offset); + handle = sys_le16_to_cpu(req->handle); + offset = sys_le16_to_cpu(req->offset); - BT_DBG("handle 0x%04x offset %u", handle, offset); + BT_DBG("handle 0x%04x offset %u", handle, offset); - return att_prep_write_rsp(att, handle, offset, buf->data, buf->len); + return att_prep_write_rsp(att, handle, offset, buf->data, buf->len); #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ } #if CONFIG_BT_ATT_PREPARE_COUNT > 0 static u8_t att_exec_write_rsp(struct bt_att *att, u8_t flags) { - struct bt_conn *conn = att->chan.chan.conn; - struct net_buf *buf; - u8_t err = 0U; + struct bt_conn *conn = att->chan.chan.conn; + struct net_buf *buf; + u8_t err = 0U; - while ((buf = net_buf_get(&att->prep_queue, K_NO_WAIT))) { - struct bt_attr_data *data = net_buf_user_data(buf); + while ((buf = net_buf_get(&att->prep_queue, K_NO_WAIT))) { + struct bt_attr_data *data = net_buf_user_data(buf); - BT_DBG("buf %p handle 0x%04x offset %u", buf, data->handle, - data->offset); + BT_DBG("buf %p handle 0x%04x offset %u", buf, data->handle, + data->offset); - /* Just discard the data if an error was set */ - if (!err && flags == BT_ATT_FLAG_EXEC) { - err = att_write_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, 0, - data->handle, data->offset, - buf->data, buf->len); - if (err) { - /* Respond here since handle is set */ - send_err_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, - data->handle, err); - } - } + /* Just discard the data if an error was set */ + if (!err && flags == BT_ATT_FLAG_EXEC) { + err = att_write_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, 0, + data->handle, data->offset, + buf->data, buf->len); + if (err) { + /* Respond here since handle is set */ + send_err_rsp(conn, BT_ATT_OP_EXEC_WRITE_REQ, + data->handle, err); + } + } - net_buf_unref(buf); - } + net_buf_unref(buf); + } - if (err) { - return 0; - } + if (err) { + return 0; + } - /* Generate response */ - buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_RSP, 0); - if (!buf) { - return BT_ATT_ERR_UNLIKELY; - } + /* Generate response */ + buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_RSP, 0); + if (!buf) { + return BT_ATT_ERR_UNLIKELY; + } - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_rsp_sent, NULL); - return 0; + return 0; } #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ @@ -1533,58 +1533,58 @@ static u8_t att_exec_write_rsp(struct bt_att *att, u8_t flags) static u8_t att_exec_write_req(struct bt_att *att, struct net_buf *buf) { #if CONFIG_BT_ATT_PREPARE_COUNT == 0 - return BT_ATT_ERR_NOT_SUPPORTED; + return BT_ATT_ERR_NOT_SUPPORTED; #else - struct bt_att_exec_write_req *req; + struct bt_att_exec_write_req *req; - req = (void *)buf->data; + req = (void *)buf->data; - BT_DBG("flags 0x%02x", req->flags); + BT_DBG("flags 0x%02x", req->flags); - return att_exec_write_rsp(att, req->flags); + return att_exec_write_rsp(att, req->flags); #endif /* CONFIG_BT_ATT_PREPARE_COUNT */ } static u8_t att_write_cmd(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - u16_t handle; + struct bt_conn *conn = att->chan.chan.conn; + u16_t handle; - handle = net_buf_pull_le16(buf); + handle = net_buf_pull_le16(buf); - BT_DBG("handle 0x%04x", handle); + BT_DBG("handle 0x%04x", handle); - return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len); + return att_write_rsp(conn, 0, 0, handle, 0, buf->data, buf->len); } #if defined(CONFIG_BT_SIGNING) static u8_t att_signed_write_cmd(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - struct bt_att_signed_write_cmd *req; - u16_t handle; - int err; + struct bt_conn *conn = att->chan.chan.conn; + struct bt_att_signed_write_cmd *req; + u16_t handle; + int err; - req = (void *)buf->data; + req = (void *)buf->data; - handle = sys_le16_to_cpu(req->handle); + handle = sys_le16_to_cpu(req->handle); - BT_DBG("handle 0x%04x", handle); + BT_DBG("handle 0x%04x", handle); - /* Verifying data requires full buffer including attribute header */ - net_buf_push(buf, sizeof(struct bt_att_hdr)); - err = bt_smp_sign_verify(conn, buf); - if (err) { - BT_ERR("Error verifying data"); - /* No response for this command */ - return 0; - } + /* Verifying data requires full buffer including attribute header */ + net_buf_push(buf, sizeof(struct bt_att_hdr)); + err = bt_smp_sign_verify(conn, buf); + if (err) { + BT_ERR("Error verifying data"); + /* No response for this command */ + return 0; + } - net_buf_pull(buf, sizeof(struct bt_att_hdr)); - net_buf_pull(buf, sizeof(*req)); + net_buf_pull(buf, sizeof(struct bt_att_hdr)); + net_buf_pull(buf, sizeof(*req)); - return att_write_rsp(conn, 0, 0, handle, 0, buf->data, - buf->len - sizeof(struct bt_att_signature)); + return att_write_rsp(conn, 0, 0, handle, 0, buf->data, + buf->len - sizeof(struct bt_att_signature)); } #endif /* CONFIG_BT_SIGNING */ @@ -1592,623 +1592,623 @@ static u8_t att_signed_write_cmd(struct bt_att *att, struct net_buf *buf) #if defined(CONFIG_BT_SMP) static int att_change_security(struct bt_conn *conn, u8_t err) { - bt_security_t sec; + bt_security_t sec; - switch (err) { - case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION: - if (conn->sec_level >= BT_SECURITY_L2) - return -EALREADY; - sec = BT_SECURITY_L2; - break; - case BT_ATT_ERR_AUTHENTICATION: - if (conn->sec_level < BT_SECURITY_L2) { - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] - * page 375: - * - * If an LTK is not available, the service request - * shall be rejected with the error code 'Insufficient - * Authentication'. - * Note: When the link is not encrypted, the error code - * "Insufficient Authentication" does not indicate that - * MITM protection is required. - */ - sec = BT_SECURITY_L2; - } else if (conn->sec_level < BT_SECURITY_L3) { - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] - * page 375: - * - * If an authenticated pairing is required but only an - * unauthenticated pairing has occurred and the link is - * currently encrypted, the service request shall be - * rejected with the error code 'Insufficient - * Authentication'. - * Note: When unauthenticated pairing has occurred and - * the link is currently encrypted, the error code - * 'Insufficient Authentication' indicates that MITM - * protection is required. - */ - sec = BT_SECURITY_L3; - } else if (conn->sec_level < BT_SECURITY_L4) { - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] - * page 375: - * - * If LE Secure Connections authenticated pairing is - * required but LE legacy pairing has occurred and the - * link is currently encrypted, the service request - * shall be rejected with the error code ''Insufficient - * Authentication'. - */ - sec = BT_SECURITY_L4; - } else { - return -EALREADY; - } - break; - default: - return -EINVAL; - } + switch (err) { + case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION: + if (conn->sec_level >= BT_SECURITY_L2) + return -EALREADY; + sec = BT_SECURITY_L2; + break; + case BT_ATT_ERR_AUTHENTICATION: + if (conn->sec_level < BT_SECURITY_L2) { + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] + * page 375: + * + * If an LTK is not available, the service request + * shall be rejected with the error code 'Insufficient + * Authentication'. + * Note: When the link is not encrypted, the error code + * "Insufficient Authentication" does not indicate that + * MITM protection is required. + */ + sec = BT_SECURITY_L2; + } else if (conn->sec_level < BT_SECURITY_L3) { + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] + * page 375: + * + * If an authenticated pairing is required but only an + * unauthenticated pairing has occurred and the link is + * currently encrypted, the service request shall be + * rejected with the error code 'Insufficient + * Authentication'. + * Note: When unauthenticated pairing has occurred and + * the link is currently encrypted, the error code + * 'Insufficient Authentication' indicates that MITM + * protection is required. + */ + sec = BT_SECURITY_L3; + } else if (conn->sec_level < BT_SECURITY_L4) { + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C] + * page 375: + * + * If LE Secure Connections authenticated pairing is + * required but LE legacy pairing has occurred and the + * link is currently encrypted, the service request + * shall be rejected with the error code ''Insufficient + * Authentication'. + */ + sec = BT_SECURITY_L4; + } else { + return -EALREADY; + } + break; + default: + return -EINVAL; + } - return bt_conn_set_security(conn, sec); + return bt_conn_set_security(conn, sec); } #endif /* CONFIG_BT_SMP */ static u8_t att_error_rsp(struct bt_att *att, struct net_buf *buf) { - struct bt_att_error_rsp *rsp; - u8_t err; + struct bt_att_error_rsp *rsp; + u8_t err; - rsp = (void *)buf->data; + rsp = (void *)buf->data; - BT_DBG("request 0x%02x handle 0x%04x error 0x%02x", rsp->request, - sys_le16_to_cpu(rsp->handle), rsp->error); + BT_DBG("request 0x%02x handle 0x%04x error 0x%02x", rsp->request, + sys_le16_to_cpu(rsp->handle), rsp->error); - /* Don't retry if there is no req pending or it has been cancelled */ - if (!att->req || att->req == &cancel) { - err = BT_ATT_ERR_UNLIKELY; - goto done; - } + /* Don't retry if there is no req pending or it has been cancelled */ + if (!att->req || att->req == &cancel) { + err = BT_ATT_ERR_UNLIKELY; + goto done; + } - if (att->req->buf) { - /* Restore state to be resent */ - net_buf_simple_restore(&att->req->buf->b, &att->req->state); - } + if (att->req->buf) { + /* Restore state to be resent */ + net_buf_simple_restore(&att->req->buf->b, &att->req->state); + } - err = rsp->error; + err = rsp->error; #if defined(CONFIG_BT_SMP) - if (att->req->retrying) { - goto done; - } + if (att->req->retrying) { + goto done; + } - /* Check if security needs to be changed */ - if (!att_change_security(att->chan.chan.conn, err)) { - att->req->retrying = true; - /* Wait security_changed: TODO: Handle fail case */ - return 0; - } + /* Check if security needs to be changed */ + if (!att_change_security(att->chan.chan.conn, err)) { + att->req->retrying = true; + /* Wait security_changed: TODO: Handle fail case */ + return 0; + } #endif /* CONFIG_BT_SMP */ done: - return att_handle_rsp(att, NULL, 0, err); + return att_handle_rsp(att, NULL, 0, err); } static u8_t att_handle_find_info_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_handle_find_type_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_handle_read_type_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_handle_read_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_handle_read_blob_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } #if defined(CONFIG_BT_GATT_READ_MULTIPLE) static u8_t att_handle_read_mult_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ static u8_t att_handle_read_group_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_handle_write_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_handle_prepare_write_rsp(struct bt_att *att, - struct net_buf *buf) + struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_handle_exec_write_rsp(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static u8_t att_notify(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - u16_t handle; + struct bt_conn *conn = att->chan.chan.conn; + u16_t handle; - handle = net_buf_pull_le16(buf); + handle = net_buf_pull_le16(buf); - BT_DBG("handle 0x%04x", handle); + BT_DBG("handle 0x%04x", handle); - bt_gatt_notification(conn, handle, buf->data, buf->len); + bt_gatt_notification(conn, handle, buf->data, buf->len); - return 0; + return 0; } static u8_t att_indicate(struct bt_att *att, struct net_buf *buf) { - struct bt_conn *conn = att->chan.chan.conn; - u16_t handle; + struct bt_conn *conn = att->chan.chan.conn; + u16_t handle; - handle = net_buf_pull_le16(buf); + handle = net_buf_pull_le16(buf); - BT_DBG("handle 0x%04x", handle); + BT_DBG("handle 0x%04x", handle); - bt_gatt_notification(conn, handle, buf->data, buf->len); + bt_gatt_notification(conn, handle, buf->data, buf->len); - buf = bt_att_create_pdu(conn, BT_ATT_OP_CONFIRM, 0); - if (!buf) { - return 0; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_CONFIRM, 0); + if (!buf) { + return 0; + } - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_cfm_sent, NULL); + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, buf, att_cfm_sent, NULL); - return 0; + return 0; } #endif /* CONFIG_BT_GATT_CLIENT */ static u8_t att_confirm(struct bt_att *att, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - return att_handle_rsp(att, buf->data, buf->len, 0); + return att_handle_rsp(att, buf->data, buf->len, 0); } static const struct att_handler { - u8_t op; - u8_t expect_len; - att_type_t type; - u8_t (*func)(struct bt_att *att, struct net_buf *buf); + u8_t op; + u8_t expect_len; + att_type_t type; + u8_t (*func)(struct bt_att *att, struct net_buf *buf); } handlers[] = { - { BT_ATT_OP_MTU_REQ, - sizeof(struct bt_att_exchange_mtu_req), - ATT_REQUEST, - att_mtu_req }, - { BT_ATT_OP_FIND_INFO_REQ, - sizeof(struct bt_att_find_info_req), - ATT_REQUEST, - att_find_info_req }, - { BT_ATT_OP_FIND_TYPE_REQ, - sizeof(struct bt_att_find_type_req), - ATT_REQUEST, - att_find_type_req }, - { BT_ATT_OP_READ_TYPE_REQ, - sizeof(struct bt_att_read_type_req), - ATT_REQUEST, - att_read_type_req }, - { BT_ATT_OP_READ_REQ, - sizeof(struct bt_att_read_req), - ATT_REQUEST, - att_read_req }, - { BT_ATT_OP_READ_BLOB_REQ, - sizeof(struct bt_att_read_blob_req), - ATT_REQUEST, - att_read_blob_req }, + { BT_ATT_OP_MTU_REQ, + sizeof(struct bt_att_exchange_mtu_req), + ATT_REQUEST, + att_mtu_req }, + { BT_ATT_OP_FIND_INFO_REQ, + sizeof(struct bt_att_find_info_req), + ATT_REQUEST, + att_find_info_req }, + { BT_ATT_OP_FIND_TYPE_REQ, + sizeof(struct bt_att_find_type_req), + ATT_REQUEST, + att_find_type_req }, + { BT_ATT_OP_READ_TYPE_REQ, + sizeof(struct bt_att_read_type_req), + ATT_REQUEST, + att_read_type_req }, + { BT_ATT_OP_READ_REQ, + sizeof(struct bt_att_read_req), + ATT_REQUEST, + att_read_req }, + { BT_ATT_OP_READ_BLOB_REQ, + sizeof(struct bt_att_read_blob_req), + ATT_REQUEST, + att_read_blob_req }, #if defined(CONFIG_BT_GATT_READ_MULTIPLE) - { BT_ATT_OP_READ_MULT_REQ, - BT_ATT_READ_MULT_MIN_LEN_REQ, - ATT_REQUEST, - att_read_mult_req }, + { BT_ATT_OP_READ_MULT_REQ, + BT_ATT_READ_MULT_MIN_LEN_REQ, + ATT_REQUEST, + att_read_mult_req }, #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ - { BT_ATT_OP_READ_GROUP_REQ, - sizeof(struct bt_att_read_group_req), - ATT_REQUEST, - att_read_group_req }, - { BT_ATT_OP_WRITE_REQ, - sizeof(struct bt_att_write_req), - ATT_REQUEST, - att_write_req }, - { BT_ATT_OP_PREPARE_WRITE_REQ, - sizeof(struct bt_att_prepare_write_req), - ATT_REQUEST, - att_prepare_write_req }, - { BT_ATT_OP_EXEC_WRITE_REQ, - sizeof(struct bt_att_exec_write_req), - ATT_REQUEST, - att_exec_write_req }, - { BT_ATT_OP_CONFIRM, - 0, - ATT_CONFIRMATION, - att_confirm }, - { BT_ATT_OP_WRITE_CMD, - sizeof(struct bt_att_write_cmd), - ATT_COMMAND, - att_write_cmd }, + { BT_ATT_OP_READ_GROUP_REQ, + sizeof(struct bt_att_read_group_req), + ATT_REQUEST, + att_read_group_req }, + { BT_ATT_OP_WRITE_REQ, + sizeof(struct bt_att_write_req), + ATT_REQUEST, + att_write_req }, + { BT_ATT_OP_PREPARE_WRITE_REQ, + sizeof(struct bt_att_prepare_write_req), + ATT_REQUEST, + att_prepare_write_req }, + { BT_ATT_OP_EXEC_WRITE_REQ, + sizeof(struct bt_att_exec_write_req), + ATT_REQUEST, + att_exec_write_req }, + { BT_ATT_OP_CONFIRM, + 0, + ATT_CONFIRMATION, + att_confirm }, + { BT_ATT_OP_WRITE_CMD, + sizeof(struct bt_att_write_cmd), + ATT_COMMAND, + att_write_cmd }, #if defined(CONFIG_BT_SIGNING) - { BT_ATT_OP_SIGNED_WRITE_CMD, - (sizeof(struct bt_att_write_cmd) + - sizeof(struct bt_att_signature)), - ATT_COMMAND, - att_signed_write_cmd }, + { BT_ATT_OP_SIGNED_WRITE_CMD, + (sizeof(struct bt_att_write_cmd) + + sizeof(struct bt_att_signature)), + ATT_COMMAND, + att_signed_write_cmd }, #endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_GATT_CLIENT) - { BT_ATT_OP_ERROR_RSP, - sizeof(struct bt_att_error_rsp), - ATT_RESPONSE, - att_error_rsp }, - { BT_ATT_OP_MTU_RSP, - sizeof(struct bt_att_exchange_mtu_rsp), - ATT_RESPONSE, - att_mtu_rsp }, - { BT_ATT_OP_FIND_INFO_RSP, - sizeof(struct bt_att_find_info_rsp), - ATT_RESPONSE, - att_handle_find_info_rsp }, - { BT_ATT_OP_FIND_TYPE_RSP, - sizeof(struct bt_att_find_type_rsp), - ATT_RESPONSE, - att_handle_find_type_rsp }, - { BT_ATT_OP_READ_TYPE_RSP, - sizeof(struct bt_att_read_type_rsp), - ATT_RESPONSE, - att_handle_read_type_rsp }, - { BT_ATT_OP_READ_RSP, - sizeof(struct bt_att_read_rsp), - ATT_RESPONSE, - att_handle_read_rsp }, - { BT_ATT_OP_READ_BLOB_RSP, - sizeof(struct bt_att_read_blob_rsp), - ATT_RESPONSE, - att_handle_read_blob_rsp }, + { BT_ATT_OP_ERROR_RSP, + sizeof(struct bt_att_error_rsp), + ATT_RESPONSE, + att_error_rsp }, + { BT_ATT_OP_MTU_RSP, + sizeof(struct bt_att_exchange_mtu_rsp), + ATT_RESPONSE, + att_mtu_rsp }, + { BT_ATT_OP_FIND_INFO_RSP, + sizeof(struct bt_att_find_info_rsp), + ATT_RESPONSE, + att_handle_find_info_rsp }, + { BT_ATT_OP_FIND_TYPE_RSP, + sizeof(struct bt_att_find_type_rsp), + ATT_RESPONSE, + att_handle_find_type_rsp }, + { BT_ATT_OP_READ_TYPE_RSP, + sizeof(struct bt_att_read_type_rsp), + ATT_RESPONSE, + att_handle_read_type_rsp }, + { BT_ATT_OP_READ_RSP, + sizeof(struct bt_att_read_rsp), + ATT_RESPONSE, + att_handle_read_rsp }, + { BT_ATT_OP_READ_BLOB_RSP, + sizeof(struct bt_att_read_blob_rsp), + ATT_RESPONSE, + att_handle_read_blob_rsp }, #if defined(CONFIG_BT_GATT_READ_MULTIPLE) - { BT_ATT_OP_READ_MULT_RSP, - sizeof(struct bt_att_read_mult_rsp), - ATT_RESPONSE, - att_handle_read_mult_rsp }, + { BT_ATT_OP_READ_MULT_RSP, + sizeof(struct bt_att_read_mult_rsp), + ATT_RESPONSE, + att_handle_read_mult_rsp }, #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ - { BT_ATT_OP_READ_GROUP_RSP, - sizeof(struct bt_att_read_group_rsp), - ATT_RESPONSE, - att_handle_read_group_rsp }, - { BT_ATT_OP_WRITE_RSP, - 0, - ATT_RESPONSE, - att_handle_write_rsp }, - { BT_ATT_OP_PREPARE_WRITE_RSP, - sizeof(struct bt_att_prepare_write_rsp), - ATT_RESPONSE, - att_handle_prepare_write_rsp }, - { BT_ATT_OP_EXEC_WRITE_RSP, - 0, - ATT_RESPONSE, - att_handle_exec_write_rsp }, - { BT_ATT_OP_NOTIFY, - sizeof(struct bt_att_notify), - ATT_NOTIFICATION, - att_notify }, - { BT_ATT_OP_INDICATE, - sizeof(struct bt_att_indicate), - ATT_INDICATION, - att_indicate }, + { BT_ATT_OP_READ_GROUP_RSP, + sizeof(struct bt_att_read_group_rsp), + ATT_RESPONSE, + att_handle_read_group_rsp }, + { BT_ATT_OP_WRITE_RSP, + 0, + ATT_RESPONSE, + att_handle_write_rsp }, + { BT_ATT_OP_PREPARE_WRITE_RSP, + sizeof(struct bt_att_prepare_write_rsp), + ATT_RESPONSE, + att_handle_prepare_write_rsp }, + { BT_ATT_OP_EXEC_WRITE_RSP, + 0, + ATT_RESPONSE, + att_handle_exec_write_rsp }, + { BT_ATT_OP_NOTIFY, + sizeof(struct bt_att_notify), + ATT_NOTIFICATION, + att_notify }, + { BT_ATT_OP_INDICATE, + sizeof(struct bt_att_indicate), + ATT_INDICATION, + att_indicate }, #endif /* CONFIG_BT_GATT_CLIENT */ }; static att_type_t att_op_get_type(u8_t op) { - switch (op) { - case BT_ATT_OP_MTU_REQ: - case BT_ATT_OP_FIND_INFO_REQ: - case BT_ATT_OP_FIND_TYPE_REQ: - case BT_ATT_OP_READ_TYPE_REQ: - case BT_ATT_OP_READ_REQ: - case BT_ATT_OP_READ_BLOB_REQ: - case BT_ATT_OP_READ_MULT_REQ: - case BT_ATT_OP_READ_GROUP_REQ: - case BT_ATT_OP_WRITE_REQ: - case BT_ATT_OP_PREPARE_WRITE_REQ: - case BT_ATT_OP_EXEC_WRITE_REQ: - return ATT_REQUEST; - case BT_ATT_OP_CONFIRM: - return ATT_CONFIRMATION; - case BT_ATT_OP_WRITE_CMD: - case BT_ATT_OP_SIGNED_WRITE_CMD: - return ATT_COMMAND; - case BT_ATT_OP_ERROR_RSP: - case BT_ATT_OP_MTU_RSP: - case BT_ATT_OP_FIND_INFO_RSP: - case BT_ATT_OP_FIND_TYPE_RSP: - case BT_ATT_OP_READ_TYPE_RSP: - case BT_ATT_OP_READ_RSP: - case BT_ATT_OP_READ_BLOB_RSP: - case BT_ATT_OP_READ_MULT_RSP: - case BT_ATT_OP_READ_GROUP_RSP: - case BT_ATT_OP_WRITE_RSP: - case BT_ATT_OP_PREPARE_WRITE_RSP: - case BT_ATT_OP_EXEC_WRITE_RSP: - return ATT_RESPONSE; - case BT_ATT_OP_NOTIFY: - return ATT_NOTIFICATION; - case BT_ATT_OP_INDICATE: - return ATT_INDICATION; - } + switch (op) { + case BT_ATT_OP_MTU_REQ: + case BT_ATT_OP_FIND_INFO_REQ: + case BT_ATT_OP_FIND_TYPE_REQ: + case BT_ATT_OP_READ_TYPE_REQ: + case BT_ATT_OP_READ_REQ: + case BT_ATT_OP_READ_BLOB_REQ: + case BT_ATT_OP_READ_MULT_REQ: + case BT_ATT_OP_READ_GROUP_REQ: + case BT_ATT_OP_WRITE_REQ: + case BT_ATT_OP_PREPARE_WRITE_REQ: + case BT_ATT_OP_EXEC_WRITE_REQ: + return ATT_REQUEST; + case BT_ATT_OP_CONFIRM: + return ATT_CONFIRMATION; + case BT_ATT_OP_WRITE_CMD: + case BT_ATT_OP_SIGNED_WRITE_CMD: + return ATT_COMMAND; + case BT_ATT_OP_ERROR_RSP: + case BT_ATT_OP_MTU_RSP: + case BT_ATT_OP_FIND_INFO_RSP: + case BT_ATT_OP_FIND_TYPE_RSP: + case BT_ATT_OP_READ_TYPE_RSP: + case BT_ATT_OP_READ_RSP: + case BT_ATT_OP_READ_BLOB_RSP: + case BT_ATT_OP_READ_MULT_RSP: + case BT_ATT_OP_READ_GROUP_RSP: + case BT_ATT_OP_WRITE_RSP: + case BT_ATT_OP_PREPARE_WRITE_RSP: + case BT_ATT_OP_EXEC_WRITE_RSP: + return ATT_RESPONSE; + case BT_ATT_OP_NOTIFY: + return ATT_NOTIFICATION; + case BT_ATT_OP_INDICATE: + return ATT_INDICATION; + } - if (op & ATT_CMD_MASK) { - return ATT_COMMAND; - } + if (op & ATT_CMD_MASK) { + return ATT_COMMAND; + } - return ATT_UNKNOWN; + return ATT_UNKNOWN; } static int bt_att_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { - struct bt_att *att = ATT_CHAN(chan); - struct bt_att_hdr *hdr; - const struct att_handler *handler; - u8_t err; - size_t i; + struct bt_att *att = ATT_CHAN(chan); + struct bt_att_hdr *hdr; + const struct att_handler *handler; + u8_t err; + size_t i; - if (buf->len < sizeof(*hdr)) { - BT_ERR("Too small ATT PDU received"); - return 0; - } + if (buf->len < sizeof(*hdr)) { + BT_ERR("Too small ATT PDU received"); + return 0; + } - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - BT_DBG("Received ATT code 0x%02x len %u", hdr->code, buf->len); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + BT_DBG("Received ATT code 0x%02x len %u", hdr->code, buf->len); - for (i = 0, handler = NULL; i < ARRAY_SIZE(handlers); i++) { - if (hdr->code == handlers[i].op) { - handler = &handlers[i]; - break; - } - } + for (i = 0, handler = NULL; i < ARRAY_SIZE(handlers); i++) { + if (hdr->code == handlers[i].op) { + handler = &handlers[i]; + break; + } + } - if (!handler) { - BT_WARN("Unhandled ATT code 0x%02x", hdr->code); - if (att_op_get_type(hdr->code) != ATT_COMMAND) { - send_err_rsp(chan->conn, hdr->code, 0, - BT_ATT_ERR_NOT_SUPPORTED); - } - return 0; - } + if (!handler) { + BT_WARN("Unhandled ATT code 0x%02x", hdr->code); + if (att_op_get_type(hdr->code) != ATT_COMMAND) { + send_err_rsp(chan->conn, hdr->code, 0, + BT_ATT_ERR_NOT_SUPPORTED); + } + return 0; + } - if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { - if (handler->type == ATT_REQUEST && - atomic_test_and_set_bit(att->flags, ATT_PENDING_RSP)) { - BT_WARN("Ignoring unexpected request"); - return 0; - } else if (handler->type == ATT_INDICATION && - atomic_test_and_set_bit(att->flags, - ATT_PENDING_CFM)) { - BT_WARN("Ignoring unexpected indication"); - return 0; - } - } + if (IS_ENABLED(CONFIG_BT_ATT_ENFORCE_FLOW)) { + if (handler->type == ATT_REQUEST && + atomic_test_and_set_bit(att->flags, ATT_PENDING_RSP)) { + BT_WARN("Ignoring unexpected request"); + return 0; + } else if (handler->type == ATT_INDICATION && + atomic_test_and_set_bit(att->flags, + ATT_PENDING_CFM)) { + BT_WARN("Ignoring unexpected indication"); + return 0; + } + } - if (buf->len < handler->expect_len) { - BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); - err = BT_ATT_ERR_INVALID_PDU; - } else { - err = handler->func(att, buf); - } + if (buf->len < handler->expect_len) { + BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); + err = BT_ATT_ERR_INVALID_PDU; + } else { + err = handler->func(att, buf); + } - if (handler->type == ATT_REQUEST && err) { - BT_DBG("ATT error 0x%02x", err); - send_err_rsp(chan->conn, hdr->code, 0, err); - } + if (handler->type == ATT_REQUEST && err) { + BT_DBG("ATT error 0x%02x", err); + send_err_rsp(chan->conn, hdr->code, 0, err); + } - return 0; + return 0; } static struct bt_att *att_chan_get(struct bt_conn *conn) { - struct bt_l2cap_chan *chan; - struct bt_att *att; + struct bt_l2cap_chan *chan; + struct bt_att *att; - if (conn->state != BT_CONN_CONNECTED) { - BT_WARN("Not connected"); - return NULL; - } + if (conn->state != BT_CONN_CONNECTED) { + BT_WARN("Not connected"); + return NULL; + } - chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_ATT); - if (!chan) { - BT_ERR("Unable to find ATT channel"); - return NULL; - } + chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_ATT); + if (!chan) { + BT_ERR("Unable to find ATT channel"); + return NULL; + } - att = ATT_CHAN(chan); - if (atomic_test_bit(att->flags, ATT_DISCONNECTED)) { - BT_WARN("ATT context flagged as disconnected"); - return NULL; - } + att = ATT_CHAN(chan); + if (atomic_test_bit(att->flags, ATT_DISCONNECTED)) { + BT_WARN("ATT context flagged as disconnected"); + return NULL; + } - return att; + return att; } struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, size_t len) { - struct bt_att_hdr *hdr; - struct net_buf *buf; - struct bt_att *att; + struct bt_att_hdr *hdr; + struct net_buf *buf; + struct bt_att *att; - att = att_chan_get(conn); - if (!att) { - return NULL; - } + att = att_chan_get(conn); + if (!att) { + return NULL; + } - if (len + sizeof(op) > att->chan.tx.mtu) { - BT_WARN("ATT MTU exceeded, max %u, wanted %zu", - att->chan.tx.mtu, len + sizeof(op)); - return NULL; - } + if (len + sizeof(op) > att->chan.tx.mtu) { + BT_WARN("ATT MTU exceeded, max %u, wanted %zu", + att->chan.tx.mtu, len + sizeof(op)); + return NULL; + } - switch (att_op_get_type(op)) { - case ATT_RESPONSE: - case ATT_CONFIRMATION: - /* Use a timeout only when responding/confirming */ - buf = bt_l2cap_create_pdu_timeout(NULL, 0, ATT_TIMEOUT); - break; - default: - buf = bt_l2cap_create_pdu(NULL, 0); - } + switch (att_op_get_type(op)) { + case ATT_RESPONSE: + case ATT_CONFIRMATION: + /* Use a timeout only when responding/confirming */ + buf = bt_l2cap_create_pdu_timeout(NULL, 0, ATT_TIMEOUT); + break; + default: + buf = bt_l2cap_create_pdu(NULL, 0); + } - if (!buf) { - BT_ERR("Unable to allocate buffer for op 0x%02x", op); - return NULL; - } + if (!buf) { + BT_ERR("Unable to allocate buffer for op 0x%02x", op); + return NULL; + } - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->code = op; + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->code = op; - return buf; + return buf; } static void att_reset(struct bt_att *att) { - struct bt_att_req *req, *tmp; - int i; - struct net_buf *buf; + struct bt_att_req *req, *tmp; + int i; + struct net_buf *buf; #if CONFIG_BT_ATT_PREPARE_COUNT > 0 - /* Discard queued buffers */ - while ((buf = k_fifo_get(&att->prep_queue, K_NO_WAIT))) { - net_buf_unref(buf); - } + /* Discard queued buffers */ + while ((buf = k_fifo_get(&att->prep_queue, K_NO_WAIT))) { + net_buf_unref(buf); + } #endif /* CONFIG_BT_ATT_PREPARE_COUNT > 0 */ - while ((buf = k_fifo_get(&att->tx_queue, K_NO_WAIT))) { - net_buf_unref(buf); - } + while ((buf = k_fifo_get(&att->tx_queue, K_NO_WAIT))) { + net_buf_unref(buf); + } - atomic_set_bit(att->flags, ATT_DISCONNECTED); + atomic_set_bit(att->flags, ATT_DISCONNECTED); - /* Ensure that any waiters are woken up */ - for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) { - k_sem_give(&att->tx_sem); - } + /* Ensure that any waiters are woken up */ + for (i = 0; i < CONFIG_BT_ATT_TX_MAX; i++) { + k_sem_give(&att->tx_sem); + } - /* Notify pending requests */ - SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->reqs, req, tmp, node) { - if (req->func) { - req->func(NULL, BT_ATT_ERR_UNLIKELY, NULL, 0, req); - } + /* Notify pending requests */ + SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&att->reqs, req, tmp, node) { + if (req->func) { + req->func(NULL, BT_ATT_ERR_UNLIKELY, NULL, 0, req); + } - att_req_destroy(req); - } + att_req_destroy(req); + } - /* Reset list */ - sys_slist_init(&att->reqs); + /* Reset list */ + sys_slist_init(&att->reqs); - if (!att->req) { - return; - } + if (!att->req) { + return; + } - /* Notify outstanding request */ - att_handle_rsp(att, NULL, 0, BT_ATT_ERR_UNLIKELY); + /* Notify outstanding request */ + att_handle_rsp(att, NULL, 0, BT_ATT_ERR_UNLIKELY); } static void att_timeout(struct k_work *work) { - struct bt_att *att = CONTAINER_OF(work, struct bt_att, timeout_work); - struct bt_l2cap_le_chan *ch = &att->chan; + struct bt_att *att = CONTAINER_OF(work, struct bt_att, timeout_work); + struct bt_l2cap_le_chan *ch = &att->chan; - BT_ERR("ATT Timeout"); + BT_ERR("ATT Timeout"); - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 480: - * - * A transaction not completed within 30 seconds shall time out. Such a - * transaction shall be considered to have failed and the local higher - * layers shall be informed of this failure. No more attribute protocol - * requests, commands, indications or notifications shall be sent to the - * target device on this ATT Bearer. - */ - att_reset(att); + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part F] page 480: + * + * A transaction not completed within 30 seconds shall time out. Such a + * transaction shall be considered to have failed and the local higher + * layers shall be informed of this failure. No more attribute protocol + * requests, commands, indications or notifications shall be sent to the + * target device on this ATT Bearer. + */ + att_reset(att); - /* Consider the channel disconnected */ - bt_gatt_disconnected(ch->chan.conn); - ch->chan.conn = NULL; + /* Consider the channel disconnected */ + bt_gatt_disconnected(ch->chan.conn); + ch->chan.conn = NULL; } static void bt_att_connected(struct bt_l2cap_chan *chan) { - struct bt_att *att = ATT_CHAN(chan); - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + struct bt_att *att = ATT_CHAN(chan); + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); + BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); - k_fifo_init(&att->tx_queue, 20); + k_fifo_init(&att->tx_queue, 20); #if CONFIG_BT_ATT_PREPARE_COUNT > 0 - k_fifo_init(&att->prep_queue, 20); + k_fifo_init(&att->prep_queue, 20); #endif - ch->tx.mtu = BT_ATT_DEFAULT_LE_MTU; - ch->rx.mtu = BT_ATT_DEFAULT_LE_MTU; + ch->tx.mtu = BT_ATT_DEFAULT_LE_MTU; + ch->rx.mtu = BT_ATT_DEFAULT_LE_MTU; - k_delayed_work_init(&att->timeout_work, att_timeout); - sys_slist_init(&att->reqs); + k_delayed_work_init(&att->timeout_work, att_timeout); + sys_slist_init(&att->reqs); } static void bt_att_disconnected(struct bt_l2cap_chan *chan) { - struct bt_att *att = ATT_CHAN(chan); - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + struct bt_att *att = ATT_CHAN(chan); + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); + BT_DBG("chan %p cid 0x%04x", ch, ch->tx.cid); - att_reset(att); + att_reset(att); - bt_gatt_disconnected(ch->chan.conn); + bt_gatt_disconnected(ch->chan.conn); #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS if(att->timeout_work.timer.timer.hdl) k_delayed_work_del_timer(&att->timeout_work); if(att->tx_queue._queue.hdl){ - k_queue_free(&att->tx_queue._queue); - att->tx_queue._queue.hdl = NULL; - } - + k_queue_free(&att->tx_queue._queue); + att->tx_queue._queue.hdl = NULL; + } + if(att->tx_sem.sem.hdl) k_sem_delete(&att->tx_sem); #endif @@ -2216,84 +2216,84 @@ static void bt_att_disconnected(struct bt_l2cap_chan *chan) #if defined(CONFIG_BT_SMP) static void bt_att_encrypt_change(struct bt_l2cap_chan *chan, - u8_t hci_status) + u8_t hci_status) { - struct bt_att *att = ATT_CHAN(chan); - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - struct bt_conn *conn = ch->chan.conn; + struct bt_att *att = ATT_CHAN(chan); + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + struct bt_conn *conn = ch->chan.conn; - BT_DBG("chan %p conn %p handle %u sec_level 0x%02x status 0x%02x", ch, - conn, conn->handle, conn->sec_level, hci_status); + BT_DBG("chan %p conn %p handle %u sec_level 0x%02x status 0x%02x", ch, + conn, conn->handle, conn->sec_level, hci_status); - /* - * If status (HCI status of security procedure) is non-zero, notify - * outstanding request about security failure. - */ - if (hci_status) { - att_handle_rsp(att, NULL, 0, BT_ATT_ERR_AUTHENTICATION); - return; - } + /* + * If status (HCI status of security procedure) is non-zero, notify + * outstanding request about security failure. + */ + if (hci_status) { + att_handle_rsp(att, NULL, 0, BT_ATT_ERR_AUTHENTICATION); + return; + } - bt_gatt_encrypt_change(conn); + bt_gatt_encrypt_change(conn); - if (conn->sec_level == BT_SECURITY_L1) { - return; - } + if (conn->sec_level == BT_SECURITY_L1) { + return; + } - if (!att->req || !att->req->retrying) { - return; - } + if (!att->req || !att->req->retrying) { + return; + } - k_sem_take(&att->tx_sem, K_FOREVER); - if (!att_is_connected(att)) { - BT_WARN("Disconnected"); - k_sem_give(&att->tx_sem); - return; - } + k_sem_take(&att->tx_sem, K_FOREVER); + if (!att_is_connected(att)) { + BT_WARN("Disconnected"); + k_sem_give(&att->tx_sem); + return; + } - BT_DBG("Retrying"); + BT_DBG("Retrying"); - /* Resend buffer */ - (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, att->req->buf, - att_cb(att->req->buf), NULL); - att->req->buf = NULL; + /* Resend buffer */ + (void)bt_l2cap_send_cb(conn, BT_L2CAP_CID_ATT, att->req->buf, + att_cb(att->req->buf), NULL); + att->req->buf = NULL; } #endif /* CONFIG_BT_SMP */ static int bt_att_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { - int i; - static struct bt_l2cap_chan_ops ops = { - .connected = bt_att_connected, - .disconnected = bt_att_disconnected, - .recv = bt_att_recv, + int i; + static struct bt_l2cap_chan_ops ops = { + .connected = bt_att_connected, + .disconnected = bt_att_disconnected, + .recv = bt_att_recv, #if defined(CONFIG_BT_SMP) - .encrypt_change = bt_att_encrypt_change, + .encrypt_change = bt_att_encrypt_change, #endif /* CONFIG_BT_SMP */ - }; + }; - BT_DBG("conn %p handle %u", conn, conn->handle); + BT_DBG("conn %p handle %u", conn, conn->handle); - for (i = 0; i < ARRAY_SIZE(bt_req_pool); i++) { - struct bt_att *att = &bt_req_pool[i]; + for (i = 0; i < ARRAY_SIZE(bt_req_pool); i++) { + struct bt_att *att = &bt_req_pool[i]; - if (att->chan.chan.conn) { - continue; - } + if (att->chan.chan.conn) { + continue; + } - (void)memset(att, 0, sizeof(*att)); - att->chan.chan.ops = &ops; - k_sem_init(&att->tx_sem, CONFIG_BT_ATT_TX_MAX, - CONFIG_BT_ATT_TX_MAX); + (void)memset(att, 0, sizeof(*att)); + att->chan.chan.ops = &ops; + k_sem_init(&att->tx_sem, CONFIG_BT_ATT_TX_MAX, + CONFIG_BT_ATT_TX_MAX); - *chan = &att->chan.chan; + *chan = &att->chan.chan; - return 0; - } + return 0; + } - BT_ERR("No available ATT context for conn %p", conn); + BT_ERR("No available ATT context for conn %p", conn); - return -ENOMEM; + return -ENOMEM; } BT_L2CAP_CHANNEL_DEFINE(att_fixed_chan, BT_L2CAP_CID_ATT, bt_att_accept); @@ -2301,113 +2301,113 @@ BT_L2CAP_CHANNEL_DEFINE(att_fixed_chan, BT_L2CAP_CID_ATT, bt_att_accept); void bt_att_init(void) { #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) - static struct bt_l2cap_fixed_chan chan = { - .cid = BT_L2CAP_CID_ATT, - .accept = bt_att_accept, - }; + static struct bt_l2cap_fixed_chan chan = { + .cid = BT_L2CAP_CID_ATT, + .accept = bt_att_accept, + }; - bt_l2cap_le_fixed_chan_register(&chan); + bt_l2cap_le_fixed_chan_register(&chan); #endif - bt_gatt_init(); + bt_gatt_init(); } u16_t bt_att_get_mtu(struct bt_conn *conn) { - struct bt_att *att; + struct bt_att *att; - att = att_chan_get(conn); - if (!att) { - return 0; - } + att = att_chan_get(conn); + if (!att) { + return 0; + } - /* tx and rx MTU shall be symmetric */ - return att->chan.tx.mtu; + /* tx and rx MTU shall be symmetric */ + return att->chan.tx.mtu; } int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, - void *user_data) + void *user_data) { - struct bt_att *att; - int err; + struct bt_att *att; + int err; - __ASSERT_NO_MSG(conn); - __ASSERT_NO_MSG(buf); + __ASSERT_NO_MSG(conn); + __ASSERT_NO_MSG(buf); - att = att_chan_get(conn); - if (!att) { - net_buf_unref(buf); - return -ENOTCONN; - } + att = att_chan_get(conn); + if (!att) { + net_buf_unref(buf); + return -ENOTCONN; + } - /* Don't use tx_sem if caller has set it own callback */ - if (!cb) { - /* Queue buffer to be send later */ - if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) { - k_fifo_put(&att->tx_queue, buf); - return 0; - } - } + /* Don't use tx_sem if caller has set it own callback */ + if (!cb) { + /* Queue buffer to be send later */ + if (k_sem_take(&att->tx_sem, K_NO_WAIT) < 0) { + k_fifo_put(&att->tx_queue, buf); + return 0; + } + } - err = att_send(conn, buf, cb, user_data); - if (err) { - if (!cb) { - k_sem_give(&att->tx_sem); - } - return err; - } + err = att_send(conn, buf, cb, user_data); + if (err) { + if (!cb) { + k_sem_give(&att->tx_sem); + } + return err; + } - return 0; + return 0; } int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req) { - struct bt_att *att; + struct bt_att *att; - BT_DBG("conn %p req %p", conn, req); + BT_DBG("conn %p req %p", conn, req); - __ASSERT_NO_MSG(conn); - __ASSERT_NO_MSG(req); + __ASSERT_NO_MSG(conn); + __ASSERT_NO_MSG(req); - att = att_chan_get(conn); - if (!att) { - net_buf_unref(req->buf); - req->buf = NULL; - return -ENOTCONN; - } + att = att_chan_get(conn); + if (!att) { + net_buf_unref(req->buf); + req->buf = NULL; + return -ENOTCONN; + } - /* Check if there is a request outstanding */ - if (att->req) { - /* Queue the request to be send later */ - sys_slist_append(&att->reqs, &req->node); - return 0; - } + /* Check if there is a request outstanding */ + if (att->req) { + /* Queue the request to be send later */ + sys_slist_append(&att->reqs, &req->node); + return 0; + } - return att_send_req(att, req); + return att_send_req(att, req); } void bt_att_req_cancel(struct bt_conn *conn, struct bt_att_req *req) { - struct bt_att *att; + struct bt_att *att; - BT_DBG("req %p", req); + BT_DBG("req %p", req); - if (!conn || !req) { - return; - } + if (!conn || !req) { + return; + } - att = att_chan_get(conn); - if (!att) { - return; - } + att = att_chan_get(conn); + if (!att) { + return; + } - /* Check if request is outstanding */ - if (att->req == req) { - att->req = &cancel; - } else { - /* Remove request from the list */ - sys_slist_find_and_remove(&att->reqs, &req->node); - } + /* Check if request is outstanding */ + if (att->req == req) { + att->req = &cancel; + } else { + /* Remove request from the list */ + sys_slist_find_and_remove(&att->reqs, &req->node); + } - att_req_destroy(req); + att_req_destroy(req); } diff --git a/components/network/ble/blestack/src/host/att_internal.h b/components/network/ble/blestack/src/host/att_internal.h index 52f499a5..ce300aa9 100644 --- a/components/network/ble/blestack/src/host/att_internal.h +++ b/components/network/ble/blestack/src/host/att_internal.h @@ -6,7 +6,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -#define BT_ATT_DEFAULT_LE_MTU 23 +#define BT_ATT_DEFAULT_LE_MTU 23 #if BT_L2CAP_RX_MTU < CONFIG_BT_L2CAP_TX_MTU #define BT_ATT_MTU BT_L2CAP_RX_MTU @@ -15,225 +15,225 @@ #endif struct bt_att_hdr { - u8_t code; + u8_t code; } __packed; -#define BT_ATT_OP_ERROR_RSP 0x01 +#define BT_ATT_OP_ERROR_RSP 0x01 struct bt_att_error_rsp { - u8_t request; - u16_t handle; - u8_t error; + u8_t request; + u16_t handle; + u8_t error; } __packed; -#define BT_ATT_OP_MTU_REQ 0x02 +#define BT_ATT_OP_MTU_REQ 0x02 struct bt_att_exchange_mtu_req { - u16_t mtu; + u16_t mtu; } __packed; -#define BT_ATT_OP_MTU_RSP 0x03 +#define BT_ATT_OP_MTU_RSP 0x03 struct bt_att_exchange_mtu_rsp { - u16_t mtu; + u16_t mtu; } __packed; /* Find Information Request */ -#define BT_ATT_OP_FIND_INFO_REQ 0x04 +#define BT_ATT_OP_FIND_INFO_REQ 0x04 struct bt_att_find_info_req { - u16_t start_handle; - u16_t end_handle; + u16_t start_handle; + u16_t end_handle; } __packed; /* Format field values for BT_ATT_OP_FIND_INFO_RSP */ -#define BT_ATT_INFO_16 0x01 -#define BT_ATT_INFO_128 0x02 +#define BT_ATT_INFO_16 0x01 +#define BT_ATT_INFO_128 0x02 struct bt_att_info_16 { - u16_t handle; - u16_t uuid; + u16_t handle; + u16_t uuid; } __packed; struct bt_att_info_128 { - u16_t handle; - u8_t uuid[16]; + u16_t handle; + u8_t uuid[16]; } __packed; /* Find Information Response */ -#define BT_ATT_OP_FIND_INFO_RSP 0x05 +#define BT_ATT_OP_FIND_INFO_RSP 0x05 struct bt_att_find_info_rsp { - u8_t format; - u8_t info[0]; + u8_t format; + u8_t info[0]; } __packed; /* Find By Type Value Request */ -#define BT_ATT_OP_FIND_TYPE_REQ 0x06 +#define BT_ATT_OP_FIND_TYPE_REQ 0x06 struct bt_att_find_type_req { - u16_t start_handle; - u16_t end_handle; - u16_t type; - u8_t value[0]; + u16_t start_handle; + u16_t end_handle; + u16_t type; + u8_t value[0]; } __packed; struct bt_att_handle_group { - u16_t start_handle; - u16_t end_handle; + u16_t start_handle; + u16_t end_handle; } __packed; /* Find By Type Value Response */ -#define BT_ATT_OP_FIND_TYPE_RSP 0x07 +#define BT_ATT_OP_FIND_TYPE_RSP 0x07 struct bt_att_find_type_rsp { - struct bt_att_handle_group list[0]; + struct bt_att_handle_group list[0]; } __packed; /* Read By Type Request */ -#define BT_ATT_OP_READ_TYPE_REQ 0x08 +#define BT_ATT_OP_READ_TYPE_REQ 0x08 struct bt_att_read_type_req { - u16_t start_handle; - u16_t end_handle; - u8_t uuid[0]; + u16_t start_handle; + u16_t end_handle; + u8_t uuid[0]; } __packed; struct bt_att_data { - u16_t handle; - u8_t value[0]; + u16_t handle; + u8_t value[0]; } __packed; /* Read By Type Response */ -#define BT_ATT_OP_READ_TYPE_RSP 0x09 +#define BT_ATT_OP_READ_TYPE_RSP 0x09 struct bt_att_read_type_rsp { - u8_t len; - struct bt_att_data data[0]; + u8_t len; + struct bt_att_data data[0]; } __packed; /* Read Request */ -#define BT_ATT_OP_READ_REQ 0x0a +#define BT_ATT_OP_READ_REQ 0x0a struct bt_att_read_req { - u16_t handle; + u16_t handle; } __packed; /* Read Response */ -#define BT_ATT_OP_READ_RSP 0x0b +#define BT_ATT_OP_READ_RSP 0x0b struct bt_att_read_rsp { - u8_t value[0]; + u8_t value[0]; } __packed; /* Read Blob Request */ -#define BT_ATT_OP_READ_BLOB_REQ 0x0c +#define BT_ATT_OP_READ_BLOB_REQ 0x0c struct bt_att_read_blob_req { - u16_t handle; - u16_t offset; + u16_t handle; + u16_t offset; } __packed; /* Read Blob Response */ -#define BT_ATT_OP_READ_BLOB_RSP 0x0d +#define BT_ATT_OP_READ_BLOB_RSP 0x0d struct bt_att_read_blob_rsp { - u8_t value[0]; + u8_t value[0]; } __packed; /* Read Multiple Request */ -#define BT_ATT_READ_MULT_MIN_LEN_REQ 0x04 +#define BT_ATT_READ_MULT_MIN_LEN_REQ 0x04 -#define BT_ATT_OP_READ_MULT_REQ 0x0e +#define BT_ATT_OP_READ_MULT_REQ 0x0e struct bt_att_read_mult_req { - u16_t handles[0]; + u16_t handles[0]; } __packed; /* Read Multiple Respose */ -#define BT_ATT_OP_READ_MULT_RSP 0x0f +#define BT_ATT_OP_READ_MULT_RSP 0x0f struct bt_att_read_mult_rsp { - u8_t value[0]; + u8_t value[0]; } __packed; /* Read by Group Type Request */ -#define BT_ATT_OP_READ_GROUP_REQ 0x10 +#define BT_ATT_OP_READ_GROUP_REQ 0x10 struct bt_att_read_group_req { - u16_t start_handle; - u16_t end_handle; - u8_t uuid[0]; + u16_t start_handle; + u16_t end_handle; + u8_t uuid[0]; } __packed; struct bt_att_group_data { - u16_t start_handle; - u16_t end_handle; - u8_t value[0]; + u16_t start_handle; + u16_t end_handle; + u8_t value[0]; } __packed; /* Read by Group Type Response */ -#define BT_ATT_OP_READ_GROUP_RSP 0x11 +#define BT_ATT_OP_READ_GROUP_RSP 0x11 struct bt_att_read_group_rsp { - u8_t len; - struct bt_att_group_data data[0]; + u8_t len; + struct bt_att_group_data data[0]; } __packed; /* Write Request */ -#define BT_ATT_OP_WRITE_REQ 0x12 +#define BT_ATT_OP_WRITE_REQ 0x12 struct bt_att_write_req { - u16_t handle; - u8_t value[0]; + u16_t handle; + u8_t value[0]; } __packed; /* Write Response */ -#define BT_ATT_OP_WRITE_RSP 0x13 +#define BT_ATT_OP_WRITE_RSP 0x13 /* Prepare Write Request */ -#define BT_ATT_OP_PREPARE_WRITE_REQ 0x16 +#define BT_ATT_OP_PREPARE_WRITE_REQ 0x16 struct bt_att_prepare_write_req { - u16_t handle; - u16_t offset; - u8_t value[0]; + u16_t handle; + u16_t offset; + u8_t value[0]; } __packed; /* Prepare Write Respond */ -#define BT_ATT_OP_PREPARE_WRITE_RSP 0x17 +#define BT_ATT_OP_PREPARE_WRITE_RSP 0x17 struct bt_att_prepare_write_rsp { - u16_t handle; - u16_t offset; - u8_t value[0]; + u16_t handle; + u16_t offset; + u8_t value[0]; } __packed; /* Execute Write Request */ -#define BT_ATT_FLAG_CANCEL 0x00 -#define BT_ATT_FLAG_EXEC 0x01 +#define BT_ATT_FLAG_CANCEL 0x00 +#define BT_ATT_FLAG_EXEC 0x01 -#define BT_ATT_OP_EXEC_WRITE_REQ 0x18 +#define BT_ATT_OP_EXEC_WRITE_REQ 0x18 struct bt_att_exec_write_req { - u8_t flags; + u8_t flags; } __packed; /* Execute Write Response */ -#define BT_ATT_OP_EXEC_WRITE_RSP 0x19 +#define BT_ATT_OP_EXEC_WRITE_RSP 0x19 /* Handle Value Notification */ -#define BT_ATT_OP_NOTIFY 0x1b +#define BT_ATT_OP_NOTIFY 0x1b struct bt_att_notify { - u16_t handle; - u8_t value[0]; + u16_t handle; + u8_t value[0]; } __packed; /* Handle Value Indication */ -#define BT_ATT_OP_INDICATE 0x1d +#define BT_ATT_OP_INDICATE 0x1d struct bt_att_indicate { - u16_t handle; - u8_t value[0]; + u16_t handle; + u8_t value[0]; } __packed; /* Handle Value Confirm */ -#define BT_ATT_OP_CONFIRM 0x1e +#define BT_ATT_OP_CONFIRM 0x1e struct bt_att_signature { - u8_t value[12]; + u8_t value[12]; } __packed; /* Write Command */ -#define BT_ATT_OP_WRITE_CMD 0x52 +#define BT_ATT_OP_WRITE_CMD 0x52 struct bt_att_write_cmd { - u16_t handle; - u8_t value[0]; + u16_t handle; + u8_t value[0]; } __packed; /* Signed Write Command */ -#define BT_ATT_OP_SIGNED_WRITE_CMD 0xd2 +#define BT_ATT_OP_SIGNED_WRITE_CMD 0xd2 struct bt_att_signed_write_cmd { - u16_t handle; - u8_t value[0]; + u16_t handle; + u8_t value[0]; } __packed; void att_pdu_sent(struct bt_conn *conn, void *user_data); @@ -247,11 +247,11 @@ void att_req_sent(struct bt_conn *conn, void *user_data); void bt_att_init(void); u16_t bt_att_get_mtu(struct bt_conn *conn); struct net_buf *bt_att_create_pdu(struct bt_conn *conn, u8_t op, - size_t len); + size_t len); /* Send ATT PDU over a connection */ int bt_att_send(struct bt_conn *conn, struct net_buf *buf, bt_conn_tx_cb_t cb, - void *user_data); + void *user_data); /* Send ATT Request over a connection */ int bt_att_req_send(struct bt_conn *conn, struct bt_att_req *req); diff --git a/components/network/ble/blestack/src/host/conn.c b/components/network/ble/blestack/src/host/conn.c index daf91ee2..f92274e0 100644 --- a/components/network/ble/blestack/src/host/conn.c +++ b/components/network/ble/blestack/src/host/conn.c @@ -40,14 +40,14 @@ extern struct k_sem g_poll_sem; #endif struct tx_meta { - struct bt_conn_tx *tx; + struct bt_conn_tx *tx; }; #define tx_data(buf) ((struct tx_meta *)net_buf_user_data(buf)) NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, - BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), - sizeof(struct tx_meta), NULL); + BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_TX_MTU), + sizeof(struct tx_meta), NULL); #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0 @@ -64,12 +64,12 @@ NET_BUF_POOL_DEFINE(acl_tx_pool, CONFIG_BT_L2CAP_TX_BUF_COUNT, * another buffer from the acl_tx_pool would result in a deadlock. */ NET_BUF_POOL_FIXED_DEFINE(frag_pool, CONFIG_BT_L2CAP_TX_FRAG_COUNT, FRAG_SIZE, - NULL); + NULL); #endif /* CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0 */ /* How long until we cancel HCI_LE_Create_Connection */ -#define CONN_TIMEOUT K_SECONDS(CONFIG_BT_CREATE_CONN_TIMEOUT) +#define CONN_TIMEOUT K_SECONDS(CONFIG_BT_CREATE_CONN_TIMEOUT) #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) const struct bt_conn_auth_cb *bt_auth; @@ -85,307 +85,307 @@ K_FIFO_DEFINE(free_tx); static struct bt_conn sco_conns[CONFIG_BT_MAX_SCO_CONN]; enum pairing_method { - LEGACY, /* Legacy (pre-SSP) pairing */ - JUST_WORKS, /* JustWorks pairing */ - PASSKEY_INPUT, /* Passkey Entry input */ - PASSKEY_DISPLAY, /* Passkey Entry display */ - PASSKEY_CONFIRM, /* Passkey confirm */ + LEGACY, /* Legacy (pre-SSP) pairing */ + JUST_WORKS, /* JustWorks pairing */ + PASSKEY_INPUT, /* Passkey Entry input */ + PASSKEY_DISPLAY, /* Passkey Entry display */ + PASSKEY_CONFIRM, /* Passkey confirm */ }; /* based on table 5.7, Core Spec 4.2, Vol.3 Part C, 5.2.2.6 */ static const u8_t ssp_method[4 /* remote */][4 /* local */] = { - { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS }, - { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS }, - { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS }, - { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, + { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS }, + { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS }, + { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS }, + { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, }; #endif /* CONFIG_BT_BREDR */ struct k_sem *bt_conn_get_pkts(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) { - return &bt_dev.br.pkts; - } + if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) { + return &bt_dev.br.pkts; + } #endif /* CONFIG_BT_BREDR */ - return &bt_dev.le.pkts; + return &bt_dev.le.pkts; } static inline const char *state2str(bt_conn_state_t state) { - switch (state) { - case BT_CONN_DISCONNECTED: - return "disconnected"; - case BT_CONN_CONNECT_SCAN: - return "connect-scan"; - case BT_CONN_CONNECT_DIR_ADV: - return "connect-dir-adv"; - case BT_CONN_CONNECT: - return "connect"; - case BT_CONN_CONNECTED: - return "connected"; - case BT_CONN_DISCONNECT: - return "disconnect"; - default: - return "(unknown)"; - } + switch (state) { + case BT_CONN_DISCONNECTED: + return "disconnected"; + case BT_CONN_CONNECT_SCAN: + return "connect-scan"; + case BT_CONN_CONNECT_DIR_ADV: + return "connect-dir-adv"; + case BT_CONN_CONNECT: + return "connect"; + case BT_CONN_CONNECTED: + return "connected"; + case BT_CONN_DISCONNECT: + return "disconnect"; + default: + return "(unknown)"; + } } static void notify_connected(struct bt_conn *conn) { - struct bt_conn_cb *cb; + struct bt_conn_cb *cb; - for (cb = callback_list; cb; cb = cb->_next) { - if (cb->connected) { - cb->connected(conn, conn->err); - } - } + for (cb = callback_list; cb; cb = cb->_next) { + if (cb->connected) { + cb->connected(conn, conn->err); + } + } - if (!conn->err) { - bt_gatt_connected(conn); - } + if (!conn->err) { + bt_gatt_connected(conn); + } } static void notify_disconnected(struct bt_conn *conn) { - struct bt_conn_cb *cb; + struct bt_conn_cb *cb; - for (cb = callback_list; cb; cb = cb->_next) { - if (cb->disconnected) { - cb->disconnected(conn, conn->err); - } - } + for (cb = callback_list; cb; cb = cb->_next) { + if (cb->disconnected) { + cb->disconnected(conn, conn->err); + } + } } void notify_le_param_updated(struct bt_conn *conn) { - struct bt_conn_cb *cb; + struct bt_conn_cb *cb; - /* If new connection parameters meet requirement of pending - * parameters don't send slave conn param request anymore on timeout - */ - if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) && - conn->le.interval >= conn->le.interval_min && - conn->le.interval <= conn->le.interval_max && - conn->le.latency == conn->le.pending_latency && - conn->le.timeout == conn->le.pending_timeout) { - atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); - } + /* If new connection parameters meet requirement of pending + * parameters don't send slave conn param request anymore on timeout + */ + if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET) && + conn->le.interval >= conn->le.interval_min && + conn->le.interval <= conn->le.interval_max && + conn->le.latency == conn->le.pending_latency && + conn->le.timeout == conn->le.pending_timeout) { + atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); + } - for (cb = callback_list; cb; cb = cb->_next) { - if (cb->le_param_updated) { - cb->le_param_updated(conn, conn->le.interval, - conn->le.latency, - conn->le.timeout); - } - } + for (cb = callback_list; cb; cb = cb->_next) { + if (cb->le_param_updated) { + cb->le_param_updated(conn, conn->le.interval, + conn->le.latency, + conn->le.timeout); + } + } } bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param) { - struct bt_conn_cb *cb; + struct bt_conn_cb *cb; - if (!bt_le_conn_params_valid(param)) { - return false; - } + if (!bt_le_conn_params_valid(param)) { + return false; + } - for (cb = callback_list; cb; cb = cb->_next) { - if (!cb->le_param_req) { - continue; - } + for (cb = callback_list; cb; cb = cb->_next) { + if (!cb->le_param_req) { + continue; + } - if (!cb->le_param_req(conn, param)) { - return false; - } + if (!cb->le_param_req(conn, param)) { + return false; + } - /* The callback may modify the parameters so we need to - * double-check that it returned valid parameters. - */ - if (!bt_le_conn_params_valid(param)) { - return false; - } - } + /* The callback may modify the parameters so we need to + * double-check that it returned valid parameters. + */ + if (!bt_le_conn_params_valid(param)) { + return false; + } + } - /* Default to accepting if there's no app callback */ - return true; + /* Default to accepting if there's no app callback */ + return true; } static int send_conn_le_param_update(struct bt_conn *conn, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, - conn->le.features[0], param->interval_min, - param->interval_max, param->latency, param->timeout); + BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, + conn->le.features[0], param->interval_min, + param->interval_max, param->latency, param->timeout); - /* Use LE connection parameter request if both local and remote support - * it; or if local role is master then use LE connection update. - */ - if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) && - BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) && - !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) || - (conn->role == BT_HCI_ROLE_MASTER)) { - int rc; + /* Use LE connection parameter request if both local and remote support + * it; or if local role is master then use LE connection update. + */ + if ((BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features) && + BT_FEAT_LE_CONN_PARAM_REQ_PROC(conn->le.features) && + !atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_L2CAP)) || + (conn->role == BT_HCI_ROLE_MASTER)) { + int rc; - rc = bt_conn_le_conn_update(conn, param); + rc = bt_conn_le_conn_update(conn, param); - /* store those in case of fallback to L2CAP */ - if (rc == 0) { - conn->le.pending_latency = param->latency; - conn->le.pending_timeout = param->timeout; - } + /* store those in case of fallback to L2CAP */ + if (rc == 0) { + conn->le.pending_latency = param->latency; + conn->le.pending_timeout = param->timeout; + } - return rc; - } + return rc; + } - /* If remote master does not support LL Connection Parameters Request - * Procedure - */ - return bt_l2cap_update_conn_param(conn, param); + /* If remote master does not support LL Connection Parameters Request + * Procedure + */ + return bt_l2cap_update_conn_param(conn, param); } static void tx_free(struct bt_conn_tx *tx) { - tx->cb = NULL; - tx->user_data = NULL; - tx->pending_no_cb = 0U; - k_fifo_put(&free_tx, tx); + tx->cb = NULL; + tx->user_data = NULL; + tx->pending_no_cb = 0U; + k_fifo_put(&free_tx, tx); } static void tx_notify(struct bt_conn *conn) { - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - while (1) { - struct bt_conn_tx *tx; - unsigned int key; - bt_conn_tx_cb_t cb; - void *user_data; + while (1) { + struct bt_conn_tx *tx; + unsigned int key; + bt_conn_tx_cb_t cb; + void *user_data; - key = irq_lock(); - if (sys_slist_is_empty(&conn->tx_complete)) { - irq_unlock(key); - break; - } + key = irq_lock(); + if (sys_slist_is_empty(&conn->tx_complete)) { + irq_unlock(key); + break; + } - tx = (void *)sys_slist_get_not_empty(&conn->tx_complete); - irq_unlock(key); + tx = (void *)sys_slist_get_not_empty(&conn->tx_complete); + irq_unlock(key); - BT_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data); + BT_DBG("tx %p cb %p user_data %p", tx, tx->cb, tx->user_data); - /* Copy over the params */ - cb = tx->cb; - user_data = tx->user_data; + /* Copy over the params */ + cb = tx->cb; + user_data = tx->user_data; - /* Free up TX notify since there may be user waiting */ - tx_free(tx); + /* Free up TX notify since there may be user waiting */ + tx_free(tx); - /* Run the callback, at this point it should be safe to - * allocate new buffers since the TX should have been - * unblocked by tx_free. - */ - cb(conn, user_data); - } + /* Run the callback, at this point it should be safe to + * allocate new buffers since the TX should have been + * unblocked by tx_free. + */ + cb(conn, user_data); + } } static void tx_complete_work(struct k_work *work) { - struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, - tx_complete_work); + struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, + tx_complete_work); - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - tx_notify(conn); + tx_notify(conn); } static void conn_update_timeout(struct k_work *work) { - struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, update_work); - const struct bt_le_conn_param *param; + struct bt_conn *conn = CONTAINER_OF(work, struct bt_conn, update_work); + const struct bt_le_conn_param *param; - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - if (conn->state == BT_CONN_DISCONNECTED) { - bt_l2cap_disconnected(conn); - notify_disconnected(conn); + if (conn->state == BT_CONN_DISCONNECTED) { + bt_l2cap_disconnected(conn); + notify_disconnected(conn); - /* Release the reference we took for the very first - * state transition. - */ - bt_conn_unref(conn); - return; - } + /* Release the reference we took for the very first + * state transition. + */ + bt_conn_unref(conn); + return; + } - if (conn->type != BT_CONN_TYPE_LE) { - return; - } + if (conn->type != BT_CONN_TYPE_LE) { + return; + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_CONN_ROLE_MASTER) { - /* we don't call bt_conn_disconnect as it would also clear - * auto connect flag if it was set, instead just cancel - * connection directly - */ - bt_hci_cmd_send(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL); - return; - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_CONN_ROLE_MASTER) { + /* we don't call bt_conn_disconnect as it would also clear + * auto connect flag if it was set, instead just cancel + * connection directly + */ + bt_hci_cmd_send(BT_HCI_OP_LE_CREATE_CONN_CANCEL, NULL); + return; + } #if defined (CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS) - /* if application set own params use those, otherwise use defaults */ - if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) { - param = BT_LE_CONN_PARAM(conn->le.interval_min, - conn->le.interval_max, - conn->le.pending_latency, - conn->le.pending_timeout); + /* if application set own params use those, otherwise use defaults */ + if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) { + param = BT_LE_CONN_PARAM(conn->le.interval_min, + conn->le.interval_max, + conn->le.pending_latency, + conn->le.pending_timeout); - send_conn_le_param_update(conn, param); - } else { - param = BT_LE_CONN_PARAM(CONFIG_BT_PERIPHERAL_PREF_MIN_INT, - CONFIG_BT_PERIPHERAL_PREF_MAX_INT, - CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY, - CONFIG_BT_PERIPHERAL_PREF_TIMEOUT); + send_conn_le_param_update(conn, param); + } else { + param = BT_LE_CONN_PARAM(CONFIG_BT_PERIPHERAL_PREF_MIN_INT, + CONFIG_BT_PERIPHERAL_PREF_MAX_INT, + CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY, + CONFIG_BT_PERIPHERAL_PREF_TIMEOUT); - send_conn_le_param_update(conn, param); - } + send_conn_le_param_update(conn, param); + } #else - /* update only if application set own params */ - if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) { - param = BT_LE_CONN_PARAM(conn->le.interval_min, - conn->le.interval_max, - conn->le.latency, - conn->le.timeout); + /* update only if application set own params */ + if (atomic_test_and_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET)) { + param = BT_LE_CONN_PARAM(conn->le.interval_min, + conn->le.interval_max, + conn->le.latency, + conn->le.timeout); - send_conn_le_param_update(conn, param); - } + send_conn_le_param_update(conn, param); + } #endif - atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE); + atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE); } static struct bt_conn *conn_new(void) { - struct bt_conn *conn = NULL; - int i; + struct bt_conn *conn = NULL; + int i; - for (i = 0; i < ARRAY_SIZE(conns); i++) { - if (!atomic_get(&conns[i].ref)) { - conn = &conns[i]; - break; - } - } + for (i = 0; i < ARRAY_SIZE(conns); i++) { + if (!atomic_get(&conns[i].ref)) { + conn = &conns[i]; + break; + } + } - if (!conn) { - return NULL; - } + if (!conn) { + return NULL; + } - (void)memset(conn, 0, sizeof(*conn)); - k_delayed_work_init(&conn->update_work, conn_update_timeout); + (void)memset(conn, 0, sizeof(*conn)); + k_delayed_work_init(&conn->update_work, conn_update_timeout); - k_work_init(&conn->tx_complete_work, tx_complete_work); + k_work_init(&conn->tx_complete_work, tx_complete_work); - atomic_set(&conn->ref, 1); + atomic_set(&conn->ref, 1); - return conn; + return conn; } #if defined(BFLB_BLE) @@ -396,7 +396,7 @@ bool le_check_valid_conn(void) for(i= 0; i < ARRAY_SIZE(conns); i++){ if(atomic_get(&conns[i].ref)){ return true; - } + } } return false; @@ -406,1080 +406,1080 @@ bool le_check_valid_conn(void) #if defined(CONFIG_BT_BREDR) void bt_sco_cleanup(struct bt_conn *sco_conn) { - bt_conn_unref(sco_conn->sco.acl); - sco_conn->sco.acl = NULL; - bt_conn_unref(sco_conn); + bt_conn_unref(sco_conn->sco.acl); + sco_conn->sco.acl = NULL; + bt_conn_unref(sco_conn); } static struct bt_conn *sco_conn_new(void) { - struct bt_conn *sco_conn = NULL; - int i; + struct bt_conn *sco_conn = NULL; + int i; - for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { - if (!atomic_get(&sco_conns[i].ref)) { - sco_conn = &sco_conns[i]; - break; - } - } + for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { + if (!atomic_get(&sco_conns[i].ref)) { + sco_conn = &sco_conns[i]; + break; + } + } - if (!sco_conn) { - return NULL; - } + if (!sco_conn) { + return NULL; + } - (void)memset(sco_conn, 0, sizeof(*sco_conn)); + (void)memset(sco_conn, 0, sizeof(*sco_conn)); - atomic_set(&sco_conn->ref, 1); + atomic_set(&sco_conn->ref, 1); - return sco_conn; + return sco_conn; } struct bt_conn *bt_conn_create_br(const bt_addr_t *peer, - const struct bt_br_conn_param *param) + const struct bt_br_conn_param *param) { - struct bt_hci_cp_connect *cp; - struct bt_conn *conn; - struct net_buf *buf; + struct bt_hci_cp_connect *cp; + struct bt_conn *conn; + struct net_buf *buf; - conn = bt_conn_lookup_addr_br(peer); - if (conn) { - switch (conn->state) { - case BT_CONN_CONNECT: - case BT_CONN_CONNECTED: - return conn; - default: - bt_conn_unref(conn); - return NULL; - } - } + conn = bt_conn_lookup_addr_br(peer); + if (conn) { + switch (conn->state) { + case BT_CONN_CONNECT: + case BT_CONN_CONNECTED: + return conn; + default: + bt_conn_unref(conn); + return NULL; + } + } - conn = bt_conn_add_br(peer); - if (!conn) { - return NULL; - } + conn = bt_conn_add_br(peer); + if (!conn) { + return NULL; + } - buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp)); - if (!buf) { - bt_conn_unref(conn); - return NULL; - } + buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT, sizeof(*cp)); + if (!buf) { + bt_conn_unref(conn); + return NULL; + } - cp = net_buf_add(buf, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); - (void)memset(cp, 0, sizeof(*cp)); + (void)memset(cp, 0, sizeof(*cp)); - memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr)); - cp->packet_type = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */ - cp->pscan_rep_mode = 0x02; /* R2 */ - cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00; - cp->clock_offset = 0x0000; /* TODO used cached clock offset */ + memcpy(&cp->bdaddr, peer, sizeof(cp->bdaddr)); + cp->packet_type = sys_cpu_to_le16(0xcc18); /* DM1 DH1 DM3 DH5 DM5 DH5 */ + cp->pscan_rep_mode = 0x02; /* R2 */ + cp->allow_role_switch = param->allow_role_switch ? 0x01 : 0x00; + cp->clock_offset = 0x0000; /* TODO used cached clock offset */ - if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) { - bt_conn_unref(conn); - return NULL; - } + if (bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT, buf, NULL) < 0) { + bt_conn_unref(conn); + return NULL; + } - bt_conn_set_state(conn, BT_CONN_CONNECT); - conn->role = BT_CONN_ROLE_MASTER; + bt_conn_set_state(conn, BT_CONN_CONNECT); + conn->role = BT_CONN_ROLE_MASTER; - return conn; + return conn; } struct bt_conn *bt_conn_create_sco(const bt_addr_t *peer) { - struct bt_hci_cp_setup_sync_conn *cp; - struct bt_conn *sco_conn; - struct net_buf *buf; - int link_type; + struct bt_hci_cp_setup_sync_conn *cp; + struct bt_conn *sco_conn; + struct net_buf *buf; + int link_type; - sco_conn = bt_conn_lookup_addr_sco(peer); - if (sco_conn) { - switch (sco_conn->state) { - case BT_CONN_CONNECT: - case BT_CONN_CONNECTED: - return sco_conn; - default: - bt_conn_unref(sco_conn); - return NULL; - } - } + sco_conn = bt_conn_lookup_addr_sco(peer); + if (sco_conn) { + switch (sco_conn->state) { + case BT_CONN_CONNECT: + case BT_CONN_CONNECTED: + return sco_conn; + default: + bt_conn_unref(sco_conn); + return NULL; + } + } - if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { - link_type = BT_HCI_ESCO; - } else { - link_type = BT_HCI_SCO; - } + if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { + link_type = BT_HCI_ESCO; + } else { + link_type = BT_HCI_SCO; + } - sco_conn = bt_conn_add_sco(peer, link_type); - if (!sco_conn) { - return NULL; - } + sco_conn = bt_conn_add_sco(peer, link_type); + if (!sco_conn) { + return NULL; + } - buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp)); - if (!buf) { - bt_sco_cleanup(sco_conn); - return NULL; - } + buf = bt_hci_cmd_create(BT_HCI_OP_SETUP_SYNC_CONN, sizeof(*cp)); + if (!buf) { + bt_sco_cleanup(sco_conn); + return NULL; + } - cp = net_buf_add(buf, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); - (void)memset(cp, 0, sizeof(*cp)); + (void)memset(cp, 0, sizeof(*cp)); - BT_ERR("handle : %x", sco_conn->sco.acl->handle); + BT_ERR("handle : %x", sco_conn->sco.acl->handle); - cp->handle = sco_conn->sco.acl->handle; - cp->pkt_type = sco_conn->sco.pkt_type; - cp->tx_bandwidth = 0x00001f40; - cp->rx_bandwidth = 0x00001f40; - cp->max_latency = 0x0007; - cp->retrans_effort = 0x01; - cp->content_format = BT_VOICE_CVSD_16BIT; + cp->handle = sco_conn->sco.acl->handle; + cp->pkt_type = sco_conn->sco.pkt_type; + cp->tx_bandwidth = 0x00001f40; + cp->rx_bandwidth = 0x00001f40; + cp->max_latency = 0x0007; + cp->retrans_effort = 0x01; + cp->content_format = BT_VOICE_CVSD_16BIT; - if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf, - NULL) < 0) { - bt_sco_cleanup(sco_conn); - return NULL; - } + if (bt_hci_cmd_send_sync(BT_HCI_OP_SETUP_SYNC_CONN, buf, + NULL) < 0) { + bt_sco_cleanup(sco_conn); + return NULL; + } - bt_conn_set_state(sco_conn, BT_CONN_CONNECT); + bt_conn_set_state(sco_conn, BT_CONN_CONNECT); - return sco_conn; + return sco_conn; } struct bt_conn *bt_conn_lookup_addr_sco(const bt_addr_t *peer) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { - if (!atomic_get(&sco_conns[i].ref)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { + if (!atomic_get(&sco_conns[i].ref)) { + continue; + } - if (sco_conns[i].type != BT_CONN_TYPE_SCO) { - continue; - } + if (sco_conns[i].type != BT_CONN_TYPE_SCO) { + continue; + } - if (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) { - return bt_conn_ref(&sco_conns[i]); - } - } + if (!bt_addr_cmp(peer, &sco_conns[i].sco.acl->br.dst)) { + return bt_conn_ref(&sco_conns[i]); + } + } - return NULL; + return NULL; } struct bt_conn *bt_conn_lookup_addr_br(const bt_addr_t *peer) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(conns); i++) { - if (!atomic_get(&conns[i].ref)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(conns); i++) { + if (!atomic_get(&conns[i].ref)) { + continue; + } - if (conns[i].type != BT_CONN_TYPE_BR) { - continue; - } + if (conns[i].type != BT_CONN_TYPE_BR) { + continue; + } - if (!bt_addr_cmp(peer, &conns[i].br.dst)) { - return bt_conn_ref(&conns[i]); - } - } + if (!bt_addr_cmp(peer, &conns[i].br.dst)) { + return bt_conn_ref(&conns[i]); + } + } - return NULL; + return NULL; } struct bt_conn *bt_conn_add_sco(const bt_addr_t *peer, int link_type) { - struct bt_conn *sco_conn = sco_conn_new(); + struct bt_conn *sco_conn = sco_conn_new(); - if (!sco_conn) { - return NULL; - } + if (!sco_conn) { + return NULL; + } - sco_conn->sco.acl = bt_conn_lookup_addr_br(peer); - sco_conn->type = BT_CONN_TYPE_SCO; + sco_conn->sco.acl = bt_conn_lookup_addr_br(peer); + sco_conn->type = BT_CONN_TYPE_SCO; - if (link_type == BT_HCI_SCO) { - if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { - sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & - ESCO_PKT_MASK); - } else { - sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & - SCO_PKT_MASK); - } - } else if (link_type == BT_HCI_ESCO) { - sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & - ~EDR_ESCO_PKT_MASK); - } + if (link_type == BT_HCI_SCO) { + if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { + sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & + ESCO_PKT_MASK); + } else { + sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & + SCO_PKT_MASK); + } + } else if (link_type == BT_HCI_ESCO) { + sco_conn->sco.pkt_type = (bt_dev.br.esco_pkt_type & + ~EDR_ESCO_PKT_MASK); + } - return sco_conn; + return sco_conn; } struct bt_conn *bt_conn_add_br(const bt_addr_t *peer) { - struct bt_conn *conn = conn_new(); + struct bt_conn *conn = conn_new(); - if (!conn) { - return NULL; - } + if (!conn) { + return NULL; + } - bt_addr_copy(&conn->br.dst, peer); - conn->type = BT_CONN_TYPE_BR; + bt_addr_copy(&conn->br.dst, peer); + conn->type = BT_CONN_TYPE_BR; - return conn; + return conn; } static int pin_code_neg_reply(const bt_addr_t *bdaddr) { - struct bt_hci_cp_pin_code_neg_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_pin_code_neg_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_NEG_REPLY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, bdaddr); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, bdaddr); - return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_NEG_REPLY, buf, NULL); } static int pin_code_reply(struct bt_conn *conn, const char *pin, u8_t len) { - struct bt_hci_cp_pin_code_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_pin_code_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_PIN_CODE_REPLY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, &conn->br.dst); - cp->pin_len = len; - strncpy((char *)cp->pin_code, pin, sizeof(cp->pin_code)); + bt_addr_copy(&cp->bdaddr, &conn->br.dst); + cp->pin_len = len; + strncpy((char *)cp->pin_code, pin, sizeof(cp->pin_code)); - return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_REPLY, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_PIN_CODE_REPLY, buf, NULL); } int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin) { - size_t len; + size_t len; - if (!bt_auth) { - return -EINVAL; - } + if (!bt_auth) { + return -EINVAL; + } - if (conn->type != BT_CONN_TYPE_BR) { - return -EINVAL; - } + if (conn->type != BT_CONN_TYPE_BR) { + return -EINVAL; + } - len = strlen(pin); - if (len > 16) { - return -EINVAL; - } + len = strlen(pin); + if (len > 16) { + return -EINVAL; + } - if (conn->required_sec_level == BT_SECURITY_L3 && len < 16) { - BT_WARN("PIN code for %s is not 16 bytes wide", - bt_addr_str(&conn->br.dst)); - return -EPERM; - } + if (conn->required_sec_level == BT_SECURITY_L3 && len < 16) { + BT_WARN("PIN code for %s is not 16 bytes wide", + bt_addr_str(&conn->br.dst)); + return -EPERM; + } - /* Allow user send entered PIN to remote, then reset user state. */ - if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { - return -EPERM; - } + /* Allow user send entered PIN to remote, then reset user state. */ + if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { + return -EPERM; + } - if (len == 16) { - atomic_set_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE); - } + if (len == 16) { + atomic_set_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE); + } - return pin_code_reply(conn, pin, len); + return pin_code_reply(conn, pin, len); } void bt_conn_pin_code_req(struct bt_conn *conn) { - if (bt_auth && bt_auth->pincode_entry) { - bool secure = false; + if (bt_auth && bt_auth->pincode_entry) { + bool secure = false; - if (conn->required_sec_level == BT_SECURITY_L3) { - secure = true; - } + if (conn->required_sec_level == BT_SECURITY_L3) { + secure = true; + } - atomic_set_bit(conn->flags, BT_CONN_USER); - atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING); - bt_auth->pincode_entry(conn, secure); - } else { - pin_code_neg_reply(&conn->br.dst); - } + atomic_set_bit(conn->flags, BT_CONN_USER); + atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING); + bt_auth->pincode_entry(conn, secure); + } else { + pin_code_neg_reply(&conn->br.dst); + } } u8_t bt_conn_get_io_capa(void) { - if (!bt_auth) { - return BT_IO_NO_INPUT_OUTPUT; - } + if (!bt_auth) { + return BT_IO_NO_INPUT_OUTPUT; + } - if (bt_auth->passkey_confirm && bt_auth->passkey_display) { - return BT_IO_DISPLAY_YESNO; - } + if (bt_auth->passkey_confirm && bt_auth->passkey_display) { + return BT_IO_DISPLAY_YESNO; + } - if (bt_auth->passkey_entry) { - return BT_IO_KEYBOARD_ONLY; - } + if (bt_auth->passkey_entry) { + return BT_IO_KEYBOARD_ONLY; + } - if (bt_auth->passkey_display) { - return BT_IO_DISPLAY_ONLY; - } + if (bt_auth->passkey_display) { + return BT_IO_DISPLAY_ONLY; + } - return BT_IO_NO_INPUT_OUTPUT; + return BT_IO_NO_INPUT_OUTPUT; } static u8_t ssp_pair_method(const struct bt_conn *conn) { - return ssp_method[conn->br.remote_io_capa][bt_conn_get_io_capa()]; + return ssp_method[conn->br.remote_io_capa][bt_conn_get_io_capa()]; } u8_t bt_conn_ssp_get_auth(const struct bt_conn *conn) { - /* Validate no bond auth request, and if valid use it. */ - if ((conn->br.remote_auth == BT_HCI_NO_BONDING) || - ((conn->br.remote_auth == BT_HCI_NO_BONDING_MITM) && - (ssp_pair_method(conn) > JUST_WORKS))) { - return conn->br.remote_auth; - } + /* Validate no bond auth request, and if valid use it. */ + if ((conn->br.remote_auth == BT_HCI_NO_BONDING) || + ((conn->br.remote_auth == BT_HCI_NO_BONDING_MITM) && + (ssp_pair_method(conn) > JUST_WORKS))) { + return conn->br.remote_auth; + } - /* Local & remote have enough IO capabilities to get MITM protection. */ - if (ssp_pair_method(conn) > JUST_WORKS) { - return conn->br.remote_auth | BT_MITM; - } + /* Local & remote have enough IO capabilities to get MITM protection. */ + if (ssp_pair_method(conn) > JUST_WORKS) { + return conn->br.remote_auth | BT_MITM; + } - /* No MITM protection possible so ignore remote MITM requirement. */ - return (conn->br.remote_auth & ~BT_MITM); + /* No MITM protection possible so ignore remote MITM requirement. */ + return (conn->br.remote_auth & ~BT_MITM); } static int ssp_confirm_reply(struct bt_conn *conn) { - struct bt_hci_cp_user_confirm_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_user_confirm_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_REPLY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_REPLY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, &conn->br.dst); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, &conn->br.dst); - return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_REPLY, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_REPLY, buf, NULL); } static int ssp_confirm_neg_reply(struct bt_conn *conn) { - struct bt_hci_cp_user_confirm_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_user_confirm_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, &conn->br.dst); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, &conn->br.dst); - return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, buf, - NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_USER_CONFIRM_NEG_REPLY, buf, + NULL); } void bt_conn_ssp_auth_complete(struct bt_conn *conn, u8_t status) { - if (!status) { - bool bond = !atomic_test_bit(conn->flags, BT_CONN_BR_NOBOND); + if (!status) { + bool bond = !atomic_test_bit(conn->flags, BT_CONN_BR_NOBOND); - if (bt_auth && bt_auth->pairing_complete) { - bt_auth->pairing_complete(conn, bond); - } - } else { - if (bt_auth && bt_auth->pairing_failed) { - bt_auth->pairing_failed(conn, status); - } - } + if (bt_auth && bt_auth->pairing_complete) { + bt_auth->pairing_complete(conn, bond); + } + } else { + if (bt_auth && bt_auth->pairing_failed) { + bt_auth->pairing_failed(conn, status); + } + } } void bt_conn_ssp_auth(struct bt_conn *conn, u32_t passkey) { - conn->br.pairing_method = ssp_pair_method(conn); + conn->br.pairing_method = ssp_pair_method(conn); - /* - * If local required security is HIGH then MITM is mandatory. - * MITM protection is no achievable when SSP 'justworks' is applied. - */ - if (conn->required_sec_level > BT_SECURITY_L2 && - conn->br.pairing_method == JUST_WORKS) { - BT_DBG("MITM protection infeasible for required security"); - ssp_confirm_neg_reply(conn); - return; - } + /* + * If local required security is HIGH then MITM is mandatory. + * MITM protection is no achievable when SSP 'justworks' is applied. + */ + if (conn->required_sec_level > BT_SECURITY_L2 && + conn->br.pairing_method == JUST_WORKS) { + BT_DBG("MITM protection infeasible for required security"); + ssp_confirm_neg_reply(conn); + return; + } - switch (conn->br.pairing_method) { - case PASSKEY_CONFIRM: - atomic_set_bit(conn->flags, BT_CONN_USER); - bt_auth->passkey_confirm(conn, passkey); - break; - case PASSKEY_DISPLAY: - atomic_set_bit(conn->flags, BT_CONN_USER); - bt_auth->passkey_display(conn, passkey); - break; - case PASSKEY_INPUT: - atomic_set_bit(conn->flags, BT_CONN_USER); - bt_auth->passkey_entry(conn); - break; - case JUST_WORKS: - /* - * When local host works as pairing acceptor and 'justworks' - * model is applied then notify user about such pairing request. - * [BT Core 4.2 table 5.7, Vol 3, Part C, 5.2.2.6] - */ - if (bt_auth && bt_auth->pairing_confirm && - !atomic_test_bit(conn->flags, - BT_CONN_BR_PAIRING_INITIATOR)) { - atomic_set_bit(conn->flags, BT_CONN_USER); - bt_auth->pairing_confirm(conn); - break; - } - ssp_confirm_reply(conn); - break; - default: - break; - } + switch (conn->br.pairing_method) { + case PASSKEY_CONFIRM: + atomic_set_bit(conn->flags, BT_CONN_USER); + bt_auth->passkey_confirm(conn, passkey); + break; + case PASSKEY_DISPLAY: + atomic_set_bit(conn->flags, BT_CONN_USER); + bt_auth->passkey_display(conn, passkey); + break; + case PASSKEY_INPUT: + atomic_set_bit(conn->flags, BT_CONN_USER); + bt_auth->passkey_entry(conn); + break; + case JUST_WORKS: + /* + * When local host works as pairing acceptor and 'justworks' + * model is applied then notify user about such pairing request. + * [BT Core 4.2 table 5.7, Vol 3, Part C, 5.2.2.6] + */ + if (bt_auth && bt_auth->pairing_confirm && + !atomic_test_bit(conn->flags, + BT_CONN_BR_PAIRING_INITIATOR)) { + atomic_set_bit(conn->flags, BT_CONN_USER); + bt_auth->pairing_confirm(conn); + break; + } + ssp_confirm_reply(conn); + break; + default: + break; + } } static int ssp_passkey_reply(struct bt_conn *conn, unsigned int passkey) { - struct bt_hci_cp_user_passkey_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_user_passkey_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_REPLY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_REPLY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, &conn->br.dst); - cp->passkey = sys_cpu_to_le32(passkey); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, &conn->br.dst); + cp->passkey = sys_cpu_to_le32(passkey); - return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_REPLY, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_REPLY, buf, NULL); } static int ssp_passkey_neg_reply(struct bt_conn *conn) { - struct bt_hci_cp_user_passkey_neg_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_user_passkey_neg_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, &conn->br.dst); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, &conn->br.dst); - return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, buf, - NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_USER_PASSKEY_NEG_REPLY, buf, + NULL); } static int bt_hci_connect_br_cancel(struct bt_conn *conn) { - struct bt_hci_cp_connect_cancel *cp; - struct bt_hci_rp_connect_cancel *rp; - struct net_buf *buf, *rsp; - int err; + struct bt_hci_cp_connect_cancel *cp; + struct bt_hci_rp_connect_cancel *rp; + struct net_buf *buf, *rsp; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_CONNECT_CANCEL, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr)); + cp = net_buf_add(buf, sizeof(*cp)); + memcpy(&cp->bdaddr, &conn->br.dst, sizeof(cp->bdaddr)); - err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_CONNECT_CANCEL, buf, &rsp); + if (err) { + return err; + } - rp = (void *)rsp->data; + rp = (void *)rsp->data; - err = rp->status ? -EIO : 0; + err = rp->status ? -EIO : 0; - net_buf_unref(rsp); + net_buf_unref(rsp); - return err; + return err; } static int conn_auth(struct bt_conn *conn) { - struct bt_hci_cp_auth_requested *auth; - struct net_buf *buf; + struct bt_hci_cp_auth_requested *auth; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_AUTH_REQUESTED, sizeof(*auth)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_AUTH_REQUESTED, sizeof(*auth)); + if (!buf) { + return -ENOBUFS; + } - auth = net_buf_add(buf, sizeof(*auth)); - auth->handle = sys_cpu_to_le16(conn->handle); + auth = net_buf_add(buf, sizeof(*auth)); + auth->handle = sys_cpu_to_le16(conn->handle); - atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR); + atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR); - return bt_hci_cmd_send_sync(BT_HCI_OP_AUTH_REQUESTED, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_AUTH_REQUESTED, buf, NULL); } #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_SMP) void bt_conn_identity_resolved(struct bt_conn *conn) { - const bt_addr_le_t *rpa; - struct bt_conn_cb *cb; + const bt_addr_le_t *rpa; + struct bt_conn_cb *cb; - if (conn->role == BT_HCI_ROLE_MASTER) { - rpa = &conn->le.resp_addr; - } else { - rpa = &conn->le.init_addr; - } + if (conn->role == BT_HCI_ROLE_MASTER) { + rpa = &conn->le.resp_addr; + } else { + rpa = &conn->le.init_addr; + } - for (cb = callback_list; cb; cb = cb->_next) { - if (cb->identity_resolved) { - cb->identity_resolved(conn, rpa, &conn->le.dst); - } - } + for (cb = callback_list; cb; cb = cb->_next) { + if (cb->identity_resolved) { + cb->identity_resolved(conn, rpa, &conn->le.dst); + } + } } int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8], - u8_t ediv[2], const u8_t *ltk, size_t len) + u8_t ediv[2], const u8_t *ltk, size_t len) { - struct bt_hci_cp_le_start_encryption *cp; - struct net_buf *buf; + struct bt_hci_cp_le_start_encryption *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_START_ENCRYPTION, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(conn->handle); - memcpy(&cp->rand, rand, sizeof(cp->rand)); - memcpy(&cp->ediv, ediv, sizeof(cp->ediv)); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(conn->handle); + memcpy(&cp->rand, rand, sizeof(cp->rand)); + memcpy(&cp->ediv, ediv, sizeof(cp->ediv)); - memcpy(cp->ltk, ltk, len); - if (len < sizeof(cp->ltk)) { - (void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len); - } + memcpy(cp->ltk, ltk, len); + if (len < sizeof(cp->ltk)) { + (void)memset(cp->ltk + len, 0, sizeof(cp->ltk) - len); + } - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_START_ENCRYPTION, buf, NULL); } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) u8_t bt_conn_enc_key_size(struct bt_conn *conn) { - if (!conn->encrypt) { - return 0; - } + if (!conn->encrypt) { + return 0; + } - if (IS_ENABLED(CONFIG_BT_BREDR) && - conn->type == BT_CONN_TYPE_BR) { - struct bt_hci_cp_read_encryption_key_size *cp; - struct bt_hci_rp_read_encryption_key_size *rp; - struct net_buf *buf; - struct net_buf *rsp; - u8_t key_size; + if (IS_ENABLED(CONFIG_BT_BREDR) && + conn->type == BT_CONN_TYPE_BR) { + struct bt_hci_cp_read_encryption_key_size *cp; + struct bt_hci_rp_read_encryption_key_size *rp; + struct net_buf *buf; + struct net_buf *rsp; + u8_t key_size; - buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, - sizeof(*cp)); - if (!buf) { - return 0; - } + buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, + sizeof(*cp)); + if (!buf) { + return 0; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(conn->handle); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(conn->handle); - if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, - buf, &rsp)) { - return 0; - } + if (bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, + buf, &rsp)) { + return 0; + } - rp = (void *)rsp->data; + rp = (void *)rsp->data; - key_size = rp->status ? 0 : rp->key_size; + key_size = rp->status ? 0 : rp->key_size; - net_buf_unref(rsp); + net_buf_unref(rsp); - return key_size; - } + return key_size; + } - if (IS_ENABLED(CONFIG_BT_SMP)) { - return conn->le.keys ? conn->le.keys->enc_size : 0; - } + if (IS_ENABLED(CONFIG_BT_SMP)) { + return conn->le.keys ? conn->le.keys->enc_size : 0; + } - return 0; + return 0; } void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err) { - struct bt_conn_cb *cb; + struct bt_conn_cb *cb; - for (cb = callback_list; cb; cb = cb->_next) { - if (cb->security_changed) { - cb->security_changed(conn, conn->sec_level, err); - } - } + for (cb = callback_list; cb; cb = cb->_next) { + if (cb->security_changed) { + cb->security_changed(conn, conn->sec_level, err); + } + } #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) - if (!err && conn->sec_level >= BT_SECURITY_L2) { - bt_keys_update_usage(conn->id, bt_conn_get_dst(conn)); - } + if (!err && conn->sec_level >= BT_SECURITY_L2) { + bt_keys_update_usage(conn->id, bt_conn_get_dst(conn)); + } #endif } static int start_security(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING)) { - return -EBUSY; - } + if (conn->type == BT_CONN_TYPE_BR) { + if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING)) { + return -EBUSY; + } - if (conn->required_sec_level > BT_SECURITY_L3) { - return -ENOTSUP; - } + if (conn->required_sec_level > BT_SECURITY_L3) { + return -ENOTSUP; + } - if (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT && - conn->required_sec_level > BT_SECURITY_L2) { - return -EINVAL; - } + if (bt_conn_get_io_capa() == BT_IO_NO_INPUT_OUTPUT && + conn->required_sec_level > BT_SECURITY_L2) { + return -EINVAL; + } - return conn_auth(conn); - } + return conn_auth(conn); + } #endif /* CONFIG_BT_BREDR */ - if (IS_ENABLED(CONFIG_BT_SMP)) { - return bt_smp_start_security(conn); - } + if (IS_ENABLED(CONFIG_BT_SMP)) { + return bt_smp_start_security(conn); + } - return -EINVAL; + return -EINVAL; } int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec) { - int err; + int err; - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) && - sec < BT_SECURITY_L4) { - return -EOPNOTSUPP; - } + if (IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) && + sec < BT_SECURITY_L4) { + return -EOPNOTSUPP; + } - /* nothing to do */ - if (conn->sec_level >= sec || conn->required_sec_level >= sec) { - return 0; - } + /* nothing to do */ + if (conn->sec_level >= sec || conn->required_sec_level >= sec) { + return 0; + } - atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR, - sec & BT_SECURITY_FORCE_PAIR); - conn->required_sec_level = sec & ~BT_SECURITY_FORCE_PAIR; + atomic_set_bit_to(conn->flags, BT_CONN_FORCE_PAIR, + sec & BT_SECURITY_FORCE_PAIR); + conn->required_sec_level = sec & ~BT_SECURITY_FORCE_PAIR; - err = start_security(conn); + err = start_security(conn); - /* reset required security level in case of error */ - if (err) { - conn->required_sec_level = conn->sec_level; - } + /* reset required security level in case of error */ + if (err) { + conn->required_sec_level = conn->sec_level; + } - return err; + return err; } bt_security_t bt_conn_get_security(struct bt_conn *conn) { - return conn->sec_level; + return conn->sec_level; } #else bt_security_t bt_conn_get_security(struct bt_conn *conn) { - return BT_SECURITY_L1; + return BT_SECURITY_L1; } #endif /* CONFIG_BT_SMP */ void bt_conn_cb_register(struct bt_conn_cb *cb) { - cb->_next = callback_list; - callback_list = cb; + cb->_next = callback_list; + callback_list = cb; } static void bt_conn_reset_rx_state(struct bt_conn *conn) { - if (!conn->rx_len) { - return; - } + if (!conn->rx_len) { + return; + } - net_buf_unref(conn->rx); - conn->rx = NULL; - conn->rx_len = 0U; + net_buf_unref(conn->rx); + conn->rx = NULL; + conn->rx_len = 0U; } void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags) { - struct bt_l2cap_hdr *hdr; - u16_t len; + struct bt_l2cap_hdr *hdr; + u16_t len; - /* Make sure we notify any pending TX callbacks before processing - * new data for this connection. - */ - tx_notify(conn); + /* Make sure we notify any pending TX callbacks before processing + * new data for this connection. + */ + tx_notify(conn); - BT_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags); + BT_DBG("handle %u len %u flags %02x", conn->handle, buf->len, flags); - /* Check packet boundary flags */ - switch (flags) { - case BT_ACL_START: - hdr = (void *)buf->data; - len = sys_le16_to_cpu(hdr->len); + /* Check packet boundary flags */ + switch (flags) { + case BT_ACL_START: + hdr = (void *)buf->data; + len = sys_le16_to_cpu(hdr->len); - BT_DBG("First, len %u final %u", buf->len, len); + BT_DBG("First, len %u final %u", buf->len, len); - if (conn->rx_len) { - BT_ERR("Unexpected first L2CAP frame"); - bt_conn_reset_rx_state(conn); - } + if (conn->rx_len) { + BT_ERR("Unexpected first L2CAP frame"); + bt_conn_reset_rx_state(conn); + } - conn->rx_len = (sizeof(*hdr) + len) - buf->len; - BT_DBG("rx_len %u", conn->rx_len); - if (conn->rx_len) { - conn->rx = buf; - return; - } + conn->rx_len = (sizeof(*hdr) + len) - buf->len; + BT_DBG("rx_len %u", conn->rx_len); + if (conn->rx_len) { + conn->rx = buf; + return; + } - break; - case BT_ACL_CONT: - if (!conn->rx_len) { - BT_ERR("Unexpected L2CAP continuation"); - bt_conn_reset_rx_state(conn); - net_buf_unref(buf); - return; - } + break; + case BT_ACL_CONT: + if (!conn->rx_len) { + BT_ERR("Unexpected L2CAP continuation"); + bt_conn_reset_rx_state(conn); + net_buf_unref(buf); + return; + } - if (buf->len > conn->rx_len) { - BT_ERR("L2CAP data overflow"); - bt_conn_reset_rx_state(conn); - net_buf_unref(buf); - return; - } + if (buf->len > conn->rx_len) { + BT_ERR("L2CAP data overflow"); + bt_conn_reset_rx_state(conn); + net_buf_unref(buf); + return; + } - BT_DBG("Cont, len %u rx_len %u", buf->len, conn->rx_len); + BT_DBG("Cont, len %u rx_len %u", buf->len, conn->rx_len); - if (buf->len > net_buf_tailroom(conn->rx)) { - BT_ERR("Not enough buffer space for L2CAP data"); - bt_conn_reset_rx_state(conn); - net_buf_unref(buf); - return; - } + if (buf->len > net_buf_tailroom(conn->rx)) { + BT_ERR("Not enough buffer space for L2CAP data"); + bt_conn_reset_rx_state(conn); + net_buf_unref(buf); + return; + } - net_buf_add_mem(conn->rx, buf->data, buf->len); - conn->rx_len -= buf->len; - net_buf_unref(buf); + net_buf_add_mem(conn->rx, buf->data, buf->len); + conn->rx_len -= buf->len; + net_buf_unref(buf); - if (conn->rx_len) { - return; - } + if (conn->rx_len) { + return; + } - buf = conn->rx; - conn->rx = NULL; - conn->rx_len = 0U; + buf = conn->rx; + conn->rx = NULL; + conn->rx_len = 0U; - break; - default: - BT_ERR("Unexpected ACL flags (0x%02x)", flags); - bt_conn_reset_rx_state(conn); - net_buf_unref(buf); - return; - } + break; + default: + BT_ERR("Unexpected ACL flags (0x%02x)", flags); + bt_conn_reset_rx_state(conn); + net_buf_unref(buf); + return; + } - hdr = (void *)buf->data; - len = sys_le16_to_cpu(hdr->len); + hdr = (void *)buf->data; + len = sys_le16_to_cpu(hdr->len); - if (sizeof(*hdr) + len != buf->len) { - BT_ERR("ACL len mismatch (%u != %u)", len, buf->len); - net_buf_unref(buf); - return; - } + if (sizeof(*hdr) + len != buf->len) { + BT_ERR("ACL len mismatch (%u != %u)", len, buf->len); + net_buf_unref(buf); + return; + } - BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len); + BT_DBG("Successfully parsed %u byte L2CAP packet", buf->len); - bt_l2cap_recv(conn, buf); + bt_l2cap_recv(conn, buf); } static struct bt_conn_tx *conn_tx_alloc(void) { - /* The TX context always get freed in the system workqueue, - * so if we're in the same workqueue but there are no immediate - * contexts available, there's no chance we'll get one by waiting. - */ + /* The TX context always get freed in the system workqueue, + * so if we're in the same workqueue but there are no immediate + * contexts available, there's no chance we'll get one by waiting. + */ #if !defined(BFLB_BLE) - if (k_current_get() == &k_sys_work_q.thread) { - return k_fifo_get(&free_tx, K_NO_WAIT); - } + if (k_current_get() == &k_sys_work_q.thread) { + return k_fifo_get(&free_tx, K_NO_WAIT); + } #endif - if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) { - struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT); + if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) { + struct bt_conn_tx *tx = k_fifo_get(&free_tx, K_NO_WAIT); - if (tx) { - return tx; - } + if (tx) { + return tx; + } - BT_WARN("Unable to get an immediate free conn_tx"); - } + BT_WARN("Unable to get an immediate free conn_tx"); + } - return k_fifo_get(&free_tx, K_FOREVER); + return k_fifo_get(&free_tx, K_FOREVER); } int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf, - bt_conn_tx_cb_t cb, void *user_data) + bt_conn_tx_cb_t cb, void *user_data) { - struct bt_conn_tx *tx; + struct bt_conn_tx *tx; - BT_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle, - buf->len, cb, user_data); + BT_DBG("conn handle %u buf len %u cb %p user_data %p", conn->handle, + buf->len, cb, user_data); - if (conn->state != BT_CONN_CONNECTED) { - BT_ERR("not connected!"); - net_buf_unref(buf); - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + BT_ERR("not connected!"); + net_buf_unref(buf); + return -ENOTCONN; + } - if (cb) { - tx = conn_tx_alloc(); - if (!tx) { - BT_ERR("Unable to allocate TX context"); - net_buf_unref(buf); - return -ENOBUFS; - } + if (cb) { + tx = conn_tx_alloc(); + if (!tx) { + BT_ERR("Unable to allocate TX context"); + net_buf_unref(buf); + return -ENOBUFS; + } - /* Verify that we're still connected after blocking */ - if (conn->state != BT_CONN_CONNECTED) { - BT_WARN("Disconnected while allocating context"); - net_buf_unref(buf); - tx_free(tx); - return -ENOTCONN; - } + /* Verify that we're still connected after blocking */ + if (conn->state != BT_CONN_CONNECTED) { + BT_WARN("Disconnected while allocating context"); + net_buf_unref(buf); + tx_free(tx); + return -ENOTCONN; + } - tx->cb = cb; - tx->user_data = user_data; - tx->pending_no_cb = 0U; + tx->cb = cb; + tx->user_data = user_data; + tx->pending_no_cb = 0U; - tx_data(buf)->tx = tx; - } else { - tx_data(buf)->tx = NULL; - } + tx_data(buf)->tx = tx; + } else { + tx_data(buf)->tx = NULL; + } - net_buf_put(&conn->tx_queue, buf); + net_buf_put(&conn->tx_queue, buf); #if defined(BFLB_BLE) k_sem_give(&g_poll_sem); #endif - return 0; + return 0; } static bool send_frag(struct bt_conn *conn, struct net_buf *buf, u8_t flags, - bool always_consume) + bool always_consume) { - struct bt_conn_tx *tx = tx_data(buf)->tx; - struct bt_hci_acl_hdr *hdr; - u32_t *pending_no_cb; - unsigned int key; - int err; + struct bt_conn_tx *tx = tx_data(buf)->tx; + struct bt_hci_acl_hdr *hdr; + u32_t *pending_no_cb; + unsigned int key; + int err; - BT_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len, - flags); + BT_DBG("conn %p buf %p len %u flags 0x%02x", conn, buf, buf->len, + flags); - /* Wait until the controller can accept ACL packets */ - k_sem_take(bt_conn_get_pkts(conn), K_FOREVER); + /* Wait until the controller can accept ACL packets */ + k_sem_take(bt_conn_get_pkts(conn), K_FOREVER); - /* Check for disconnection while waiting for pkts_sem */ - if (conn->state != BT_CONN_CONNECTED) { - goto fail; - } + /* Check for disconnection while waiting for pkts_sem */ + if (conn->state != BT_CONN_CONNECTED) { + goto fail; + } - hdr = net_buf_push(buf, sizeof(*hdr)); - hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags)); - hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); + hdr = net_buf_push(buf, sizeof(*hdr)); + hdr->handle = sys_cpu_to_le16(bt_acl_handle_pack(conn->handle, flags)); + hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); - /* Add to pending, it must be done before bt_buf_set_type */ - key = irq_lock(); - if (tx) { - sys_slist_append(&conn->tx_pending, &tx->node); - } else { - struct bt_conn_tx *tail_tx; + /* Add to pending, it must be done before bt_buf_set_type */ + key = irq_lock(); + if (tx) { + sys_slist_append(&conn->tx_pending, &tx->node); + } else { + struct bt_conn_tx *tail_tx; - tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending); - if (tail_tx) { - pending_no_cb = &tail_tx->pending_no_cb; - } else { - pending_no_cb = &conn->pending_no_cb; - } + tail_tx = (void *)sys_slist_peek_tail(&conn->tx_pending); + if (tail_tx) { + pending_no_cb = &tail_tx->pending_no_cb; + } else { + pending_no_cb = &conn->pending_no_cb; + } - (*pending_no_cb)++; - } - irq_unlock(key); + (*pending_no_cb)++; + } + irq_unlock(key); - bt_buf_set_type(buf, BT_BUF_ACL_OUT); + bt_buf_set_type(buf, BT_BUF_ACL_OUT); - err = bt_send(buf); - if (err) { - BT_ERR("Unable to send to driver (err %d)", err); - key = irq_lock(); - /* Roll back the pending TX info */ - if (tx) { - sys_slist_find_and_remove(&conn->tx_pending, &tx->node); - } else { - __ASSERT_NO_MSG(*pending_no_cb > 0); - (*pending_no_cb)--; - } - irq_unlock(key); - goto fail; - } + err = bt_send(buf); + if (err) { + BT_ERR("Unable to send to driver (err %d)", err); + key = irq_lock(); + /* Roll back the pending TX info */ + if (tx) { + sys_slist_find_and_remove(&conn->tx_pending, &tx->node); + } else { + __ASSERT_NO_MSG(*pending_no_cb > 0); + (*pending_no_cb)--; + } + irq_unlock(key); + goto fail; + } - return true; + return true; fail: - k_sem_give(bt_conn_get_pkts(conn)); - if (tx) { - tx_free(tx); - } + k_sem_give(bt_conn_get_pkts(conn)); + if (tx) { + tx_free(tx); + } - if (always_consume) { - net_buf_unref(buf); - } - return false; + if (always_consume) { + net_buf_unref(buf); + } + return false; } static inline u16_t conn_mtu(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) { - return bt_dev.br.mtu; - } + if (conn->type == BT_CONN_TYPE_BR || !bt_dev.le.mtu) { + return bt_dev.br.mtu; + } #endif /* CONFIG_BT_BREDR */ - return bt_dev.le.mtu; + return bt_dev.le.mtu; } static struct net_buf *create_frag(struct bt_conn *conn, struct net_buf *buf) { - struct net_buf *frag; - u16_t frag_len; + struct net_buf *frag; + u16_t frag_len; #if CONFIG_BT_L2CAP_TX_FRAG_COUNT > 0 - frag = bt_conn_create_pdu(&frag_pool, 0); + frag = bt_conn_create_pdu(&frag_pool, 0); #else - frag = bt_conn_create_pdu(NULL, 0); + frag = bt_conn_create_pdu(NULL, 0); #endif - if (conn->state != BT_CONN_CONNECTED) { - net_buf_unref(frag); - return NULL; - } + if (conn->state != BT_CONN_CONNECTED) { + net_buf_unref(frag); + return NULL; + } - /* Fragments never have a TX completion callback */ - tx_data(frag)->tx = NULL; + /* Fragments never have a TX completion callback */ + tx_data(frag)->tx = NULL; - frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag)); + frag_len = MIN(conn_mtu(conn), net_buf_tailroom(frag)); - net_buf_add_mem(frag, buf->data, frag_len); - net_buf_pull(buf, frag_len); + net_buf_add_mem(frag, buf->data, frag_len); + net_buf_pull(buf, frag_len); - return frag; + return frag; } static bool send_buf(struct bt_conn *conn, struct net_buf *buf) { - struct net_buf *frag; + struct net_buf *frag; - BT_DBG("conn %p buf %p len %u", conn, buf, buf->len); + BT_DBG("conn %p buf %p len %u", conn, buf, buf->len); - /* Send directly if the packet fits the ACL MTU */ - if (buf->len <= conn_mtu(conn)) { - return send_frag(conn, buf, BT_ACL_START_NO_FLUSH, false); - } + /* Send directly if the packet fits the ACL MTU */ + if (buf->len <= conn_mtu(conn)) { + return send_frag(conn, buf, BT_ACL_START_NO_FLUSH, false); + } - /* Create & enqueue first fragment */ - frag = create_frag(conn, buf); - if (!frag) { - return false; - } + /* Create & enqueue first fragment */ + frag = create_frag(conn, buf); + if (!frag) { + return false; + } - if (!send_frag(conn, frag, BT_ACL_START_NO_FLUSH, true)) { - return false; - } + if (!send_frag(conn, frag, BT_ACL_START_NO_FLUSH, true)) { + return false; + } - /* - * Send the fragments. For the last one simply use the original - * buffer (which works since we've used net_buf_pull on it. - */ - while (buf->len > conn_mtu(conn)) { - frag = create_frag(conn, buf); - if (!frag) { - return false; - } + /* + * Send the fragments. For the last one simply use the original + * buffer (which works since we've used net_buf_pull on it. + */ + while (buf->len > conn_mtu(conn)) { + frag = create_frag(conn, buf); + if (!frag) { + return false; + } - if (!send_frag(conn, frag, BT_ACL_CONT, true)) { - return false; - } - } + if (!send_frag(conn, frag, BT_ACL_CONT, true)) { + return false; + } + } - return send_frag(conn, buf, BT_ACL_CONT, false); + return send_frag(conn, buf, BT_ACL_CONT, false); } static struct k_poll_signal conn_change = - K_POLL_SIGNAL_INITIALIZER(conn_change); + K_POLL_SIGNAL_INITIALIZER(conn_change); static void conn_cleanup(struct bt_conn *conn) { - struct net_buf *buf; + struct net_buf *buf; - /* Give back any allocated buffers */ - while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) { - if (tx_data(buf)->tx) { - tx_free(tx_data(buf)->tx); - } + /* Give back any allocated buffers */ + while ((buf = net_buf_get(&conn->tx_queue, K_NO_WAIT))) { + if (tx_data(buf)->tx) { + tx_free(tx_data(buf)->tx); + } - net_buf_unref(buf); - } + net_buf_unref(buf); + } - __ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets"); - __ASSERT_NO_MSG(conn->pending_no_cb == 0); + __ASSERT(sys_slist_is_empty(&conn->tx_pending), "Pending TX packets"); + __ASSERT_NO_MSG(conn->pending_no_cb == 0); - bt_conn_reset_rx_state(conn); + bt_conn_reset_rx_state(conn); k_delayed_work_submit(&conn->update_work, K_NO_WAIT); - - #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS + + #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS k_queue_free(&conn->tx_queue._queue); // k_queue_free(&conn->tx_notify._queue); conn->tx_queue._queue.hdl = NULL; @@ -1491,438 +1491,438 @@ static void conn_cleanup(struct bt_conn *conn) int bt_conn_prepare_events(struct k_poll_event events[]) { - int i, ev_count = 0; + int i, ev_count = 0; - BT_DBG(""); + BT_DBG(""); - conn_change.signaled = 0U; - k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL, - K_POLL_MODE_NOTIFY_ONLY, &conn_change); + conn_change.signaled = 0U; + k_poll_event_init(&events[ev_count++], K_POLL_TYPE_SIGNAL, + K_POLL_MODE_NOTIFY_ONLY, &conn_change); - for (i = 0; i < ARRAY_SIZE(conns); i++) { - struct bt_conn *conn = &conns[i]; + for (i = 0; i < ARRAY_SIZE(conns); i++) { + struct bt_conn *conn = &conns[i]; - if (!atomic_get(&conn->ref)) { - continue; - } + if (!atomic_get(&conn->ref)) { + continue; + } - if (conn->state == BT_CONN_DISCONNECTED && - atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) { - conn_cleanup(conn); - continue; - } + if (conn->state == BT_CONN_DISCONNECTED && + atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) { + conn_cleanup(conn); + continue; + } - if (conn->state != BT_CONN_CONNECTED) { - continue; - } + if (conn->state != BT_CONN_CONNECTED) { + continue; + } - BT_DBG("Adding conn %p to poll list", conn); + BT_DBG("Adding conn %p to poll list", conn); - k_poll_event_init(&events[ev_count], - K_POLL_TYPE_FIFO_DATA_AVAILABLE, - K_POLL_MODE_NOTIFY_ONLY, - &conn->tx_queue); - events[ev_count++].tag = BT_EVENT_CONN_TX_QUEUE; - } + k_poll_event_init(&events[ev_count], + K_POLL_TYPE_FIFO_DATA_AVAILABLE, + K_POLL_MODE_NOTIFY_ONLY, + &conn->tx_queue); + events[ev_count++].tag = BT_EVENT_CONN_TX_QUEUE; + } - return ev_count; + return ev_count; } void bt_conn_process_tx(struct bt_conn *conn) { - struct net_buf *buf; + struct net_buf *buf; - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - if (conn->state == BT_CONN_DISCONNECTED && - atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) { - BT_DBG("handle %u disconnected - cleaning up", conn->handle); - conn_cleanup(conn); - return; - } + if (conn->state == BT_CONN_DISCONNECTED && + atomic_test_and_clear_bit(conn->flags, BT_CONN_CLEANUP)) { + BT_DBG("handle %u disconnected - cleaning up", conn->handle); + conn_cleanup(conn); + return; + } - /* Get next ACL packet for connection */ - buf = net_buf_get(&conn->tx_queue, K_NO_WAIT); - BT_ASSERT(buf); - if (!send_buf(conn, buf)) { - net_buf_unref(buf); - } + /* Get next ACL packet for connection */ + buf = net_buf_get(&conn->tx_queue, K_NO_WAIT); + BT_ASSERT(buf); + if (!send_buf(conn, buf)) { + net_buf_unref(buf); + } } struct bt_conn *bt_conn_add_le(u8_t id, const bt_addr_le_t *peer) { - struct bt_conn *conn = conn_new(); + struct bt_conn *conn = conn_new(); - if (!conn) { - return NULL; - } + if (!conn) { + return NULL; + } - conn->id = id; - bt_addr_le_copy(&conn->le.dst, peer); + conn->id = id; + bt_addr_le_copy(&conn->le.dst, peer); #if defined(CONFIG_BT_SMP) - conn->sec_level = BT_SECURITY_L1; - conn->required_sec_level = BT_SECURITY_L1; + conn->sec_level = BT_SECURITY_L1; + conn->required_sec_level = BT_SECURITY_L1; #endif /* CONFIG_BT_SMP */ - conn->type = BT_CONN_TYPE_LE; - conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN; - conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX; + conn->type = BT_CONN_TYPE_LE; + conn->le.interval_min = BT_GAP_INIT_CONN_INT_MIN; + conn->le.interval_max = BT_GAP_INIT_CONN_INT_MAX; - return conn; + return conn; } static void process_unack_tx(struct bt_conn *conn) { - /* Return any unacknowledged packets */ - while (1) { - struct bt_conn_tx *tx; - sys_snode_t *node; - unsigned int key; + /* Return any unacknowledged packets */ + while (1) { + struct bt_conn_tx *tx; + sys_snode_t *node; + unsigned int key; - key = irq_lock(); + key = irq_lock(); - if (conn->pending_no_cb) { - conn->pending_no_cb--; - irq_unlock(key); - k_sem_give(bt_conn_get_pkts(conn)); - continue; - } + if (conn->pending_no_cb) { + conn->pending_no_cb--; + irq_unlock(key); + k_sem_give(bt_conn_get_pkts(conn)); + continue; + } - node = sys_slist_get(&conn->tx_pending); - irq_unlock(key); + node = sys_slist_get(&conn->tx_pending); + irq_unlock(key); - if (!node) { - break; - } + if (!node) { + break; + } - tx = CONTAINER_OF(node, struct bt_conn_tx, node); + tx = CONTAINER_OF(node, struct bt_conn_tx, node); - key = irq_lock(); - conn->pending_no_cb = tx->pending_no_cb; - tx->pending_no_cb = 0U; - irq_unlock(key); + key = irq_lock(); + conn->pending_no_cb = tx->pending_no_cb; + tx->pending_no_cb = 0U; + irq_unlock(key); - tx_free(tx); + tx_free(tx); - k_sem_give(bt_conn_get_pkts(conn)); - } + k_sem_give(bt_conn_get_pkts(conn)); + } } void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state) { - bt_conn_state_t old_state; + bt_conn_state_t old_state; - BT_DBG("%s -> %s", state2str(conn->state), state2str(state)); + BT_DBG("%s -> %s", state2str(conn->state), state2str(state)); - if (conn->state == state) { - BT_WARN("no transition"); - return; - } + if (conn->state == state) { + BT_WARN("no transition"); + return; + } - old_state = conn->state; - conn->state = state; + old_state = conn->state; + conn->state = state; - /* Actions needed for exiting the old state */ - switch (old_state) { - case BT_CONN_DISCONNECTED: - /* Take a reference for the first state transition after - * bt_conn_add_le() and keep it until reaching DISCONNECTED - * again. - */ - bt_conn_ref(conn); - break; - case BT_CONN_CONNECT: - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->type == BT_CONN_TYPE_LE) { - k_delayed_work_cancel(&conn->update_work); - } - break; - default: - break; - } + /* Actions needed for exiting the old state */ + switch (old_state) { + case BT_CONN_DISCONNECTED: + /* Take a reference for the first state transition after + * bt_conn_add_le() and keep it until reaching DISCONNECTED + * again. + */ + bt_conn_ref(conn); + break; + case BT_CONN_CONNECT: + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->type == BT_CONN_TYPE_LE) { + k_delayed_work_cancel(&conn->update_work); + } + break; + default: + break; + } - /* Actions needed for entering the new state */ - switch (conn->state) { - case BT_CONN_CONNECTED: - if (conn->type == BT_CONN_TYPE_SCO) { - /* TODO: Notify sco connected */ - break; - } - k_fifo_init(&conn->tx_queue, 20); - k_poll_signal_raise(&conn_change, 0); + /* Actions needed for entering the new state */ + switch (conn->state) { + case BT_CONN_CONNECTED: + if (conn->type == BT_CONN_TYPE_SCO) { + /* TODO: Notify sco connected */ + break; + } + k_fifo_init(&conn->tx_queue, 20); + k_poll_signal_raise(&conn_change, 0); - sys_slist_init(&conn->channels); + sys_slist_init(&conn->channels); - bt_l2cap_connected(conn); - notify_connected(conn); - break; - case BT_CONN_DISCONNECTED: - if (conn->type == BT_CONN_TYPE_SCO) { - /* TODO: Notify sco disconnected */ - bt_conn_unref(conn); - break; - } - /* Notify disconnection and queue a dummy buffer to wake - * up and stop the tx thread for states where it was - * running. - */ - if (old_state == BT_CONN_CONNECTED || - old_state == BT_CONN_DISCONNECT) { - process_unack_tx(conn); - tx_notify(conn); + bt_l2cap_connected(conn); + notify_connected(conn); + break; + case BT_CONN_DISCONNECTED: + if (conn->type == BT_CONN_TYPE_SCO) { + /* TODO: Notify sco disconnected */ + bt_conn_unref(conn); + break; + } + /* Notify disconnection and queue a dummy buffer to wake + * up and stop the tx thread for states where it was + * running. + */ + if (old_state == BT_CONN_CONNECTED || + old_state == BT_CONN_DISCONNECT) { + process_unack_tx(conn); + tx_notify(conn); - /* Cancel Connection Update if it is pending */ - if (conn->type == BT_CONN_TYPE_LE) { - k_delayed_work_cancel(&conn->update_work); - } + /* Cancel Connection Update if it is pending */ + if (conn->type == BT_CONN_TYPE_LE) { + k_delayed_work_cancel(&conn->update_work); + } - atomic_set_bit(conn->flags, BT_CONN_CLEANUP); - k_poll_signal_raise(&conn_change, 0); - /* The last ref will be dropped during cleanup */ - } else if (old_state == BT_CONN_CONNECT) { - /* conn->err will be set in this case */ - notify_connected(conn); - bt_conn_unref(conn); - } else if (old_state == BT_CONN_CONNECT_SCAN) { - /* this indicate LE Create Connection failed */ - if (conn->err) { - notify_connected(conn); - } + atomic_set_bit(conn->flags, BT_CONN_CLEANUP); + k_poll_signal_raise(&conn_change, 0); + /* The last ref will be dropped during cleanup */ + } else if (old_state == BT_CONN_CONNECT) { + /* conn->err will be set in this case */ + notify_connected(conn); + bt_conn_unref(conn); + } else if (old_state == BT_CONN_CONNECT_SCAN) { + /* this indicate LE Create Connection failed */ + if (conn->err) { + notify_connected(conn); + } - bt_conn_unref(conn); - } else if (old_state == BT_CONN_CONNECT_DIR_ADV) { - /* this indicate Directed advertising stopped */ - if (conn->err) { - notify_connected(conn); - } + bt_conn_unref(conn); + } else if (old_state == BT_CONN_CONNECT_DIR_ADV) { + /* this indicate Directed advertising stopped */ + if (conn->err) { + notify_connected(conn); + } - bt_conn_unref(conn); - } + bt_conn_unref(conn); + } - break; - case BT_CONN_CONNECT_SCAN: - break; - case BT_CONN_CONNECT_DIR_ADV: - break; - case BT_CONN_CONNECT: - if (conn->type == BT_CONN_TYPE_SCO) { - break; - } - /* - * Timer is needed only for LE. For other link types controller - * will handle connection timeout. - */ - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->type == BT_CONN_TYPE_LE) { - k_delayed_work_submit(&conn->update_work, CONN_TIMEOUT); - } + break; + case BT_CONN_CONNECT_SCAN: + break; + case BT_CONN_CONNECT_DIR_ADV: + break; + case BT_CONN_CONNECT: + if (conn->type == BT_CONN_TYPE_SCO) { + break; + } + /* + * Timer is needed only for LE. For other link types controller + * will handle connection timeout. + */ + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->type == BT_CONN_TYPE_LE) { + k_delayed_work_submit(&conn->update_work, CONN_TIMEOUT); + } - break; - case BT_CONN_DISCONNECT: - break; - default: - BT_WARN("no valid (%u) state was set", state); + break; + case BT_CONN_DISCONNECT: + break; + default: + BT_WARN("no valid (%u) state was set", state); - break; - } + break; + } } struct bt_conn *bt_conn_lookup_handle(u16_t handle) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(conns); i++) { - if (!atomic_get(&conns[i].ref)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(conns); i++) { + if (!atomic_get(&conns[i].ref)) { + continue; + } - /* We only care about connections with a valid handle */ - if (conns[i].state != BT_CONN_CONNECTED && - conns[i].state != BT_CONN_DISCONNECT) { - continue; - } + /* We only care about connections with a valid handle */ + if (conns[i].state != BT_CONN_CONNECTED && + conns[i].state != BT_CONN_DISCONNECT) { + continue; + } - if (conns[i].handle == handle) { - return bt_conn_ref(&conns[i]); - } - } + if (conns[i].handle == handle) { + return bt_conn_ref(&conns[i]); + } + } #if defined(CONFIG_BT_BREDR) - for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { - if (!atomic_get(&sco_conns[i].ref)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { + if (!atomic_get(&sco_conns[i].ref)) { + continue; + } - /* We only care about connections with a valid handle */ - if (sco_conns[i].state != BT_CONN_CONNECTED && - sco_conns[i].state != BT_CONN_DISCONNECT) { - continue; - } + /* We only care about connections with a valid handle */ + if (sco_conns[i].state != BT_CONN_CONNECTED && + sco_conns[i].state != BT_CONN_DISCONNECT) { + continue; + } - if (sco_conns[i].handle == handle) { - return bt_conn_ref(&sco_conns[i]); - } - } + if (sco_conns[i].handle == handle) { + return bt_conn_ref(&sco_conns[i]); + } + } #endif - return NULL; + return NULL; } int bt_conn_addr_le_cmp(const struct bt_conn *conn, const bt_addr_le_t *peer) { - /* Check against conn dst address as it may be the identity address */ - if (!bt_addr_le_cmp(peer, &conn->le.dst)) { - return 0; - } + /* Check against conn dst address as it may be the identity address */ + if (!bt_addr_le_cmp(peer, &conn->le.dst)) { + return 0; + } - /* Check against initial connection address */ - if (conn->role == BT_HCI_ROLE_MASTER) { - return bt_addr_le_cmp(peer, &conn->le.resp_addr); - } + /* Check against initial connection address */ + if (conn->role == BT_HCI_ROLE_MASTER) { + return bt_addr_le_cmp(peer, &conn->le.resp_addr); + } - return bt_addr_le_cmp(peer, &conn->le.init_addr); + return bt_addr_le_cmp(peer, &conn->le.init_addr); } struct bt_conn *bt_conn_lookup_addr_le(u8_t id, const bt_addr_le_t *peer) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(conns); i++) { - if (!atomic_get(&conns[i].ref)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(conns); i++) { + if (!atomic_get(&conns[i].ref)) { + continue; + } - if (conns[i].type != BT_CONN_TYPE_LE) { - continue; - } + if (conns[i].type != BT_CONN_TYPE_LE) { + continue; + } - if (conns[i].id == id && - !bt_conn_addr_le_cmp(&conns[i], peer)) { - return bt_conn_ref(&conns[i]); - } - } + if (conns[i].id == id && + !bt_conn_addr_le_cmp(&conns[i], peer)) { + return bt_conn_ref(&conns[i]); + } + } - return NULL; + return NULL; } struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer, - const bt_conn_state_t state) + const bt_conn_state_t state) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(conns); i++) { - if (!atomic_get(&conns[i].ref)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(conns); i++) { + if (!atomic_get(&conns[i].ref)) { + continue; + } - if (conns[i].type != BT_CONN_TYPE_LE) { - continue; - } + if (conns[i].type != BT_CONN_TYPE_LE) { + continue; + } - if (peer && bt_conn_addr_le_cmp(&conns[i], peer)) { - continue; - } + if (peer && bt_conn_addr_le_cmp(&conns[i], peer)) { + continue; + } - if (conns[i].state == state) { - return bt_conn_ref(&conns[i]); - } - } + if (conns[i].state == state) { + return bt_conn_ref(&conns[i]); + } + } - return NULL; + return NULL; } void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), - void *data) + void *data) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(conns); i++) { - if (!atomic_get(&conns[i].ref)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(conns); i++) { + if (!atomic_get(&conns[i].ref)) { + continue; + } - if (!(conns[i].type & type)) { - continue; - } + if (!(conns[i].type & type)) { + continue; + } - func(&conns[i], data); - } + func(&conns[i], data); + } #if defined(CONFIG_BT_BREDR) - if (type & BT_CONN_TYPE_SCO) { - for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { - if (!atomic_get(&sco_conns[i].ref)) { - continue; - } + if (type & BT_CONN_TYPE_SCO) { + for (i = 0; i < ARRAY_SIZE(sco_conns); i++) { + if (!atomic_get(&sco_conns[i].ref)) { + continue; + } - func(&sco_conns[i], data); - } - } + func(&sco_conns[i], data); + } + } #endif /* defined(CONFIG_BT_BREDR) */ } static void disconnect_all(struct bt_conn *conn, void *data) { - u8_t *id = (u8_t *)data; + u8_t *id = (u8_t *)data; - if (conn->id == *id && conn->state == BT_CONN_CONNECTED) { - bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); - } + if (conn->id == *id && conn->state == BT_CONN_CONNECTED) { + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + } } void bt_conn_disconnect_all(u8_t id) { - bt_conn_foreach(BT_CONN_TYPE_ALL, disconnect_all, &id); + bt_conn_foreach(BT_CONN_TYPE_ALL, disconnect_all, &id); } struct bt_conn *bt_conn_ref(struct bt_conn *conn) { - atomic_inc(&conn->ref); + atomic_inc(&conn->ref); - BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref)); + BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref)); - return conn; + return conn; } void bt_conn_unref(struct bt_conn *conn) { - atomic_dec(&conn->ref); + atomic_dec(&conn->ref); - BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref)); + BT_DBG("handle %u ref %u", conn->handle, atomic_get(&conn->ref)); } const bt_addr_le_t *bt_conn_get_dst(const struct bt_conn *conn) { - return &conn->le.dst; + return &conn->le.dst; } int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info) { - info->type = conn->type; - info->role = conn->role; - info->id = conn->id; + info->type = conn->type; + info->role = conn->role; + info->id = conn->id; - switch (conn->type) { - case BT_CONN_TYPE_LE: - info->le.dst = &conn->le.dst; - info->le.src = &bt_dev.id_addr[conn->id]; - if (conn->role == BT_HCI_ROLE_MASTER) { - info->le.local = &conn->le.init_addr; - info->le.remote = &conn->le.resp_addr; - } else { - info->le.local = &conn->le.resp_addr; - info->le.remote = &conn->le.init_addr; - } - info->le.interval = conn->le.interval; - info->le.latency = conn->le.latency; - info->le.timeout = conn->le.timeout; - return 0; + switch (conn->type) { + case BT_CONN_TYPE_LE: + info->le.dst = &conn->le.dst; + info->le.src = &bt_dev.id_addr[conn->id]; + if (conn->role == BT_HCI_ROLE_MASTER) { + info->le.local = &conn->le.init_addr; + info->le.remote = &conn->le.resp_addr; + } else { + info->le.local = &conn->le.resp_addr; + info->le.remote = &conn->le.init_addr; + } + info->le.interval = conn->le.interval; + info->le.latency = conn->le.latency; + info->le.timeout = conn->le.timeout; + return 0; #if defined(CONFIG_BT_BREDR) - case BT_CONN_TYPE_BR: - info->br.dst = &conn->br.dst; - return 0; + case BT_CONN_TYPE_BR: + info->br.dst = &conn->br.dst; + return 0; #endif - } + } - return -EINVAL; + return -EINVAL; } int bt_conn_get_remote_dev_info(struct bt_conn_info *info) @@ -1935,679 +1935,679 @@ int bt_conn_get_remote_dev_info(struct bt_conn_info *info) } bt_conn_get_info(&conns[i], &info[link_num]); link_num ++; - } + } - return link_num; + return link_num; } static int bt_hci_disconnect(struct bt_conn *conn, u8_t reason) { - struct net_buf *buf; - struct bt_hci_cp_disconnect *disconn; - int err; + struct net_buf *buf; + struct bt_hci_cp_disconnect *disconn; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_DISCONNECT, sizeof(*disconn)); + if (!buf) { + return -ENOBUFS; + } - disconn = net_buf_add(buf, sizeof(*disconn)); - disconn->handle = sys_cpu_to_le16(conn->handle); - disconn->reason = reason; + disconn = net_buf_add(buf, sizeof(*disconn)); + disconn->handle = sys_cpu_to_le16(conn->handle); + disconn->reason = reason; - err = bt_hci_cmd_send(BT_HCI_OP_DISCONNECT, buf); - if (err) { - return err; - } + err = bt_hci_cmd_send(BT_HCI_OP_DISCONNECT, buf); + if (err) { + return err; + } - bt_conn_set_state(conn, BT_CONN_DISCONNECT); + bt_conn_set_state(conn, BT_CONN_DISCONNECT); - return 0; + return 0; } #if defined(CONFIG_BT_STACK_PTS) int pts_bt_conn_le_param_update(struct bt_conn *conn, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, - conn->le.features[0], param->interval_min, - param->interval_max, param->latency, param->timeout); + BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, + conn->le.features[0], param->interval_min, + param->interval_max, param->latency, param->timeout); - /* Check if there's a need to update conn params */ - if (conn->le.interval >= param->interval_min && - conn->le.interval <= param->interval_max && - conn->le.latency == param->latency && - conn->le.timeout == param->timeout) { - return -EALREADY; - } + /* Check if there's a need to update conn params */ + if (conn->le.interval >= param->interval_min && + conn->le.interval <= param->interval_max && + conn->le.latency == param->latency && + conn->le.timeout == param->timeout) { + return -EALREADY; + } - /* Cancel any pending update */ - k_delayed_work_cancel(&conn->update_work); + /* Cancel any pending update */ + k_delayed_work_cancel(&conn->update_work); - return bt_l2cap_update_conn_param(conn, param); + return bt_l2cap_update_conn_param(conn, param); } #endif int bt_conn_le_param_update(struct bt_conn *conn, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, - conn->le.features[0], param->interval_min, - param->interval_max, param->latency, param->timeout); + BT_DBG("conn %p features 0x%02x params (%d-%d %d %d)", conn, + conn->le.features[0], param->interval_min, + param->interval_max, param->latency, param->timeout); - /* Check if there's a need to update conn params */ - if (conn->le.interval >= param->interval_min && - conn->le.interval <= param->interval_max && - conn->le.latency == param->latency && - conn->le.timeout == param->timeout) { - atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); - return -EALREADY; - } + /* Check if there's a need to update conn params */ + if (conn->le.interval >= param->interval_min && + conn->le.interval <= param->interval_max && + conn->le.latency == param->latency && + conn->le.timeout == param->timeout) { + atomic_clear_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); + return -EALREADY; + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_CONN_ROLE_MASTER) { - return send_conn_le_param_update(conn, param); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_CONN_ROLE_MASTER) { + return send_conn_le_param_update(conn, param); + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - /* if slave conn param update timer expired just send request */ - if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) { - return send_conn_le_param_update(conn, param); - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + /* if slave conn param update timer expired just send request */ + if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) { + return send_conn_le_param_update(conn, param); + } - /* store new conn params to be used by update timer */ - conn->le.interval_min = param->interval_min; - conn->le.interval_max = param->interval_max; - conn->le.pending_latency = param->latency; - conn->le.pending_timeout = param->timeout; - atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); - } + /* store new conn params to be used by update timer */ + conn->le.interval_min = param->interval_min; + conn->le.interval_max = param->interval_max; + conn->le.pending_latency = param->latency; + conn->le.pending_timeout = param->timeout; + atomic_set_bit(conn->flags, BT_CONN_SLAVE_PARAM_SET); + } - return 0; + return 0; } int bt_conn_disconnect(struct bt_conn *conn, u8_t reason) { - /* Disconnection is initiated by us, so auto connection shall - * be disabled. Otherwise the passive scan would be enabled - * and we could send LE Create Connection as soon as the remote - * starts advertising. - */ + /* Disconnection is initiated by us, so auto connection shall + * be disabled. Otherwise the passive scan would be enabled + * and we could send LE Create Connection as soon as the remote + * starts advertising. + */ #if !defined(CONFIG_BT_WHITELIST) - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->type == BT_CONN_TYPE_LE) { - bt_le_set_auto_conn(&conn->le.dst, NULL); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->type == BT_CONN_TYPE_LE) { + bt_le_set_auto_conn(&conn->le.dst, NULL); + } #endif /* !defined(CONFIG_BT_WHITELIST) */ - switch (conn->state) { - case BT_CONN_CONNECT_SCAN: - conn->err = reason; - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); - if (IS_ENABLED(CONFIG_BT_CENTRAL)) { - bt_le_scan_update(false); - } - return 0; - case BT_CONN_CONNECT_DIR_ADV: - conn->err = reason; - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); - if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - /* User should unref connection object when receiving - * error in connection callback. - */ - return bt_le_adv_stop(); - } - return 0; - case BT_CONN_CONNECT: + switch (conn->state) { + case BT_CONN_CONNECT_SCAN: + conn->err = reason; + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + if (IS_ENABLED(CONFIG_BT_CENTRAL)) { + bt_le_scan_update(false); + } + return 0; + case BT_CONN_CONNECT_DIR_ADV: + conn->err = reason; + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + /* User should unref connection object when receiving + * error in connection callback. + */ + return bt_le_adv_stop(); + } + return 0; + case BT_CONN_CONNECT: #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - return bt_hci_connect_br_cancel(conn); - } + if (conn->type == BT_CONN_TYPE_BR) { + return bt_hci_connect_br_cancel(conn); + } #endif /* CONFIG_BT_BREDR */ - if (IS_ENABLED(CONFIG_BT_CENTRAL)) { - k_delayed_work_cancel(&conn->update_work); - return bt_hci_cmd_send(BT_HCI_OP_LE_CREATE_CONN_CANCEL, - NULL); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL)) { + k_delayed_work_cancel(&conn->update_work); + return bt_hci_cmd_send(BT_HCI_OP_LE_CREATE_CONN_CANCEL, + NULL); + } - return 0; - case BT_CONN_CONNECTED: - return bt_hci_disconnect(conn, reason); - case BT_CONN_DISCONNECT: - return 0; - case BT_CONN_DISCONNECTED: - default: - return -ENOTCONN; - } + return 0; + case BT_CONN_CONNECTED: + return bt_hci_disconnect(conn, reason); + case BT_CONN_DISCONNECT: + return 0; + case BT_CONN_DISCONNECTED: + default: + return -ENOTCONN; + } } #if defined(CONFIG_BT_CENTRAL) static void bt_conn_set_param_le(struct bt_conn *conn, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - conn->le.interval_min = param->interval_min; - conn->le.interval_max = param->interval_max; - conn->le.latency = param->latency; - conn->le.timeout = param->timeout; + conn->le.interval_min = param->interval_min; + conn->le.interval_max = param->interval_max; + conn->le.latency = param->latency; + conn->le.timeout = param->timeout; - #if defined(CONFIG_BT_STACK_PTS) - conn->le.own_adder_type = param->own_address_type; - #endif + #if defined(CONFIG_BT_STACK_PTS) + conn->le.own_adder_type = param->own_address_type; + #endif } #if defined(CONFIG_BT_WHITELIST) int bt_conn_create_auto_le(const struct bt_le_conn_param *param) { - struct bt_conn *conn; - int err; + struct bt_conn *conn; + int err; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - return -EINVAL; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + return -EINVAL; + } - if (!bt_le_conn_params_valid(param)) { - return -EINVAL; - } + if (!bt_le_conn_params_valid(param)) { + return -EINVAL; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { - return -EINVAL; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { + return -EINVAL; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { - return -EALREADY; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { + return -EALREADY; + } - if (!bt_dev.le.wl_entries) { - return -EINVAL; - } + if (!bt_dev.le.wl_entries) { + return -EINVAL; + } - /* Don't start initiator if we have general discovery procedure. */ - conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN); - if (conn) { - bt_conn_unref(conn); - return -EINVAL; - } + /* Don't start initiator if we have general discovery procedure. */ + conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN); + if (conn) { + bt_conn_unref(conn); + return -EINVAL; + } - /* Don't start initiator if we have direct discovery procedure. */ - conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); - if (conn) { - bt_conn_unref(conn); - return -EINVAL; - } + /* Don't start initiator if we have direct discovery procedure. */ + conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); + if (conn) { + bt_conn_unref(conn); + return -EINVAL; + } - err = bt_le_auto_conn(param); - if (err) { - BT_ERR("Failed to start whitelist scan"); - return err; - } + err = bt_le_auto_conn(param); + if (err) { + BT_ERR("Failed to start whitelist scan"); + return err; + } - return 0; + return 0; } int bt_conn_create_auto_stop(void) { - int err; + int err; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - return -EINVAL; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + return -EINVAL; + } - if (!atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { - return -EINVAL; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { + return -EINVAL; + } - err = bt_le_auto_conn_cancel(); - if (err) { - BT_ERR("Failed to stop initiator"); - return err; - } + err = bt_le_auto_conn_cancel(); + if (err) { + BT_ERR("Failed to stop initiator"); + return err; + } - return 0; + return 0; } #endif /* defined(CONFIG_BT_WHITELIST) */ struct bt_conn *bt_conn_create_le(const bt_addr_le_t *peer, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - struct bt_conn *conn; - bt_addr_le_t dst; + struct bt_conn *conn; + bt_addr_le_t dst; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - return NULL; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + return NULL; + } - if (!bt_le_conn_params_valid(param)) { - return NULL; - } + if (!bt_le_conn_params_valid(param)) { + return NULL; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { - return NULL; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { + return NULL; + } - if (IS_ENABLED(CONFIG_BT_WHITELIST) && - atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { - return NULL; - } + if (IS_ENABLED(CONFIG_BT_WHITELIST) && + atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { + return NULL; + } - conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, peer); - if (conn) { - switch (conn->state) { - case BT_CONN_CONNECT_SCAN: - bt_conn_set_param_le(conn, param); - return conn; - case BT_CONN_CONNECT: - case BT_CONN_CONNECTED: - return conn; - case BT_CONN_DISCONNECTED: - BT_WARN("Found valid but disconnected conn object"); - goto start_scan; - default: - bt_conn_unref(conn); - return NULL; - } - } + conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, peer); + if (conn) { + switch (conn->state) { + case BT_CONN_CONNECT_SCAN: + bt_conn_set_param_le(conn, param); + return conn; + case BT_CONN_CONNECT: + case BT_CONN_CONNECTED: + return conn; + case BT_CONN_DISCONNECTED: + BT_WARN("Found valid but disconnected conn object"); + goto start_scan; + default: + bt_conn_unref(conn); + return NULL; + } + } - if (peer->type == BT_ADDR_LE_PUBLIC_ID || - peer->type == BT_ADDR_LE_RANDOM_ID) { - bt_addr_le_copy(&dst, peer); - dst.type -= BT_ADDR_LE_PUBLIC_ID; - } else { - bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer)); - } + if (peer->type == BT_ADDR_LE_PUBLIC_ID || + peer->type == BT_ADDR_LE_RANDOM_ID) { + bt_addr_le_copy(&dst, peer); + dst.type -= BT_ADDR_LE_PUBLIC_ID; + } else { + bt_addr_le_copy(&dst, bt_lookup_id_addr(BT_ID_DEFAULT, peer)); + } - /* Only default identity supported for now */ - conn = bt_conn_add_le(BT_ID_DEFAULT, &dst); - if (!conn) { - return NULL; - } + /* Only default identity supported for now */ + conn = bt_conn_add_le(BT_ID_DEFAULT, &dst); + if (!conn) { + return NULL; + } start_scan: - bt_conn_set_param_le(conn, param); + bt_conn_set_param_le(conn, param); - bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); + bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); - bt_le_scan_update(true); + bt_le_scan_update(true); - return conn; + return conn; } #if !defined(CONFIG_BT_WHITELIST) int bt_le_set_auto_conn(const bt_addr_le_t *addr, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - struct bt_conn *conn; + struct bt_conn *conn; - if (param && !bt_le_conn_params_valid(param)) { - return -EINVAL; - } + if (param && !bt_le_conn_params_valid(param)) { + return -EINVAL; + } - /* Only default identity is supported */ - conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr); - if (!conn) { - conn = bt_conn_add_le(BT_ID_DEFAULT, addr); - if (!conn) { - return -ENOMEM; - } - } + /* Only default identity is supported */ + conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, addr); + if (!conn) { + conn = bt_conn_add_le(BT_ID_DEFAULT, addr); + if (!conn) { + return -ENOMEM; + } + } - if (param) { - bt_conn_set_param_le(conn, param); + if (param) { + bt_conn_set_param_le(conn, param); - if (!atomic_test_and_set_bit(conn->flags, - BT_CONN_AUTO_CONNECT)) { - bt_conn_ref(conn); - } - } else { - if (atomic_test_and_clear_bit(conn->flags, - BT_CONN_AUTO_CONNECT)) { - bt_conn_unref(conn); - if (conn->state == BT_CONN_CONNECT_SCAN) { - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); - } - } - } + if (!atomic_test_and_set_bit(conn->flags, + BT_CONN_AUTO_CONNECT)) { + bt_conn_ref(conn); + } + } else { + if (atomic_test_and_clear_bit(conn->flags, + BT_CONN_AUTO_CONNECT)) { + bt_conn_unref(conn); + if (conn->state == BT_CONN_CONNECT_SCAN) { + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + } + } + } - if (conn->state == BT_CONN_DISCONNECTED && - atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - if (param) { - bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); - } - bt_le_scan_update(false); - } + if (conn->state == BT_CONN_DISCONNECTED && + atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + if (param) { + bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); + } + bt_le_scan_update(false); + } - bt_conn_unref(conn); + bt_conn_unref(conn); - return 0; + return 0; } #endif /* !defined(CONFIG_BT_WHITELIST) */ #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) struct bt_conn *bt_conn_create_slave_le(const bt_addr_le_t *peer, - const struct bt_le_adv_param *param) + const struct bt_le_adv_param *param) { - int err; - struct bt_conn *conn; - struct bt_le_adv_param param_int; + int err; + struct bt_conn *conn; + struct bt_le_adv_param param_int; - memcpy(¶m_int, param, sizeof(param_int)); - param_int.options |= (BT_LE_ADV_OPT_CONNECTABLE | - BT_LE_ADV_OPT_ONE_TIME); + memcpy(¶m_int, param, sizeof(param_int)); + param_int.options |= (BT_LE_ADV_OPT_CONNECTABLE | + BT_LE_ADV_OPT_ONE_TIME); - conn = bt_conn_lookup_addr_le(param->id, peer); - if (conn) { - switch (conn->state) { - case BT_CONN_CONNECT_DIR_ADV: - /* Handle the case when advertising is stopped with - * bt_le_adv_stop function - */ - err = bt_le_adv_start_internal(¶m_int, NULL, 0, - NULL, 0, peer); - if (err && (err != -EALREADY)) { - BT_WARN("Directed advertising could not be" - " started: %d", err); - bt_conn_unref(conn); - return NULL; - } + conn = bt_conn_lookup_addr_le(param->id, peer); + if (conn) { + switch (conn->state) { + case BT_CONN_CONNECT_DIR_ADV: + /* Handle the case when advertising is stopped with + * bt_le_adv_stop function + */ + err = bt_le_adv_start_internal(¶m_int, NULL, 0, + NULL, 0, peer); + if (err && (err != -EALREADY)) { + BT_WARN("Directed advertising could not be" + " started: %d", err); + bt_conn_unref(conn); + return NULL; + } __attribute__((fallthrough)); - case BT_CONN_CONNECT: - case BT_CONN_CONNECTED: - return conn; - case BT_CONN_DISCONNECTED: - BT_WARN("Found valid but disconnected conn object"); - goto start_adv; - default: - bt_conn_unref(conn); - return NULL; - } - } + case BT_CONN_CONNECT: + case BT_CONN_CONNECTED: + return conn; + case BT_CONN_DISCONNECTED: + BT_WARN("Found valid but disconnected conn object"); + goto start_adv; + default: + bt_conn_unref(conn); + return NULL; + } + } - conn = bt_conn_add_le(param->id, peer); - if (!conn) { - return NULL; - } + conn = bt_conn_add_le(param->id, peer); + if (!conn) { + return NULL; + } start_adv: - bt_conn_set_state(conn, BT_CONN_CONNECT_DIR_ADV); + bt_conn_set_state(conn, BT_CONN_CONNECT_DIR_ADV); - err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer); - if (err) { - BT_WARN("Directed advertising could not be started: %d", err); + err = bt_le_adv_start_internal(¶m_int, NULL, 0, NULL, 0, peer); + if (err) { + BT_WARN("Directed advertising could not be started: %d", err); - bt_conn_unref(conn); - return NULL; - } + bt_conn_unref(conn); + return NULL; + } - return conn; + return conn; } #endif /* CONFIG_BT_PERIPHERAL */ int bt_conn_le_conn_update(struct bt_conn *conn, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - struct hci_cp_le_conn_update *conn_update; - struct net_buf *buf; + struct hci_cp_le_conn_update *conn_update; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE, - sizeof(*conn_update)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_UPDATE, + sizeof(*conn_update)); + if (!buf) { + return -ENOBUFS; + } - conn_update = net_buf_add(buf, sizeof(*conn_update)); - (void)memset(conn_update, 0, sizeof(*conn_update)); - conn_update->handle = sys_cpu_to_le16(conn->handle); - conn_update->conn_interval_min = sys_cpu_to_le16(param->interval_min); - conn_update->conn_interval_max = sys_cpu_to_le16(param->interval_max); - conn_update->conn_latency = sys_cpu_to_le16(param->latency); - conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout); + conn_update = net_buf_add(buf, sizeof(*conn_update)); + (void)memset(conn_update, 0, sizeof(*conn_update)); + conn_update->handle = sys_cpu_to_le16(conn->handle); + conn_update->conn_interval_min = sys_cpu_to_le16(param->interval_min); + conn_update->conn_interval_max = sys_cpu_to_le16(param->interval_max); + conn_update->conn_latency = sys_cpu_to_le16(param->latency); + conn_update->supervision_timeout = sys_cpu_to_le16(param->timeout); - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CONN_UPDATE, buf, NULL); } struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool, - size_t reserve, s32_t timeout) + size_t reserve, s32_t timeout) { - struct net_buf *buf; + struct net_buf *buf; - /* - * PDU must not be allocated from ISR as we block with 'K_FOREVER' - * during the allocation - */ - __ASSERT_NO_MSG(!k_is_in_isr()); + /* + * PDU must not be allocated from ISR as we block with 'K_FOREVER' + * during the allocation + */ + __ASSERT_NO_MSG(!k_is_in_isr()); - if (!pool) { - pool = &acl_tx_pool; - } + if (!pool) { + pool = &acl_tx_pool; + } - if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) { - buf = net_buf_alloc(pool, K_NO_WAIT); - if (!buf) { - BT_WARN("Unable to allocate buffer with K_NO_WAIT"); - buf = net_buf_alloc(pool, timeout); - } - } else { - buf = net_buf_alloc(pool, timeout); - } + if (IS_ENABLED(CONFIG_BT_DEBUG_CONN)) { + buf = net_buf_alloc(pool, K_NO_WAIT); + if (!buf) { + BT_WARN("Unable to allocate buffer with K_NO_WAIT"); + buf = net_buf_alloc(pool, timeout); + } + } else { + buf = net_buf_alloc(pool, timeout); + } - if (!buf) { - BT_WARN("Unable to allocate buffer: timeout %d", timeout); - return NULL; - } + if (!buf) { + BT_WARN("Unable to allocate buffer: timeout %d", timeout); + return NULL; + } - reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE; - net_buf_reserve(buf, reserve); + reserve += sizeof(struct bt_hci_acl_hdr) + BT_BUF_RESERVE; + net_buf_reserve(buf, reserve); - return buf; + return buf; } #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) int bt_conn_auth_cb_register(const struct bt_conn_auth_cb *cb) { - if (!cb) { - bt_auth = NULL; - return 0; - } + if (!cb) { + bt_auth = NULL; + return 0; + } - if (bt_auth) { - return -EALREADY; - } + if (bt_auth) { + return -EALREADY; + } - /* The cancel callback must always be provided if the app provides - * interactive callbacks. - */ - if (!cb->cancel && - (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm || + /* The cancel callback must always be provided if the app provides + * interactive callbacks. + */ + if (!cb->cancel && + (cb->passkey_display || cb->passkey_entry || cb->passkey_confirm || #if defined(CONFIG_BT_BREDR) - cb->pincode_entry || + cb->pincode_entry || #endif - cb->pairing_confirm)) { - return -EINVAL; - } + cb->pairing_confirm)) { + return -EINVAL; + } - bt_auth = cb; - return 0; + bt_auth = cb; + return 0; } int bt_conn_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey) { - if (!bt_auth) { - return -EINVAL; - } + if (!bt_auth) { + return -EINVAL; + } - if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) { - bt_smp_auth_passkey_entry(conn, passkey); - return 0; - } + if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) { + bt_smp_auth_passkey_entry(conn, passkey); + return 0; + } #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - /* User entered passkey, reset user state. */ - if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { - return -EPERM; - } + if (conn->type == BT_CONN_TYPE_BR) { + /* User entered passkey, reset user state. */ + if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { + return -EPERM; + } - if (conn->br.pairing_method == PASSKEY_INPUT) { - return ssp_passkey_reply(conn, passkey); - } - } + if (conn->br.pairing_method == PASSKEY_INPUT) { + return ssp_passkey_reply(conn, passkey); + } + } #endif /* CONFIG_BT_BREDR */ - return -EINVAL; + return -EINVAL; } int bt_conn_auth_passkey_confirm(struct bt_conn *conn) { - if (!bt_auth) { - return -EINVAL; - } + if (!bt_auth) { + return -EINVAL; + } - if (IS_ENABLED(CONFIG_BT_SMP) && - conn->type == BT_CONN_TYPE_LE) { - return bt_smp_auth_passkey_confirm(conn); - } + if (IS_ENABLED(CONFIG_BT_SMP) && + conn->type == BT_CONN_TYPE_LE) { + return bt_smp_auth_passkey_confirm(conn); + } #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - /* Allow user confirm passkey value, then reset user state. */ - if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { - return -EPERM; - } + if (conn->type == BT_CONN_TYPE_BR) { + /* Allow user confirm passkey value, then reset user state. */ + if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { + return -EPERM; + } - return ssp_confirm_reply(conn); - } + return ssp_confirm_reply(conn); + } #endif /* CONFIG_BT_BREDR */ - return -EINVAL; + return -EINVAL; } int bt_conn_auth_cancel(struct bt_conn *conn) { - if (!bt_auth) { - return -EINVAL; - } + if (!bt_auth) { + return -EINVAL; + } - if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) { - return bt_smp_auth_cancel(conn); - } + if (IS_ENABLED(CONFIG_BT_SMP) && conn->type == BT_CONN_TYPE_LE) { + return bt_smp_auth_cancel(conn); + } #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - /* Allow user cancel authentication, then reset user state. */ - if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { - return -EPERM; - } + if (conn->type == BT_CONN_TYPE_BR) { + /* Allow user cancel authentication, then reset user state. */ + if (!atomic_test_and_clear_bit(conn->flags, BT_CONN_USER)) { + return -EPERM; + } - switch (conn->br.pairing_method) { - case JUST_WORKS: - case PASSKEY_CONFIRM: - return ssp_confirm_neg_reply(conn); - case PASSKEY_INPUT: - return ssp_passkey_neg_reply(conn); - case PASSKEY_DISPLAY: - return bt_conn_disconnect(conn, - BT_HCI_ERR_AUTH_FAIL); - case LEGACY: - return pin_code_neg_reply(&conn->br.dst); - default: - break; - } - } + switch (conn->br.pairing_method) { + case JUST_WORKS: + case PASSKEY_CONFIRM: + return ssp_confirm_neg_reply(conn); + case PASSKEY_INPUT: + return ssp_passkey_neg_reply(conn); + case PASSKEY_DISPLAY: + return bt_conn_disconnect(conn, + BT_HCI_ERR_AUTH_FAIL); + case LEGACY: + return pin_code_neg_reply(&conn->br.dst); + default: + break; + } + } #endif /* CONFIG_BT_BREDR */ - return -EINVAL; + return -EINVAL; } int bt_conn_auth_pairing_confirm(struct bt_conn *conn) { - if (!bt_auth) { - return -EINVAL; - } + if (!bt_auth) { + return -EINVAL; + } - switch (conn->type) { + switch (conn->type) { #if defined(CONFIG_BT_SMP) - case BT_CONN_TYPE_LE: - return bt_smp_auth_pairing_confirm(conn); + case BT_CONN_TYPE_LE: + return bt_smp_auth_pairing_confirm(conn); #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_BREDR) - case BT_CONN_TYPE_BR: - return ssp_confirm_reply(conn); + case BT_CONN_TYPE_BR: + return ssp_confirm_reply(conn); #endif /* CONFIG_BT_BREDR */ - default: - return -EINVAL; - } + default: + return -EINVAL; + } } #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ u8_t bt_conn_index(struct bt_conn *conn) { - u8_t index = conn - conns; + u8_t index = conn - conns; - __ASSERT(index < CONFIG_BT_MAX_CONN, "Invalid bt_conn pointer"); - return index; + __ASSERT(index < CONFIG_BT_MAX_CONN, "Invalid bt_conn pointer"); + return index; } struct bt_conn *bt_conn_lookup_id(u8_t id) { - struct bt_conn *conn; + struct bt_conn *conn; - if (id >= ARRAY_SIZE(conns)) { - return NULL; - } + if (id >= ARRAY_SIZE(conns)) { + return NULL; + } - conn = &conns[id]; + conn = &conns[id]; - if (!atomic_get(&conn->ref)) { - return NULL; - } + if (!atomic_get(&conn->ref)) { + return NULL; + } - return bt_conn_ref(conn); + return bt_conn_ref(conn); } extern bool queue_inited; int bt_conn_init(void) { - int err, i; + int err, i; #if defined(BFLB_BLE) if(queue_inited == false) k_lifo_init(&acl_tx_pool.free, CONFIG_BT_L2CAP_TX_BUF_COUNT); k_fifo_init(&free_tx, 20); #endif - for (i = 0; i < ARRAY_SIZE(conn_tx); i++) { - k_fifo_put(&free_tx, &conn_tx[i]); - } + for (i = 0; i < ARRAY_SIZE(conn_tx); i++) { + k_fifo_put(&free_tx, &conn_tx[i]); + } + + bt_att_init(); - bt_att_init(); - #if defined(CONFIG_BT_SMP) - err = bt_smp_init(); - if (err) { - return err; - } + err = bt_smp_init(); + if (err) { + return err; + } #endif - - bt_l2cap_init(); - /* Initialize background scan */ - if (IS_ENABLED(CONFIG_BT_CENTRAL)) { - for (i = 0; i < ARRAY_SIZE(conns); i++) { - struct bt_conn *conn = &conns[i]; + bt_l2cap_init(); - if (!atomic_get(&conn->ref)) { - continue; - } + /* Initialize background scan */ + if (IS_ENABLED(CONFIG_BT_CENTRAL)) { + for (i = 0; i < ARRAY_SIZE(conns); i++) { + struct bt_conn *conn = &conns[i]; - if (atomic_test_bit(conn->flags, - BT_CONN_AUTO_CONNECT)) { - /* Only the default identity is supported */ - conn->id = BT_ID_DEFAULT; - bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); - } - } - } + if (!atomic_get(&conn->ref)) { + continue; + } - return 0; + if (atomic_test_bit(conn->flags, + BT_CONN_AUTO_CONNECT)) { + /* Only the default identity is supported */ + conn->id = BT_ID_DEFAULT; + bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); + } + } + } + + return 0; } diff --git a/components/network/ble/blestack/src/host/conn_internal.h b/components/network/ble/blestack/src/host/conn_internal.h index 81782dc2..ff429272 100644 --- a/components/network/ble/blestack/src/host/conn_internal.h +++ b/components/network/ble/blestack/src/host/conn_internal.h @@ -8,58 +8,58 @@ * SPDX-License-Identifier: Apache-2.0 */ typedef enum __packed { - BT_CONN_DISCONNECTED, - BT_CONN_CONNECT_SCAN, - BT_CONN_CONNECT_DIR_ADV, - BT_CONN_CONNECT, - BT_CONN_CONNECTED, - BT_CONN_DISCONNECT, + BT_CONN_DISCONNECTED, + BT_CONN_CONNECT_SCAN, + BT_CONN_CONNECT_DIR_ADV, + BT_CONN_CONNECT, + BT_CONN_CONNECTED, + BT_CONN_DISCONNECT, } bt_conn_state_t; /* bt_conn flags: the flags defined here represent connection parameters */ enum { - BT_CONN_AUTO_CONNECT, - BT_CONN_BR_LEGACY_SECURE, /* 16 digits legacy PIN tracker */ - BT_CONN_USER, /* user I/O when pairing */ - BT_CONN_BR_PAIRING, /* BR connection in pairing context */ - BT_CONN_BR_NOBOND, /* SSP no bond pairing tracker */ - BT_CONN_BR_PAIRING_INITIATOR, /* local host starts authentication */ - BT_CONN_CLEANUP, /* Disconnected, pending cleanup */ - BT_CONN_AUTO_PHY_UPDATE, /* Auto-update PHY */ - BT_CONN_SLAVE_PARAM_UPDATE, /* If slave param update timer fired */ - BT_CONN_SLAVE_PARAM_SET, /* If slave param were set from app */ - BT_CONN_SLAVE_PARAM_L2CAP, /* If should force L2CAP for CPUP */ - BT_CONN_FORCE_PAIR, /* Pairing even with existing keys. */ + BT_CONN_AUTO_CONNECT, + BT_CONN_BR_LEGACY_SECURE, /* 16 digits legacy PIN tracker */ + BT_CONN_USER, /* user I/O when pairing */ + BT_CONN_BR_PAIRING, /* BR connection in pairing context */ + BT_CONN_BR_NOBOND, /* SSP no bond pairing tracker */ + BT_CONN_BR_PAIRING_INITIATOR, /* local host starts authentication */ + BT_CONN_CLEANUP, /* Disconnected, pending cleanup */ + BT_CONN_AUTO_PHY_UPDATE, /* Auto-update PHY */ + BT_CONN_SLAVE_PARAM_UPDATE, /* If slave param update timer fired */ + BT_CONN_SLAVE_PARAM_SET, /* If slave param were set from app */ + BT_CONN_SLAVE_PARAM_L2CAP, /* If should force L2CAP for CPUP */ + BT_CONN_FORCE_PAIR, /* Pairing even with existing keys. */ - BT_CONN_AUTO_PHY_COMPLETE, /* Auto-initiated PHY procedure done */ - BT_CONN_AUTO_FEATURE_EXCH, /* Auto-initiated LE Feat done */ - BT_CONN_AUTO_VERSION_INFO, /* Auto-initiated LE version done */ + BT_CONN_AUTO_PHY_COMPLETE, /* Auto-initiated PHY procedure done */ + BT_CONN_AUTO_FEATURE_EXCH, /* Auto-initiated LE Feat done */ + BT_CONN_AUTO_VERSION_INFO, /* Auto-initiated LE version done */ - /* Total number of flags - must be at the end of the enum */ - BT_CONN_NUM_FLAGS, + /* Total number of flags - must be at the end of the enum */ + BT_CONN_NUM_FLAGS, }; struct bt_conn_le { - bt_addr_le_t dst; + bt_addr_le_t dst; - bt_addr_le_t init_addr; - bt_addr_le_t resp_addr; + bt_addr_le_t init_addr; + bt_addr_le_t resp_addr; - u16_t interval; - u16_t interval_min; - u16_t interval_max; + u16_t interval; + u16_t interval_min; + u16_t interval_max; - u16_t latency; - u16_t timeout; - u16_t pending_latency; - u16_t pending_timeout; + u16_t latency; + u16_t timeout; + u16_t pending_latency; + u16_t pending_timeout; - u8_t features[8]; + u8_t features[8]; - struct bt_keys *keys; + struct bt_keys *keys; #if defined(CONFIG_BT_STACK_PTS) - u8_t own_adder_type; + u8_t own_adder_type; #endif }; @@ -69,96 +69,96 @@ struct bt_conn_le { #define LMP_MAX_PAGES 2 struct bt_conn_br { - bt_addr_t dst; - u8_t remote_io_capa; - u8_t remote_auth; - u8_t pairing_method; - /* remote LMP features pages per 8 bytes each */ - u8_t features[LMP_MAX_PAGES][8]; + bt_addr_t dst; + u8_t remote_io_capa; + u8_t remote_auth; + u8_t pairing_method; + /* remote LMP features pages per 8 bytes each */ + u8_t features[LMP_MAX_PAGES][8]; - struct bt_keys_link_key *link_key; + struct bt_keys_link_key *link_key; }; struct bt_conn_sco { - /* Reference to ACL Connection */ - struct bt_conn *acl; - u16_t pkt_type; + /* Reference to ACL Connection */ + struct bt_conn *acl; + u16_t pkt_type; }; #endif typedef void (*bt_conn_tx_cb_t)(struct bt_conn *conn, void *user_data); struct bt_conn_tx { - sys_snode_t node; + sys_snode_t node; - bt_conn_tx_cb_t cb; - void *user_data; + bt_conn_tx_cb_t cb; + void *user_data; - /* Number of pending packets without a callback after this one */ - u32_t pending_no_cb; + /* Number of pending packets without a callback after this one */ + u32_t pending_no_cb; }; struct bt_conn { - u16_t handle; - u8_t type; - u8_t role; + u16_t handle; + u8_t type; + u8_t role; - ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS); + ATOMIC_DEFINE(flags, BT_CONN_NUM_FLAGS); - /* Which local identity address this connection uses */ - u8_t id; + /* Which local identity address this connection uses */ + u8_t id; #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) - bt_security_t sec_level; - bt_security_t required_sec_level; - u8_t encrypt; + bt_security_t sec_level; + bt_security_t required_sec_level; + u8_t encrypt; #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ - /* Connection error or reason for disconnect */ - u8_t err; + /* Connection error or reason for disconnect */ + u8_t err; - bt_conn_state_t state; + bt_conn_state_t state; - u16_t rx_len; - struct net_buf *rx; + u16_t rx_len; + struct net_buf *rx; - /* Sent but not acknowledged TX packets with a callback */ - sys_slist_t tx_pending; - /* Sent but not acknowledged TX packets without a callback before - * the next packet (if any) in tx_pending. - */ - u32_t pending_no_cb; + /* Sent but not acknowledged TX packets with a callback */ + sys_slist_t tx_pending; + /* Sent but not acknowledged TX packets without a callback before + * the next packet (if any) in tx_pending. + */ + u32_t pending_no_cb; - /* Completed TX for which we need to call the callback */ - sys_slist_t tx_complete; - struct k_work tx_complete_work; + /* Completed TX for which we need to call the callback */ + sys_slist_t tx_complete; + struct k_work tx_complete_work; - /* Queue for outgoing ACL data */ - struct k_fifo tx_queue; + /* Queue for outgoing ACL data */ + struct k_fifo tx_queue; - /* Active L2CAP channels */ - sys_slist_t channels; + /* Active L2CAP channels */ + sys_slist_t channels; - atomic_t ref; + atomic_t ref; - /* Delayed work for connection update and other deferred tasks */ - struct k_delayed_work update_work; + /* Delayed work for connection update and other deferred tasks */ + struct k_delayed_work update_work; - union { - struct bt_conn_le le; + union { + struct bt_conn_le le; #if defined(CONFIG_BT_BREDR) - struct bt_conn_br br; - struct bt_conn_sco sco; + struct bt_conn_br br; + struct bt_conn_sco sco; #endif - }; + }; #if defined(CONFIG_BT_REMOTE_VERSION) - struct bt_conn_rv { - u8_t version; - u16_t manufacturer; - u16_t subversion; - } rv; + struct bt_conn_rv { + u8_t version; + u16_t manufacturer; + u16_t subversion; + } rv; #endif }; @@ -167,11 +167,11 @@ void bt_conn_recv(struct bt_conn *conn, struct net_buf *buf, u8_t flags); /* Send data over a connection */ int bt_conn_send_cb(struct bt_conn *conn, struct net_buf *buf, - bt_conn_tx_cb_t cb, void *user_data); + bt_conn_tx_cb_t cb, void *user_data); static inline int bt_conn_send(struct bt_conn *conn, struct net_buf *buf) { - return bt_conn_send_cb(conn, buf, NULL, NULL); + return bt_conn_send_cb(conn, buf, NULL, NULL); } /* Add a new LE connection */ @@ -218,13 +218,13 @@ struct bt_conn *bt_conn_lookup_id(u8_t id); * with the specific state */ struct bt_conn *bt_conn_lookup_state_le(const bt_addr_le_t *peer, - const bt_conn_state_t state); + const bt_conn_state_t state); /* Set connection object in certain state and perform action related to state */ void bt_conn_set_state(struct bt_conn *conn, bt_conn_state_t state); int bt_conn_le_conn_update(struct bt_conn *conn, - const struct bt_le_conn_param *param); + const struct bt_le_conn_param *param); void notify_remote_info(struct bt_conn *conn); @@ -235,7 +235,7 @@ bool le_param_req(struct bt_conn *conn, struct bt_le_conn_param *param); #if defined(CONFIG_BT_SMP) /* rand and ediv should be in BT order */ int bt_conn_le_start_encryption(struct bt_conn *conn, u8_t rand[8], - u8_t ediv[2], const u8_t *ltk, size_t len); + u8_t ediv[2], const u8_t *ltk, size_t len); /* Notify higher layers that RPA was resolved */ void bt_conn_identity_resolved(struct bt_conn *conn); @@ -249,40 +249,40 @@ void bt_conn_security_changed(struct bt_conn *conn, enum bt_security_err err); /* Prepare a PDU to be sent over a connection */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *bt_conn_create_pdu_timeout_debug(struct net_buf_pool *pool, - size_t reserve, s32_t timeout, - const char *func, int line); + size_t reserve, s32_t timeout, + const char *func, int line); #define bt_conn_create_pdu_timeout(_pool, _reserve, _timeout) \ - bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \ - __func__, __LINE__) + bt_conn_create_pdu_timeout_debug(_pool, _reserve, _timeout, \ + __func__, __LINE__) #define bt_conn_create_pdu(_pool, _reserve) \ - bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \ - __func__, __line__) + bt_conn_create_pdu_timeout_debug(_pool, _reserve, K_FOREVER, \ + __func__, __line__) #else struct net_buf *bt_conn_create_pdu_timeout(struct net_buf_pool *pool, - size_t reserve, s32_t timeout); + size_t reserve, s32_t timeout); #define bt_conn_create_pdu(_pool, _reserve) \ - bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER) + bt_conn_create_pdu_timeout(_pool, _reserve, K_FOREVER) #endif /* Prepare a PDU to be sent over a connection */ #if defined(CONFIG_NET_BUF_LOG) struct net_buf *bt_conn_create_frag_timeout_debug(size_t reserve, s32_t timeout, - const char *func, int line); + const char *func, int line); #define bt_conn_create_frag_timeout(_reserve, _timeout) \ - bt_conn_create_frag_timeout_debug(_reserve, _timeout, \ - __func__, __LINE__) + bt_conn_create_frag_timeout_debug(_reserve, _timeout, \ + __func__, __LINE__) #define bt_conn_create_frag(_reserve) \ - bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \ - __func__, __LINE__) + bt_conn_create_frag_timeout_debug(_reserve, K_FOREVER, \ + __func__, __LINE__) #else struct net_buf *bt_conn_create_frag_timeout(size_t reserve, s32_t timeout); #define bt_conn_create_frag(_reserve) \ - bt_conn_create_frag_timeout(_reserve, K_FOREVER) + bt_conn_create_frag_timeout(_reserve, K_FOREVER) #endif /* Initialize connection management */ diff --git a/components/network/ble/blestack/src/host/crypto.c b/components/network/ble/blestack/src/host/crypto.c index 30b14fbf..58e98a8a 100644 --- a/components/network/ble/blestack/src/host/crypto.c +++ b/components/network/ble/blestack/src/host/crypto.c @@ -30,66 +30,66 @@ static struct tc_hmac_prng_struct prng; static int prng_reseed(struct tc_hmac_prng_struct *h) { - u8_t seed[32]; - s64_t extra; - int ret, i; + u8_t seed[32]; + s64_t extra; + int ret, i; - for (i = 0; i < (sizeof(seed) / 8); i++) { - struct bt_hci_rp_le_rand *rp; - struct net_buf *rsp; + for (i = 0; i < (sizeof(seed) / 8); i++) { + struct bt_hci_rp_le_rand *rp; + struct net_buf *rsp; - ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp); - if (ret) { - return ret; - } + ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp); + if (ret) { + return ret; + } - rp = (void *)rsp->data; - memcpy(&seed[i * 8], rp->rand, 8); + rp = (void *)rsp->data; + memcpy(&seed[i * 8], rp->rand, 8); - net_buf_unref(rsp); - } + net_buf_unref(rsp); + } - extra = k_uptime_get(); + extra = k_uptime_get(); - ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra, - sizeof(extra)); - if (ret == TC_CRYPTO_FAIL) { - BT_ERR("Failed to re-seed PRNG"); - return -EIO; - } + ret = tc_hmac_prng_reseed(h, seed, sizeof(seed), (u8_t *)&extra, + sizeof(extra)); + if (ret == TC_CRYPTO_FAIL) { + BT_ERR("Failed to re-seed PRNG"); + return -EIO; + } - return 0; + return 0; } int prng_init(void) { - struct bt_hci_rp_le_rand *rp; - struct net_buf *rsp; - int ret; + struct bt_hci_rp_le_rand *rp; + struct net_buf *rsp; + int ret; - /* Check first that HCI_LE_Rand is supported */ - if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 7)) { - return -ENOTSUP; - } + /* Check first that HCI_LE_Rand is supported */ + if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 7)) { + return -ENOTSUP; + } - ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp); - if (ret) { - return ret; - } + ret = bt_hci_cmd_send_sync(BT_HCI_OP_LE_RAND, NULL, &rsp); + if (ret) { + return ret; + } - rp = (void *)rsp->data; + rp = (void *)rsp->data; - ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand)); + ret = tc_hmac_prng_init(&prng, rp->rand, sizeof(rp->rand)); - net_buf_unref(rsp); + net_buf_unref(rsp); - if (ret == TC_CRYPTO_FAIL) { - BT_ERR("Failed to initialize PRNG"); - return -EIO; - } + if (ret == TC_CRYPTO_FAIL) { + BT_ERR("Failed to initialize PRNG"); + return -EIO; + } - /* re-seed is needed after init */ - return prng_reseed(&prng); + /* re-seed is needed after init */ + return prng_reseed(&prng); } int bt_rand(void *buf, size_t len) @@ -99,69 +99,69 @@ int bt_rand(void *buf, size_t len) return 0; #else int ret; - ret = tc_hmac_prng_generate(buf, len, &prng); - if (ret == TC_HMAC_PRNG_RESEED_REQ) { - ret = prng_reseed(&prng); - if (ret) { - return ret; - } + ret = tc_hmac_prng_generate(buf, len, &prng); + if (ret == TC_HMAC_PRNG_RESEED_REQ) { + ret = prng_reseed(&prng); + if (ret) { + return ret; + } - ret = tc_hmac_prng_generate(buf, len, &prng); - } + ret = tc_hmac_prng_generate(buf, len, &prng); + } - if (ret == TC_CRYPTO_SUCCESS) { - return 0; - } - - return -EIO; + if (ret == TC_CRYPTO_SUCCESS) { + return 0; + } + + return -EIO; #endif } int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16], - u8_t enc_data[16]) + u8_t enc_data[16]) { - struct tc_aes_key_sched_struct s; - u8_t tmp[16]; + struct tc_aes_key_sched_struct s; + u8_t tmp[16]; - BT_DBG("key %s", bt_hex(key, 16)); - BT_DBG("plaintext %s", bt_hex(plaintext, 16)); + BT_DBG("key %s", bt_hex(key, 16)); + BT_DBG("plaintext %s", bt_hex(plaintext, 16)); - sys_memcpy_swap(tmp, key, 16); + sys_memcpy_swap(tmp, key, 16); - if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) { - return -EINVAL; - } + if (tc_aes128_set_encrypt_key(&s, tmp) == TC_CRYPTO_FAIL) { + return -EINVAL; + } - sys_memcpy_swap(tmp, plaintext, 16); + sys_memcpy_swap(tmp, plaintext, 16); - if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) { - return -EINVAL; - } + if (tc_aes_encrypt(enc_data, tmp, &s) == TC_CRYPTO_FAIL) { + return -EINVAL; + } - sys_mem_swap(enc_data, 16); + sys_mem_swap(enc_data, 16); - BT_DBG("enc_data %s", bt_hex(enc_data, 16)); + BT_DBG("enc_data %s", bt_hex(enc_data, 16)); - return 0; + return 0; } int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16], - u8_t enc_data[16]) + u8_t enc_data[16]) { - struct tc_aes_key_sched_struct s; + struct tc_aes_key_sched_struct s; - BT_DBG("key %s", bt_hex(key, 16)); - BT_DBG("plaintext %s", bt_hex(plaintext, 16)); + BT_DBG("key %s", bt_hex(key, 16)); + BT_DBG("plaintext %s", bt_hex(plaintext, 16)); - if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) { - return -EINVAL; - } + if (tc_aes128_set_encrypt_key(&s, key) == TC_CRYPTO_FAIL) { + return -EINVAL; + } - if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) { - return -EINVAL; - } + if (tc_aes_encrypt(enc_data, plaintext, &s) == TC_CRYPTO_FAIL) { + return -EINVAL; + } - BT_DBG("enc_data %s", bt_hex(enc_data, 16)); + BT_DBG("enc_data %s", bt_hex(enc_data, 16)); - return 0; + return 0; } diff --git a/components/network/ble/blestack/src/host/ecc.h b/components/network/ble/blestack/src/host/ecc.h index 05538101..5eb12078 100644 --- a/components/network/ble/blestack/src/host/ecc.h +++ b/components/network/ble/blestack/src/host/ecc.h @@ -8,17 +8,17 @@ /* @brief Container for public key callback */ struct bt_pub_key_cb { - /** @brief Callback type for Public Key generation. - * - * Used to notify of the local public key or that the local key is not - * available (either because of a failure to read it or because it is - * being regenerated). - * - * @param key The local public key, or NULL in case of no key. - */ - void (*func)(const u8_t key[64]); + /** @brief Callback type for Public Key generation. + * + * Used to notify of the local public key or that the local key is not + * available (either because of a failure to read it or because it is + * being regenerated). + * + * @param key The local public key, or NULL in case of no key. + */ + void (*func)(const u8_t key[64]); - struct bt_pub_key_cb *_next; + struct bt_pub_key_cb *_next; }; /* @brief Generate a new Public Key. diff --git a/components/network/ble/blestack/src/host/gatt.c b/components/network/ble/blestack/src/host/gatt.c index 4a5ffea2..df254577 100644 --- a/components/network/ble/blestack/src/host/gatt.c +++ b/components/network/ble/blestack/src/host/gatt.c @@ -51,17 +51,17 @@ extern u8_t event_flag; #include "settings.h" #include "gatt_internal.h" -#define SC_TIMEOUT K_MSEC(10) -#define CCC_STORE_DELAY K_SECONDS(1) +#define SC_TIMEOUT K_MSEC(10) +#define CCC_STORE_DELAY K_SECONDS(1) -#define DB_HASH_TIMEOUT K_MSEC(10) +#define DB_HASH_TIMEOUT K_MSEC(10) static u16_t last_static_handle; /* Persistent storage format for GATT CCC */ struct ccc_store { - u16_t handle; - u16_t value; + u16_t handle; + u16_t value; }; #if defined(CONFIG_BT_GATT_CLIENT) @@ -77,90 +77,90 @@ static sys_slist_t db; static atomic_t init; static ssize_t read_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + void *buf, u16_t len, u16_t offset) { - const char *name = bt_get_name(); + const char *name = bt_get_name(); - return bt_gatt_attr_read(conn, attr, buf, len, offset, name, - strlen(name)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, name, + strlen(name)); } #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE) static ssize_t write_name(struct bt_conn *conn, const struct bt_gatt_attr *attr, - const void *buf, u16_t len, u16_t offset, - u8_t flags) + const void *buf, u16_t len, u16_t offset, + u8_t flags) { - char value[CONFIG_BT_DEVICE_NAME_MAX] = {}; + char value[CONFIG_BT_DEVICE_NAME_MAX] = {}; - if (offset) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); - } + if (offset) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); + } - if (len >= sizeof(value)) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); - } + if (len >= sizeof(value)) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } - memcpy(value, buf, len); + memcpy(value, buf, len); - bt_set_name(value); + bt_set_name(value); - return len; + return len; } #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */ static ssize_t read_appearance(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - u16_t appearance = sys_cpu_to_le16(gap_appearance); + u16_t appearance = sys_cpu_to_le16(gap_appearance); - return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance, - sizeof(appearance)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &appearance, + sizeof(appearance)); } #if defined (CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS) /* This checks if the range entered is valid */ BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MIN_INT > 3200 && - CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff)); + CONFIG_BT_PERIPHERAL_PREF_MIN_INT < 0xffff)); BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_MAX_INT > 3200 && - CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff)); + CONFIG_BT_PERIPHERAL_PREF_MAX_INT < 0xffff)); BUILD_ASSERT(!(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT > 3200 && - CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff)); + CONFIG_BT_PERIPHERAL_PREF_TIMEOUT < 0xffff)); BUILD_ASSERT((CONFIG_BT_PERIPHERAL_PREF_MIN_INT == 0xffff) || - (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <= - CONFIG_BT_PERIPHERAL_PREF_MAX_INT)); + (CONFIG_BT_PERIPHERAL_PREF_MIN_INT <= + CONFIG_BT_PERIPHERAL_PREF_MAX_INT)); static ssize_t read_ppcp(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + void *buf, u16_t len, u16_t offset) { - struct __packed { - u16_t min_int; - u16_t max_int; - u16_t latency; - u16_t timeout; - } ppcp; + struct __packed { + u16_t min_int; + u16_t max_int; + u16_t latency; + u16_t timeout; + } ppcp; - ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT); - ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT); - ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY); - ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT); + ppcp.min_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MIN_INT); + ppcp.max_int = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_MAX_INT); + ppcp.latency = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY); + ppcp.timeout = sys_cpu_to_le16(CONFIG_BT_PERIPHERAL_PREF_TIMEOUT); - return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp, - sizeof(ppcp)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &ppcp, + sizeof(ppcp)); } #endif #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY) static ssize_t read_central_addr_res(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - u8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP; + u8_t central_addr_res = BT_GATT_CENTRAL_ADDR_RES_SUPP; - return bt_gatt_attr_read(conn, attr, buf, len, offset, - ¢ral_addr_res, sizeof(central_addr_res)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, + ¢ral_addr_res, sizeof(central_addr_res)); } #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */ @@ -169,28 +169,28 @@ static struct bt_gatt_attr gap_attrs[] = { #else BT_GATT_SERVICE_DEFINE(_2_gap_svc, #endif - BT_GATT_PRIMARY_SERVICE(BT_UUID_GAP), + BT_GATT_PRIMARY_SERVICE(BT_UUID_GAP), #if defined(CONFIG_BT_DEVICE_NAME_GATT_WRITABLE) - /* Require pairing for writes to device name */ - BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_ENCRYPT, - read_name, write_name, bt_dev.name), + /* Require pairing for writes to device name */ + BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE_ENCRYPT, + read_name, write_name, bt_dev.name), #else - BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ, - BT_GATT_PERM_READ, read_name, NULL, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_GAP_DEVICE_NAME, BT_GATT_CHRC_READ, + BT_GATT_PERM_READ, read_name, NULL, NULL), #endif /* CONFIG_BT_DEVICE_NAME_GATT_WRITABLE */ - BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, BT_GATT_CHRC_READ, - BT_GATT_PERM_READ, read_appearance, NULL, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_GAP_APPEARANCE, BT_GATT_CHRC_READ, + BT_GATT_PERM_READ, read_appearance, NULL, NULL), #if defined(CONFIG_BT_CENTRAL) && defined(CONFIG_BT_PRIVACY) - BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_central_addr_res, NULL, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_CENTRAL_ADDR_RES, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_central_addr_res, NULL, NULL), #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS) - BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ, - BT_GATT_PERM_READ, read_ppcp, NULL, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_GAP_PPCP, BT_GATT_CHRC_READ, + BT_GATT_PERM_READ, read_ppcp, NULL, NULL), #endif #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) }; @@ -203,17 +203,17 @@ static struct bt_gatt_service gap_svc = BT_GATT_SERVICE(gap_attrs); #endif struct sc_data { - u16_t start; - u16_t end; + u16_t start; + u16_t end; } __packed; struct gatt_sc_cfg { - u8_t id; - bt_addr_le_t peer; - struct { - u16_t start; - u16_t end; - } data; + u8_t id; + bt_addr_le_t peer; + struct { + u16_t start; + u16_t end; + } data; }; #define SC_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) @@ -222,199 +222,199 @@ BUILD_ASSERT(sizeof(struct sc_data) == sizeof(sc_cfg[0].data)); static struct gatt_sc_cfg *find_sc_cfg(u8_t id, bt_addr_le_t *addr) { - BT_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr)); + BT_DBG("id: %u, addr: %s", id, bt_addr_le_str(addr)); - for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) { - if (id == sc_cfg[i].id && - !bt_addr_le_cmp(&sc_cfg[i].peer, addr)) { - return &sc_cfg[i]; - } - } + for (size_t i = 0; i < ARRAY_SIZE(sc_cfg); i++) { + if (id == sc_cfg[i].id && + !bt_addr_le_cmp(&sc_cfg[i].peer, addr)) { + return &sc_cfg[i]; + } + } - return NULL; + return NULL; } static void sc_store(struct gatt_sc_cfg *cfg) { - char key[BT_SETTINGS_KEY_MAX]; - int err; + char key[BT_SETTINGS_KEY_MAX]; + int err; - if (cfg->id) { - char id_str[4]; + if (cfg->id) { + char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), cfg->id); - bt_settings_encode_key(key, sizeof(key), "sc", - &cfg->peer, id_str); - } else { - bt_settings_encode_key(key, sizeof(key), "sc", - &cfg->peer, NULL); - } + u8_to_dec(id_str, sizeof(id_str), cfg->id); + bt_settings_encode_key(key, sizeof(key), "sc", + &cfg->peer, id_str); + } else { + bt_settings_encode_key(key, sizeof(key), "sc", + &cfg->peer, NULL); + } - err = settings_save_one(key, (u8_t *)&cfg->data, sizeof(cfg->data)); - if (err) { - BT_ERR("failed to store SC (err %d)", err); - return; - } + err = settings_save_one(key, (u8_t *)&cfg->data, sizeof(cfg->data)); + if (err) { + BT_ERR("failed to store SC (err %d)", err); + return; + } - BT_DBG("stored SC for %s (%s, 0x%04x-0x%04x)", - bt_addr_le_str(&cfg->peer), log_strdup(key), cfg->data.start, - cfg->data.end); + BT_DBG("stored SC for %s (%s, 0x%04x-0x%04x)", + bt_addr_le_str(&cfg->peer), log_strdup(key), cfg->data.start, + cfg->data.end); } static void sc_clear(struct gatt_sc_cfg *cfg) { - BT_DBG("peer %s", bt_addr_le_str(&cfg->peer)); + BT_DBG("peer %s", bt_addr_le_str(&cfg->peer)); - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bool modified = false; + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bool modified = false; - if (cfg->data.start || cfg->data.end) { - modified = true; - } + if (cfg->data.start || cfg->data.end) { + modified = true; + } - if (modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) { - char key[BT_SETTINGS_KEY_MAX]; - int err; + if (modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) { + char key[BT_SETTINGS_KEY_MAX]; + int err; - if (cfg->id) { - char id_str[4]; + if (cfg->id) { + char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), cfg->id); - bt_settings_encode_key(key, sizeof(key), "sc", - &cfg->peer, id_str); - } else { - bt_settings_encode_key(key, sizeof(key), "sc", - &cfg->peer, NULL); - } + u8_to_dec(id_str, sizeof(id_str), cfg->id); + bt_settings_encode_key(key, sizeof(key), "sc", + &cfg->peer, id_str); + } else { + bt_settings_encode_key(key, sizeof(key), "sc", + &cfg->peer, NULL); + } - err = settings_delete(key); - if (err) { - BT_ERR("failed to delete SC (err %d)", err); - } else { - BT_DBG("deleted SC for %s (%s)", - bt_addr_le_str(&cfg->peer), - log_strdup(key)); - } - } - } + err = settings_delete(key); + if (err) { + BT_ERR("failed to delete SC (err %d)", err); + } else { + BT_DBG("deleted SC for %s (%s)", + bt_addr_le_str(&cfg->peer), + log_strdup(key)); + } + } + } - memset(cfg, 0, sizeof(*cfg)); + memset(cfg, 0, sizeof(*cfg)); } static void sc_reset(struct gatt_sc_cfg *cfg) { - BT_DBG("peer %s", bt_addr_le_str(&cfg->peer)); + BT_DBG("peer %s", bt_addr_le_str(&cfg->peer)); - memset(&cfg->data, 0, sizeof(cfg->data)); + memset(&cfg->data, 0, sizeof(cfg->data)); - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - sc_store(cfg); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + sc_store(cfg); + } } static bool update_range(u16_t *start, u16_t *end, u16_t new_start, - u16_t new_end) + u16_t new_end) { - BT_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x", - *start, *end, new_start, new_end); + BT_DBG("start 0x%04x end 0x%04x new_start 0x%04x new_end 0x%04x", + *start, *end, new_start, new_end); - /* Check if inside existing range */ - if (new_start >= *start && new_end <= *end) { - return false; - } + /* Check if inside existing range */ + if (new_start >= *start && new_end <= *end) { + return false; + } - /* Update range */ - if (*start > new_start) { - *start = new_start; - } + /* Update range */ + if (*start > new_start) { + *start = new_start; + } - if (*end < new_end) { - *end = new_end; - } + if (*end < new_end) { + *end = new_end; + } - return true; + return true; } static void sc_save(u8_t id, bt_addr_le_t *peer, u16_t start, u16_t end) { - struct gatt_sc_cfg *cfg; - bool modified = false; + struct gatt_sc_cfg *cfg; + bool modified = false; - BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start, - end); + BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(peer), start, + end); - cfg = find_sc_cfg(id, peer); - if (!cfg) { - /* Find and initialize a free sc_cfg entry */ - cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); - if (!cfg) { - BT_ERR("unable to save SC: no cfg left"); - return; - } + cfg = find_sc_cfg(id, peer); + if (!cfg) { + /* Find and initialize a free sc_cfg entry */ + cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); + if (!cfg) { + BT_ERR("unable to save SC: no cfg left"); + return; + } - cfg->id = id; - bt_addr_le_copy(&cfg->peer, peer); - } + cfg->id = id; + bt_addr_le_copy(&cfg->peer, peer); + } - /* Check if there is any change stored */ - if (!(cfg->data.start || cfg->data.end)) { - cfg->data.start = start; - cfg->data.end = end; - modified = true; - goto done; - } + /* Check if there is any change stored */ + if (!(cfg->data.start || cfg->data.end)) { + cfg->data.start = start; + cfg->data.end = end; + modified = true; + goto done; + } - modified = update_range(&cfg->data.start, &cfg->data.end, start, end); + modified = update_range(&cfg->data.start, &cfg->data.end, start, end); done: - if (IS_ENABLED(CONFIG_BT_SETTINGS) && - modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) { - sc_store(cfg); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && + modified && bt_addr_le_is_bonded(cfg->id, &cfg->peer)) { + sc_store(cfg); + } } static bool sc_ccc_cfg_write(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - u16_t value) + const struct bt_gatt_attr *attr, + u16_t value) { - BT_DBG("value 0x%04x", value); + BT_DBG("value 0x%04x", value); - if (value == BT_GATT_CCC_INDICATE) { - /* Create a new SC configuration entry if subscribed */ - sc_save(conn->id, &conn->le.dst, 0, 0); - } else { - struct gatt_sc_cfg *cfg; + if (value == BT_GATT_CCC_INDICATE) { + /* Create a new SC configuration entry if subscribed */ + sc_save(conn->id, &conn->le.dst, 0, 0); + } else { + struct gatt_sc_cfg *cfg; - /* Clear SC configuration if unsubscribed */ - cfg = find_sc_cfg(conn->id, &conn->le.dst); - if (cfg) { - sc_clear(cfg); - } - } + /* Clear SC configuration if unsubscribed */ + cfg = find_sc_cfg(conn->id, &conn->le.dst); + if (cfg) { + sc_clear(cfg); + } + } - return true; + return true; } static struct _bt_gatt_ccc sc_ccc = BT_GATT_CCC_INITIALIZER(NULL, - sc_ccc_cfg_write, - NULL); + sc_ccc_cfg_write, + NULL); #if defined(CONFIG_BT_GATT_CACHING) enum { - CF_CHANGE_AWARE, /* Client is changed aware */ - CF_OUT_OF_SYNC, /* Client is out of sync */ + CF_CHANGE_AWARE, /* Client is changed aware */ + CF_OUT_OF_SYNC, /* Client is out of sync */ - /* Total number of flags - must be at the end of the enum */ - CF_NUM_FLAGS, + /* Total number of flags - must be at the end of the enum */ + CF_NUM_FLAGS, }; #define CF_ROBUST_CACHING(_cfg) (_cfg->data[0] & BIT(0)) struct gatt_cf_cfg { - u8_t id; - bt_addr_le_t peer; - u8_t data[1]; - ATOMIC_DEFINE(flags, CF_NUM_FLAGS); + u8_t id; + bt_addr_le_t peer; + u8_t data[1]; + ATOMIC_DEFINE(flags, CF_NUM_FLAGS); }; #define CF_CFG_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) @@ -422,287 +422,287 @@ static struct gatt_cf_cfg cf_cfg[CF_CFG_MAX] = {}; static struct gatt_cf_cfg *find_cf_cfg(struct bt_conn *conn) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { - if (!conn) { - if (!bt_addr_le_cmp(&cf_cfg[i].peer, BT_ADDR_LE_ANY)) { - return &cf_cfg[i]; - } - } else if (!bt_conn_addr_le_cmp(conn, &cf_cfg[i].peer)) { - return &cf_cfg[i]; - } - } + for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { + if (!conn) { + if (!bt_addr_le_cmp(&cf_cfg[i].peer, BT_ADDR_LE_ANY)) { + return &cf_cfg[i]; + } + } else if (!bt_conn_addr_le_cmp(conn, &cf_cfg[i].peer)) { + return &cf_cfg[i]; + } + } - return NULL; + return NULL; } static ssize_t cf_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + void *buf, u16_t len, u16_t offset) { - struct gatt_cf_cfg *cfg; - u8_t data[1] = {}; + struct gatt_cf_cfg *cfg; + u8_t data[1] = {}; - cfg = find_cf_cfg(conn); - if (cfg) { - memcpy(data, cfg->data, sizeof(data)); - } + cfg = find_cf_cfg(conn); + if (cfg) { + memcpy(data, cfg->data, sizeof(data)); + } - return bt_gatt_attr_read(conn, attr, buf, len, offset, data, - sizeof(data)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, data, + sizeof(data)); } static bool cf_set_value(struct gatt_cf_cfg *cfg, const u8_t *value, u16_t len) { - u16_t i; - u8_t last_byte = 1U; - u8_t last_bit = 1U; + u16_t i; + u8_t last_byte = 1U; + u8_t last_bit = 1U; - /* Validate the bits */ - for (i = 0U; i < len && i < last_byte; i++) { - u8_t chg_bits = value[i] ^ cfg->data[i]; - u8_t bit; + /* Validate the bits */ + for (i = 0U; i < len && i < last_byte; i++) { + u8_t chg_bits = value[i] ^ cfg->data[i]; + u8_t bit; - for (bit = 0U; bit < last_bit; bit++) { - /* A client shall never clear a bit it has set */ - if ((BIT(bit) & chg_bits) && - (BIT(bit) & cfg->data[i])) { - return false; - } - } - } + for (bit = 0U; bit < last_bit; bit++) { + /* A client shall never clear a bit it has set */ + if ((BIT(bit) & chg_bits) && + (BIT(bit) & cfg->data[i])) { + return false; + } + } + } - /* Set the bits for each octect */ - for (i = 0U; i < len && i < last_byte; i++) { - cfg->data[i] |= value[i] & ((1 << last_bit) - 1); - BT_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i], - value[i]); - } + /* Set the bits for each octect */ + for (i = 0U; i < len && i < last_byte; i++) { + cfg->data[i] |= value[i] & ((1 << last_bit) - 1); + BT_DBG("byte %u: data 0x%02x value 0x%02x", i, cfg->data[i], + value[i]); + } - return true; + return true; } static ssize_t cf_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, - const void *buf, u16_t len, u16_t offset, u8_t flags) + const void *buf, u16_t len, u16_t offset, u8_t flags) { - struct gatt_cf_cfg *cfg; - const u8_t *value = buf; + struct gatt_cf_cfg *cfg; + const u8_t *value = buf; - if (offset > sizeof(cfg->data)) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); - } + if (offset > sizeof(cfg->data)) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); + } - if (offset + len > sizeof(cfg->data)) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); - } + if (offset + len > sizeof(cfg->data)) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } - cfg = find_cf_cfg(conn); - if (!cfg) { - cfg = find_cf_cfg(NULL); - } + cfg = find_cf_cfg(conn); + if (!cfg) { + cfg = find_cf_cfg(NULL); + } - if (!cfg) { - BT_WARN("No space to store Client Supported Features"); - return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES); - } + if (!cfg) { + BT_WARN("No space to store Client Supported Features"); + return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES); + } - BT_DBG("handle 0x%04x len %u", attr->handle, len); + BT_DBG("handle 0x%04x len %u", attr->handle, len); - if (!cf_set_value(cfg, value, len)) { - return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED); - } + if (!cf_set_value(cfg, value, len)) { + return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED); + } - bt_addr_le_copy(&cfg->peer, &conn->le.dst); - atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); + bt_addr_le_copy(&cfg->peer, &conn->le.dst); + atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); - return len; + return len; } static u8_t db_hash[16]; struct k_delayed_work db_hash_work; struct gen_hash_state { - struct tc_cmac_struct state; - int err; + struct tc_cmac_struct state; + int err; }; static u8_t gen_hash_m(const struct bt_gatt_attr *attr, void *user_data) { - struct gen_hash_state *state = user_data; - struct bt_uuid_16 *u16; - u8_t data[16]; - ssize_t len; - u16_t value; + struct gen_hash_state *state = user_data; + struct bt_uuid_16 *u16; + u8_t data[16]; + ssize_t len; + u16_t value; - if (attr->uuid->type != BT_UUID_TYPE_16) - return BT_GATT_ITER_CONTINUE; + if (attr->uuid->type != BT_UUID_TYPE_16) + return BT_GATT_ITER_CONTINUE; - u16 = (struct bt_uuid_16 *)attr->uuid; + u16 = (struct bt_uuid_16 *)attr->uuid; - switch (u16->val) { - /* Attributes to hash: handle + UUID + value */ - case 0x2800: /* GATT Primary Service */ - case 0x2801: /* GATT Secondary Service */ - case 0x2802: /* GATT Include Service */ - case 0x2803: /* GATT Characteristic */ - case 0x2900: /* GATT Characteristic Extended Properties */ - value = sys_cpu_to_le16(attr->handle); - if (tc_cmac_update(&state->state, (uint8_t *)&value, - sizeof(attr->handle)) == TC_CRYPTO_FAIL) { - state->err = -EINVAL; - return BT_GATT_ITER_STOP; - } + switch (u16->val) { + /* Attributes to hash: handle + UUID + value */ + case 0x2800: /* GATT Primary Service */ + case 0x2801: /* GATT Secondary Service */ + case 0x2802: /* GATT Include Service */ + case 0x2803: /* GATT Characteristic */ + case 0x2900: /* GATT Characteristic Extended Properties */ + value = sys_cpu_to_le16(attr->handle); + if (tc_cmac_update(&state->state, (uint8_t *)&value, + sizeof(attr->handle)) == TC_CRYPTO_FAIL) { + state->err = -EINVAL; + return BT_GATT_ITER_STOP; + } - value = sys_cpu_to_le16(u16->val); - if (tc_cmac_update(&state->state, (uint8_t *)&value, - sizeof(u16->val)) == TC_CRYPTO_FAIL) { - state->err = -EINVAL; - return BT_GATT_ITER_STOP; - } + value = sys_cpu_to_le16(u16->val); + if (tc_cmac_update(&state->state, (uint8_t *)&value, + sizeof(u16->val)) == TC_CRYPTO_FAIL) { + state->err = -EINVAL; + return BT_GATT_ITER_STOP; + } - len = attr->read(NULL, attr, data, sizeof(data), 0); - if (len < 0) { - state->err = len; - return BT_GATT_ITER_STOP; - } + len = attr->read(NULL, attr, data, sizeof(data), 0); + if (len < 0) { + state->err = len; + return BT_GATT_ITER_STOP; + } - if (tc_cmac_update(&state->state, data, len) == - TC_CRYPTO_FAIL) { - state->err = -EINVAL; - return BT_GATT_ITER_STOP; - } + if (tc_cmac_update(&state->state, data, len) == + TC_CRYPTO_FAIL) { + state->err = -EINVAL; + return BT_GATT_ITER_STOP; + } - break; - /* Attributes to hash: handle + UUID */ - case 0x2901: /* GATT Characteristic User Descriptor */ - case 0x2902: /* GATT Client Characteristic Configuration */ - case 0x2903: /* GATT Server Characteristic Configuration */ - case 0x2904: /* GATT Characteristic Presentation Format */ - case 0x2905: /* GATT Characteristic Aggregated Format */ - value = sys_cpu_to_le16(attr->handle); - if (tc_cmac_update(&state->state, (uint8_t *)&value, - sizeof(attr->handle)) == TC_CRYPTO_FAIL) { - state->err = -EINVAL; - return BT_GATT_ITER_STOP; - } + break; + /* Attributes to hash: handle + UUID */ + case 0x2901: /* GATT Characteristic User Descriptor */ + case 0x2902: /* GATT Client Characteristic Configuration */ + case 0x2903: /* GATT Server Characteristic Configuration */ + case 0x2904: /* GATT Characteristic Presentation Format */ + case 0x2905: /* GATT Characteristic Aggregated Format */ + value = sys_cpu_to_le16(attr->handle); + if (tc_cmac_update(&state->state, (uint8_t *)&value, + sizeof(attr->handle)) == TC_CRYPTO_FAIL) { + state->err = -EINVAL; + return BT_GATT_ITER_STOP; + } - value = sys_cpu_to_le16(u16->val); - if (tc_cmac_update(&state->state, (uint8_t *)&value, - sizeof(u16->val)) == TC_CRYPTO_FAIL) { - state->err = -EINVAL; - return BT_GATT_ITER_STOP; - } - break; - default: - return BT_GATT_ITER_CONTINUE; - } + value = sys_cpu_to_le16(u16->val); + if (tc_cmac_update(&state->state, (uint8_t *)&value, + sizeof(u16->val)) == TC_CRYPTO_FAIL) { + state->err = -EINVAL; + return BT_GATT_ITER_STOP; + } + break; + default: + return BT_GATT_ITER_CONTINUE; + } - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static void db_hash_store(void) { - int err; + int err; - err = settings_save_one("bt/hash", &db_hash, sizeof(db_hash)); - if (err) { - BT_ERR("Failed to save Database Hash (err %d)", err); - } + err = settings_save_one("bt/hash", &db_hash, sizeof(db_hash)); + if (err) { + BT_ERR("Failed to save Database Hash (err %d)", err); + } - BT_DBG("Database Hash stored"); + BT_DBG("Database Hash stored"); } static void db_hash_gen(bool store) { - u8_t key[16] = {}; - struct tc_aes_key_sched_struct sched; - struct gen_hash_state state; + u8_t key[16] = {}; + struct tc_aes_key_sched_struct sched; + struct gen_hash_state state; - if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) { - BT_ERR("Unable to setup AES CMAC"); - return; - } + if (tc_cmac_setup(&state.state, key, &sched) == TC_CRYPTO_FAIL) { + BT_ERR("Unable to setup AES CMAC"); + return; + } - bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state); + bt_gatt_foreach_attr(0x0001, 0xffff, gen_hash_m, &state); - if (tc_cmac_final(db_hash, &state.state) == TC_CRYPTO_FAIL) { - BT_ERR("Unable to calculate hash"); - return; - } + if (tc_cmac_final(db_hash, &state.state) == TC_CRYPTO_FAIL) { + BT_ERR("Unable to calculate hash"); + return; + } - /** - * Core 5.1 does not state the endianess of the hash. - * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic - * Values shall be LE unless otherwise defined. PTS expects hash to be - * in little endianess as well. bt_smp_aes_cmac calculates the hash in - * big endianess so we have to swap. - */ - sys_mem_swap(db_hash, sizeof(db_hash)); + /** + * Core 5.1 does not state the endianess of the hash. + * However Vol 3, Part F, 3.3.1 says that multi-octet Characteristic + * Values shall be LE unless otherwise defined. PTS expects hash to be + * in little endianess as well. bt_smp_aes_cmac calculates the hash in + * big endianess so we have to swap. + */ + sys_mem_swap(db_hash, sizeof(db_hash)); - BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "Hash: "); + BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "Hash: "); - if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { - db_hash_store(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) { + db_hash_store(); + } } static void db_hash_process(struct k_work *work) { - db_hash_gen(true); + db_hash_gen(true); } static ssize_t db_hash_read(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset) { - /* Check if db_hash is already pending in which case it shall be - * generated immediately instead of waiting the work to complete. - */ - if (k_delayed_work_remaining_get(&db_hash_work)) { - k_delayed_work_cancel(&db_hash_work); - db_hash_gen(true); - } + /* Check if db_hash is already pending in which case it shall be + * generated immediately instead of waiting the work to complete. + */ + if (k_delayed_work_remaining_get(&db_hash_work)) { + k_delayed_work_cancel(&db_hash_work); + db_hash_gen(true); + } - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: - * 2.5.2.1 Robust Caching - * A connected client becomes change-aware when... - * The client reads the Database Hash characteristic and then the server - * receives another ATT request from the client. - */ - bt_gatt_change_aware(conn, true); + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: + * 2.5.2.1 Robust Caching + * A connected client becomes change-aware when... + * The client reads the Database Hash characteristic and then the server + * receives another ATT request from the client. + */ + bt_gatt_change_aware(conn, true); - return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash, - sizeof(db_hash)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, db_hash, + sizeof(db_hash)); } static void clear_cf_cfg(struct gatt_cf_cfg *cfg) { - bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY); - memset(cfg->data, 0, sizeof(cfg->data)); - atomic_set(cfg->flags, 0); + bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY); + memset(cfg->data, 0, sizeof(cfg->data)); + atomic_set(cfg->flags, 0); } static void remove_cf_cfg(struct bt_conn *conn) { - struct gatt_cf_cfg *cfg; + struct gatt_cf_cfg *cfg; - cfg = find_cf_cfg(conn); - if (!cfg) { - return; - } + cfg = find_cf_cfg(conn); + if (!cfg) { + return; + } - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405: - * For clients with a trusted relationship, the characteristic value - * shall be persistent across connections. For clients without a - * trusted relationship the characteristic value shall be set to the - * default value at each connection. - */ - if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { - clear_cf_cfg(cfg); - } else { - /* Update address in case it has changed */ - bt_addr_le_copy(&cfg->peer, &conn->le.dst); - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2405: + * For clients with a trusted relationship, the characteristic value + * shall be persistent across connections. For clients without a + * trusted relationship the characteristic value shall be set to the + * default value at each connection. + */ + if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { + clear_cf_cfg(cfg); + } else { + /* Update address in case it has changed */ + bt_addr_le_copy(&cfg->peer, &conn->le.dst); + } } #endif /* CONFIG_BT_GATT_CACHING */ @@ -711,27 +711,27 @@ static struct bt_gatt_attr gatt_attrs[] = { #else BT_GATT_SERVICE_DEFINE(_1_gatt_svc, #endif - BT_GATT_PRIMARY_SERVICE(BT_UUID_GATT), + BT_GATT_PRIMARY_SERVICE(BT_UUID_GATT), #if defined(CONFIG_BT_GATT_SERVICE_CHANGED) - /* Bluetooth 5.0, Vol3 Part G: - * The Service Changed characteristic Attribute Handle on the server - * shall not change if the server has a trusted relationship with any - * client. - */ - BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE, - BT_GATT_PERM_NONE, NULL, NULL, NULL), - - BT_GATT_CCC_MANAGED(&sc_ccc, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), + /* Bluetooth 5.0, Vol3 Part G: + * The Service Changed characteristic Attribute Handle on the server + * shall not change if the server has a trusted relationship with any + * client. + */ + BT_GATT_CHARACTERISTIC(BT_UUID_GATT_SC, BT_GATT_CHRC_INDICATE, + BT_GATT_PERM_NONE, NULL, NULL, NULL), + + BT_GATT_CCC_MANAGED(&sc_ccc, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), #if defined(CONFIG_BT_GATT_CACHING) - BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES, - BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - cf_read, cf_write, NULL), - BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - db_hash_read, NULL, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_GATT_CLIENT_FEATURES, + BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + cf_read, cf_write, NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_GATT_DB_HASH, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + db_hash_read, NULL, NULL), #endif /* CONFIG_BT_GATT_CACHING */ #endif /* CONFIG_BT_GATT_SERVICE_CHANGED */ #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) @@ -748,286 +748,286 @@ static struct bt_gatt_service gatt_svc = BT_GATT_SERVICE(gatt_attrs); #if defined(CONFIG_BT_GATT_DYNAMIC_DB) static u8_t found_attr(const struct bt_gatt_attr *attr, void *user_data) { - const struct bt_gatt_attr **found = user_data; + const struct bt_gatt_attr **found = user_data; - *found = attr; + *found = attr; - return BT_GATT_ITER_STOP; + return BT_GATT_ITER_STOP; } static const struct bt_gatt_attr *find_attr(uint16_t handle) { - const struct bt_gatt_attr *attr = NULL; + const struct bt_gatt_attr *attr = NULL; - bt_gatt_foreach_attr(handle, handle, found_attr, &attr); + bt_gatt_foreach_attr(handle, handle, found_attr, &attr); - return attr; + return attr; } static void gatt_insert(struct bt_gatt_service *svc, u16_t last_handle) { - struct bt_gatt_service *tmp, *prev = NULL; + struct bt_gatt_service *tmp, *prev = NULL; - if (last_handle == 0 || svc->attrs[0].handle > last_handle) { - sys_slist_append(&db, &svc->node); - return; - } + if (last_handle == 0 || svc->attrs[0].handle > last_handle) { + sys_slist_append(&db, &svc->node); + return; + } - /* DB shall always have its service in ascending order */ - SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node) { - if (tmp->attrs[0].handle > svc->attrs[0].handle) { - if (prev) { - sys_slist_insert(&db, &prev->node, &svc->node); - } else { - sys_slist_prepend(&db, &svc->node); - } - return; - } + /* DB shall always have its service in ascending order */ + SYS_SLIST_FOR_EACH_CONTAINER(&db, tmp, node) { + if (tmp->attrs[0].handle > svc->attrs[0].handle) { + if (prev) { + sys_slist_insert(&db, &prev->node, &svc->node); + } else { + sys_slist_prepend(&db, &svc->node); + } + return; + } - prev = tmp; - } + prev = tmp; + } } static int gatt_register(struct bt_gatt_service *svc) { - struct bt_gatt_service *last; - u16_t handle, last_handle; - struct bt_gatt_attr *attrs = svc->attrs; - u16_t count = svc->attr_count; + struct bt_gatt_service *last; + u16_t handle, last_handle; + struct bt_gatt_attr *attrs = svc->attrs; + u16_t count = svc->attr_count; - if (sys_slist_is_empty(&db)) { - handle = last_static_handle; - last_handle = 0; - goto populate; - } + if (sys_slist_is_empty(&db)) { + handle = last_static_handle; + last_handle = 0; + goto populate; + } - last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node); - handle = last->attrs[last->attr_count - 1].handle; - last_handle = handle; + last = SYS_SLIST_PEEK_TAIL_CONTAINER(&db, last, node); + handle = last->attrs[last->attr_count - 1].handle; + last_handle = handle; populate: - /* Populate the handles and append them to the list */ - for (; attrs && count; attrs++, count--) { - if (!attrs->handle) { - /* Allocate handle if not set already */ - attrs->handle = ++handle; - } else if (attrs->handle > handle) { - /* Use existing handle if valid */ - handle = attrs->handle; - } else if (find_attr(attrs->handle)) { - /* Service has conflicting handles */ - BT_ERR("Unable to register handle 0x%04x", - attrs->handle); - return -EINVAL; - } + /* Populate the handles and append them to the list */ + for (; attrs && count; attrs++, count--) { + if (!attrs->handle) { + /* Allocate handle if not set already */ + attrs->handle = ++handle; + } else if (attrs->handle > handle) { + /* Use existing handle if valid */ + handle = attrs->handle; + } else if (find_attr(attrs->handle)) { + /* Service has conflicting handles */ + BT_ERR("Unable to register handle 0x%04x", + attrs->handle); + return -EINVAL; + } - BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x", - attrs, attrs->handle, bt_uuid_str(attrs->uuid), - attrs->perm); - } + BT_DBG("attr %p handle 0x%04x uuid %s perm 0x%02x", + attrs, attrs->handle, bt_uuid_str(attrs->uuid), + attrs->perm); + } - gatt_insert(svc, last_handle); + gatt_insert(svc, last_handle); - return 0; + return 0; } #endif /* CONFIG_BT_GATT_DYNAMIC_DB */ enum { - SC_RANGE_CHANGED, /* SC range changed */ - SC_INDICATE_PENDING, /* SC indicate pending */ + SC_RANGE_CHANGED, /* SC range changed */ + SC_INDICATE_PENDING, /* SC indicate pending */ - /* Total number of flags - must be at the end of the enum */ - SC_NUM_FLAGS, + /* Total number of flags - must be at the end of the enum */ + SC_NUM_FLAGS, }; static struct gatt_sc { - struct bt_gatt_indicate_params params; - u16_t start; - u16_t end; - struct k_delayed_work work; - ATOMIC_DEFINE(flags, SC_NUM_FLAGS); + struct bt_gatt_indicate_params params; + u16_t start; + u16_t end; + struct k_delayed_work work; + ATOMIC_DEFINE(flags, SC_NUM_FLAGS); } gatt_sc; static void sc_indicate_rsp(struct bt_conn *conn, - const struct bt_gatt_attr *attr, u8_t err) + const struct bt_gatt_attr *attr, u8_t err) { #if defined(CONFIG_BT_GATT_CACHING) - struct gatt_cf_cfg *cfg; + struct gatt_cf_cfg *cfg; #endif - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING); + atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING); - /* Check if there is new change in the meantime */ - if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { - /* Reschedule without any delay since it is waiting already */ - k_delayed_work_submit(&gatt_sc.work, K_NO_WAIT); - } + /* Check if there is new change in the meantime */ + if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { + /* Reschedule without any delay since it is waiting already */ + k_delayed_work_submit(&gatt_sc.work, K_NO_WAIT); + } #if defined(CONFIG_BT_GATT_CACHING) - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: - * 2.5.2.1 Robust Caching - * A connected client becomes change-aware when... - * The client receives and confirms a Service Changed indication. - */ - cfg = find_cf_cfg(conn); - if (cfg && CF_ROBUST_CACHING(cfg)) { - atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); - BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: + * 2.5.2.1 Robust Caching + * A connected client becomes change-aware when... + * The client receives and confirms a Service Changed indication. + */ + cfg = find_cf_cfg(conn); + if (cfg && CF_ROBUST_CACHING(cfg)) { + atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); + BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); + } #endif } static void sc_process(struct k_work *work) { - struct gatt_sc *sc = CONTAINER_OF(work, struct gatt_sc, work); - u16_t sc_range[2]; + struct gatt_sc *sc = CONTAINER_OF(work, struct gatt_sc, work); + u16_t sc_range[2]; - __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING), - "Indicate already pending"); + __ASSERT(!atomic_test_bit(sc->flags, SC_INDICATE_PENDING), + "Indicate already pending"); - BT_DBG("start 0x%04x end 0x%04x", sc->start, sc->end); - - sc_range[0] = sys_cpu_to_le16(sc->start); - sc_range[1] = sys_cpu_to_le16(sc->end); + BT_DBG("start 0x%04x end 0x%04x", sc->start, sc->end); - atomic_clear_bit(sc->flags, SC_RANGE_CHANGED); - sc->start = 0U; - sc->end = 0U; + sc_range[0] = sys_cpu_to_le16(sc->start); + sc_range[1] = sys_cpu_to_le16(sc->end); + + atomic_clear_bit(sc->flags, SC_RANGE_CHANGED); + sc->start = 0U; + sc->end = 0U; #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) sc->params.attr = &gatt_attrs[2]; #else - sc->params.attr = &_1_gatt_svc.attrs[2]; + sc->params.attr = &_1_gatt_svc.attrs[2]; #endif - sc->params.func = sc_indicate_rsp; - sc->params.data = &sc_range[0]; - sc->params.len = sizeof(sc_range); + sc->params.func = sc_indicate_rsp; + sc->params.data = &sc_range[0]; + sc->params.len = sizeof(sc_range); - if (bt_gatt_indicate(NULL, &sc->params)) { - /* No connections to indicate */ - return; - } + if (bt_gatt_indicate(NULL, &sc->params)) { + /* No connections to indicate */ + return; + } - atomic_set_bit(sc->flags, SC_INDICATE_PENDING); + atomic_set_bit(sc->flags, SC_INDICATE_PENDING); } #if defined(CONFIG_BT_STACK_PTS) int service_change_test(struct bt_gatt_indicate_params *params,const struct bt_conn *con) { - u16_t sc_range[2]; - - if(!params->attr){ - #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) - params->attr = &gatt_attrs[2]; - #else - params->attr = &_1_gatt_svc.attrs[2]; - #endif - } - sc_range[0] = 0x000e; - sc_range[1] = 0x001e; - - params->data = &sc_range[0]; - params->len = sizeof(sc_range); - - if (bt_gatt_indicate(con, params)) { - /* No connections to indicate */ - return; - } + u16_t sc_range[2]; + + if(!params->attr){ + #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) + params->attr = &gatt_attrs[2]; + #else + params->attr = &_1_gatt_svc.attrs[2]; + #endif + } + sc_range[0] = 0x000e; + sc_range[1] = 0x001e; + + params->data = &sc_range[0]; + params->len = sizeof(sc_range); + + if (bt_gatt_indicate(con, params)) { + /* No connections to indicate */ + return; + } } #endif #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) static struct gatt_ccc_store { - struct bt_conn *conn_list[CONFIG_BT_MAX_CONN]; - struct k_delayed_work work; + struct bt_conn *conn_list[CONFIG_BT_MAX_CONN]; + struct k_delayed_work work; } gatt_ccc_store; static bool gatt_ccc_conn_is_queued(struct bt_conn *conn) { - return (conn == gatt_ccc_store.conn_list[bt_conn_index(conn)]); + return (conn == gatt_ccc_store.conn_list[bt_conn_index(conn)]); } static void gatt_ccc_conn_unqueue(struct bt_conn *conn) { - u8_t index = bt_conn_index(conn); + u8_t index = bt_conn_index(conn); - if (gatt_ccc_store.conn_list[index] != NULL) { - bt_conn_unref(gatt_ccc_store.conn_list[index]); - gatt_ccc_store.conn_list[index] = NULL; - } + if (gatt_ccc_store.conn_list[index] != NULL) { + bt_conn_unref(gatt_ccc_store.conn_list[index]); + gatt_ccc_store.conn_list[index] = NULL; + } } static bool gatt_ccc_conn_queue_is_empty(void) { - for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) { - if (gatt_ccc_store.conn_list[i]) { - return false; - } - } + for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) { + if (gatt_ccc_store.conn_list[i]) { + return false; + } + } - return true; + return true; } static void ccc_delayed_store(struct k_work *work) { - struct gatt_ccc_store *ccc_store = - CONTAINER_OF(work, struct gatt_ccc_store, work); + struct gatt_ccc_store *ccc_store = + CONTAINER_OF(work, struct gatt_ccc_store, work); - for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) { - struct bt_conn *conn = ccc_store->conn_list[i]; + for (size_t i = 0; i < CONFIG_BT_MAX_CONN; i++) { + struct bt_conn *conn = ccc_store->conn_list[i]; - if (!conn) { - continue; - } + if (!conn) { + continue; + } - if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { - bt_gatt_store_ccc(conn->id, &conn->le.dst); - bt_conn_unref(conn); - ccc_store->conn_list[i] = NULL; - } - } + if (bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { + bt_gatt_store_ccc(conn->id, &conn->le.dst); + bt_conn_unref(conn); + ccc_store->conn_list[i] = NULL; + } + } } #endif void bt_gatt_init(void) { - if (!atomic_cas(&init, 0, 1)) { - return; - } - + if (!atomic_cas(&init, 0, 1)) { + return; + } + #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) /* Register mandatory services */ - gatt_register(&gap_svc); - gatt_register(&gatt_svc); - + gatt_register(&gap_svc); + gatt_register(&gatt_svc); + #else - Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc) { - last_static_handle += svc->attr_count; - } + Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, svc) { + last_static_handle += svc->attr_count; + } #endif #if defined(CONFIG_BT_GATT_CACHING) - k_delayed_work_init(&db_hash_work, db_hash_process); + k_delayed_work_init(&db_hash_work, db_hash_process); - /* Submit work to Generate initial hash as there could be static - * services already in the database. - */ - k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT); + /* Submit work to Generate initial hash as there could be static + * services already in the database. + */ + k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT); #endif /* CONFIG_BT_GATT_CACHING */ - if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) { - k_delayed_work_init(&gatt_sc.work, sc_process); - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - /* Make sure to not send SC indications until SC - * settings are loaded - */ - atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING); - } - } + if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) { + k_delayed_work_init(&gatt_sc.work, sc_process); + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + /* Make sure to not send SC indications until SC + * settings are loaded + */ + atomic_set_bit(gatt_sc.flags, SC_INDICATE_PENDING); + } + } #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) - k_delayed_work_init(&gatt_ccc_store.work, ccc_delayed_store); + k_delayed_work_init(&gatt_ccc_store.work, ccc_delayed_store); #endif } @@ -1041,7 +1041,7 @@ void bt_gatt_deinit(void) if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)){ k_delayed_work_del_timer(&gatt_sc.work); } - + #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) k_delayed_work_del_timer(&gatt_ccc_store.work); #endif @@ -1052,36 +1052,36 @@ void bt_gatt_deinit(void) (defined(CONFIG_BT_GATT_CACHING) && defined(CONFIG_BT_SETTINGS)) static void sc_indicate(u16_t start, u16_t end) { - BT_DBG("start 0x%04x end 0x%04x", start, end); + BT_DBG("start 0x%04x end 0x%04x", start, end); #if defined (BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE) struct bt_conn *conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECTED); - if(conn){ + if(conn){ #endif - if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { - gatt_sc.start = start; - gatt_sc.end = end; - goto submit; - } + if (!atomic_test_and_set_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { + gatt_sc.start = start; + gatt_sc.end = end; + goto submit; + } #if defined (BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE) } #endif - if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) { - return; - } + if (!update_range(&gatt_sc.start, &gatt_sc.end, start, end)) { + return; + } submit: - if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) { - BT_DBG("indicate pending, waiting until complete..."); - return; - } + if (atomic_test_bit(gatt_sc.flags, SC_INDICATE_PENDING)) { + BT_DBG("indicate pending, waiting until complete..."); + return; + } #if defined (BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE) if(conn){ #endif - /* Reschedule since the range has changed */ - k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT); + /* Reschedule since the range has changed */ + k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT); #if defined (BFLB_BLE_PATCH_SET_SCRANGE_CHAGD_ONLY_IN_CONNECTED_STATE) bt_conn_unref(conn); } @@ -1094,62 +1094,62 @@ submit: static void db_changed(void) { #if defined(CONFIG_BT_GATT_CACHING) - int i; + int i; - k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT); + k_delayed_work_submit(&db_hash_work, DB_HASH_TIMEOUT); - for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { - struct gatt_cf_cfg *cfg = &cf_cfg[i]; + for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { + struct gatt_cf_cfg *cfg = &cf_cfg[i]; - if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { - continue; - } + if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { + continue; + } - if (CF_ROBUST_CACHING(cfg)) { - /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching - *... the database changes again before the client - * becomes change-aware in which case the error response - * shall be sent again. - */ - atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC); - if (atomic_test_and_clear_bit(cfg->flags, - CF_CHANGE_AWARE)) { - BT_DBG("%s change-unaware", - bt_addr_le_str(&cfg->peer)); - } - } - } + if (CF_ROBUST_CACHING(cfg)) { + /* Core Spec 5.1 | Vol 3, Part G, 2.5.2.1 Robust Caching + *... the database changes again before the client + * becomes change-aware in which case the error response + * shall be sent again. + */ + atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC); + if (atomic_test_and_clear_bit(cfg->flags, + CF_CHANGE_AWARE)) { + BT_DBG("%s change-unaware", + bt_addr_le_str(&cfg->peer)); + } + } + } #endif } int bt_gatt_service_register(struct bt_gatt_service *svc) { - int err; + int err; - __ASSERT(svc, "invalid parameters\n"); - __ASSERT(svc->attrs, "invalid parameters\n"); - __ASSERT(svc->attr_count, "invalid parameters\n"); + __ASSERT(svc, "invalid parameters\n"); + __ASSERT(svc->attrs, "invalid parameters\n"); + __ASSERT(svc->attr_count, "invalid parameters\n"); - /* Init GATT core services */ - bt_gatt_init(); + /* Init GATT core services */ + bt_gatt_init(); - /* Do no allow to register mandatory services twice */ - if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) || - !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) { - return -EALREADY; - } + /* Do no allow to register mandatory services twice */ + if (!bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GAP) || + !bt_uuid_cmp(svc->attrs[0].uuid, BT_UUID_GATT)) { + return -EALREADY; + } - err = gatt_register(svc); - if (err < 0) { - return err; - } + err = gatt_register(svc); + if (err < 0) { + return err; + } - sc_indicate(svc->attrs[0].handle, - svc->attrs[svc->attr_count - 1].handle); + sc_indicate(svc->attrs[0].handle, + svc->attrs[svc->attr_count - 1].handle); - db_changed(); + db_changed(); - return 0; + return 0; } @@ -1162,925 +1162,925 @@ void bt_gatt_cancle_sc_work(void) int bt_gatt_service_unregister(struct bt_gatt_service *svc) { - __ASSERT(svc, "invalid parameters\n"); + __ASSERT(svc, "invalid parameters\n"); - if (!sys_slist_find_and_remove(&db, &svc->node)) { - return -ENOENT; - } + if (!sys_slist_find_and_remove(&db, &svc->node)) { + return -ENOENT; + } - sc_indicate(svc->attrs[0].handle, - svc->attrs[svc->attr_count - 1].handle); + sc_indicate(svc->attrs[0].handle, + svc->attrs[svc->attr_count - 1].handle); - db_changed(); + db_changed(); - return 0; + return 0; } #endif /* CONFIG_BT_GATT_DYNAMIC_DB */ ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t buf_len, u16_t offset, - const void *value, u16_t value_len) + void *buf, u16_t buf_len, u16_t offset, + const void *value, u16_t value_len) { - u16_t len; - #if defined(CONFIG_BT_STACK_PTS) - u8_t *data = NULL; - u8_t i = 0; - #endif + u16_t len; + #if defined(CONFIG_BT_STACK_PTS) + u8_t *data = NULL; + u8_t i = 0; + #endif - if (offset > value_len) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); - } + if (offset > value_len) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); + } - len = MIN(buf_len, value_len - offset); + len = MIN(buf_len, value_len - offset); - BT_DBG("handle 0x%04x offset %u length %u", attr->handle, offset, - len); + BT_DBG("handle 0x%04x offset %u length %u", attr->handle, offset, + len); - memcpy(buf, (u8_t *)value + offset, len); + memcpy(buf, (u8_t *)value + offset, len); - #if defined(CONFIG_BT_STACK_PTS) - /* PTS sends a request to iut read all primary services it contains. - * Set event flags to avoid comflicts when other test cases need to add reference codes. - */ - if(event_flag == att_read_by_group_type_ind){ - data = (u8_t *)buf; - for(i=0;ihandle, i, data[i]); - } - } - #endif - - return len; + #if defined(CONFIG_BT_STACK_PTS) + /* PTS sends a request to iut read all primary services it contains. + * Set event flags to avoid comflicts when other test cases need to add reference codes. + */ + if(event_flag == att_read_by_group_type_ind){ + data = (u8_t *)buf; + for(i=0;ihandle, i, data[i]); + } + } + #endif + + return len; } ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset) { - struct bt_uuid *uuid = attr->user_data; + struct bt_uuid *uuid = attr->user_data; - if (uuid->type == BT_UUID_TYPE_16) { - u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val); + if (uuid->type == BT_UUID_TYPE_16) { + u16_t uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val); - return bt_gatt_attr_read(conn, attr, buf, len, offset, - &uuid16, 2); - } + return bt_gatt_attr_read(conn, attr, buf, len, offset, + &uuid16, 2); + } - return bt_gatt_attr_read(conn, attr, buf, len, offset, - BT_UUID_128(uuid)->val, 16); + return bt_gatt_attr_read(conn, attr, buf, len, offset, + BT_UUID_128(uuid)->val, 16); } struct gatt_incl { - u16_t start_handle; - u16_t end_handle; - u16_t uuid16; + u16_t start_handle; + u16_t end_handle; + u16_t uuid16; } __packed; static u8_t get_service_handles(const struct bt_gatt_attr *attr, - void *user_data) + void *user_data) { - struct gatt_incl *include = user_data; + struct gatt_incl *include = user_data; - /* Stop if attribute is a service */ - if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) || - !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { - return BT_GATT_ITER_STOP; - } + /* Stop if attribute is a service */ + if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_PRIMARY) || + !bt_uuid_cmp(attr->uuid, BT_UUID_GATT_SECONDARY)) { + return BT_GATT_ITER_STOP; + } - include->end_handle = attr->handle; + include->end_handle = attr->handle; - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR) static u16_t find_static_attr(const struct bt_gatt_attr *attr) { - u16_t handle = 1; + u16_t handle = 1; - Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) { - for (int i = 0; i < static_svc->attr_count; i++, handle++) { - if (attr == &static_svc->attrs[i]) { - return handle; - } - } - } + Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) { + for (int i = 0; i < static_svc->attr_count; i++, handle++) { + if (attr == &static_svc->attrs[i]) { + return handle; + } + } + } - return 0; + return 0; } #endif ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset) { - struct bt_gatt_attr *incl = attr->user_data; + struct bt_gatt_attr *incl = attr->user_data; #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) u16_t handle = incl->handle; #else - u16_t handle = incl->handle ? : find_static_attr(incl); + u16_t handle = incl->handle ? : find_static_attr(incl); #endif - struct bt_uuid *uuid = incl->user_data; - struct gatt_incl pdu; - u8_t value_len; + struct bt_uuid *uuid = incl->user_data; + struct gatt_incl pdu; + u8_t value_len; - /* first attr points to the start handle */ - pdu.start_handle = sys_cpu_to_le16(handle); - value_len = sizeof(pdu.start_handle) + sizeof(pdu.end_handle); + /* first attr points to the start handle */ + pdu.start_handle = sys_cpu_to_le16(handle); + value_len = sizeof(pdu.start_handle) + sizeof(pdu.end_handle); - /* - * Core 4.2, Vol 3, Part G, 3.2, - * The Service UUID shall only be present when the UUID is a - * 16-bit Bluetooth UUID. - */ - if (uuid->type == BT_UUID_TYPE_16) { - pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val); - value_len += sizeof(pdu.uuid16); - } + /* + * Core 4.2, Vol 3, Part G, 3.2, + * The Service UUID shall only be present when the UUID is a + * 16-bit Bluetooth UUID. + */ + if (uuid->type == BT_UUID_TYPE_16) { + pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(uuid)->val); + value_len += sizeof(pdu.uuid16); + } - /* Lookup for service end handle */ - bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu); + /* Lookup for service end handle */ + bt_gatt_foreach_attr(handle + 1, 0xffff, get_service_handles, &pdu); - return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len); } struct gatt_chrc { - u8_t properties; - u16_t value_handle; - union { - u16_t uuid16; - u8_t uuid[16]; - }; + u8_t properties; + u16_t value_handle; + union { + u16_t uuid16; + u8_t uuid[16]; + }; } __packed; uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr) { - u16_t handle = 0; + u16_t handle = 0; - if ((attr != NULL) - && (attr->read == bt_gatt_attr_read_chrc)) { - struct bt_gatt_chrc *chrc = attr->user_data; + if ((attr != NULL) + && (attr->read == bt_gatt_attr_read_chrc)) { + struct bt_gatt_chrc *chrc = attr->user_data; - handle = chrc->value_handle; + handle = chrc->value_handle; #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR) - if (handle == 0) { - /* Fall back to Zephyr value handle policy */ - handle = (attr->handle ? : find_static_attr(attr)) + 1U; - } + if (handle == 0) { + /* Fall back to Zephyr value handle policy */ + handle = (attr->handle ? : find_static_attr(attr)) + 1U; + } #endif - } + } - return handle; + return handle; } ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - struct bt_gatt_chrc *chrc = attr->user_data; - struct gatt_chrc pdu; - u8_t value_len; + struct bt_gatt_chrc *chrc = attr->user_data; + struct gatt_chrc pdu; + u8_t value_len; - pdu.properties = chrc->properties; - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534: - * 3.3.2 Characteristic Value Declaration - * The Characteristic Value declaration contains the value of the - * characteristic. It is the first Attribute after the characteristic - * declaration. All characteristic definitions shall have a - * Characteristic Value declaration. - */ - pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr)); + pdu.properties = chrc->properties; + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 534: + * 3.3.2 Characteristic Value Declaration + * The Characteristic Value declaration contains the value of the + * characteristic. It is the first Attribute after the characteristic + * declaration. All characteristic definitions shall have a + * Characteristic Value declaration. + */ + pdu.value_handle = sys_cpu_to_le16(bt_gatt_attr_value_handle(attr)); - value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle); + value_len = sizeof(pdu.properties) + sizeof(pdu.value_handle); - if (chrc->uuid->type == BT_UUID_TYPE_16) { - pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val); - value_len += 2U; - } else { - memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16); - value_len += 16U; - } + if (chrc->uuid->type == BT_UUID_TYPE_16) { + pdu.uuid16 = sys_cpu_to_le16(BT_UUID_16(chrc->uuid)->val); + value_len += 2U; + } else { + memcpy(pdu.uuid, BT_UUID_128(chrc->uuid)->val, 16); + value_len += 16U; + } - return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &pdu, value_len); } static u8_t gatt_foreach_iter(const struct bt_gatt_attr *attr, - u16_t start_handle, u16_t end_handle, - const struct bt_uuid *uuid, - const void *attr_data, uint16_t *num_matches, - bt_gatt_attr_func_t func, void *user_data) + u16_t start_handle, u16_t end_handle, + const struct bt_uuid *uuid, + const void *attr_data, uint16_t *num_matches, + bt_gatt_attr_func_t func, void *user_data) { - u8_t result; + u8_t result; - /* Stop if over the requested range */ - if (attr->handle > end_handle) { - return BT_GATT_ITER_STOP; - } + /* Stop if over the requested range */ + if (attr->handle > end_handle) { + return BT_GATT_ITER_STOP; + } - /* Check if attribute handle is within range */ - if (attr->handle < start_handle) { - return BT_GATT_ITER_CONTINUE; - } + /* Check if attribute handle is within range */ + if (attr->handle < start_handle) { + return BT_GATT_ITER_CONTINUE; + } - /* Match attribute UUID if set */ - if (uuid && bt_uuid_cmp(uuid, attr->uuid)) { - return BT_GATT_ITER_CONTINUE; - } + /* Match attribute UUID if set */ + if (uuid && bt_uuid_cmp(uuid, attr->uuid)) { + return BT_GATT_ITER_CONTINUE; + } - /* Match attribute user_data if set */ - if (attr_data && attr_data != attr->user_data) { - return BT_GATT_ITER_CONTINUE; - } + /* Match attribute user_data if set */ + if (attr_data && attr_data != attr->user_data) { + return BT_GATT_ITER_CONTINUE; + } - *num_matches -= 1; + *num_matches -= 1; - result = func(attr, user_data); + result = func(attr, user_data); - if (!*num_matches) { - return BT_GATT_ITER_STOP; - } + if (!*num_matches) { + return BT_GATT_ITER_STOP; + } - return result; + return result; } static void foreach_attr_type_dyndb(u16_t start_handle, u16_t end_handle, - const struct bt_uuid *uuid, - const void *attr_data, uint16_t num_matches, - bt_gatt_attr_func_t func, void *user_data) + const struct bt_uuid *uuid, + const void *attr_data, uint16_t num_matches, + bt_gatt_attr_func_t func, void *user_data) { #if defined(CONFIG_BT_GATT_DYNAMIC_DB) - int i; - struct bt_gatt_service *svc; + int i; + struct bt_gatt_service *svc; - SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node) { - struct bt_gatt_service *next; + SYS_SLIST_FOR_EACH_CONTAINER(&db, svc, node) { + struct bt_gatt_service *next; - next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node); - if (next) { - /* Skip ahead if start is not within service handles */ - if (next->attrs[0].handle <= start_handle) { - continue; - } - } + next = SYS_SLIST_PEEK_NEXT_CONTAINER(svc, node); + if (next) { + /* Skip ahead if start is not within service handles */ + if (next->attrs[0].handle <= start_handle) { + continue; + } + } - for (i = 0; i < svc->attr_count; i++) { - struct bt_gatt_attr *attr = &svc->attrs[i]; + for (i = 0; i < svc->attr_count; i++) { + struct bt_gatt_attr *attr = &svc->attrs[i]; - if (gatt_foreach_iter(attr, - start_handle, - end_handle, - uuid, attr_data, - &num_matches, - func, user_data) == - BT_GATT_ITER_STOP) { - return; - } - } - } + if (gatt_foreach_iter(attr, + start_handle, + end_handle, + uuid, attr_data, + &num_matches, + func, user_data) == + BT_GATT_ITER_STOP) { + return; + } + } + } #endif /* CONFIG_BT_GATT_DYNAMIC_DB */ } void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle, - const struct bt_uuid *uuid, - const void *attr_data, uint16_t num_matches, - bt_gatt_attr_func_t func, void *user_data) + const struct bt_uuid *uuid, + const void *attr_data, uint16_t num_matches, + bt_gatt_attr_func_t func, void *user_data) { - int i; + int i; - if (!num_matches) { - num_matches = UINT16_MAX; - } + if (!num_matches) { + num_matches = UINT16_MAX; + } #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR) - if (start_handle <= last_static_handle) { - u16_t handle = 1; + if (start_handle <= last_static_handle) { + u16_t handle = 1; - Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) { - /* Skip ahead if start is not within service handles */ - if (handle + static_svc->attr_count < start_handle) { - handle += static_svc->attr_count; - continue; - } + Z_STRUCT_SECTION_FOREACH(bt_gatt_service_static, static_svc) { + /* Skip ahead if start is not within service handles */ + if (handle + static_svc->attr_count < start_handle) { + handle += static_svc->attr_count; + continue; + } - for (i = 0; i < static_svc->attr_count; i++, handle++) { - struct bt_gatt_attr attr; + for (i = 0; i < static_svc->attr_count; i++, handle++) { + struct bt_gatt_attr attr; - memcpy(&attr, &static_svc->attrs[i], - sizeof(attr)); + memcpy(&attr, &static_svc->attrs[i], + sizeof(attr)); - attr.handle = handle; + attr.handle = handle; - if (gatt_foreach_iter(&attr, start_handle, - end_handle, uuid, - attr_data, &num_matches, - func, user_data) == - BT_GATT_ITER_STOP) { - return; - } - } - } - } + if (gatt_foreach_iter(&attr, start_handle, + end_handle, uuid, + attr_data, &num_matches, + func, user_data) == + BT_GATT_ITER_STOP) { + return; + } + } + } + } #endif - /* Iterate over dynamic db */ - foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data, - num_matches, func, user_data); + /* Iterate over dynamic db */ + foreach_attr_type_dyndb(start_handle, end_handle, uuid, attr_data, + num_matches, func, user_data); } static u8_t find_next(const struct bt_gatt_attr *attr, void *user_data) { - struct bt_gatt_attr **next = user_data; + struct bt_gatt_attr **next = user_data; - *next = (struct bt_gatt_attr *)attr; + *next = (struct bt_gatt_attr *)attr; - return BT_GATT_ITER_STOP; + return BT_GATT_ITER_STOP; } struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr) { - struct bt_gatt_attr *next = NULL; + struct bt_gatt_attr *next = NULL; #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) u16_t handle = attr->handle; #else - u16_t handle = attr->handle ? : find_static_attr(attr); + u16_t handle = attr->handle ? : find_static_attr(attr); #endif - bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next); + bt_gatt_foreach_attr(handle + 1, handle + 1, find_next, &next); - return next; + return next; } static void clear_ccc_cfg(struct bt_gatt_ccc_cfg *cfg) { - bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY); - cfg->id = 0U; - cfg->value = 0U; + bt_addr_le_copy(&cfg->peer, BT_ADDR_LE_ANY); + cfg->id = 0U; + cfg->value = 0U; } static struct bt_gatt_ccc_cfg *find_ccc_cfg(const struct bt_conn *conn, - struct _bt_gatt_ccc *ccc) + struct _bt_gatt_ccc *ccc) { - for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { - if (conn) { - if (conn->id == ccc->cfg[i].id && - !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) { - return &ccc->cfg[i]; - } - } else if (!bt_addr_le_cmp(&ccc->cfg[i].peer, BT_ADDR_LE_ANY)) { - return &ccc->cfg[i]; - } - } + for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { + if (conn) { + if (conn->id == ccc->cfg[i].id && + !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) { + return &ccc->cfg[i]; + } + } else if (!bt_addr_le_cmp(&ccc->cfg[i].peer, BT_ADDR_LE_ANY)) { + return &ccc->cfg[i]; + } + } - return NULL; + return NULL; } ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - struct _bt_gatt_ccc *ccc = attr->user_data; - const struct bt_gatt_ccc_cfg *cfg; - u16_t value; + struct _bt_gatt_ccc *ccc = attr->user_data; + const struct bt_gatt_ccc_cfg *cfg; + u16_t value; - cfg = find_ccc_cfg(conn, ccc); - if (cfg) { - value = sys_cpu_to_le16(cfg->value); - } else { - /* Default to disable if there is no cfg for the peer */ - value = 0x0000; - } + cfg = find_ccc_cfg(conn, ccc); + if (cfg) { + value = sys_cpu_to_le16(cfg->value); + } else { + /* Default to disable if there is no cfg for the peer */ + value = 0x0000; + } - return bt_gatt_attr_read(conn, attr, buf, len, offset, &value, - sizeof(value)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &value, + sizeof(value)); } static void gatt_ccc_changed(const struct bt_gatt_attr *attr, - struct _bt_gatt_ccc *ccc) + struct _bt_gatt_ccc *ccc) { - int i; - u16_t value = 0x0000; + int i; + u16_t value = 0x0000; - for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { - if (ccc->cfg[i].value > value) { - value = ccc->cfg[i].value; - } - } + for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { + if (ccc->cfg[i].value > value) { + value = ccc->cfg[i].value; + } + } - BT_DBG("ccc %p value 0x%04x", ccc, value); + BT_DBG("ccc %p value 0x%04x", ccc, value); - if (value != ccc->value) { - ccc->value = value; - if (ccc->cfg_changed) { - ccc->cfg_changed(attr, value); - } - } + if (value != ccc->value) { + ccc->value = value; + if (ccc->cfg_changed) { + ccc->cfg_changed(attr, value); + } + } } ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, - const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, const void *buf, + u16_t len, u16_t offset, u8_t flags) { - struct _bt_gatt_ccc *ccc = attr->user_data; - struct bt_gatt_ccc_cfg *cfg; - u16_t value; + struct _bt_gatt_ccc *ccc = attr->user_data; + struct bt_gatt_ccc_cfg *cfg; + u16_t value; - if (offset) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); - } + if (offset) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); + } - if (!len || len > sizeof(u16_t)) { - return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); - } + if (!len || len > sizeof(u16_t)) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } - if (len < sizeof(u16_t)) { - value = *(u8_t *)buf; - } else { - value = sys_get_le16(buf); - } + if (len < sizeof(u16_t)) { + value = *(u8_t *)buf; + } else { + value = sys_get_le16(buf); + } - cfg = find_ccc_cfg(conn, ccc); - if (!cfg) { - /* If there's no existing entry, but the new value is zero, - * we don't need to do anything, since a disabled CCC is - * behavioraly the same as no written CCC. - */ - if (!value) { - return len; - } + cfg = find_ccc_cfg(conn, ccc); + if (!cfg) { + /* If there's no existing entry, but the new value is zero, + * we don't need to do anything, since a disabled CCC is + * behavioraly the same as no written CCC. + */ + if (!value) { + return len; + } - cfg = find_ccc_cfg(NULL, ccc); - if (!cfg) { - BT_WARN("No space to store CCC cfg"); - return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES); - } + cfg = find_ccc_cfg(NULL, ccc); + if (!cfg) { + BT_WARN("No space to store CCC cfg"); + return BT_GATT_ERR(BT_ATT_ERR_INSUFFICIENT_RESOURCES); + } - bt_addr_le_copy(&cfg->peer, &conn->le.dst); - cfg->id = conn->id; - } + bt_addr_le_copy(&cfg->peer, &conn->le.dst); + cfg->id = conn->id; + } - /* Confirm write if cfg is managed by application */ - if (ccc->cfg_write && !ccc->cfg_write(conn, attr, value)) { - return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED); - } + /* Confirm write if cfg is managed by application */ + if (ccc->cfg_write && !ccc->cfg_write(conn, attr, value)) { + return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED); + } - cfg->value = value; + cfg->value = value; - BT_DBG("handle 0x%04x value %u", attr->handle, cfg->value); + BT_DBG("handle 0x%04x value %u", attr->handle, cfg->value); - /* Update cfg if don't match */ - if (cfg->value != ccc->value) { - gatt_ccc_changed(attr, ccc); + /* Update cfg if don't match */ + if (cfg->value != ccc->value) { + gatt_ccc_changed(attr, ccc); #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) - if ((!gatt_ccc_conn_is_queued(conn)) && - bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { - /* Store the connection with the same index it has in - * the conns array - */ - gatt_ccc_store.conn_list[bt_conn_index(conn)] = - bt_conn_ref(conn); - k_delayed_work_submit(&gatt_ccc_store.work, - CCC_STORE_DELAY); - } + if ((!gatt_ccc_conn_is_queued(conn)) && + bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { + /* Store the connection with the same index it has in + * the conns array + */ + gatt_ccc_store.conn_list[bt_conn_index(conn)] = + bt_conn_ref(conn); + k_delayed_work_submit(&gatt_ccc_store.work, + CCC_STORE_DELAY); + } #endif - } + } - /* Disabled CCC is the same as no configured CCC, so clear the entry */ - if (!value) { - clear_ccc_cfg(cfg); - } + /* Disabled CCC is the same as no configured CCC, so clear the entry */ + if (!value) { + clear_ccc_cfg(cfg); + } - return len; + return len; } ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - const struct bt_gatt_cep *value = attr->user_data; - u16_t props = sys_cpu_to_le16(value->properties); + const struct bt_gatt_cep *value = attr->user_data; + u16_t props = sys_cpu_to_le16(value->properties); - return bt_gatt_attr_read(conn, attr, buf, len, offset, &props, - sizeof(props)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &props, + sizeof(props)); } ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - const char *value = attr->user_data; + const char *value = attr->user_data; - return bt_gatt_attr_read(conn, attr, buf, len, offset, value, - strlen(value)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, value, + strlen(value)); } ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - const struct bt_gatt_cpf *value = attr->user_data; + const struct bt_gatt_cpf *value = attr->user_data; - return bt_gatt_attr_read(conn, attr, buf, len, offset, value, - sizeof(*value)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, value, + sizeof(*value)); } struct notify_data { - int err; - u16_t type; - union { - struct bt_gatt_notify_params *nfy_params; - struct bt_gatt_indicate_params *ind_params; - }; + int err; + u16_t type; + union { + struct bt_gatt_notify_params *nfy_params; + struct bt_gatt_indicate_params *ind_params; + }; }; static int gatt_notify(struct bt_conn *conn, u16_t handle, - struct bt_gatt_notify_params *params) + struct bt_gatt_notify_params *params) { - struct net_buf *buf; - struct bt_att_notify *nfy; + struct net_buf *buf; + struct bt_att_notify *nfy; #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE) - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: - * Except for the Handle Value indication, the server shall not send - * notifications and indications to such a client until it becomes - * change-aware. - */ - if (!bt_gatt_change_aware(conn, false)) { - return -EAGAIN; - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: + * Except for the Handle Value indication, the server shall not send + * notifications and indications to such a client until it becomes + * change-aware. + */ + if (!bt_gatt_change_aware(conn, false)) { + return -EAGAIN; + } #endif - buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY, - sizeof(*nfy) + params->len); - if (!buf) { - BT_WARN("No buffer available to send notification"); - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_NOTIFY, + sizeof(*nfy) + params->len); + if (!buf) { + BT_WARN("No buffer available to send notification"); + return -ENOMEM; + } - BT_DBG("conn %p handle 0x%04x", conn, handle); + BT_DBG("conn %p handle 0x%04x", conn, handle); - nfy = net_buf_add(buf, sizeof(*nfy)); - nfy->handle = sys_cpu_to_le16(handle); + nfy = net_buf_add(buf, sizeof(*nfy)); + nfy->handle = sys_cpu_to_le16(handle); - net_buf_add(buf, params->len); - memcpy(nfy->value, params->data, params->len); + net_buf_add(buf, params->len); + memcpy(nfy->value, params->data, params->len); - return bt_att_send(conn, buf, params->func, params->user_data); + return bt_att_send(conn, buf, params->func, params->user_data); } static void gatt_indicate_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, void *user_data) + const void *pdu, u16_t length, void *user_data) { - struct bt_gatt_indicate_params *params = user_data; + struct bt_gatt_indicate_params *params = user_data; - params->func(conn, params->attr, err); + params->func(conn, params->attr, err); } static int gatt_send(struct bt_conn *conn, struct net_buf *buf, - bt_att_func_t func, void *params, - bt_att_destroy_t destroy) + bt_att_func_t func, void *params, + bt_att_destroy_t destroy) { - int err; + int err; - if (params) { - struct bt_att_req *req = params; - req->buf = buf; - req->func = func; - req->destroy = destroy; + if (params) { + struct bt_att_req *req = params; + req->buf = buf; + req->func = func; + req->destroy = destroy; - err = bt_att_req_send(conn, req); - } else { - err = bt_att_send(conn, buf, NULL, NULL); - } + err = bt_att_req_send(conn, req); + } else { + err = bt_att_send(conn, buf, NULL, NULL); + } - if (err) { - BT_ERR("Error sending ATT PDU: %d", err); - } + if (err) { + BT_ERR("Error sending ATT PDU: %d", err); + } - return err; + return err; } static int gatt_indicate(struct bt_conn *conn, u16_t handle, - struct bt_gatt_indicate_params *params) + struct bt_gatt_indicate_params *params) { - struct net_buf *buf; - struct bt_att_indicate *ind; + struct net_buf *buf; + struct bt_att_indicate *ind; #if defined(CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE) - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: - * Except for the Handle Value indication, the server shall not send - * notifications and indications to such a client until it becomes - * change-aware. - */ - if (!(params->func && (params->func == sc_indicate_rsp || - params->func == sc_restore_rsp)) && - !bt_gatt_change_aware(conn, false)) { - return -EAGAIN; - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: + * Except for the Handle Value indication, the server shall not send + * notifications and indications to such a client until it becomes + * change-aware. + */ + if (!(params->func && (params->func == sc_indicate_rsp || + params->func == sc_restore_rsp)) && + !bt_gatt_change_aware(conn, false)) { + return -EAGAIN; + } #endif - buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE, - sizeof(*ind) + params->len); - if (!buf) { - BT_WARN("No buffer available to send indication"); - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_INDICATE, + sizeof(*ind) + params->len); + if (!buf) { + BT_WARN("No buffer available to send indication"); + return -ENOMEM; + } - BT_DBG("conn %p handle 0x%04x", conn, handle); + BT_DBG("conn %p handle 0x%04x", conn, handle); - ind = net_buf_add(buf, sizeof(*ind)); - ind->handle = sys_cpu_to_le16(handle); + ind = net_buf_add(buf, sizeof(*ind)); + ind->handle = sys_cpu_to_le16(handle); - net_buf_add(buf, params->len); - memcpy(ind->value, params->data, params->len); + net_buf_add(buf, params->len); + memcpy(ind->value, params->data, params->len); - if (!params->func) { - return gatt_send(conn, buf, NULL, NULL, NULL); - } + if (!params->func) { + return gatt_send(conn, buf, NULL, NULL, NULL); + } - return gatt_send(conn, buf, gatt_indicate_rsp, params, NULL); + return gatt_send(conn, buf, gatt_indicate_rsp, params, NULL); } static u8_t notify_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct notify_data *data = user_data; - struct _bt_gatt_ccc *ccc; - size_t i; + struct notify_data *data = user_data; + struct _bt_gatt_ccc *ccc; + size_t i; - /* Check attribute user_data must be of type struct _bt_gatt_ccc */ - if (attr->write != bt_gatt_attr_write_ccc) { - return BT_GATT_ITER_CONTINUE; - } + /* Check attribute user_data must be of type struct _bt_gatt_ccc */ + if (attr->write != bt_gatt_attr_write_ccc) { + return BT_GATT_ITER_CONTINUE; + } - ccc = attr->user_data; + ccc = attr->user_data; - /* Save Service Changed data if peer is not connected */ - if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) { - for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) { - struct gatt_sc_cfg *cfg = &sc_cfg[i]; - struct bt_conn *conn; + /* Save Service Changed data if peer is not connected */ + if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && ccc == &sc_ccc) { + for (i = 0; i < ARRAY_SIZE(sc_cfg); i++) { + struct gatt_sc_cfg *cfg = &sc_cfg[i]; + struct bt_conn *conn; - if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { - continue; - } + if (!bt_addr_le_cmp(&cfg->peer, BT_ADDR_LE_ANY)) { + continue; + } - conn = bt_conn_lookup_state_le(&cfg->peer, - BT_CONN_CONNECTED); - if (!conn) { - struct sc_data *sc; + conn = bt_conn_lookup_state_le(&cfg->peer, + BT_CONN_CONNECTED); + if (!conn) { + struct sc_data *sc; - sc = (struct sc_data *)data->ind_params->data; - sc_save(cfg->id, &cfg->peer, - sys_le16_to_cpu(sc->start), - sys_le16_to_cpu(sc->end)); - continue; - } - bt_conn_unref(conn); - } - } + sc = (struct sc_data *)data->ind_params->data; + sc_save(cfg->id, &cfg->peer, + sys_le16_to_cpu(sc->start), + sys_le16_to_cpu(sc->end)); + continue; + } + bt_conn_unref(conn); + } + } - /* Notify all peers configured */ - for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { - struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; - struct bt_conn *conn; - int err; + /* Notify all peers configured */ + for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { + struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; + struct bt_conn *conn; + int err; - /* Check if config value matches data type since consolidated - * value may be for a different peer. - */ - if (cfg->value != data->type) { - continue; - } + /* Check if config value matches data type since consolidated + * value may be for a different peer. + */ + if (cfg->value != data->type) { + continue; + } - conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer); - if (!conn) { - continue; - } + conn = bt_conn_lookup_addr_le(cfg->id, &cfg->peer); + if (!conn) { + continue; + } - if (conn->state != BT_CONN_CONNECTED) { - bt_conn_unref(conn); - continue; - } + if (conn->state != BT_CONN_CONNECTED) { + bt_conn_unref(conn); + continue; + } - /* Confirm match if cfg is managed by application */ - if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) { - bt_conn_unref(conn); - continue; - } + /* Confirm match if cfg is managed by application */ + if (ccc->cfg_match && !ccc->cfg_match(conn, attr)) { + bt_conn_unref(conn); + continue; + } - if (data->type == BT_GATT_CCC_INDICATE) { - err = gatt_indicate(conn, attr->handle - 1, - data->ind_params); - } else { - err = gatt_notify(conn, attr->handle - 1, - data->nfy_params); - } + if (data->type == BT_GATT_CCC_INDICATE) { + err = gatt_indicate(conn, attr->handle - 1, + data->ind_params); + } else { + err = gatt_notify(conn, attr->handle - 1, + data->nfy_params); + } - bt_conn_unref(conn); + bt_conn_unref(conn); - if (err < 0) { - return BT_GATT_ITER_STOP; - } + if (err < 0) { + return BT_GATT_ITER_STOP; + } - data->err = 0; - } + data->err = 0; + } - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static u8_t match_uuid(const struct bt_gatt_attr *attr, void *user_data) { - const struct bt_gatt_attr **found = user_data; + const struct bt_gatt_attr **found = user_data; - *found = attr; + *found = attr; - return BT_GATT_ITER_STOP; + return BT_GATT_ITER_STOP; } int bt_gatt_notify_cb(struct bt_conn *conn, - struct bt_gatt_notify_params *params) + struct bt_gatt_notify_params *params) { - struct notify_data data; - const struct bt_gatt_attr *attr; - u16_t handle; + struct notify_data data; + const struct bt_gatt_attr *attr; + u16_t handle; - __ASSERT(params, "invalid parameters\n"); - __ASSERT(params->attr, "invalid parameters\n"); + __ASSERT(params, "invalid parameters\n"); + __ASSERT(params->attr, "invalid parameters\n"); - attr = params->attr; + attr = params->attr; - if (conn && conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn && conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR) - handle = attr->handle ? : find_static_attr(attr); + handle = attr->handle ? : find_static_attr(attr); #endif - if (!handle) { - return -ENOENT; - } + if (!handle) { + return -ENOENT; + } - /* Lookup UUID if it was given */ - if (params->uuid) { - attr = NULL; + /* Lookup UUID if it was given */ + if (params->uuid) { + attr = NULL; - bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, - NULL, 1, match_uuid, &attr); - if (!attr) { - return -ENOENT; - } + bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, + NULL, 1, match_uuid, &attr); + if (!attr) { + return -ENOENT; + } #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR) - handle = attr->handle ? : find_static_attr(attr); + handle = attr->handle ? : find_static_attr(attr); #endif - if (!handle) { - return -ENOENT; - } - } + if (!handle) { + return -ENOENT; + } + } - /* Check if attribute is a characteristic then adjust the handle */ - if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { - struct bt_gatt_chrc *chrc = attr->user_data; + /* Check if attribute is a characteristic then adjust the handle */ + if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { + struct bt_gatt_chrc *chrc = attr->user_data; - if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) { - return -EINVAL; - } + if (!(chrc->properties & BT_GATT_CHRC_NOTIFY)) { + return -EINVAL; + } - handle = bt_gatt_attr_value_handle(attr); - } + handle = bt_gatt_attr_value_handle(attr); + } - if (conn) { - return gatt_notify(conn, handle, params); - } + if (conn) { + return gatt_notify(conn, handle, params); + } - data.err = -ENOTCONN; - data.type = BT_GATT_CCC_NOTIFY; - data.nfy_params = params; + data.err = -ENOTCONN; + data.type = BT_GATT_CCC_NOTIFY; + data.nfy_params = params; - bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, - notify_cb, &data); + bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, + notify_cb, &data); - return data.err; + return data.err; } int bt_gatt_indicate(struct bt_conn *conn, - struct bt_gatt_indicate_params *params) + struct bt_gatt_indicate_params *params) { - struct notify_data data; - const struct bt_gatt_attr *attr; - u16_t handle; + struct notify_data data; + const struct bt_gatt_attr *attr; + u16_t handle; - __ASSERT(params, "invalid parameters\n"); - __ASSERT(params->attr, "invalid parameters\n"); + __ASSERT(params, "invalid parameters\n"); + __ASSERT(params->attr, "invalid parameters\n"); - attr = params->attr; + attr = params->attr; - if (conn && conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn && conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR) - handle = attr->handle ? : find_static_attr(attr); + handle = attr->handle ? : find_static_attr(attr); #endif - if (!handle) { - return -ENOENT; - } + if (!handle) { + return -ENOENT; + } - /* Lookup UUID if it was given */ - if (params->uuid) { - attr = NULL; + /* Lookup UUID if it was given */ + if (params->uuid) { + attr = NULL; - bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, - NULL, 1, match_uuid, &attr); - if (!attr) { - return -ENOENT; - } + bt_gatt_foreach_attr_type(handle, 0xffff, params->uuid, + NULL, 1, match_uuid, &attr); + if (!attr) { + return -ENOENT; + } #if !defined(BFLB_BLE_DISABLE_STATIC_ATTR) - handle = attr->handle ? : find_static_attr(attr); + handle = attr->handle ? : find_static_attr(attr); #endif - if (!handle) { - return -ENOENT; - } - } + if (!handle) { + return -ENOENT; + } + } - /* Check if attribute is a characteristic then adjust the handle */ - if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { - struct bt_gatt_chrc *chrc = params->attr->user_data; + /* Check if attribute is a characteristic then adjust the handle */ + if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { + struct bt_gatt_chrc *chrc = params->attr->user_data; - if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) { - return -EINVAL; - } + if (!(chrc->properties & BT_GATT_CHRC_INDICATE)) { + return -EINVAL; + } - handle = bt_gatt_attr_value_handle(params->attr); - } + handle = bt_gatt_attr_value_handle(params->attr); + } - if (conn) { - return gatt_indicate(conn, handle, params); - } + if (conn) { + return gatt_indicate(conn, handle, params); + } - data.err = -ENOTCONN; - data.type = BT_GATT_CCC_INDICATE; - data.ind_params = params; + data.err = -ENOTCONN; + data.type = BT_GATT_CCC_INDICATE; + data.ind_params = params; - bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, - notify_cb, &data); + bt_gatt_foreach_attr_type(handle, 0xffff, BT_UUID_GATT_CCC, NULL, 1, + notify_cb, &data); - return data.err; + return data.err; } u16_t bt_gatt_get_mtu(struct bt_conn *conn) { - return bt_att_get_mtu(conn); + return bt_att_get_mtu(conn); } u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr, - u8_t mask) + u8_t mask) { - if ((mask & BT_GATT_PERM_READ) && - (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) { - return BT_ATT_ERR_READ_NOT_PERMITTED; - } + if ((mask & BT_GATT_PERM_READ) && + (!(attr->perm & BT_GATT_PERM_READ_MASK) || !attr->read)) { + return BT_ATT_ERR_READ_NOT_PERMITTED; + } - if ((mask & BT_GATT_PERM_WRITE) && - (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) { - return BT_ATT_ERR_WRITE_NOT_PERMITTED; - } + if ((mask & BT_GATT_PERM_WRITE) && + (!(attr->perm & BT_GATT_PERM_WRITE_MASK) || !attr->write)) { + return BT_ATT_ERR_WRITE_NOT_PERMITTED; + } - mask &= attr->perm; - if (mask & BT_GATT_PERM_AUTHEN_MASK) { - if (bt_conn_get_security(conn) < BT_SECURITY_L3) { - return BT_ATT_ERR_AUTHENTICATION; - } - } + mask &= attr->perm; + if (mask & BT_GATT_PERM_AUTHEN_MASK) { + if (bt_conn_get_security(conn) < BT_SECURITY_L3) { + return BT_ATT_ERR_AUTHENTICATION; + } + } - if ((mask & BT_GATT_PERM_ENCRYPT_MASK)) { + if ((mask & BT_GATT_PERM_ENCRYPT_MASK)) { #if defined(CONFIG_BT_SMP) - if (!conn->encrypt) { - return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION; - } + if (!conn->encrypt) { + return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION; + } #else - return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION; + return BT_ATT_ERR_INSUFFICIENT_ENCRYPTION; #endif /* CONFIG_BT_SMP */ - } + } - return 0; + return 0; } static void sc_restore_rsp(struct bt_conn *conn, - const struct bt_gatt_attr *attr, u8_t err) + const struct bt_gatt_attr *attr, u8_t err) { #if defined(CONFIG_BT_GATT_CACHING) - struct gatt_cf_cfg *cfg; + struct gatt_cf_cfg *cfg; #endif - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); #if defined(CONFIG_BT_GATT_CACHING) - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: - * 2.5.2.1 Robust Caching - * A connected client becomes change-aware when... - * The client receives and confirms a Service Changed indication. - */ - cfg = find_cf_cfg(conn); - if (cfg && CF_ROBUST_CACHING(cfg)) { - atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); - BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: + * 2.5.2.1 Robust Caching + * A connected client becomes change-aware when... + * The client receives and confirms a Service Changed indication. + */ + cfg = find_cf_cfg(conn); + if (cfg && CF_ROBUST_CACHING(cfg)) { + atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); + BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); + } #endif } @@ -2088,1440 +2088,1440 @@ static struct bt_gatt_indicate_params sc_restore_params[CONFIG_BT_MAX_CONN]; static void sc_restore(struct bt_conn *conn) { - struct gatt_sc_cfg *cfg; - u16_t sc_range[2]; - u8_t index; + struct gatt_sc_cfg *cfg; + u16_t sc_range[2]; + u8_t index; - cfg = find_sc_cfg(conn->id, &conn->le.dst); - if (!cfg) { - BT_DBG("no SC data found"); - return; - } + cfg = find_sc_cfg(conn->id, &conn->le.dst); + if (!cfg) { + BT_DBG("no SC data found"); + return; + } - if (!(cfg->data.start || cfg->data.end)) { - return; - } + if (!(cfg->data.start || cfg->data.end)) { + return; + } - BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer), - cfg->data.start, cfg->data.end); + BT_DBG("peer %s start 0x%04x end 0x%04x", bt_addr_le_str(&cfg->peer), + cfg->data.start, cfg->data.end); - sc_range[0] = sys_cpu_to_le16(cfg->data.start); - sc_range[1] = sys_cpu_to_le16(cfg->data.end); + sc_range[0] = sys_cpu_to_le16(cfg->data.start); + sc_range[1] = sys_cpu_to_le16(cfg->data.end); - index = bt_conn_index(conn); + index = bt_conn_index(conn); #if defined(BFLB_BLE_DISABLE_STATIC_ATTR) sc_restore_params[index].attr = &gatt_attrs[2]; #else - sc_restore_params[index].attr = &_1_gatt_svc.attrs[2]; + sc_restore_params[index].attr = &_1_gatt_svc.attrs[2]; #endif - sc_restore_params[index].func = sc_restore_rsp; - sc_restore_params[index].data = &sc_range[0]; - sc_restore_params[index].len = sizeof(sc_range); + sc_restore_params[index].func = sc_restore_rsp; + sc_restore_params[index].data = &sc_range[0]; + sc_restore_params[index].len = sizeof(sc_range); - if (bt_gatt_indicate(conn, &sc_restore_params[index])) { - BT_ERR("SC restore indication failed"); - } + if (bt_gatt_indicate(conn, &sc_restore_params[index])) { + BT_ERR("SC restore indication failed"); + } - /* Reset config data */ - sc_reset(cfg); + /* Reset config data */ + sc_reset(cfg); } struct conn_data { - struct bt_conn *conn; - bt_security_t sec; + struct bt_conn *conn; + bt_security_t sec; }; static u8_t update_ccc(const struct bt_gatt_attr *attr, void *user_data) { - struct conn_data *data = user_data; - struct bt_conn *conn = data->conn; - struct _bt_gatt_ccc *ccc; - size_t i; - u8_t err; + struct conn_data *data = user_data; + struct bt_conn *conn = data->conn; + struct _bt_gatt_ccc *ccc; + size_t i; + u8_t err; - /* Check attribute user_data must be of type struct _bt_gatt_ccc */ - if (attr->write != bt_gatt_attr_write_ccc) { - return BT_GATT_ITER_CONTINUE; - } + /* Check attribute user_data must be of type struct _bt_gatt_ccc */ + if (attr->write != bt_gatt_attr_write_ccc) { + return BT_GATT_ITER_CONTINUE; + } - ccc = attr->user_data; + ccc = attr->user_data; - for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { - /* Ignore configuration for different peer */ - if (bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { + /* Ignore configuration for different peer */ + if (bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer)) { + continue; + } - /* Check if attribute requires encryption/authentication */ - err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK); - if (err) { - bt_security_t sec; + /* Check if attribute requires encryption/authentication */ + err = bt_gatt_check_perm(conn, attr, BT_GATT_PERM_WRITE_MASK); + if (err) { + bt_security_t sec; - if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) { - BT_WARN("CCC %p not writable", attr); - continue; - } + if (err == BT_ATT_ERR_WRITE_NOT_PERMITTED) { + BT_WARN("CCC %p not writable", attr); + continue; + } - sec = BT_SECURITY_L2; + sec = BT_SECURITY_L2; - if (err == BT_ATT_ERR_AUTHENTICATION) { - sec = BT_SECURITY_L3; - } + if (err == BT_ATT_ERR_AUTHENTICATION) { + sec = BT_SECURITY_L3; + } - /* Check if current security is enough */ - if (IS_ENABLED(CONFIG_BT_SMP) && - bt_conn_get_security(conn) < sec) { - if (data->sec < sec) { - data->sec = sec; - } - continue; - } - } + /* Check if current security is enough */ + if (IS_ENABLED(CONFIG_BT_SMP) && + bt_conn_get_security(conn) < sec) { + if (data->sec < sec) { + data->sec = sec; + } + continue; + } + } - if (ccc->cfg[i].value) { - gatt_ccc_changed(attr, ccc); - if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && - ccc == &sc_ccc) { - sc_restore(conn); - } - return BT_GATT_ITER_CONTINUE; - } - } + if (ccc->cfg[i].value) { + gatt_ccc_changed(attr, ccc); + if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED) && + ccc == &sc_ccc) { + sc_restore(conn); + } + return BT_GATT_ITER_CONTINUE; + } + } - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static u8_t disconnected_cb(const struct bt_gatt_attr *attr, void *user_data) { - struct bt_conn *conn = user_data; - struct _bt_gatt_ccc *ccc; - bool value_used; - size_t i; + struct bt_conn *conn = user_data; + struct _bt_gatt_ccc *ccc; + bool value_used; + size_t i; - /* Check attribute user_data must be of type struct _bt_gatt_ccc */ - if (attr->write != bt_gatt_attr_write_ccc) { - return BT_GATT_ITER_CONTINUE; - } + /* Check attribute user_data must be of type struct _bt_gatt_ccc */ + if (attr->write != bt_gatt_attr_write_ccc) { + return BT_GATT_ITER_CONTINUE; + } - ccc = attr->user_data; + ccc = attr->user_data; - /* If already disabled skip */ - if (!ccc->value) { - return BT_GATT_ITER_CONTINUE; - } + /* If already disabled skip */ + if (!ccc->value) { + return BT_GATT_ITER_CONTINUE; + } - /* Checking if all values are disabled */ - value_used = false; + /* Checking if all values are disabled */ + value_used = false; - for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { - struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; + for (i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { + struct bt_gatt_ccc_cfg *cfg = &ccc->cfg[i]; - /* Ignore configurations with disabled value */ - if (!cfg->value) { - continue; - } + /* Ignore configurations with disabled value */ + if (!cfg->value) { + continue; + } - if (conn->id != cfg->id || - bt_conn_addr_le_cmp(conn, &cfg->peer)) { - struct bt_conn *tmp; + if (conn->id != cfg->id || + bt_conn_addr_le_cmp(conn, &cfg->peer)) { + struct bt_conn *tmp; - /* Skip if there is another peer connected */ - tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer); - if (tmp) { - if (tmp->state == BT_CONN_CONNECTED) { - value_used = true; - } + /* Skip if there is another peer connected */ + tmp = bt_conn_lookup_addr_le(cfg->id, &cfg->peer); + if (tmp) { + if (tmp->state == BT_CONN_CONNECTED) { + value_used = true; + } - bt_conn_unref(tmp); - } - } else { - /* Clear value if not paired */ - if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { - clear_ccc_cfg(cfg); - } else { - /* Update address in case it has changed */ - bt_addr_le_copy(&cfg->peer, &conn->le.dst); - } - } - } + bt_conn_unref(tmp); + } + } else { + /* Clear value if not paired */ + if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { + clear_ccc_cfg(cfg); + } else { + /* Update address in case it has changed */ + bt_addr_le_copy(&cfg->peer, &conn->le.dst); + } + } + } - /* If all values are now disabled, reset value while disconnected */ - if (!value_used) { - ccc->value = 0U; - if (ccc->cfg_changed) { - ccc->cfg_changed(attr, ccc->value); - } + /* If all values are now disabled, reset value while disconnected */ + if (!value_used) { + ccc->value = 0U; + if (ccc->cfg_changed) { + ccc->cfg_changed(attr, ccc->value); + } - BT_DBG("ccc %p reseted", ccc); - } + BT_DBG("ccc %p reseted", ccc); + } - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } bool bt_gatt_is_subscribed(struct bt_conn *conn, - const struct bt_gatt_attr *attr, u16_t ccc_value) + const struct bt_gatt_attr *attr, u16_t ccc_value) { - const struct _bt_gatt_ccc *ccc; + const struct _bt_gatt_ccc *ccc; - __ASSERT(conn, "invalid parameter\n"); - __ASSERT(attr, "invalid parameter\n"); + __ASSERT(conn, "invalid parameter\n"); + __ASSERT(attr, "invalid parameter\n"); - if (conn->state != BT_CONN_CONNECTED) { - return false; - } + if (conn->state != BT_CONN_CONNECTED) { + return false; + } - /* Check if attribute is a characteristic declaration */ - if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { - struct bt_gatt_chrc *chrc = attr->user_data; + /* Check if attribute is a characteristic declaration */ + if (!bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CHRC)) { + struct bt_gatt_chrc *chrc = attr->user_data; - if (!(chrc->properties & - (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) { - /* Characteristic doesn't support subscription */ - return false; - } + if (!(chrc->properties & + (BT_GATT_CHRC_NOTIFY | BT_GATT_CHRC_INDICATE))) { + /* Characteristic doesn't support subscription */ + return false; + } - attr = bt_gatt_attr_next(attr); - } + attr = bt_gatt_attr_next(attr); + } - /* Check if attribute is a characteristic value */ - if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) { - attr = bt_gatt_attr_next(attr); - } + /* Check if attribute is a characteristic value */ + if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) { + attr = bt_gatt_attr_next(attr); + } - /* Check if the attribute is the CCC Descriptor */ - if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) { - return false; - } + /* Check if the attribute is the CCC Descriptor */ + if (bt_uuid_cmp(attr->uuid, BT_UUID_GATT_CCC) != 0) { + return false; + } - ccc = attr->user_data; + ccc = attr->user_data; - /* Check if the connection is subscribed */ - for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) { - if (conn->id == ccc->cfg[i].id && - !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer) && - (ccc_value & ccc->cfg[i].value)) { - return true; - } - } + /* Check if the connection is subscribed */ + for (size_t i = 0; i < BT_GATT_CCC_MAX; i++) { + if (conn->id == ccc->cfg[i].id && + !bt_conn_addr_le_cmp(conn, &ccc->cfg[i].peer) && + (ccc_value & ccc->cfg[i].value)) { + return true; + } + } - return false; + return false; } #if defined(CONFIG_BT_GATT_CLIENT) void bt_gatt_notification(struct bt_conn *conn, u16_t handle, - const void *data, u16_t length) + const void *data, u16_t length) { - struct bt_gatt_subscribe_params *params, *tmp; + struct bt_gatt_subscribe_params *params, *tmp; - BT_DBG("handle 0x%04x length %u", handle, length); + BT_DBG("handle 0x%04x length %u", handle, length); - SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) { - if (bt_conn_addr_le_cmp(conn, ¶ms->_peer) || - handle != params->value_handle) { - continue; - } + SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) { + if (bt_conn_addr_le_cmp(conn, ¶ms->_peer) || + handle != params->value_handle) { + continue; + } - if (params->notify(conn, params, data, length) == - BT_GATT_ITER_STOP) { - bt_gatt_unsubscribe(conn, params); - } - } + if (params->notify(conn, params, data, length) == + BT_GATT_ITER_STOP) { + bt_gatt_unsubscribe(conn, params); + } + } } static void update_subscription(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params) + struct bt_gatt_subscribe_params *params) { - if (params->_peer.type == BT_ADDR_LE_PUBLIC) { - return; - } + if (params->_peer.type == BT_ADDR_LE_PUBLIC) { + return; + } - /* Update address */ - bt_addr_le_copy(¶ms->_peer, &conn->le.dst); + /* Update address */ + bt_addr_le_copy(¶ms->_peer, &conn->le.dst); } static void gatt_subscription_remove(struct bt_conn *conn, sys_snode_t *prev, - struct bt_gatt_subscribe_params *params) + struct bt_gatt_subscribe_params *params) { - /* Remove subscription from the list*/ - sys_slist_remove(&subscriptions, prev, ¶ms->node); + /* Remove subscription from the list*/ + sys_slist_remove(&subscriptions, prev, ¶ms->node); - params->notify(conn, params, NULL, 0); + params->notify(conn, params, NULL, 0); } static void remove_subscriptions(struct bt_conn *conn) { - struct bt_gatt_subscribe_params *params, *tmp; - sys_snode_t *prev = NULL; + struct bt_gatt_subscribe_params *params, *tmp; + sys_snode_t *prev = NULL; - /* Lookup existing subscriptions */ - SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) { - if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) { - prev = ¶ms->node; - continue; - } + /* Lookup existing subscriptions */ + SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) { + if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) { + prev = ¶ms->node; + continue; + } - if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) || - (atomic_test_bit(params->flags, - BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) { - /* Remove subscription */ - params->value = 0U; - gatt_subscription_remove(conn, prev, params); - } else { - update_subscription(conn, params); - prev = ¶ms->node; - } - } + if (!bt_addr_le_is_bonded(conn->id, &conn->le.dst) || + (atomic_test_bit(params->flags, + BT_GATT_SUBSCRIBE_FLAG_VOLATILE))) { + /* Remove subscription */ + params->value = 0U; + gatt_subscription_remove(conn, prev, params); + } else { + update_subscription(conn, params); + prev = ¶ms->node; + } + } } static void gatt_mtu_rsp(struct bt_conn *conn, u8_t err, const void *pdu, - u16_t length, void *user_data) + u16_t length, void *user_data) { - struct bt_gatt_exchange_params *params = user_data; + struct bt_gatt_exchange_params *params = user_data; - params->func(conn, err, params); + params->func(conn, err, params); } int bt_gatt_exchange_mtu(struct bt_conn *conn, - struct bt_gatt_exchange_params *params) + struct bt_gatt_exchange_params *params) { - struct bt_att_exchange_mtu_req *req; - struct net_buf *buf; - u16_t mtu; + struct bt_att_exchange_mtu_req *req; + struct net_buf *buf; + u16_t mtu; - __ASSERT(conn, "invalid parameter\n"); - __ASSERT(params && params->func, "invalid parameters\n"); + __ASSERT(conn, "invalid parameter\n"); + __ASSERT(params && params->func, "invalid parameters\n"); - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_MTU_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - mtu = BT_ATT_MTU; + mtu = BT_ATT_MTU; - BT_DBG("Client MTU %u", mtu); + BT_DBG("Client MTU %u", mtu); - req = net_buf_add(buf, sizeof(*req)); - req->mtu = sys_cpu_to_le16(mtu); + req = net_buf_add(buf, sizeof(*req)); + req->mtu = sys_cpu_to_le16(mtu); - return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL); + return gatt_send(conn, buf, gatt_mtu_rsp, params, NULL); } static void gatt_discover_next(struct bt_conn *conn, u16_t last_handle, - struct bt_gatt_discover_params *params) + struct bt_gatt_discover_params *params) { - /* Skip if last_handle is not set */ - if (!last_handle) - goto discover; + /* Skip if last_handle is not set */ + if (!last_handle) + goto discover; - /* Continue from the last found handle */ - params->start_handle = last_handle; - if (params->start_handle < UINT16_MAX) { - params->start_handle++; - } else { - goto done; - } + /* Continue from the last found handle */ + params->start_handle = last_handle; + if (params->start_handle < UINT16_MAX) { + params->start_handle++; + } else { + goto done; + } - /* Stop if over the range or the requests */ - if (params->start_handle > params->end_handle) { - goto done; - } + /* Stop if over the range or the requests */ + if (params->start_handle > params->end_handle) { + goto done; + } discover: - /* Discover next range */ - if (!bt_gatt_discover(conn, params)) { - return; - } + /* Discover next range */ + if (!bt_gatt_discover(conn, params)) { + return; + } done: - params->func(conn, NULL, params); + params->func(conn, NULL, params); } static void gatt_find_type_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - const struct bt_att_find_type_rsp *rsp = pdu; - struct bt_gatt_discover_params *params = user_data; - u8_t i; - u16_t end_handle = 0U, start_handle; + const struct bt_att_find_type_rsp *rsp = pdu; + struct bt_gatt_discover_params *params = user_data; + u8_t i; + u16_t end_handle = 0U, start_handle; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - if (err) { - goto done; - } + if (err) { + goto done; + } - /* Parse attributes found */ - for (i = 0U; length >= sizeof(rsp->list[i]); - i++, length -= sizeof(rsp->list[i])) { - struct bt_gatt_attr attr = {}; - struct bt_gatt_service_val value; + /* Parse attributes found */ + for (i = 0U; length >= sizeof(rsp->list[i]); + i++, length -= sizeof(rsp->list[i])) { + struct bt_gatt_attr attr = {}; + struct bt_gatt_service_val value; - start_handle = sys_le16_to_cpu(rsp->list[i].start_handle); - end_handle = sys_le16_to_cpu(rsp->list[i].end_handle); + start_handle = sys_le16_to_cpu(rsp->list[i].start_handle); + end_handle = sys_le16_to_cpu(rsp->list[i].end_handle); - BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, - end_handle); + BT_DBG("start_handle 0x%04x end_handle 0x%04x", start_handle, + end_handle); - if (params->type == BT_GATT_DISCOVER_PRIMARY) { - attr.uuid = BT_UUID_GATT_PRIMARY; - } else { - attr.uuid = BT_UUID_GATT_SECONDARY; - } + if (params->type == BT_GATT_DISCOVER_PRIMARY) { + attr.uuid = BT_UUID_GATT_PRIMARY; + } else { + attr.uuid = BT_UUID_GATT_SECONDARY; + } - value.end_handle = end_handle; - value.uuid = params->uuid; + value.end_handle = end_handle; + value.uuid = params->uuid; - attr.handle = start_handle; - attr.user_data = &value; + attr.handle = start_handle; + attr.user_data = &value; - if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) { - return; - } - } + if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) { + return; + } + } - /* Stop if could not parse the whole PDU */ - if (length > 0) { - goto done; - } + /* Stop if could not parse the whole PDU */ + if (length > 0) { + goto done; + } - gatt_discover_next(conn, end_handle, params); + gatt_discover_next(conn, end_handle, params); - return; + return; done: - params->func(conn, NULL, params); + params->func(conn, NULL, params); } static int gatt_find_type(struct bt_conn *conn, - struct bt_gatt_discover_params *params) + struct bt_gatt_discover_params *params) { - struct net_buf *buf; - struct bt_att_find_type_req *req; - struct bt_uuid *uuid; + struct net_buf *buf; + struct bt_att_find_type_req *req; + struct bt_uuid *uuid; - buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_TYPE_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->start_handle = sys_cpu_to_le16(params->start_handle); - req->end_handle = sys_cpu_to_le16(params->end_handle); + req = net_buf_add(buf, sizeof(*req)); + req->start_handle = sys_cpu_to_le16(params->start_handle); + req->end_handle = sys_cpu_to_le16(params->end_handle); - if (params->type == BT_GATT_DISCOVER_PRIMARY) { - uuid = BT_UUID_GATT_PRIMARY; - } else { - uuid = BT_UUID_GATT_SECONDARY; - } + if (params->type == BT_GATT_DISCOVER_PRIMARY) { + uuid = BT_UUID_GATT_PRIMARY; + } else { + uuid = BT_UUID_GATT_SECONDARY; + } - req->type = sys_cpu_to_le16(BT_UUID_16(uuid)->val); + req->type = sys_cpu_to_le16(BT_UUID_16(uuid)->val); - BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x", - bt_uuid_str(params->uuid), params->start_handle, - params->end_handle); + BT_DBG("uuid %s start_handle 0x%04x end_handle 0x%04x", + bt_uuid_str(params->uuid), params->start_handle, + params->end_handle); - switch (params->uuid->type) { - case BT_UUID_TYPE_16: - net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val); - break; - case BT_UUID_TYPE_128: - net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16); - break; - default: - BT_ERR("Unknown UUID type %u", params->uuid->type); - net_buf_unref(buf); - return -EINVAL; - } + switch (params->uuid->type) { + case BT_UUID_TYPE_16: + net_buf_add_le16(buf, BT_UUID_16(params->uuid)->val); + break; + case BT_UUID_TYPE_128: + net_buf_add_mem(buf, BT_UUID_128(params->uuid)->val, 16); + break; + default: + BT_ERR("Unknown UUID type %u", params->uuid->type); + net_buf_unref(buf); + return -EINVAL; + } - return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL); + return gatt_send(conn, buf, gatt_find_type_rsp, params, NULL); } static void read_included_uuid_cb(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - struct bt_gatt_discover_params *params = user_data; - struct bt_gatt_include value; - struct bt_gatt_attr *attr; - union { - struct bt_uuid uuid; - struct bt_uuid_128 u128; - } u; + struct bt_gatt_discover_params *params = user_data; + struct bt_gatt_include value; + struct bt_gatt_attr *attr; + union { + struct bt_uuid uuid; + struct bt_uuid_128 u128; + } u; - if (length != 16U) { - BT_ERR("Invalid data len %u", length); - params->func(conn, NULL, params); - return; - } + if (length != 16U) { + BT_ERR("Invalid data len %u", length); + params->func(conn, NULL, params); + return; + } - value.start_handle = params->_included.start_handle; - value.end_handle = params->_included.end_handle; - value.uuid = &u.uuid; - u.uuid.type = BT_UUID_TYPE_128; - memcpy(u.u128.val, pdu, length); + value.start_handle = params->_included.start_handle; + value.end_handle = params->_included.end_handle; + value.uuid = &u.uuid; + u.uuid.type = BT_UUID_TYPE_128; + memcpy(u.u128.val, pdu, length); - BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x " - "end_handle 0x%04x\n", params->_included.attr_handle, - bt_uuid_str(&u.uuid), value.start_handle, value.end_handle); + BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x " + "end_handle 0x%04x\n", params->_included.attr_handle, + bt_uuid_str(&u.uuid), value.start_handle, value.end_handle); - /* Skip if UUID is set but doesn't match */ - if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { - goto next; - } + /* Skip if UUID is set but doesn't match */ + if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { + goto next; + } - attr = (&(struct bt_gatt_attr) { - .uuid = BT_UUID_GATT_INCLUDE, - .user_data = &value, }); - attr->handle = params->_included.attr_handle; + attr = (&(struct bt_gatt_attr) { + .uuid = BT_UUID_GATT_INCLUDE, + .user_data = &value, }); + attr->handle = params->_included.attr_handle; - if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { - return; - } + if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { + return; + } next: - gatt_discover_next(conn, params->start_handle, params); + gatt_discover_next(conn, params->start_handle, params); - return; + return; } static int read_included_uuid(struct bt_conn *conn, - struct bt_gatt_discover_params *params) + struct bt_gatt_discover_params *params) { - struct net_buf *buf; - struct bt_att_read_req *req; + struct net_buf *buf; + struct bt_att_read_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->handle = sys_cpu_to_le16(params->_included.start_handle); + req = net_buf_add(buf, sizeof(*req)); + req->handle = sys_cpu_to_le16(params->_included.start_handle); - BT_DBG("handle 0x%04x", params->_included.start_handle); + BT_DBG("handle 0x%04x", params->_included.start_handle); - return gatt_send(conn, buf, read_included_uuid_cb, params, NULL); + return gatt_send(conn, buf, read_included_uuid_cb, params, NULL); } static u16_t parse_include(struct bt_conn *conn, const void *pdu, - struct bt_gatt_discover_params *params, - u16_t length) + struct bt_gatt_discover_params *params, + u16_t length) { - const struct bt_att_read_type_rsp *rsp = pdu; - u16_t handle = 0U; - struct bt_gatt_include value; - union { - struct bt_uuid uuid; - struct bt_uuid_16 u16; - struct bt_uuid_128 u128; - } u; + const struct bt_att_read_type_rsp *rsp = pdu; + u16_t handle = 0U; + struct bt_gatt_include value; + union { + struct bt_uuid uuid; + struct bt_uuid_16 u16; + struct bt_uuid_128 u128; + } u; - /* Data can be either in UUID16 or UUID128 */ - switch (rsp->len) { - case 8: /* UUID16 */ - u.uuid.type = BT_UUID_TYPE_16; - break; - case 6: /* UUID128 */ - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550 - * To get the included service UUID when the included service - * uses a 128-bit UUID, the Read Request is used. - */ - u.uuid.type = BT_UUID_TYPE_128; - break; - default: - BT_ERR("Invalid data len %u", rsp->len); - goto done; - } + /* Data can be either in UUID16 or UUID128 */ + switch (rsp->len) { + case 8: /* UUID16 */ + u.uuid.type = BT_UUID_TYPE_16; + break; + case 6: /* UUID128 */ + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part G] page 550 + * To get the included service UUID when the included service + * uses a 128-bit UUID, the Read Request is used. + */ + u.uuid.type = BT_UUID_TYPE_128; + break; + default: + BT_ERR("Invalid data len %u", rsp->len); + goto done; + } - /* Parse include found */ - for (length--, pdu = rsp->data; length >= rsp->len; - length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { - struct bt_gatt_attr *attr; - const struct bt_att_data *data = pdu; - struct gatt_incl *incl = (void *)data->value; + /* Parse include found */ + for (length--, pdu = rsp->data; length >= rsp->len; + length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { + struct bt_gatt_attr *attr; + const struct bt_att_data *data = pdu; + struct gatt_incl *incl = (void *)data->value; - handle = sys_le16_to_cpu(data->handle); - /* Handle 0 is invalid */ - if (!handle) { - goto done; - } + handle = sys_le16_to_cpu(data->handle); + /* Handle 0 is invalid */ + if (!handle) { + goto done; + } - /* Convert include data, bt_gatt_incl and gatt_incl - * have different formats so the conversion have to be done - * field by field. - */ - value.start_handle = sys_le16_to_cpu(incl->start_handle); - value.end_handle = sys_le16_to_cpu(incl->end_handle); + /* Convert include data, bt_gatt_incl and gatt_incl + * have different formats so the conversion have to be done + * field by field. + */ + value.start_handle = sys_le16_to_cpu(incl->start_handle); + value.end_handle = sys_le16_to_cpu(incl->end_handle); - switch (u.uuid.type) { - case BT_UUID_TYPE_16: - value.uuid = &u.uuid; - u.u16.val = sys_le16_to_cpu(incl->uuid16); - break; - case BT_UUID_TYPE_128: - params->_included.attr_handle = handle; - params->_included.start_handle = value.start_handle; - params->_included.end_handle = value.end_handle; + switch (u.uuid.type) { + case BT_UUID_TYPE_16: + value.uuid = &u.uuid; + u.u16.val = sys_le16_to_cpu(incl->uuid16); + break; + case BT_UUID_TYPE_128: + params->_included.attr_handle = handle; + params->_included.start_handle = value.start_handle; + params->_included.end_handle = value.end_handle; - return read_included_uuid(conn, params); - } + return read_included_uuid(conn, params); + } - BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x " - "end_handle 0x%04x\n", handle, bt_uuid_str(&u.uuid), - value.start_handle, value.end_handle); + BT_DBG("handle 0x%04x uuid %s start_handle 0x%04x " + "end_handle 0x%04x\n", handle, bt_uuid_str(&u.uuid), + value.start_handle, value.end_handle); - /* Skip if UUID is set but doesn't match */ - if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { - continue; - } + /* Skip if UUID is set but doesn't match */ + if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { + continue; + } - attr = (&(struct bt_gatt_attr) { - .uuid = BT_UUID_GATT_INCLUDE, - .user_data = &value, }); - attr->handle = handle; + attr = (&(struct bt_gatt_attr) { + .uuid = BT_UUID_GATT_INCLUDE, + .user_data = &value, }); + attr->handle = handle; - if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { - return 0; - } - } + if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { + return 0; + } + } - /* Whole PDU read without error */ - if (length == 0U && handle) { - return handle; - } + /* Whole PDU read without error */ + if (length == 0U && handle) { + return handle; + } done: - params->func(conn, NULL, params); - return 0; + params->func(conn, NULL, params); + return 0; } -#define BT_GATT_CHRC(_uuid, _handle, _props) \ - BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \ - bt_gatt_attr_read_chrc, NULL, \ - (&(struct bt_gatt_chrc) { .uuid = _uuid, \ - .value_handle = _handle, \ - .properties = _props, })) +#define BT_GATT_CHRC(_uuid, _handle, _props) \ + BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \ + bt_gatt_attr_read_chrc, NULL, \ + (&(struct bt_gatt_chrc) { .uuid = _uuid, \ + .value_handle = _handle, \ + .properties = _props, })) static u16_t parse_characteristic(struct bt_conn *conn, const void *pdu, - struct bt_gatt_discover_params *params, - u16_t length) + struct bt_gatt_discover_params *params, + u16_t length) { - const struct bt_att_read_type_rsp *rsp = pdu; - u16_t handle = 0U; - union { - struct bt_uuid uuid; - struct bt_uuid_16 u16; - struct bt_uuid_128 u128; - } u; + const struct bt_att_read_type_rsp *rsp = pdu; + u16_t handle = 0U; + union { + struct bt_uuid uuid; + struct bt_uuid_16 u16; + struct bt_uuid_128 u128; + } u; - /* Data can be either in UUID16 or UUID128 */ - switch (rsp->len) { - case 7: /* UUID16 */ - u.uuid.type = BT_UUID_TYPE_16; - break; - case 21: /* UUID128 */ - u.uuid.type = BT_UUID_TYPE_128; - break; - default: - BT_ERR("Invalid data len %u", rsp->len); - goto done; - } + /* Data can be either in UUID16 or UUID128 */ + switch (rsp->len) { + case 7: /* UUID16 */ + u.uuid.type = BT_UUID_TYPE_16; + break; + case 21: /* UUID128 */ + u.uuid.type = BT_UUID_TYPE_128; + break; + default: + BT_ERR("Invalid data len %u", rsp->len); + goto done; + } - /* Parse characteristics found */ - for (length--, pdu = rsp->data; length >= rsp->len; - length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { - struct bt_gatt_attr *attr; - const struct bt_att_data *data = pdu; - struct gatt_chrc *chrc = (void *)data->value; + /* Parse characteristics found */ + for (length--, pdu = rsp->data; length >= rsp->len; + length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { + struct bt_gatt_attr *attr; + const struct bt_att_data *data = pdu; + struct gatt_chrc *chrc = (void *)data->value; - handle = sys_le16_to_cpu(data->handle); - /* Handle 0 is invalid */ - if (!handle) { - goto done; - } + handle = sys_le16_to_cpu(data->handle); + /* Handle 0 is invalid */ + if (!handle) { + goto done; + } - switch (u.uuid.type) { - case BT_UUID_TYPE_16: - u.u16.val = sys_le16_to_cpu(chrc->uuid16); - break; - case BT_UUID_TYPE_128: - memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid)); - break; - } + switch (u.uuid.type) { + case BT_UUID_TYPE_16: + u.u16.val = sys_le16_to_cpu(chrc->uuid16); + break; + case BT_UUID_TYPE_128: + memcpy(u.u128.val, chrc->uuid, sizeof(chrc->uuid)); + break; + } - BT_DBG("handle 0x%04x uuid %s properties 0x%02x", handle, - bt_uuid_str(&u.uuid), chrc->properties); + BT_DBG("handle 0x%04x uuid %s properties 0x%02x", handle, + bt_uuid_str(&u.uuid), chrc->properties); - #if defined(CONFIG_BT_STACK_PTS) - if(event_flag != gatt_discover_chara){ - /* Skip if UUID is set but doesn't match */ - if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) - continue; - } - #else - /* Skip if UUID is set but doesn't match */ - if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { - continue; - } - #endif + #if defined(CONFIG_BT_STACK_PTS) + if(event_flag != gatt_discover_chara){ + /* Skip if UUID is set but doesn't match */ + if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) + continue; + } + #else + /* Skip if UUID is set but doesn't match */ + if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { + continue; + } + #endif - attr = (&(struct bt_gatt_attr)BT_GATT_CHRC(&u.uuid, - chrc->value_handle, - chrc->properties)); - attr->handle = handle; + attr = (&(struct bt_gatt_attr)BT_GATT_CHRC(&u.uuid, + chrc->value_handle, + chrc->properties)); + attr->handle = handle; - if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { - return 0; - } - } + if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { + return 0; + } + } - /* Whole PDU read without error */ - if (length == 0U && handle) { - return handle; - } + /* Whole PDU read without error */ + if (length == 0U && handle) { + return handle; + } done: - params->func(conn, NULL, params); - return 0; + params->func(conn, NULL, params); + return 0; } static void gatt_read_type_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - struct bt_gatt_discover_params *params = user_data; - u16_t handle; + struct bt_gatt_discover_params *params = user_data; + u16_t handle; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - if (err) { - params->func(conn, NULL, params); - return; - } + if (err) { + params->func(conn, NULL, params); + return; + } - if (params->type == BT_GATT_DISCOVER_INCLUDE) { - handle = parse_include(conn, pdu, params, length); - } else { - handle = parse_characteristic(conn, pdu, params, length); - } + if (params->type == BT_GATT_DISCOVER_INCLUDE) { + handle = parse_include(conn, pdu, params, length); + } else { + handle = parse_characteristic(conn, pdu, params, length); + } - if (!handle) { - return; - } + if (!handle) { + return; + } - gatt_discover_next(conn, handle, params); + gatt_discover_next(conn, handle, params); } static int gatt_read_type(struct bt_conn *conn, - struct bt_gatt_discover_params *params) + struct bt_gatt_discover_params *params) { - struct net_buf *buf; - struct bt_att_read_type_req *req; + struct net_buf *buf; + struct bt_att_read_type_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->start_handle = sys_cpu_to_le16(params->start_handle); - req->end_handle = sys_cpu_to_le16(params->end_handle); + req = net_buf_add(buf, sizeof(*req)); + req->start_handle = sys_cpu_to_le16(params->start_handle); + req->end_handle = sys_cpu_to_le16(params->end_handle); - if (params->type == BT_GATT_DISCOVER_INCLUDE) { - net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_INCLUDE)->val); - } else { - net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_CHRC)->val); - } + if (params->type == BT_GATT_DISCOVER_INCLUDE) { + net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_INCLUDE)->val); + } else { + net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_CHRC)->val); + } - BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, - params->end_handle); + BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, + params->end_handle); - return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL); + return gatt_send(conn, buf, gatt_read_type_rsp, params, NULL); } static u16_t parse_service(struct bt_conn *conn, const void *pdu, - struct bt_gatt_discover_params *params, - u16_t length) + struct bt_gatt_discover_params *params, + u16_t length) { - const struct bt_att_read_group_rsp *rsp = pdu; - u16_t start_handle, end_handle = 0U; - union { - struct bt_uuid uuid; - struct bt_uuid_16 u16; - struct bt_uuid_128 u128; - } u; + const struct bt_att_read_group_rsp *rsp = pdu; + u16_t start_handle, end_handle = 0U; + union { + struct bt_uuid uuid; + struct bt_uuid_16 u16; + struct bt_uuid_128 u128; + } u; - /* Data can be either in UUID16 or UUID128 */ - switch (rsp->len) { - case 6: /* UUID16 */ - u.uuid.type = BT_UUID_TYPE_16; - break; - case 20: /* UUID128 */ - u.uuid.type = BT_UUID_TYPE_128; - break; - default: - BT_ERR("Invalid data len %u", rsp->len); - goto done; - } + /* Data can be either in UUID16 or UUID128 */ + switch (rsp->len) { + case 6: /* UUID16 */ + u.uuid.type = BT_UUID_TYPE_16; + break; + case 20: /* UUID128 */ + u.uuid.type = BT_UUID_TYPE_128; + break; + default: + BT_ERR("Invalid data len %u", rsp->len); + goto done; + } - /* Parse services found */ - for (length--, pdu = rsp->data; length >= rsp->len; - length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { - struct bt_gatt_attr attr = {}; - struct bt_gatt_service_val value; - const struct bt_att_group_data *data = pdu; + /* Parse services found */ + for (length--, pdu = rsp->data; length >= rsp->len; + length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { + struct bt_gatt_attr attr = {}; + struct bt_gatt_service_val value; + const struct bt_att_group_data *data = pdu; - start_handle = sys_le16_to_cpu(data->start_handle); - if (!start_handle) { - goto done; - } + start_handle = sys_le16_to_cpu(data->start_handle); + if (!start_handle) { + goto done; + } - end_handle = sys_le16_to_cpu(data->end_handle); - if (!end_handle || end_handle < start_handle) { - goto done; - } + end_handle = sys_le16_to_cpu(data->end_handle); + if (!end_handle || end_handle < start_handle) { + goto done; + } - switch (u.uuid.type) { - case BT_UUID_TYPE_16: - memcpy(&u.u16.val, data->value, sizeof(u.u16.val)); - u.u16.val = sys_le16_to_cpu(u.u16.val); - break; - case BT_UUID_TYPE_128: - memcpy(u.u128.val, data->value, sizeof(u.u128.val)); - break; - } + switch (u.uuid.type) { + case BT_UUID_TYPE_16: + memcpy(&u.u16.val, data->value, sizeof(u.u16.val)); + u.u16.val = sys_le16_to_cpu(u.u16.val); + break; + case BT_UUID_TYPE_128: + memcpy(u.u128.val, data->value, sizeof(u.u128.val)); + break; + } - BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", - start_handle, end_handle, bt_uuid_str(&u.uuid)); + BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", + start_handle, end_handle, bt_uuid_str(&u.uuid)); - if (params->type == BT_GATT_DISCOVER_PRIMARY) { - attr.uuid = BT_UUID_GATT_PRIMARY; - } else { - attr.uuid = BT_UUID_GATT_SECONDARY; - } + if (params->type == BT_GATT_DISCOVER_PRIMARY) { + attr.uuid = BT_UUID_GATT_PRIMARY; + } else { + attr.uuid = BT_UUID_GATT_SECONDARY; + } - value.end_handle = end_handle; - value.uuid = &u.uuid; + value.end_handle = end_handle; + value.uuid = &u.uuid; - attr.handle = start_handle; - attr.user_data = &value; + attr.handle = start_handle; + attr.user_data = &value; - if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) { - return 0; - } - } + if (params->func(conn, &attr, params) == BT_GATT_ITER_STOP) { + return 0; + } + } - /* Whole PDU read without error */ - if (length == 0U && end_handle) { - return end_handle; - } + /* Whole PDU read without error */ + if (length == 0U && end_handle) { + return end_handle; + } done: - params->func(conn, NULL, params); - return 0; + params->func(conn, NULL, params); + return 0; } static void gatt_read_group_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - struct bt_gatt_discover_params *params = user_data; - u16_t handle; + struct bt_gatt_discover_params *params = user_data; + u16_t handle; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - if (err) { - params->func(conn, NULL, params); - return; - } + if (err) { + params->func(conn, NULL, params); + return; + } - handle = parse_service(conn, pdu, params, length); - if (!handle) { - return; - } + handle = parse_service(conn, pdu, params, length); + if (!handle) { + return; + } - gatt_discover_next(conn, handle, params); + gatt_discover_next(conn, handle, params); } static int gatt_read_group(struct bt_conn *conn, - struct bt_gatt_discover_params *params) + struct bt_gatt_discover_params *params) { - struct net_buf *buf; - struct bt_att_read_group_req *req; + struct net_buf *buf; + struct bt_att_read_group_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_GROUP_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->start_handle = sys_cpu_to_le16(params->start_handle); - req->end_handle = sys_cpu_to_le16(params->end_handle); + req = net_buf_add(buf, sizeof(*req)); + req->start_handle = sys_cpu_to_le16(params->start_handle); + req->end_handle = sys_cpu_to_le16(params->end_handle); - if (params->type == BT_GATT_DISCOVER_PRIMARY) { - net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val); - } else { - net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val); - } + if (params->type == BT_GATT_DISCOVER_PRIMARY) { + net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_PRIMARY)->val); + } else { + net_buf_add_le16(buf, BT_UUID_16(BT_UUID_GATT_SECONDARY)->val); + } - BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, - params->end_handle); + BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, + params->end_handle); - return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL); + return gatt_send(conn, buf, gatt_read_group_rsp, params, NULL); } static void gatt_find_info_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - const struct bt_att_find_info_rsp *rsp = pdu; - struct bt_gatt_discover_params *params = user_data; - u16_t handle = 0U; - u16_t len; - union { - const struct bt_att_info_16 *i16; - const struct bt_att_info_128 *i128; - } info; - union { - struct bt_uuid uuid; - struct bt_uuid_16 u16; - struct bt_uuid_128 u128; - } u; - int i; - bool skip = false; + const struct bt_att_find_info_rsp *rsp = pdu; + struct bt_gatt_discover_params *params = user_data; + u16_t handle = 0U; + u16_t len; + union { + const struct bt_att_info_16 *i16; + const struct bt_att_info_128 *i128; + } info; + union { + struct bt_uuid uuid; + struct bt_uuid_16 u16; + struct bt_uuid_128 u128; + } u; + int i; + bool skip = false; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - if (err) { - goto done; - } + if (err) { + goto done; + } - /* Data can be either in UUID16 or UUID128 */ - switch (rsp->format) { - case BT_ATT_INFO_16: - u.uuid.type = BT_UUID_TYPE_16; - len = sizeof(*info.i16); - break; - case BT_ATT_INFO_128: - u.uuid.type = BT_UUID_TYPE_128; - len = sizeof(*info.i128); - break; - default: - BT_ERR("Invalid format %u", rsp->format); - goto done; - } + /* Data can be either in UUID16 or UUID128 */ + switch (rsp->format) { + case BT_ATT_INFO_16: + u.uuid.type = BT_UUID_TYPE_16; + len = sizeof(*info.i16); + break; + case BT_ATT_INFO_128: + u.uuid.type = BT_UUID_TYPE_128; + len = sizeof(*info.i128); + break; + default: + BT_ERR("Invalid format %u", rsp->format); + goto done; + } - length--; + length--; - /* Check if there is a least one descriptor in the response */ - if (length < len) { - goto done; - } + /* Check if there is a least one descriptor in the response */ + if (length < len) { + goto done; + } - /* Parse descriptors found */ - for (i = length / len, pdu = rsp->info; i != 0; - i--, pdu = (const u8_t *)pdu + len) { - struct bt_gatt_attr *attr; + /* Parse descriptors found */ + for (i = length / len, pdu = rsp->info; i != 0; + i--, pdu = (const u8_t *)pdu + len) { + struct bt_gatt_attr *attr; - info.i16 = pdu; - handle = sys_le16_to_cpu(info.i16->handle); + info.i16 = pdu; + handle = sys_le16_to_cpu(info.i16->handle); - if (skip) { - skip = false; - continue; - } + if (skip) { + skip = false; + continue; + } - switch (u.uuid.type) { - case BT_UUID_TYPE_16: - u.u16.val = sys_le16_to_cpu(info.i16->uuid); - break; - case BT_UUID_TYPE_128: - memcpy(u.u128.val, info.i128->uuid, 16); - break; - } + switch (u.uuid.type) { + case BT_UUID_TYPE_16: + u.u16.val = sys_le16_to_cpu(info.i16->uuid); + break; + case BT_UUID_TYPE_128: + memcpy(u.u128.val, info.i128->uuid, 16); + break; + } - BT_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid)); + BT_DBG("handle 0x%04x uuid %s", handle, bt_uuid_str(&u.uuid)); - /* Skip if UUID is set but doesn't match */ - if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { - continue; - } + /* Skip if UUID is set but doesn't match */ + if (params->uuid && bt_uuid_cmp(&u.uuid, params->uuid)) { + continue; + } - if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) { - /* Skip attributes that are not considered - * descriptors. - */ - if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) || - !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) || - !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) { - continue; - } + if (params->type == BT_GATT_DISCOVER_DESCRIPTOR) { + /* Skip attributes that are not considered + * descriptors. + */ + if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_PRIMARY) || + !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_SECONDARY) || + !bt_uuid_cmp(&u.uuid, BT_UUID_GATT_INCLUDE)) { + continue; + } - /* If Characteristic Declaration skip ahead as the next - * entry must be its value. - */ - if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) { - skip = true; - continue; - } - } + /* If Characteristic Declaration skip ahead as the next + * entry must be its value. + */ + if (!bt_uuid_cmp(&u.uuid, BT_UUID_GATT_CHRC)) { + skip = true; + continue; + } + } - attr = (&(struct bt_gatt_attr) - BT_GATT_DESCRIPTOR(&u.uuid, 0, NULL, NULL, NULL)); - attr->handle = handle; + attr = (&(struct bt_gatt_attr) + BT_GATT_DESCRIPTOR(&u.uuid, 0, NULL, NULL, NULL)); + attr->handle = handle; - if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { - return; - } - } + if (params->func(conn, attr, params) == BT_GATT_ITER_STOP) { + return; + } + } - gatt_discover_next(conn, handle, params); + gatt_discover_next(conn, handle, params); - return; + return; done: - params->func(conn, NULL, params); + params->func(conn, NULL, params); } static int gatt_find_info(struct bt_conn *conn, - struct bt_gatt_discover_params *params) + struct bt_gatt_discover_params *params) { - struct net_buf *buf; - struct bt_att_find_info_req *req; + struct net_buf *buf; + struct bt_att_find_info_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_FIND_INFO_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->start_handle = sys_cpu_to_le16(params->start_handle); - req->end_handle = sys_cpu_to_le16(params->end_handle); + req = net_buf_add(buf, sizeof(*req)); + req->start_handle = sys_cpu_to_le16(params->start_handle); + req->end_handle = sys_cpu_to_le16(params->end_handle); - BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, - params->end_handle); + BT_DBG("start_handle 0x%04x end_handle 0x%04x", params->start_handle, + params->end_handle); - return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL); + return gatt_send(conn, buf, gatt_find_info_rsp, params, NULL); } int bt_gatt_discover(struct bt_conn *conn, - struct bt_gatt_discover_params *params) + struct bt_gatt_discover_params *params) { - __ASSERT(conn, "invalid parameters\n"); - __ASSERT(params && params->func, "invalid parameters\n"); - __ASSERT((params->start_handle && params->end_handle), - "invalid parameters\n"); - __ASSERT((params->start_handle <= params->end_handle), - "invalid parameters\n"); + __ASSERT(conn, "invalid parameters\n"); + __ASSERT(params && params->func, "invalid parameters\n"); + __ASSERT((params->start_handle && params->end_handle), + "invalid parameters\n"); + __ASSERT((params->start_handle <= params->end_handle), + "invalid parameters\n"); - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - switch (params->type) { - case BT_GATT_DISCOVER_PRIMARY: - case BT_GATT_DISCOVER_SECONDARY: - if (params->uuid) { - return gatt_find_type(conn, params); - } - return gatt_read_group(conn, params); - case BT_GATT_DISCOVER_INCLUDE: - case BT_GATT_DISCOVER_CHARACTERISTIC: - return gatt_read_type(conn, params); - case BT_GATT_DISCOVER_DESCRIPTOR: - /* Only descriptors can be filtered */ - if (params->uuid && - (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) || - !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) || - !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) || - !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) { - return -EINVAL; - } - - #if defined(BFLB_BLE) - __attribute__((fallthrough)); - #endif - - /* Fallthrough. */ - case BT_GATT_DISCOVER_ATTRIBUTE: - return gatt_find_info(conn, params); - default: - BT_ERR("Invalid discovery type: %u", params->type); - } + switch (params->type) { + case BT_GATT_DISCOVER_PRIMARY: + case BT_GATT_DISCOVER_SECONDARY: + if (params->uuid) { + return gatt_find_type(conn, params); + } + return gatt_read_group(conn, params); + case BT_GATT_DISCOVER_INCLUDE: + case BT_GATT_DISCOVER_CHARACTERISTIC: + return gatt_read_type(conn, params); + case BT_GATT_DISCOVER_DESCRIPTOR: + /* Only descriptors can be filtered */ + if (params->uuid && + (!bt_uuid_cmp(params->uuid, BT_UUID_GATT_PRIMARY) || + !bt_uuid_cmp(params->uuid, BT_UUID_GATT_SECONDARY) || + !bt_uuid_cmp(params->uuid, BT_UUID_GATT_INCLUDE) || + !bt_uuid_cmp(params->uuid, BT_UUID_GATT_CHRC))) { + return -EINVAL; + } - return -EINVAL; + #if defined(BFLB_BLE) + __attribute__((fallthrough)); + #endif + + /* Fallthrough. */ + case BT_GATT_DISCOVER_ATTRIBUTE: + return gatt_find_info(conn, params); + default: + BT_ERR("Invalid discovery type: %u", params->type); + } + + return -EINVAL; } static void parse_read_by_uuid(struct bt_conn *conn, - struct bt_gatt_read_params *params, - const void *pdu, u16_t length) + struct bt_gatt_read_params *params, + const void *pdu, u16_t length) { - const struct bt_att_read_type_rsp *rsp = pdu; + const struct bt_att_read_type_rsp *rsp = pdu; - /* Parse values found */ - for (length--, pdu = rsp->data; length; - length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { - const struct bt_att_data *data = pdu; - u16_t handle; - u16_t len; + /* Parse values found */ + for (length--, pdu = rsp->data; length; + length -= rsp->len, pdu = (const u8_t *)pdu + rsp->len) { + const struct bt_att_data *data = pdu; + u16_t handle; + u16_t len; - handle = sys_le16_to_cpu(data->handle); + handle = sys_le16_to_cpu(data->handle); - /* Handle 0 is invalid */ - if (!handle) { - BT_ERR("Invalid handle"); - return; - } + /* Handle 0 is invalid */ + if (!handle) { + BT_ERR("Invalid handle"); + return; + } - len = rsp->len > length ? length - 2 : rsp->len - 2; + len = rsp->len > length ? length - 2 : rsp->len - 2; - BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len); + BT_DBG("handle 0x%04x len %u value %u", handle, rsp->len, len); - /* Update start_handle */ - params->by_uuid.start_handle = handle; + /* Update start_handle */ + params->by_uuid.start_handle = handle; - if (params->func(conn, 0, params, data->value, len) == - BT_GATT_ITER_STOP) { - return; - } + if (params->func(conn, 0, params, data->value, len) == + BT_GATT_ITER_STOP) { + return; + } - /* Check if long attribute */ - if (rsp->len > length) { - break; - } + /* Check if long attribute */ + if (rsp->len > length) { + break; + } - /* Stop if it's the last handle to be read */ - if (params->by_uuid.start_handle == params->by_uuid.end_handle) { - params->func(conn, 0, params, NULL, 0); - return; - } + /* Stop if it's the last handle to be read */ + if (params->by_uuid.start_handle == params->by_uuid.end_handle) { + params->func(conn, 0, params, NULL, 0); + return; + } - params->by_uuid.start_handle++; - } + params->by_uuid.start_handle++; + } - /* Continue reading the attributes */ - if (bt_gatt_read(conn, params) < 0) { - params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0); - } + /* Continue reading the attributes */ + if (bt_gatt_read(conn, params) < 0) { + params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0); + } } static void gatt_read_rsp(struct bt_conn *conn, u8_t err, const void *pdu, - u16_t length, void *user_data) + u16_t length, void *user_data) { - struct bt_gatt_read_params *params = user_data; + struct bt_gatt_read_params *params = user_data; - BT_DBG("err 0x%02x", err); - - if (err || !length) { - params->func(conn, err, params, NULL, 0); - return; - } + BT_DBG("err 0x%02x", err); - if (!params->handle_count) { - parse_read_by_uuid(conn, params, pdu, length); - return; - } + if (err || !length) { + params->func(conn, err, params, NULL, 0); + return; + } - if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) { - return; - } + if (!params->handle_count) { + parse_read_by_uuid(conn, params, pdu, length); + return; + } - /* - * Core Spec 4.2, Vol. 3, Part G, 4.8.1 - * If the Characteristic Value is greater than (ATT_MTU - 1) octets - * in length, the Read Long Characteristic Value procedure may be used - * if the rest of the Characteristic Value is required. - */ - if (length < (bt_att_get_mtu(conn) - 1)) { - params->func(conn, 0, params, NULL, 0); - return; - } + if (params->func(conn, 0, params, pdu, length) == BT_GATT_ITER_STOP) { + return; + } - params->single.offset += length; + /* + * Core Spec 4.2, Vol. 3, Part G, 4.8.1 + * If the Characteristic Value is greater than (ATT_MTU - 1) octets + * in length, the Read Long Characteristic Value procedure may be used + * if the rest of the Characteristic Value is required. + */ + if (length < (bt_att_get_mtu(conn) - 1)) { + params->func(conn, 0, params, NULL, 0); + return; + } + + params->single.offset += length; + + /* Continue reading the attribute */ + if (bt_gatt_read(conn, params) < 0) { + params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0); + } - /* Continue reading the attribute */ - if (bt_gatt_read(conn, params) < 0) { - params->func(conn, BT_ATT_ERR_UNLIKELY, params, NULL, 0); - } - } static int gatt_read_blob(struct bt_conn *conn, - struct bt_gatt_read_params *params) + struct bt_gatt_read_params *params) { - struct net_buf *buf; - struct bt_att_read_blob_req *req; + struct net_buf *buf; + struct bt_att_read_blob_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_BLOB_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_BLOB_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->handle = sys_cpu_to_le16(params->single.handle); - req->offset = sys_cpu_to_le16(params->single.offset); + req = net_buf_add(buf, sizeof(*req)); + req->handle = sys_cpu_to_le16(params->single.handle); + req->offset = sys_cpu_to_le16(params->single.offset); - BT_DBG("handle 0x%04x offset 0x%04x", params->single.handle, - params->single.offset); + BT_DBG("handle 0x%04x offset 0x%04x", params->single.handle, + params->single.offset); - return gatt_send(conn, buf, gatt_read_rsp, params, NULL); + return gatt_send(conn, buf, gatt_read_rsp, params, NULL); } static int gatt_read_uuid(struct bt_conn *conn, - struct bt_gatt_read_params *params) + struct bt_gatt_read_params *params) { - struct net_buf *buf; - struct bt_att_read_type_req *req; + struct net_buf *buf; + struct bt_att_read_type_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_TYPE_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle); - req->end_handle = sys_cpu_to_le16(params->by_uuid.end_handle); + req = net_buf_add(buf, sizeof(*req)); + req->start_handle = sys_cpu_to_le16(params->by_uuid.start_handle); + req->end_handle = sys_cpu_to_le16(params->by_uuid.end_handle); - if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) { - net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val); - } else { - net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16); - } + if (params->by_uuid.uuid->type == BT_UUID_TYPE_16) { + net_buf_add_le16(buf, BT_UUID_16(params->by_uuid.uuid)->val); + } else { + net_buf_add_mem(buf, BT_UUID_128(params->by_uuid.uuid)->val, 16); + } - BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", - params->by_uuid.start_handle, params->by_uuid.end_handle, - bt_uuid_str(params->by_uuid.uuid)); + BT_DBG("start_handle 0x%04x end_handle 0x%04x uuid %s", + params->by_uuid.start_handle, params->by_uuid.end_handle, + bt_uuid_str(params->by_uuid.uuid)); - return gatt_send(conn, buf, gatt_read_rsp, params, NULL); + return gatt_send(conn, buf, gatt_read_rsp, params, NULL); } #if defined(CONFIG_BT_GATT_READ_MULTIPLE) static void gatt_read_multiple_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - struct bt_gatt_read_params *params = user_data; + struct bt_gatt_read_params *params = user_data; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - if (err || !length) { - params->func(conn, err, params, NULL, 0); - return; - } + if (err || !length) { + params->func(conn, err, params, NULL, 0); + return; + } - params->func(conn, 0, params, pdu, length); + params->func(conn, 0, params, pdu, length); - /* mark read as complete since read multiple is single response */ - params->func(conn, 0, params, NULL, 0); + /* mark read as complete since read multiple is single response */ + params->func(conn, 0, params, NULL, 0); } static int gatt_read_multiple(struct bt_conn *conn, - struct bt_gatt_read_params *params) + struct bt_gatt_read_params *params) { - struct net_buf *buf; - u8_t i; + struct net_buf *buf; + u8_t i; - buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_REQ, - params->handle_count * sizeof(u16_t)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_MULT_REQ, + params->handle_count * sizeof(u16_t)); + if (!buf) { + return -ENOMEM; + } - for (i = 0U; i < params->handle_count; i++) { - net_buf_add_le16(buf, params->handles[i]); - } + for (i = 0U; i < params->handle_count; i++) { + net_buf_add_le16(buf, params->handles[i]); + } - return gatt_send(conn, buf, gatt_read_multiple_rsp, params, NULL); + return gatt_send(conn, buf, gatt_read_multiple_rsp, params, NULL); } #else static int gatt_read_multiple(struct bt_conn *conn, - struct bt_gatt_read_params *params) + struct bt_gatt_read_params *params) { - return -ENOTSUP; + return -ENOTSUP; } #endif /* CONFIG_BT_GATT_READ_MULTIPLE */ int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params) { - struct net_buf *buf; - struct bt_att_read_req *req; + struct net_buf *buf; + struct bt_att_read_req *req; - __ASSERT(conn, "invalid parameters\n"); - __ASSERT(params && params->func, "invalid parameters\n"); - - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } - - if (params->handle_count == 0) { - return gatt_read_uuid(conn, params); - } - - if (params->handle_count > 1) { - return gatt_read_multiple(conn, params); - } + __ASSERT(conn, "invalid parameters\n"); + __ASSERT(params && params->func, "invalid parameters\n"); - if (params->single.offset) { - return gatt_read_blob(conn, params); - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + if (params->handle_count == 0) { + return gatt_read_uuid(conn, params); + } - req = net_buf_add(buf, sizeof(*req)); - req->handle = sys_cpu_to_le16(params->single.handle); + if (params->handle_count > 1) { + return gatt_read_multiple(conn, params); + } - BT_DBG("handle 0x%04x", params->single.handle); + if (params->single.offset) { + return gatt_read_blob(conn, params); + } - return gatt_send(conn, buf, gatt_read_rsp, params, NULL); + buf = bt_att_create_pdu(conn, BT_ATT_OP_READ_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } + + req = net_buf_add(buf, sizeof(*req)); + req->handle = sys_cpu_to_le16(params->single.handle); + + BT_DBG("handle 0x%04x", params->single.handle); + + return gatt_send(conn, buf, gatt_read_rsp, params, NULL); } static void gatt_write_rsp(struct bt_conn *conn, u8_t err, const void *pdu, - u16_t length, void *user_data) + u16_t length, void *user_data) { - struct bt_gatt_write_params *params = user_data; + struct bt_gatt_write_params *params = user_data; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - params->func(conn, err, params); + params->func(conn, err, params); } int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle, - const void *data, u16_t length, bool sign, - bt_gatt_complete_func_t func, - void *user_data) + const void *data, u16_t length, bool sign, + bt_gatt_complete_func_t func, + void *user_data) { - struct net_buf *buf; - struct bt_att_write_cmd *cmd; + struct net_buf *buf; + struct bt_att_write_cmd *cmd; - __ASSERT(conn, "invalid parameters\n"); - __ASSERT(handle, "invalid parameters\n"); + __ASSERT(conn, "invalid parameters\n"); + __ASSERT(handle, "invalid parameters\n"); - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } #if defined(CONFIG_BT_SMP) - if (conn->encrypt) { - /* Don't need to sign if already encrypted */ - sign = false; - } + if (conn->encrypt) { + /* Don't need to sign if already encrypted */ + sign = false; + } #endif - if (sign) { - buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD, - sizeof(*cmd) + length + 12); - } else { - buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD, - sizeof(*cmd) + length); - } - if (!buf) { - return -ENOMEM; - } + if (sign) { + buf = bt_att_create_pdu(conn, BT_ATT_OP_SIGNED_WRITE_CMD, + sizeof(*cmd) + length + 12); + } else { + buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_CMD, + sizeof(*cmd) + length); + } + if (!buf) { + return -ENOMEM; + } - cmd = net_buf_add(buf, sizeof(*cmd)); - cmd->handle = sys_cpu_to_le16(handle); - memcpy(cmd->value, data, length); - net_buf_add(buf, length); + cmd = net_buf_add(buf, sizeof(*cmd)); + cmd->handle = sys_cpu_to_le16(handle); + memcpy(cmd->value, data, length); + net_buf_add(buf, length); - BT_DBG("handle 0x%04x length %u", handle, length); + BT_DBG("handle 0x%04x length %u", handle, length); - return bt_att_send(conn, buf, func, user_data); + return bt_att_send(conn, buf, func, user_data); } static int gatt_exec_write(struct bt_conn *conn, - struct bt_gatt_write_params *params) + struct bt_gatt_write_params *params) { - struct net_buf *buf; - struct bt_att_exec_write_req *req; + struct net_buf *buf; + struct bt_att_exec_write_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_REQ, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_EXEC_WRITE_REQ, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - #if defined(CONFIG_BT_STACK_PTS) - if(event_flag == gatt_cancel_write_req) - req->flags = BT_ATT_FLAG_CANCEL; - else - req->flags = BT_ATT_FLAG_EXEC; - #else - req->flags = BT_ATT_FLAG_EXEC; - #endif + req = net_buf_add(buf, sizeof(*req)); + #if defined(CONFIG_BT_STACK_PTS) + if(event_flag == gatt_cancel_write_req) + req->flags = BT_ATT_FLAG_CANCEL; + else + req->flags = BT_ATT_FLAG_EXEC; + #else + req->flags = BT_ATT_FLAG_EXEC; + #endif - BT_DBG(""); + BT_DBG(""); - return gatt_send(conn, buf, gatt_write_rsp, params, NULL); + return gatt_send(conn, buf, gatt_write_rsp, params, NULL); } static void gatt_prepare_write_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - struct bt_gatt_write_params *params = user_data; + struct bt_gatt_write_params *params = user_data; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - /* Don't continue in case of error */ - if (err) { - params->func(conn, err, params); - return; - } - /* If there is no more data execute */ - if (!params->length) { - gatt_exec_write(conn, params); - return; - } + /* Don't continue in case of error */ + if (err) { + params->func(conn, err, params); + return; + } + /* If there is no more data execute */ + if (!params->length) { + gatt_exec_write(conn, params); + return; + } + + /* Write next chunk */ + bt_gatt_write(conn, params); - /* Write next chunk */ - bt_gatt_write(conn, params); - } static int gatt_prepare_write(struct bt_conn *conn, - struct bt_gatt_write_params *params) + struct bt_gatt_write_params *params) { - struct net_buf *buf; - struct bt_att_prepare_write_req *req; - u16_t len; + struct net_buf *buf; + struct bt_att_prepare_write_req *req; + u16_t len; - len = MIN(params->length, bt_att_get_mtu(conn) - sizeof(*req) - 1); + len = MIN(params->length, bt_att_get_mtu(conn) - sizeof(*req) - 1); - buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_REQ, - sizeof(*req) + len); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_PREPARE_WRITE_REQ, + sizeof(*req) + len); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->handle = sys_cpu_to_le16(params->handle); - req->offset = sys_cpu_to_le16(params->offset); - memcpy(req->value, params->data, len); - net_buf_add(buf, len); + req = net_buf_add(buf, sizeof(*req)); + req->handle = sys_cpu_to_le16(params->handle); + req->offset = sys_cpu_to_le16(params->offset); + memcpy(req->value, params->data, len); + net_buf_add(buf, len); - /* Update params */ - params->offset += len; - params->data = (const u8_t *)params->data + len; - params->length -= len; + /* Update params */ + params->offset += len; + params->data = (const u8_t *)params->data + len; + params->length -= len; - BT_DBG("handle 0x%04x offset %u len %u", params->handle, params->offset, - params->length); + BT_DBG("handle 0x%04x offset %u len %u", params->handle, params->offset, + params->length); - return gatt_send(conn, buf, gatt_prepare_write_rsp, params, NULL); + return gatt_send(conn, buf, gatt_prepare_write_rsp, params, NULL); } #if defined(CONFIG_BT_STACK_PTS) int bt_gatt_prepare_write(struct bt_conn *conn, - struct bt_gatt_write_params *params) + struct bt_gatt_write_params *params) { return gatt_prepare_write(conn, params); } @@ -3530,74 +3530,74 @@ int bt_gatt_prepare_write(struct bt_conn *conn, int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params) { - struct net_buf *buf; - struct bt_att_write_req *req; + struct net_buf *buf; + struct bt_att_write_req *req; - __ASSERT(conn, "invalid parameters\n"); - __ASSERT(params && params->func, "invalid parameters\n"); - __ASSERT(params->handle, "invalid parameters\n"); + __ASSERT(conn, "invalid parameters\n"); + __ASSERT(params && params->func, "invalid parameters\n"); + __ASSERT(params->handle, "invalid parameters\n"); - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - /* Use Prepare Write if offset is set or Long Write is required */ - if (params->offset || - params->length > (bt_att_get_mtu(conn) - sizeof(*req) - 1)) { - return gatt_prepare_write(conn, params); - } + /* Use Prepare Write if offset is set or Long Write is required */ + if (params->offset || + params->length > (bt_att_get_mtu(conn) - sizeof(*req) - 1)) { + return gatt_prepare_write(conn, params); + } - buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, - sizeof(*req) + params->length); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, + sizeof(*req) + params->length); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->handle = sys_cpu_to_le16(params->handle); - memcpy(req->value, params->data, params->length); - net_buf_add(buf, params->length); + req = net_buf_add(buf, sizeof(*req)); + req->handle = sys_cpu_to_le16(params->handle); + memcpy(req->value, params->data, params->length); + net_buf_add(buf, params->length); - BT_DBG("handle 0x%04x length %u", params->handle, params->length); + BT_DBG("handle 0x%04x length %u", params->handle, params->length); - return gatt_send(conn, buf, gatt_write_rsp, params, NULL); + return gatt_send(conn, buf, gatt_write_rsp, params, NULL); } static void gatt_subscription_add(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params) + struct bt_gatt_subscribe_params *params) { - bt_addr_le_copy(¶ms->_peer, &conn->le.dst); + bt_addr_le_copy(¶ms->_peer, &conn->le.dst); - /* Prepend subscription */ - sys_slist_prepend(&subscriptions, ¶ms->node); + /* Prepend subscription */ + sys_slist_prepend(&subscriptions, ¶ms->node); } static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data) + const void *pdu, u16_t length, + void *user_data) { - struct bt_gatt_subscribe_params *params = user_data; + struct bt_gatt_subscribe_params *params = user_data; - BT_DBG("err 0x%02x", err); + BT_DBG("err 0x%02x", err); - atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING); + atomic_clear_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING); - /* if write to CCC failed we remove subscription and notify app */ - if (err) { - sys_snode_t *node, *tmp, *prev = NULL; + /* if write to CCC failed we remove subscription and notify app */ + if (err) { + sys_snode_t *node, *tmp, *prev = NULL; - SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp) { - if (node == ¶ms->node) { - gatt_subscription_remove(conn, tmp, params); - break; - } + SYS_SLIST_FOR_EACH_NODE_SAFE(&subscriptions, node, tmp) { + if (node == ¶ms->node) { + gatt_subscription_remove(conn, tmp, params); + break; + } - prev = node; - } - } else if (!params->value) { - /* Notify with NULL data to complete unsubscribe */ - params->notify(conn, params, NULL, 0); - } + prev = node; + } + } else if (!params->value) { + /* Notify with NULL data to complete unsubscribe */ + params->notify(conn, params, NULL, 0); + } #if defined(BFLB_BLE_PATCH_NOTIFY_WRITE_CCC_RSP) else{ params->notify(conn, params, NULL, 0); @@ -3606,153 +3606,153 @@ static void gatt_write_ccc_rsp(struct bt_conn *conn, u8_t err, } static int gatt_write_ccc(struct bt_conn *conn, u16_t handle, u16_t value, - bt_att_func_t func, - struct bt_gatt_subscribe_params *params) + bt_att_func_t func, + struct bt_gatt_subscribe_params *params) { - struct net_buf *buf; - struct bt_att_write_req *req; + struct net_buf *buf; + struct bt_att_write_req *req; - buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, - sizeof(*req) + sizeof(u16_t)); - if (!buf) { - return -ENOMEM; - } + buf = bt_att_create_pdu(conn, BT_ATT_OP_WRITE_REQ, + sizeof(*req) + sizeof(u16_t)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->handle = sys_cpu_to_le16(handle); - net_buf_add_le16(buf, value); + req = net_buf_add(buf, sizeof(*req)); + req->handle = sys_cpu_to_le16(handle); + net_buf_add_le16(buf, value); - BT_DBG("handle 0x%04x value 0x%04x", handle, value); + BT_DBG("handle 0x%04x value 0x%04x", handle, value); - atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING); + atomic_set_bit(params->flags, BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING); - return gatt_send(conn, buf, func, params, NULL); + return gatt_send(conn, buf, func, params, NULL); } int bt_gatt_subscribe(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params) + struct bt_gatt_subscribe_params *params) { - struct bt_gatt_subscribe_params *tmp; - bool has_subscription = false; + struct bt_gatt_subscribe_params *tmp; + bool has_subscription = false; - __ASSERT(conn, "invalid parameters\n"); - __ASSERT(params && params->notify, "invalid parameters\n"); - __ASSERT(params->value, "invalid parameters\n"); - __ASSERT(params->ccc_handle, "invalid parameters\n"); + __ASSERT(conn, "invalid parameters\n"); + __ASSERT(params && params->notify, "invalid parameters\n"); + __ASSERT(params->value, "invalid parameters\n"); + __ASSERT(params->ccc_handle, "invalid parameters\n"); - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - /* Lookup existing subscriptions */ - SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node) { - /* Fail if entry already exists */ - if (tmp == params) { - return -EALREADY; - } + /* Lookup existing subscriptions */ + SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, tmp, node) { + /* Fail if entry already exists */ + if (tmp == params) { + return -EALREADY; + } - /* Check if another subscription exists */ - if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && - tmp->value_handle == params->value_handle && - tmp->value >= params->value) { - has_subscription = true; - } - } + /* Check if another subscription exists */ + if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && + tmp->value_handle == params->value_handle && + tmp->value >= params->value) { + has_subscription = true; + } + } - /* Skip write if already subscribed */ - if (!has_subscription) { - int err; + /* Skip write if already subscribed */ + if (!has_subscription) { + int err; - err = gatt_write_ccc(conn, params->ccc_handle, params->value, - gatt_write_ccc_rsp, params); - if (err) { - return err; - } - } + err = gatt_write_ccc(conn, params->ccc_handle, params->value, + gatt_write_ccc_rsp, params); + if (err) { + return err; + } + } - /* - * Add subscription before write complete as some implementation were - * reported to send notification before reply to CCC write. - */ - gatt_subscription_add(conn, params); + /* + * Add subscription before write complete as some implementation were + * reported to send notification before reply to CCC write. + */ + gatt_subscription_add(conn, params); - return 0; + return 0; } int bt_gatt_unsubscribe(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params) + struct bt_gatt_subscribe_params *params) { - struct bt_gatt_subscribe_params *tmp, *next; - bool has_subscription = false, found = false; - sys_snode_t *prev = NULL; + struct bt_gatt_subscribe_params *tmp, *next; + bool has_subscription = false, found = false; + sys_snode_t *prev = NULL; - __ASSERT(conn, "invalid parameters\n"); - __ASSERT(params, "invalid parameters\n"); + __ASSERT(conn, "invalid parameters\n"); + __ASSERT(params, "invalid parameters\n"); - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - /* Lookup existing subscriptions */ - SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, tmp, next, node) { - /* Remove subscription */ - if (params == tmp) { - found = true; - sys_slist_remove(&subscriptions, prev, &tmp->node); - /* Attempt to cancel if write is pending */ - if (atomic_test_bit(params->flags, - BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) { - bt_gatt_cancel(conn, params); - } - continue; - } else { - prev = &tmp->node; - } + /* Lookup existing subscriptions */ + SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, tmp, next, node) { + /* Remove subscription */ + if (params == tmp) { + found = true; + sys_slist_remove(&subscriptions, prev, &tmp->node); + /* Attempt to cancel if write is pending */ + if (atomic_test_bit(params->flags, + BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING)) { + bt_gatt_cancel(conn, params); + } + continue; + } else { + prev = &tmp->node; + } - /* Check if there still remains any other subscription */ - if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && - tmp->value_handle == params->value_handle) { - has_subscription = true; - } - } + /* Check if there still remains any other subscription */ + if (!bt_conn_addr_le_cmp(conn, &tmp->_peer) && + tmp->value_handle == params->value_handle) { + has_subscription = true; + } + } - if (!found) { - return -EINVAL; - } + if (!found) { + return -EINVAL; + } - if (has_subscription) { - /* Notify with NULL data to complete unsubscribe */ - params->notify(conn, params, NULL, 0); - return 0; - } + if (has_subscription) { + /* Notify with NULL data to complete unsubscribe */ + params->notify(conn, params, NULL, 0); + return 0; + } - params->value = 0x0000; + params->value = 0x0000; - return gatt_write_ccc(conn, params->ccc_handle, params->value, - gatt_write_ccc_rsp, params); + return gatt_write_ccc(conn, params->ccc_handle, params->value, + gatt_write_ccc_rsp, params); } void bt_gatt_cancel(struct bt_conn *conn, void *params) { - bt_att_req_cancel(conn, params); + bt_att_req_cancel(conn, params); } static void add_subscriptions(struct bt_conn *conn) { - struct bt_gatt_subscribe_params *params; + struct bt_gatt_subscribe_params *params; - /* Lookup existing subscriptions */ - SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, params, node) { - if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) { - continue; - } + /* Lookup existing subscriptions */ + SYS_SLIST_FOR_EACH_CONTAINER(&subscriptions, params, node) { + if (bt_conn_addr_le_cmp(conn, ¶ms->_peer)) { + continue; + } - /* Force write to CCC to workaround devices that don't track - * it properly. - */ - gatt_write_ccc(conn, params->ccc_handle, params->value, - gatt_write_ccc_rsp, params); - } + /* Force write to CCC to workaround devices that don't track + * it properly. + */ + gatt_write_ccc(conn, params->ccc_handle, params->value, + gatt_write_ccc_rsp, params); + } } #endif /* CONFIG_BT_GATT_CLIENT */ @@ -3760,180 +3760,180 @@ static void add_subscriptions(struct bt_conn *conn) #define CCC_STORE_MAX 48 static struct bt_gatt_ccc_cfg *ccc_find_cfg(struct _bt_gatt_ccc *ccc, - const bt_addr_le_t *addr, - u8_t id) + const bt_addr_le_t *addr, + u8_t id) { - for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { - if (id == ccc->cfg[i].id && - !bt_addr_le_cmp(&ccc->cfg[i].peer, addr)) { - return &ccc->cfg[i]; - } - } + for (size_t i = 0; i < ARRAY_SIZE(ccc->cfg); i++) { + if (id == ccc->cfg[i].id && + !bt_addr_le_cmp(&ccc->cfg[i].peer, addr)) { + return &ccc->cfg[i]; + } + } - return NULL; + return NULL; } struct addr_with_id { - const bt_addr_le_t *addr; - u8_t id; + const bt_addr_le_t *addr; + u8_t id; }; struct ccc_load { - struct addr_with_id addr_with_id; - struct ccc_store *entry; - size_t count; + struct addr_with_id addr_with_id; + struct ccc_store *entry; + size_t count; }; static void ccc_clear(struct _bt_gatt_ccc *ccc, - const bt_addr_le_t *addr, - u8_t id) + const bt_addr_le_t *addr, + u8_t id) { - struct bt_gatt_ccc_cfg *cfg; + struct bt_gatt_ccc_cfg *cfg; - cfg = ccc_find_cfg(ccc, addr, id); - if (!cfg) { - BT_DBG("Unable to clear CCC: cfg not found"); - return; - } + cfg = ccc_find_cfg(ccc, addr, id); + if (!cfg) { + BT_DBG("Unable to clear CCC: cfg not found"); + return; + } - clear_ccc_cfg(cfg); + clear_ccc_cfg(cfg); } static u8_t ccc_load(const struct bt_gatt_attr *attr, void *user_data) { - struct ccc_load *load = user_data; - struct _bt_gatt_ccc *ccc; - struct bt_gatt_ccc_cfg *cfg; + struct ccc_load *load = user_data; + struct _bt_gatt_ccc *ccc; + struct bt_gatt_ccc_cfg *cfg; - /* Check if attribute is a CCC */ - if (attr->write != bt_gatt_attr_write_ccc) { - return BT_GATT_ITER_CONTINUE; - } + /* Check if attribute is a CCC */ + if (attr->write != bt_gatt_attr_write_ccc) { + return BT_GATT_ITER_CONTINUE; + } - ccc = attr->user_data; + ccc = attr->user_data; - /* Clear if value was invalidated */ - if (!load->entry) { - ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id); - return BT_GATT_ITER_CONTINUE; - } else if (!load->count) { - return BT_GATT_ITER_STOP; - } + /* Clear if value was invalidated */ + if (!load->entry) { + ccc_clear(ccc, load->addr_with_id.addr, load->addr_with_id.id); + return BT_GATT_ITER_CONTINUE; + } else if (!load->count) { + return BT_GATT_ITER_STOP; + } - /* Skip if value is not for the given attribute */ - if (load->entry->handle != attr->handle) { - /* If attribute handle is bigger then it means - * the attribute no longer exists and cannot - * be restored. - */ - if (load->entry->handle < attr->handle) { - BT_DBG("Unable to restore CCC: handle 0x%04x cannot be" - " found", load->entry->handle); - goto next; - } - return BT_GATT_ITER_CONTINUE; - } + /* Skip if value is not for the given attribute */ + if (load->entry->handle != attr->handle) { + /* If attribute handle is bigger then it means + * the attribute no longer exists and cannot + * be restored. + */ + if (load->entry->handle < attr->handle) { + BT_DBG("Unable to restore CCC: handle 0x%04x cannot be" + " found", load->entry->handle); + goto next; + } + return BT_GATT_ITER_CONTINUE; + } - BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle, - load->entry->value); + BT_DBG("Restoring CCC: handle 0x%04x value 0x%04x", load->entry->handle, + load->entry->value); - cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id); - if (!cfg) { - cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0); - if (!cfg) { - BT_DBG("Unable to restore CCC: no cfg left"); - goto next; - } - bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr); - cfg->id = load->addr_with_id.id; - } + cfg = ccc_find_cfg(ccc, load->addr_with_id.addr, load->addr_with_id.id); + if (!cfg) { + cfg = ccc_find_cfg(ccc, BT_ADDR_LE_ANY, 0); + if (!cfg) { + BT_DBG("Unable to restore CCC: no cfg left"); + goto next; + } + bt_addr_le_copy(&cfg->peer, load->addr_with_id.addr); + cfg->id = load->addr_with_id.id; + } - cfg->value = load->entry->value; + cfg->value = load->entry->value; next: - load->entry++; - load->count--; + load->entry++; + load->count--; - return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP; + return load->count ? BT_GATT_ITER_CONTINUE : BT_GATT_ITER_STOP; } #if defined(BFLB_BLE) static int ccc_set(const char *key, u8_t id, bt_addr_le_t *addr) #else static int ccc_set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) #endif { - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - struct ccc_store ccc_store[CCC_STORE_MAX]; - struct ccc_load load; + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + struct ccc_store ccc_store[CCC_STORE_MAX]; + struct ccc_load load; #if defined(BFLB_BLE) size_t len; int err; #else - bt_addr_le_t addr; + bt_addr_le_t addr; const char *next; - int len, err; + int len, err; #endif - + #if defined(BFLB_BLE) err = bt_settings_get_bin(key, (u8_t *)ccc_store, CCC_STORE_MAX, &len); if(err) return err; load.addr_with_id.id = id; - load.addr_with_id.addr = addr; + load.addr_with_id.addr = addr; load.entry = ccc_store; - load.count = len / sizeof(*ccc_store); + load.count = len / sizeof(*ccc_store); #else - settings_name_next(name, &next); - - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -EINVAL; - } else if (!next) { - load.addr_with_id.id = BT_ID_DEFAULT; - } else { - load.addr_with_id.id = strtol(next, NULL, 10); - } + settings_name_next(name, &next); - err = bt_settings_decode_key(name, &addr); - if (err) { - BT_ERR("Unable to decode address %s", log_strdup(name)); - return -EINVAL; - } - - load.addr_with_id.addr = &addr; + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -EINVAL; + } else if (!next) { + load.addr_with_id.id = BT_ID_DEFAULT; + } else { + load.addr_with_id.id = strtol(next, NULL, 10); + } - if (len_rd) { - len = read_cb(cb_arg, ccc_store, sizeof(ccc_store)); + err = bt_settings_decode_key(name, &addr); + if (err) { + BT_ERR("Unable to decode address %s", log_strdup(name)); + return -EINVAL; + } - if (len < 0) { - BT_ERR("Failed to decode value (err %d)", len); - return len; - } - - load.entry = ccc_store; - load.count = len / sizeof(*ccc_store); + load.addr_with_id.addr = &addr; - for (int i = 0; i < load.count; i++) { - BT_DBG("Read CCC: handle 0x%04x value 0x%04x", - ccc_store[i].handle, ccc_store[i].value); - } - } else { - load.entry = NULL; - load.count = 0; - } + if (len_rd) { + len = read_cb(cb_arg, ccc_store, sizeof(ccc_store)); + + if (len < 0) { + BT_ERR("Failed to decode value (err %d)", len); + return len; + } + + load.entry = ccc_store; + load.count = len / sizeof(*ccc_store); + + for (int i = 0; i < load.count; i++) { + BT_DBG("Read CCC: handle 0x%04x value 0x%04x", + ccc_store[i].handle, ccc_store[i].value); + } + } else { + load.entry = NULL; + load.count = 0; + } #endif - - bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load); - BT_DBG("Restored CCC for id:%x" "PRIu8" " addr:%s", - load.addr_with_id.id, - bt_addr_le_str(load.addr_with_id.addr)); - } + bt_gatt_foreach_attr(0x0001, 0xffff, ccc_load, &load); - return 0; + BT_DBG("Restored CCC for id:%x" "PRIu8" " addr:%s", + load.addr_with_id.id, + bt_addr_le_str(load.addr_with_id.addr)); + } + + return 0; } #if !defined(BFLB_BLE) @@ -3945,22 +3945,22 @@ SETTINGS_STATIC_HANDLER_DEFINE(bt_ccc, "bt/ccc", NULL, ccc_set, NULL, NULL); #if !defined(BFLB_BLE) static int ccc_set_direct(const char *key, size_t len, settings_read_cb read_cb, - void *cb_arg, void *param) + void *cb_arg, void *param) { - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - const char *name; + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + const char *name; - BT_DBG("key: %s", log_strdup((const char *)param)); + BT_DBG("key: %s", log_strdup((const char *)param)); - /* Only "bt/ccc" settings should ever come here */ - if (!settings_name_steq((const char *)param, "bt/ccc", &name)) { - BT_ERR("Invalid key"); - return -EINVAL; - } + /* Only "bt/ccc" settings should ever come here */ + if (!settings_name_steq((const char *)param, "bt/ccc", &name)) { + BT_ERR("Invalid key"); + return -EINVAL; + } - return ccc_set(name, len, read_cb, cb_arg); - } - return 0; + return ccc_set(name, len, read_cb, cb_arg); + } + return 0; } #endif @@ -3974,62 +3974,62 @@ static int sc_commit(void); #endif void bt_gatt_connected(struct bt_conn *conn) { - struct conn_data data; + struct conn_data data; - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - data.conn = conn; - data.sec = BT_SECURITY_L1; + data.conn = conn; + data.sec = BT_SECURITY_L1; - /* Load CCC settings from backend if bonded */ - if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) && - bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { - char key[BT_SETTINGS_KEY_MAX]; + /* Load CCC settings from backend if bonded */ + if (IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) && + bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { + char key[BT_SETTINGS_KEY_MAX]; - if (conn->id) { - char id_str[4]; + if (conn->id) { + char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), conn->id); - bt_settings_encode_key(key, sizeof(key), "ccc", - &conn->le.dst, id_str); - } else { - bt_settings_encode_key(key, sizeof(key), "ccc", - &conn->le.dst, NULL); - } + u8_to_dec(id_str, sizeof(id_str), conn->id); + bt_settings_encode_key(key, sizeof(key), "ccc", + &conn->le.dst, id_str); + } else { + bt_settings_encode_key(key, sizeof(key), "ccc", + &conn->le.dst, NULL); + } #if defined(BFLB_BLE) ccc_set(key, conn->id, &conn->le.dst); #else - settings_load_subtree_direct(key, ccc_set_direct, (void *)key); + settings_load_subtree_direct(key, ccc_set_direct, (void *)key); #endif - } + } - bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data); + bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data); - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192: - * - * 10.3.1.1 Handling of GATT indications and notifications - * - * A client requests a server to send indications and notifications - * by appropriately configuring the server via a Client Characteristic - * Configuration Descriptor. Since the configuration is persistent - * across a disconnection and reconnection, security requirements must - * be checked against the configuration upon a reconnection before - * sending indications or notifications. When a server reconnects to a - * client to send an indication or notification for which security is - * required, the server shall initiate or request encryption with the - * client prior to sending an indication or notification. If the client - * does not have an LTK indicating that the client has lost the bond, - * enabling encryption will fail. - */ - if (IS_ENABLED(CONFIG_BT_SMP) && - bt_conn_get_security(conn) < data.sec) { - bt_conn_set_security(conn, data.sec); - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part C page 2192: + * + * 10.3.1.1 Handling of GATT indications and notifications + * + * A client requests a server to send indications and notifications + * by appropriately configuring the server via a Client Characteristic + * Configuration Descriptor. Since the configuration is persistent + * across a disconnection and reconnection, security requirements must + * be checked against the configuration upon a reconnection before + * sending indications or notifications. When a server reconnects to a + * client to send an indication or notification for which security is + * required, the server shall initiate or request encryption with the + * client prior to sending an indication or notification. If the client + * does not have an LTK indicating that the client has lost the bond, + * enabling encryption will fail. + */ + if (IS_ENABLED(CONFIG_BT_SMP) && + bt_conn_get_security(conn) < data.sec) { + bt_conn_set_security(conn, data.sec); + } #if defined(CONFIG_BT_GATT_CLIENT) - add_subscriptions(conn); + add_subscriptions(conn); #endif /* CONFIG_BT_GATT_CLIENT */ - + #if defined(BFLB_BLE) #if defined(CONFIG_BT_GATT_SERVICE_CHANGED) #if defined(CONFIG_BT_SETTINGS) @@ -4042,367 +4042,367 @@ void bt_gatt_connected(struct bt_conn *conn) void bt_gatt_encrypt_change(struct bt_conn *conn) { - struct conn_data data; + struct conn_data data; - BT_DBG("conn %p", conn); + BT_DBG("conn %p", conn); - data.conn = conn; - data.sec = BT_SECURITY_L1; + data.conn = conn; + data.sec = BT_SECURITY_L1; - bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data); + bt_gatt_foreach_attr(0x0001, 0xffff, update_ccc, &data); } bool bt_gatt_change_aware(struct bt_conn *conn, bool req) { #if defined(CONFIG_BT_GATT_CACHING) - struct gatt_cf_cfg *cfg; + struct gatt_cf_cfg *cfg; - cfg = find_cf_cfg(conn); - if (!cfg || !CF_ROBUST_CACHING(cfg)) { - return true; - } + cfg = find_cf_cfg(conn); + if (!cfg || !CF_ROBUST_CACHING(cfg)) { + return true; + } - if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) { - return true; - } + if (atomic_test_bit(cfg->flags, CF_CHANGE_AWARE)) { + return true; + } - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: - * If a change-unaware client sends an ATT command, the server shall - * ignore it. - */ - if (!req) { - return false; - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2350: + * If a change-unaware client sends an ATT command, the server shall + * ignore it. + */ + if (!req) { + return false; + } - /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: - * 2.5.2.1 Robust Caching - * A connected client becomes change-aware when... - * The server sends the client a response with the error code set to - * Database Out Of Sync and then the server receives another ATT - * request from the client. - */ - if (atomic_test_bit(cfg->flags, CF_OUT_OF_SYNC)) { - atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC); - atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); - BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); - return true; - } + /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G page 2347: + * 2.5.2.1 Robust Caching + * A connected client becomes change-aware when... + * The server sends the client a response with the error code set to + * Database Out Of Sync and then the server receives another ATT + * request from the client. + */ + if (atomic_test_bit(cfg->flags, CF_OUT_OF_SYNC)) { + atomic_clear_bit(cfg->flags, CF_OUT_OF_SYNC); + atomic_set_bit(cfg->flags, CF_CHANGE_AWARE); + BT_DBG("%s change-aware", bt_addr_le_str(&cfg->peer)); + return true; + } - atomic_set_bit(cfg->flags, CF_OUT_OF_SYNC); + atomic_set_bit(cfg->flags, CF_OUT_OF_SYNC); - return false; + return false; #else - return true; + return true; #endif } static int bt_gatt_store_cf(struct bt_conn *conn) { #if defined(CONFIG_BT_GATT_CACHING) - struct gatt_cf_cfg *cfg; - char key[BT_SETTINGS_KEY_MAX]; - char *str; - size_t len; - int err; + struct gatt_cf_cfg *cfg; + char key[BT_SETTINGS_KEY_MAX]; + char *str; + size_t len; + int err; - cfg = find_cf_cfg(conn); - if (!cfg) { - /* No cfg found, just clear it */ - BT_DBG("No config for CF"); - str = NULL; - len = 0; - } else { - str = (char *)cfg->data; - len = sizeof(cfg->data); + cfg = find_cf_cfg(conn); + if (!cfg) { + /* No cfg found, just clear it */ + BT_DBG("No config for CF"); + str = NULL; + len = 0; + } else { + str = (char *)cfg->data; + len = sizeof(cfg->data); - if (conn->id) { - char id_str[4]; + if (conn->id) { + char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), conn->id); - bt_settings_encode_key(key, sizeof(key), "cf", - &conn->le.dst, id_str); - } - } + u8_to_dec(id_str, sizeof(id_str), conn->id); + bt_settings_encode_key(key, sizeof(key), "cf", + &conn->le.dst, id_str); + } + } - if (!cfg || !conn->id) { - bt_settings_encode_key(key, sizeof(key), "cf", - &conn->le.dst, NULL); - } + if (!cfg || !conn->id) { + bt_settings_encode_key(key, sizeof(key), "cf", + &conn->le.dst, NULL); + } - err = settings_save_one(key, str, len); - if (err) { - BT_ERR("Failed to store Client Features (err %d)", err); - return err; - } + err = settings_save_one(key, str, len); + if (err) { + BT_ERR("Failed to store Client Features (err %d)", err); + return err; + } - BT_DBG("Stored CF for %s (%s)", bt_addr_le_str(&conn->le.dst), log_strdup(key)); + BT_DBG("Stored CF for %s (%s)", bt_addr_le_str(&conn->le.dst), log_strdup(key)); #endif /* CONFIG_BT_GATT_CACHING */ - return 0; + return 0; } void bt_gatt_disconnected(struct bt_conn *conn) { - BT_DBG("conn %p", conn); - bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn); + BT_DBG("conn %p", conn); + bt_gatt_foreach_attr(0x0001, 0xffff, disconnected_cb, conn); #if defined(CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE) - gatt_ccc_conn_unqueue(conn); + gatt_ccc_conn_unqueue(conn); - if (gatt_ccc_conn_queue_is_empty()) { - k_delayed_work_cancel(&gatt_ccc_store.work); - } + if (gatt_ccc_conn_queue_is_empty()) { + k_delayed_work_cancel(&gatt_ccc_store.work); + } #endif - if (IS_ENABLED(CONFIG_BT_SETTINGS) && - bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { - bt_gatt_store_ccc(conn->id, &conn->le.dst); - bt_gatt_store_cf(conn); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && + bt_addr_le_is_bonded(conn->id, &conn->le.dst)) { + bt_gatt_store_ccc(conn->id, &conn->le.dst); + bt_gatt_store_cf(conn); + } #if defined(CONFIG_BT_GATT_CLIENT) - remove_subscriptions(conn); + remove_subscriptions(conn); #endif /* CONFIG_BT_GATT_CLIENT */ #if defined(CONFIG_BT_GATT_CACHING) - remove_cf_cfg(conn); + remove_cf_cfg(conn); #endif } #if defined(CONFIG_BT_SETTINGS) struct ccc_save { - struct addr_with_id addr_with_id; - struct ccc_store store[CCC_STORE_MAX]; - size_t count; + struct addr_with_id addr_with_id; + struct ccc_store store[CCC_STORE_MAX]; + size_t count; }; static u8_t ccc_save(const struct bt_gatt_attr *attr, void *user_data) { - struct ccc_save *save = user_data; - struct _bt_gatt_ccc *ccc; - struct bt_gatt_ccc_cfg *cfg; + struct ccc_save *save = user_data; + struct _bt_gatt_ccc *ccc; + struct bt_gatt_ccc_cfg *cfg; - /* Check if attribute is a CCC */ - if (attr->write != bt_gatt_attr_write_ccc) { - return BT_GATT_ITER_CONTINUE; - } + /* Check if attribute is a CCC */ + if (attr->write != bt_gatt_attr_write_ccc) { + return BT_GATT_ITER_CONTINUE; + } - ccc = attr->user_data; + ccc = attr->user_data; - /* Check if there is a cfg for the peer */ - cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id); - if (!cfg) { - return BT_GATT_ITER_CONTINUE; - } + /* Check if there is a cfg for the peer */ + cfg = ccc_find_cfg(ccc, save->addr_with_id.addr, save->addr_with_id.id); + if (!cfg) { + return BT_GATT_ITER_CONTINUE; + } - BT_DBG("Storing CCCs handle 0x%04x value 0x%04x", attr->handle, - cfg->value); + BT_DBG("Storing CCCs handle 0x%04x value 0x%04x", attr->handle, + cfg->value); - save->store[save->count].handle = attr->handle; - save->store[save->count].value = cfg->value; - save->count++; + save->store[save->count].handle = attr->handle; + save->store[save->count].value = cfg->value; + save->count++; - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } int bt_gatt_store_ccc(u8_t id, const bt_addr_le_t *addr) { - struct ccc_save save; - char key[BT_SETTINGS_KEY_MAX]; - size_t len; - char *str; - int err; + struct ccc_save save; + char key[BT_SETTINGS_KEY_MAX]; + size_t len; + char *str; + int err; - save.addr_with_id.addr = addr; - save.addr_with_id.id = id; - save.count = 0; + save.addr_with_id.addr = addr; + save.addr_with_id.id = id; + save.count = 0; - bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save); + bt_gatt_foreach_attr(0x0001, 0xffff, ccc_save, &save); - if (id) { - char id_str[4]; + if (id) { + char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), id); - bt_settings_encode_key(key, sizeof(key), "ccc", - (bt_addr_le_t *)addr, id_str); - } else { - bt_settings_encode_key(key, sizeof(key), "ccc", - (bt_addr_le_t *)addr, NULL); - } + u8_to_dec(id_str, sizeof(id_str), id); + bt_settings_encode_key(key, sizeof(key), "ccc", + (bt_addr_le_t *)addr, id_str); + } else { + bt_settings_encode_key(key, sizeof(key), "ccc", + (bt_addr_le_t *)addr, NULL); + } - if (save.count) { - str = (char *)save.store; - len = save.count * sizeof(*save.store); - } else { - /* No entries to encode, just clear */ - str = NULL; - len = 0; - } + if (save.count) { + str = (char *)save.store; + len = save.count * sizeof(*save.store); + } else { + /* No entries to encode, just clear */ + str = NULL; + len = 0; + } - err = settings_save_one(key, (const u8_t *)str, len); - if (err) { - BT_ERR("Failed to store CCCs (err %d)", err); - return err; - } + err = settings_save_one(key, (const u8_t *)str, len); + if (err) { + BT_ERR("Failed to store CCCs (err %d)", err); + return err; + } - BT_DBG("Stored CCCs for %s (%s)", bt_addr_le_str(addr), - log_strdup(key)); - if (len) { - for (int i = 0; i < save.count; i++) { - BT_DBG(" CCC: handle 0x%04x value 0x%04x", - save.store[i].handle, save.store[i].value); - } - } else { - BT_DBG(" CCC: NULL"); - } + BT_DBG("Stored CCCs for %s (%s)", bt_addr_le_str(addr), + log_strdup(key)); + if (len) { + for (int i = 0; i < save.count; i++) { + BT_DBG(" CCC: handle 0x%04x value 0x%04x", + save.store[i].handle, save.store[i].value); + } + } else { + BT_DBG(" CCC: NULL"); + } - return 0; + return 0; } static u8_t remove_peer_from_attr(const struct bt_gatt_attr *attr, - void *user_data) + void *user_data) { - const struct addr_with_id *addr_with_id = user_data; - struct _bt_gatt_ccc *ccc; - struct bt_gatt_ccc_cfg *cfg; + const struct addr_with_id *addr_with_id = user_data; + struct _bt_gatt_ccc *ccc; + struct bt_gatt_ccc_cfg *cfg; - /* Check if attribute is a CCC */ - if (attr->write != bt_gatt_attr_write_ccc) { - return BT_GATT_ITER_CONTINUE; - } + /* Check if attribute is a CCC */ + if (attr->write != bt_gatt_attr_write_ccc) { + return BT_GATT_ITER_CONTINUE; + } - ccc = attr->user_data; + ccc = attr->user_data; - /* Check if there is a cfg for the peer */ - cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id); - if (cfg) { - memset(cfg, 0, sizeof(*cfg)); - } + /* Check if there is a cfg for the peer */ + cfg = ccc_find_cfg(ccc, addr_with_id->addr, addr_with_id->id); + if (cfg) { + memset(cfg, 0, sizeof(*cfg)); + } - return BT_GATT_ITER_CONTINUE; + return BT_GATT_ITER_CONTINUE; } static int bt_gatt_clear_ccc(u8_t id, const bt_addr_le_t *addr) { - char key[BT_SETTINGS_KEY_MAX]; - struct addr_with_id addr_with_id = { - .addr = addr, - .id = id, - }; + char key[BT_SETTINGS_KEY_MAX]; + struct addr_with_id addr_with_id = { + .addr = addr, + .id = id, + }; - if (id) { - char id_str[4]; + if (id) { + char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), id); - bt_settings_encode_key(key, sizeof(key), "ccc", - (bt_addr_le_t *)addr, id_str); - } else { - bt_settings_encode_key(key, sizeof(key), "ccc", - (bt_addr_le_t *)addr, NULL); - } + u8_to_dec(id_str, sizeof(id_str), id); + bt_settings_encode_key(key, sizeof(key), "ccc", + (bt_addr_le_t *)addr, id_str); + } else { + bt_settings_encode_key(key, sizeof(key), "ccc", + (bt_addr_le_t *)addr, NULL); + } - bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr, - &addr_with_id); + bt_gatt_foreach_attr(0x0001, 0xffff, remove_peer_from_attr, + &addr_with_id); - return settings_delete(key); + return settings_delete(key); } #if defined(CONFIG_BT_GATT_CACHING) static struct gatt_cf_cfg *find_cf_cfg_by_addr(const bt_addr_le_t *addr) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { - if (!bt_addr_le_cmp(addr, &cf_cfg[i].peer)) { - return &cf_cfg[i]; - } - } + for (i = 0; i < ARRAY_SIZE(cf_cfg); i++) { + if (!bt_addr_le_cmp(addr, &cf_cfg[i].peer)) { + return &cf_cfg[i]; + } + } - return NULL; + return NULL; } #endif /* CONFIG_BT_GATT_CACHING */ static int bt_gatt_clear_cf(u8_t id, const bt_addr_le_t *addr) { #if defined(CONFIG_BT_GATT_CACHING) - char key[BT_SETTINGS_KEY_MAX]; - struct gatt_cf_cfg *cfg; + char key[BT_SETTINGS_KEY_MAX]; + struct gatt_cf_cfg *cfg; - if (id) { - char id_str[4]; + if (id) { + char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), id); - bt_settings_encode_key(key, sizeof(key), "cf", - (bt_addr_le_t *)addr, id_str); - } else { - bt_settings_encode_key(key, sizeof(key), "cf", - (bt_addr_le_t *)addr, NULL); - } + u8_to_dec(id_str, sizeof(id_str), id); + bt_settings_encode_key(key, sizeof(key), "cf", + (bt_addr_le_t *)addr, id_str); + } else { + bt_settings_encode_key(key, sizeof(key), "cf", + (bt_addr_le_t *)addr, NULL); + } - cfg = find_cf_cfg_by_addr(addr); - if (cfg) { - clear_cf_cfg(cfg); - } + cfg = find_cf_cfg_by_addr(addr); + if (cfg) { + clear_cf_cfg(cfg); + } - return settings_delete(key); + return settings_delete(key); #endif /* CONFIG_BT_GATT_CACHING */ - return 0; + return 0; } static int sc_clear_by_addr(u8_t id, const bt_addr_le_t *addr) { - if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) { - struct gatt_sc_cfg *cfg; + if (IS_ENABLED(CONFIG_BT_GATT_SERVICE_CHANGED)) { + struct gatt_sc_cfg *cfg; - cfg = find_sc_cfg(id, (bt_addr_le_t *)addr); - if (cfg) { - sc_clear(cfg); - } - } - return 0; + cfg = find_sc_cfg(id, (bt_addr_le_t *)addr); + if (cfg) { + sc_clear(cfg); + } + } + return 0; } static void bt_gatt_clear_subscriptions(const bt_addr_le_t *addr) { #if defined(CONFIG_BT_GATT_CLIENT) - struct bt_gatt_subscribe_params *params, *tmp; - sys_snode_t *prev = NULL; + struct bt_gatt_subscribe_params *params, *tmp; + sys_snode_t *prev = NULL; - SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) { - if (bt_addr_le_cmp(addr, ¶ms->_peer)) { - prev = ¶ms->node; - continue; - } - params->value = 0U; - gatt_subscription_remove(NULL, prev, params); - } + SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&subscriptions, params, tmp, node) { + if (bt_addr_le_cmp(addr, ¶ms->_peer)) { + prev = ¶ms->node; + continue; + } + params->value = 0U; + gatt_subscription_remove(NULL, prev, params); + } #endif /* CONFIG_BT_GATT_CLIENT */ } int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr) { - int err; + int err; - err = bt_gatt_clear_ccc(id, addr); - if (err < 0) { - return err; - } + err = bt_gatt_clear_ccc(id, addr); + if (err < 0) { + return err; + } - err = sc_clear_by_addr(id, addr); - if (err < 0) { - return err; - } + err = sc_clear_by_addr(id, addr); + if (err < 0) { + return err; + } - err = bt_gatt_clear_cf(id, addr); - if (err < 0) { - return err; - } + err = bt_gatt_clear_cf(id, addr); + if (err < 0) { + return err; + } - bt_gatt_clear_subscriptions(addr); + bt_gatt_clear_subscriptions(addr); - return 0; + return 0; } #if defined(CONFIG_BT_GATT_SERVICE_CHANGED) @@ -4410,112 +4410,112 @@ int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr) static int sc_set(u8_t id, bt_addr_le_t *addr) #else static int sc_set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) #endif { - struct gatt_sc_cfg *cfg; + struct gatt_sc_cfg *cfg; #if !defined(BFLB_BLE) - u8_t id; - bt_addr_le_t addr; - int len, err; - const char *next; + u8_t id; + bt_addr_le_t addr; + int len, err; + const char *next; #endif #if defined(BFLB_BLE) int err; char key[BT_SETTINGS_KEY_MAX]; - + cfg = find_sc_cfg(id, addr); if (!cfg) { - /* Find and initialize a free sc_cfg entry */ - cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); - if (!cfg) { - BT_ERR("Unable to restore SC: no cfg left"); - return -ENOMEM; - } + /* Find and initialize a free sc_cfg entry */ + cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); + if (!cfg) { + BT_ERR("Unable to restore SC: no cfg left"); + return -ENOMEM; + } - cfg->id = id; - bt_addr_le_copy(&cfg->peer, addr); - } + cfg->id = id; + bt_addr_le_copy(&cfg->peer, addr); + } if(id){ char id_str[4]; - u8_to_dec(id_str, sizeof(id_str), id); - bt_settings_encode_key(key, sizeof(key), "sc", - addr, id_str); + u8_to_dec(id_str, sizeof(id_str), id); + bt_settings_encode_key(key, sizeof(key), "sc", + addr, id_str); }else{ bt_settings_encode_key(key, sizeof(key), "sc", - addr, NULL); + addr, NULL); } - + err = bt_settings_get_bin(key, (u8_t *)cfg, sizeof(*cfg), NULL); if(err) memset(cfg, 0, sizeof(*cfg)); return err; #else - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -EINVAL; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -EINVAL; + } - err = bt_settings_decode_key(name, &addr); - if (err) { - BT_ERR("Unable to decode address %s", log_strdup(name)); - return -EINVAL; - } + err = bt_settings_decode_key(name, &addr); + if (err) { + BT_ERR("Unable to decode address %s", log_strdup(name)); + return -EINVAL; + } - settings_name_next(name, &next); + settings_name_next(name, &next); - if (!next) { - id = BT_ID_DEFAULT; - } else { - id = strtol(next, NULL, 10); - } + if (!next) { + id = BT_ID_DEFAULT; + } else { + id = strtol(next, NULL, 10); + } - cfg = find_sc_cfg(id, &addr); - if (!cfg && len_rd) { - /* Find and initialize a free sc_cfg entry */ - cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); - if (!cfg) { - BT_ERR("Unable to restore SC: no cfg left"); - return -ENOMEM; - } + cfg = find_sc_cfg(id, &addr); + if (!cfg && len_rd) { + /* Find and initialize a free sc_cfg entry */ + cfg = find_sc_cfg(BT_ID_DEFAULT, BT_ADDR_LE_ANY); + if (!cfg) { + BT_ERR("Unable to restore SC: no cfg left"); + return -ENOMEM; + } - cfg->id = id; - bt_addr_le_copy(&cfg->peer, &addr); - } + cfg->id = id; + bt_addr_le_copy(&cfg->peer, &addr); + } - if (len_rd) { - len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data)); - if (len < 0) { - BT_ERR("Failed to decode value (err %d)", len); - return len; - } - BT_DBG("Read SC: len %d", len); + if (len_rd) { + len = read_cb(cb_arg, &cfg->data, sizeof(cfg->data)); + if (len < 0) { + BT_ERR("Failed to decode value (err %d)", len); + return len; + } + BT_DBG("Read SC: len %d", len); - BT_DBG("Restored SC for %s", bt_addr_le_str(&addr)); - } else if (cfg) { - /* Clear configuration */ - memset(cfg, 0, sizeof(*cfg)); + BT_DBG("Restored SC for %s", bt_addr_le_str(&addr)); + } else if (cfg) { + /* Clear configuration */ + memset(cfg, 0, sizeof(*cfg)); - BT_DBG("Removed SC for %s", bt_addr_le_str(&addr)); - } + BT_DBG("Removed SC for %s", bt_addr_le_str(&addr)); + } - return 0; + return 0; #endif } static int sc_commit(void) { - atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING); + atomic_clear_bit(gatt_sc.flags, SC_INDICATE_PENDING); - if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { - /* Schedule SC indication since the range has changed */ - k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT); - } + if (atomic_test_bit(gatt_sc.flags, SC_RANGE_CHANGED)) { + /* Schedule SC indication since the range has changed */ + k_delayed_work_submit(&gatt_sc.work, SC_TIMEOUT); + } - return 0; + return 0; } #if !defined(BFLB_BLE) @@ -4525,47 +4525,47 @@ SETTINGS_STATIC_HANDLER_DEFINE(bt_sc, "bt/sc", NULL, sc_set, sc_commit, NULL); #if defined(CONFIG_BT_GATT_CACHING) static int cf_set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) { - struct gatt_cf_cfg *cfg; - bt_addr_le_t addr; - int len, err; + struct gatt_cf_cfg *cfg; + bt_addr_le_t addr; + int len, err; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -EINVAL; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -EINVAL; + } - err = bt_settings_decode_key(name, &addr); - if (err) { - BT_ERR("Unable to decode address %s", log_strdup(name)); - return -EINVAL; - } + err = bt_settings_decode_key(name, &addr); + if (err) { + BT_ERR("Unable to decode address %s", log_strdup(name)); + return -EINVAL; + } - cfg = find_cf_cfg_by_addr(&addr); - if (!cfg) { - cfg = find_cf_cfg(NULL); - if (!cfg) { - BT_ERR("Unable to restore CF: no cfg left"); - return 0; - } - } + cfg = find_cf_cfg_by_addr(&addr); + if (!cfg) { + cfg = find_cf_cfg(NULL); + if (!cfg) { + BT_ERR("Unable to restore CF: no cfg left"); + return 0; + } + } - if (len_rd) { - len = read_cb(cb_arg, cfg->data, sizeof(cfg->data)); - if (len < 0) { - BT_ERR("Failed to decode value (err %d)", len); - return len; - } + if (len_rd) { + len = read_cb(cb_arg, cfg->data, sizeof(cfg->data)); + if (len < 0) { + BT_ERR("Failed to decode value (err %d)", len); + return len; + } - BT_DBG("Read CF: len %d", len); - } else { - clear_cf_cfg(cfg); - } + BT_DBG("Read CF: len %d", len); + } else { + clear_cf_cfg(cfg); + } - BT_DBG("Restored CF for %s", bt_addr_le_str(&addr)); + BT_DBG("Restored CF for %s", bt_addr_le_str(&addr)); - return 0; + return 0; } SETTINGS_STATIC_HANDLER_DEFINE(bt_cf, "bt/cf", NULL, cf_set, NULL, NULL); @@ -4573,54 +4573,54 @@ SETTINGS_STATIC_HANDLER_DEFINE(bt_cf, "bt/cf", NULL, cf_set, NULL, NULL); static u8_t stored_hash[16]; static int db_hash_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *cb_arg) + settings_read_cb read_cb, void *cb_arg) { - int len; + int len; - len = read_cb(cb_arg, stored_hash, sizeof(stored_hash)); - if (len < 0) { - BT_ERR("Failed to decode value (err %d)", len); - return len; - } + len = read_cb(cb_arg, stored_hash, sizeof(stored_hash)); + if (len < 0) { + BT_ERR("Failed to decode value (err %d)", len); + return len; + } - BT_HEXDUMP_DBG(stored_hash, sizeof(stored_hash), "Stored Hash: "); + BT_HEXDUMP_DBG(stored_hash, sizeof(stored_hash), "Stored Hash: "); - return 0; + return 0; } static int db_hash_commit(void) { - /* Stop work and generate the hash */ - if (k_delayed_work_remaining_get(&db_hash_work)) { - k_delayed_work_cancel(&db_hash_work); - db_hash_gen(false); - } + /* Stop work and generate the hash */ + if (k_delayed_work_remaining_get(&db_hash_work)) { + k_delayed_work_cancel(&db_hash_work); + db_hash_gen(false); + } - /* Check if hash matches then skip SC update */ - if (!memcmp(stored_hash, db_hash, sizeof(stored_hash))) { - BT_DBG("Database Hash matches"); - k_delayed_work_cancel(&gatt_sc.work); - return 0; - } + /* Check if hash matches then skip SC update */ + if (!memcmp(stored_hash, db_hash, sizeof(stored_hash))) { + BT_DBG("Database Hash matches"); + k_delayed_work_cancel(&gatt_sc.work); + return 0; + } - BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "New Hash: "); + BT_HEXDUMP_DBG(db_hash, sizeof(db_hash), "New Hash: "); - /** - * GATT database has been modified since last boot, likely due to - * a firmware update or a dynamic service that was not re-registered on - * boot. Indicate Service Changed to all bonded devices for the full - * database range to invalidate client-side cache and force discovery on - * reconnect. - */ - sc_indicate(0x0001, 0xffff); + /** + * GATT database has been modified since last boot, likely due to + * a firmware update or a dynamic service that was not re-registered on + * boot. Indicate Service Changed to all bonded devices for the full + * database range to invalidate client-side cache and force discovery on + * reconnect. + */ + sc_indicate(0x0001, 0xffff); - /* Hash did not match overwrite with current hash */ - db_hash_store(); + /* Hash did not match overwrite with current hash */ + db_hash_store(); - return 0; + return 0; } SETTINGS_STATIC_HANDLER_DEFINE(bt_hash, "bt/hash", NULL, db_hash_set, - db_hash_commit, NULL); + db_hash_commit, NULL); #endif /*CONFIG_BT_GATT_CACHING */ #endif /* CONFIG_BT_SETTINGS */ diff --git a/components/network/ble/blestack/src/host/gatt_internal.h b/components/network/ble/blestack/src/host/gatt_internal.h index 63f03731..240949e6 100644 --- a/components/network/ble/blestack/src/host/gatt_internal.h +++ b/components/network/ble/blestack/src/host/gatt_internal.h @@ -8,21 +8,21 @@ * SPDX-License-Identifier: Apache-2.0 */ -#define BT_GATT_CENTRAL_ADDR_RES_NOT_SUPP 0 -#define BT_GATT_CENTRAL_ADDR_RES_SUPP 1 +#define BT_GATT_CENTRAL_ADDR_RES_NOT_SUPP 0 +#define BT_GATT_CENTRAL_ADDR_RES_SUPP 1 #include -#define BT_GATT_PERM_READ_MASK (BT_GATT_PERM_READ | \ - BT_GATT_PERM_READ_ENCRYPT | \ - BT_GATT_PERM_READ_AUTHEN) -#define BT_GATT_PERM_WRITE_MASK (BT_GATT_PERM_WRITE | \ - BT_GATT_PERM_WRITE_ENCRYPT | \ - BT_GATT_PERM_WRITE_AUTHEN) -#define BT_GATT_PERM_ENCRYPT_MASK (BT_GATT_PERM_READ_ENCRYPT | \ - BT_GATT_PERM_WRITE_ENCRYPT) -#define BT_GATT_PERM_AUTHEN_MASK (BT_GATT_PERM_READ_AUTHEN | \ - BT_GATT_PERM_WRITE_AUTHEN) +#define BT_GATT_PERM_READ_MASK (BT_GATT_PERM_READ | \ + BT_GATT_PERM_READ_ENCRYPT | \ + BT_GATT_PERM_READ_AUTHEN) +#define BT_GATT_PERM_WRITE_MASK (BT_GATT_PERM_WRITE | \ + BT_GATT_PERM_WRITE_ENCRYPT | \ + BT_GATT_PERM_WRITE_AUTHEN) +#define BT_GATT_PERM_ENCRYPT_MASK (BT_GATT_PERM_READ_ENCRYPT | \ + BT_GATT_PERM_WRITE_ENCRYPT) +#define BT_GATT_PERM_AUTHEN_MASK (BT_GATT_PERM_READ_AUTHEN | \ + BT_GATT_PERM_WRITE_AUTHEN) void bt_gatt_init(void); #if defined(BFLB_BLE) @@ -40,10 +40,10 @@ int bt_gatt_clear(u8_t id, const bt_addr_le_t *addr); #if defined(CONFIG_BT_GATT_CLIENT) void bt_gatt_notification(struct bt_conn *conn, u16_t handle, - const void *data, u16_t length); + const void *data, u16_t length); #else static inline void bt_gatt_notification(struct bt_conn *conn, u16_t handle, - const void *data, u16_t length) + const void *data, u16_t length) { } #endif /* CONFIG_BT_GATT_CLIENT */ @@ -52,4 +52,4 @@ struct bt_gatt_attr; /* Check attribute permission */ u8_t bt_gatt_check_perm(struct bt_conn *conn, const struct bt_gatt_attr *attr, - u8_t mask); + u8_t mask); diff --git a/components/network/ble/blestack/src/host/hci_core.c b/components/network/ble/blestack/src/host/hci_core.c index 79736cc2..63633d26 100644 --- a/components/network/ble/blestack/src/host/hci_core.c +++ b/components/network/ble/blestack/src/host/hci_core.c @@ -74,30 +74,30 @@ static K_THREAD_STACK_DEFINE(tx_thread_stack, CONFIG_BT_HCI_TX_STACK_SIZE); static void init_work(struct k_work *work); struct bt_dev bt_dev = { - .init = _K_WORK_INITIALIZER(init_work), - /* Give cmd_sem allowing to send first HCI_Reset cmd, the only - * exception is if the controller requests to wait for an - * initial Command Complete for NOP. - */ + .init = _K_WORK_INITIALIZER(init_work), + /* Give cmd_sem allowing to send first HCI_Reset cmd, the only + * exception is if the controller requests to wait for an + * initial Command Complete for NOP. + */ #if defined(BFLB_BLE) #if !defined(CONFIG_BT_WAIT_NOP) - .ncmd_sem = _K_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1), + .ncmd_sem = _K_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1), #else - .ncmd_sem = _K_SEM_INITIALIZER(bt_dev.ncmd_sem, 0, 1), + .ncmd_sem = _K_SEM_INITIALIZER(bt_dev.ncmd_sem, 0, 1), #endif - .cmd_tx_queue = _K_FIFO_INITIALIZER(bt_dev.cmd_tx_queue), + .cmd_tx_queue = _K_FIFO_INITIALIZER(bt_dev.cmd_tx_queue), #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) - .rx_queue = Z_FIFO_INITIALIZER(bt_dev.rx_queue), + .rx_queue = Z_FIFO_INITIALIZER(bt_dev.rx_queue), #endif #else //BFLB_BLE #if !defined(CONFIG_BT_WAIT_NOP) - .ncmd_sem = Z_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1), + .ncmd_sem = Z_SEM_INITIALIZER(bt_dev.ncmd_sem, 1, 1), #else - .ncmd_sem = Z_SEM_INITIALIZER(bt_dev.ncmd_sem, 0, 1), + .ncmd_sem = Z_SEM_INITIALIZER(bt_dev.ncmd_sem, 0, 1), #endif - .cmd_tx_queue = Z_FIFO_INITIALIZER(bt_dev.cmd_tx_queue), + .cmd_tx_queue = Z_FIFO_INITIALIZER(bt_dev.cmd_tx_queue), #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) - .rx_queue = Z_FIFO_INITIALIZER(bt_dev.rx_queue), + .rx_queue = Z_FIFO_INITIALIZER(bt_dev.rx_queue), #endif #endif }; @@ -131,42 +131,42 @@ volatile u8_t event_flag = 0; #endif struct cmd_state_set { - atomic_t *target; - int bit; - bool val; + atomic_t *target; + int bit; + bool val; }; void cmd_state_set_init(struct cmd_state_set *state, atomic_t *target, int bit, - bool val) + bool val) { - state->target = target; - state->bit = bit; - state->val = val; + state->target = target; + state->bit = bit; + state->val = val; } struct cmd_data { - /** HCI status of the command completion */ - u8_t status; + /** HCI status of the command completion */ + u8_t status; - /** The command OpCode that the buffer contains */ - u16_t opcode; + /** The command OpCode that the buffer contains */ + u16_t opcode; - /** The state to update when command completes with success. */ - struct cmd_state_set *state; + /** The state to update when command completes with success. */ + struct cmd_state_set *state; - /** Used by bt_hci_cmd_send_sync. */ - struct k_sem *sync; + /** Used by bt_hci_cmd_send_sync. */ + struct k_sem *sync; }; struct acl_data { - /** BT_BUF_ACL_IN */ - u8_t type; + /** BT_BUF_ACL_IN */ + u8_t type; - /* Index into the bt_conn storage array */ - u8_t id; + /* Index into the bt_conn storage array */ + u8_t id; - /** ACL connection handle */ - u16_t handle; + /** ACL connection handle */ + u16_t handle; }; #if defined(BFLB_BLE) @@ -183,10 +183,10 @@ static struct cmd_data cmd_data[CONFIG_BT_HCI_CMD_COUNT]; */ #define CMD_BUF_SIZE BT_BUF_RX_SIZE NET_BUF_POOL_FIXED_DEFINE(hci_cmd_pool, CONFIG_BT_HCI_CMD_COUNT, - CMD_BUF_SIZE, NULL); + CMD_BUF_SIZE, NULL); NET_BUF_POOL_FIXED_DEFINE(hci_rx_pool, CONFIG_BT_RX_BUF_COUNT, - BT_BUF_RX_SIZE, NULL); + BT_BUF_RX_SIZE, NULL); #if defined(CONFIG_BT_CONN) /* Dedicated pool for HCI_Number_of_Completed_Packets. This event is always @@ -199,55 +199,55 @@ NET_BUF_POOL_FIXED_DEFINE(num_complete_pool, 1, BT_BUF_RX_SIZE, NULL); #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT) NET_BUF_POOL_FIXED_DEFINE(discardable_pool, CONFIG_BT_DISCARDABLE_BUF_COUNT, - BT_BUF_RX_SIZE, NULL); + BT_BUF_RX_SIZE, NULL); #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */ struct event_handler { - u8_t event; - u8_t min_len; - void (*handler)(struct net_buf *buf); + u8_t event; + u8_t min_len; + void (*handler)(struct net_buf *buf); }; #define EVENT_HANDLER(_evt, _handler, _min_len) \ { \ - .event = _evt, \ - .handler = _handler, \ - .min_len = _min_len, \ + .event = _evt, \ + .handler = _handler, \ + .min_len = _min_len, \ } static inline void handle_event(u8_t event, struct net_buf *buf, - const struct event_handler *handlers, - size_t num_handlers) + const struct event_handler *handlers, + size_t num_handlers) { - size_t i; + size_t i; - for (i = 0; i < num_handlers; i++) { - const struct event_handler *handler = &handlers[i]; + for (i = 0; i < num_handlers; i++) { + const struct event_handler *handler = &handlers[i]; - if (handler->event != event) { - continue; - } + if (handler->event != event) { + continue; + } - if (buf->len < handler->min_len) { - BT_ERR("Too small (%u bytes) event 0x%02x", - buf->len, event); - return; - } + if (buf->len < handler->min_len) { + BT_ERR("Too small (%u bytes) event 0x%02x", + buf->len, event); + return; + } - handler->handler(buf); - return; - } + handler->handler(buf); + return; + } - BT_WARN("Unhandled event 0x%02x len %u: %s", event, - buf->len, bt_hex(buf->data, buf->len)); + BT_WARN("Unhandled event 0x%02x len %u: %s", event, + buf->len, bt_hex(buf->data, buf->len)); } static inline bool is_wl_empty(void) { #if defined(CONFIG_BT_WHITELIST) - return !bt_dev.le.wl_entries; + return !bt_dev.le.wl_entries; #else - return true; + return true; #endif /* defined(CONFIG_BT_WHITELIST) */ } @@ -255,396 +255,396 @@ static inline bool is_wl_empty(void) static void report_completed_packet(struct net_buf *buf) { - struct bt_hci_cp_host_num_completed_packets *cp; - u16_t handle = acl(buf)->handle; - struct bt_hci_handle_count *hc; - struct bt_conn *conn; + struct bt_hci_cp_host_num_completed_packets *cp; + u16_t handle = acl(buf)->handle; + struct bt_hci_handle_count *hc; + struct bt_conn *conn; - net_buf_destroy(buf); + net_buf_destroy(buf); - /* Do nothing if controller to host flow control is not supported */ - if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) { - return; - } + /* Do nothing if controller to host flow control is not supported */ + if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) { + return; + } - conn = bt_conn_lookup_id(acl(buf)->id); - if (!conn) { - BT_WARN("Unable to look up conn with id 0x%02x", acl(buf)->id); - return; - } + conn = bt_conn_lookup_id(acl(buf)->id); + if (!conn) { + BT_WARN("Unable to look up conn with id 0x%02x", acl(buf)->id); + return; + } - if (conn->state != BT_CONN_CONNECTED && - conn->state != BT_CONN_DISCONNECT) { - BT_WARN("Not reporting packet for non-connected conn"); - bt_conn_unref(conn); - return; - } + if (conn->state != BT_CONN_CONNECTED && + conn->state != BT_CONN_DISCONNECT) { + BT_WARN("Not reporting packet for non-connected conn"); + bt_conn_unref(conn); + return; + } - bt_conn_unref(conn); + bt_conn_unref(conn); - BT_DBG("Reporting completed packet for handle %u", handle); + BT_DBG("Reporting completed packet for handle %u", handle); - buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, - sizeof(*cp) + sizeof(*hc)); - if (!buf) { - BT_ERR("Unable to allocate new HCI command"); - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, + sizeof(*cp) + sizeof(*hc)); + if (!buf) { + BT_ERR("Unable to allocate new HCI command"); + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->num_handles = sys_cpu_to_le16(1); + cp = net_buf_add(buf, sizeof(*cp)); + cp->num_handles = sys_cpu_to_le16(1); - hc = net_buf_add(buf, sizeof(*hc)); - hc->handle = sys_cpu_to_le16(handle); - hc->count = sys_cpu_to_le16(1); + hc = net_buf_add(buf, sizeof(*hc)); + hc->handle = sys_cpu_to_le16(handle); + hc->count = sys_cpu_to_le16(1); - bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf); + bt_hci_cmd_send(BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS, buf); } #define ACL_IN_SIZE BT_L2CAP_BUF_SIZE(CONFIG_BT_L2CAP_RX_MTU) NET_BUF_POOL_DEFINE(acl_in_pool, CONFIG_BT_ACL_RX_COUNT, ACL_IN_SIZE, - sizeof(struct acl_data), report_completed_packet); + sizeof(struct acl_data), report_completed_packet); #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */ struct net_buf *bt_hci_cmd_create(u16_t opcode, u8_t param_len) { - struct bt_hci_cmd_hdr *hdr; - struct net_buf *buf; + struct bt_hci_cmd_hdr *hdr; + struct net_buf *buf; - BT_DBG("opcode 0x%04x param_len %u", opcode, param_len); + BT_DBG("opcode 0x%04x param_len %u", opcode, param_len); - buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER); - __ASSERT_NO_MSG(buf); + buf = net_buf_alloc(&hci_cmd_pool, K_FOREVER); + __ASSERT_NO_MSG(buf); - BT_DBG("buf %p", buf); + BT_DBG("buf %p", buf); - net_buf_reserve(buf, BT_BUF_RESERVE); + net_buf_reserve(buf, BT_BUF_RESERVE); - bt_buf_set_type(buf, BT_BUF_CMD); + bt_buf_set_type(buf, BT_BUF_CMD); - cmd(buf)->opcode = opcode; - cmd(buf)->sync = NULL; - cmd(buf)->state = NULL; + cmd(buf)->opcode = opcode; + cmd(buf)->sync = NULL; + cmd(buf)->state = NULL; - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->opcode = sys_cpu_to_le16(opcode); - hdr->param_len = param_len; + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->opcode = sys_cpu_to_le16(opcode); + hdr->param_len = param_len; - return buf; + return buf; } int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf) { - if (!buf) { - buf = bt_hci_cmd_create(opcode, 0); - if (!buf) { - return -ENOBUFS; - } - } + if (!buf) { + buf = bt_hci_cmd_create(opcode, 0); + if (!buf) { + return -ENOBUFS; + } + } - BT_DBG("opcode 0x%04x len %u", opcode, buf->len); + BT_DBG("opcode 0x%04x len %u", opcode, buf->len); - /* Host Number of Completed Packets can ignore the ncmd value - * and does not generate any cmd complete/status events. - */ - if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) { - int err; + /* Host Number of Completed Packets can ignore the ncmd value + * and does not generate any cmd complete/status events. + */ + if (opcode == BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS) { + int err; - err = bt_send(buf); - if (err) { - BT_ERR("Unable to send to driver (err %d)", err); - net_buf_unref(buf); - } + err = bt_send(buf); + if (err) { + BT_ERR("Unable to send to driver (err %d)", err); + net_buf_unref(buf); + } - return err; - } + return err; + } - net_buf_put(&bt_dev.cmd_tx_queue, buf); + net_buf_put(&bt_dev.cmd_tx_queue, buf); #if defined(BFLB_BLE) k_sem_give(&g_poll_sem); #endif - return 0; + return 0; } int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf, - struct net_buf **rsp) + struct net_buf **rsp) { - struct k_sem sync_sem; - int err; + struct k_sem sync_sem; + int err; - if (!buf) { - buf = bt_hci_cmd_create(opcode, 0); - if (!buf) { - return -ENOBUFS; - } - } + if (!buf) { + buf = bt_hci_cmd_create(opcode, 0); + if (!buf) { + return -ENOBUFS; + } + } - BT_DBG("buf %p opcode 0x%04x len %u", buf, opcode, buf->len); + BT_DBG("buf %p opcode 0x%04x len %u", buf, opcode, buf->len); - k_sem_init(&sync_sem, 0, 1); - cmd(buf)->sync = &sync_sem; + k_sem_init(&sync_sem, 0, 1); + cmd(buf)->sync = &sync_sem; #if defined(BFLB_BLE) /*Assign a initial value to status in order to check if hci cmd timeout*/ cmd(buf)->status = 0xff; #endif - /* Make sure the buffer stays around until the command completes */ - net_buf_ref(buf); + /* Make sure the buffer stays around until the command completes */ + net_buf_ref(buf); - net_buf_put(&bt_dev.cmd_tx_queue, buf); + net_buf_put(&bt_dev.cmd_tx_queue, buf); #if defined(BFLB_BLE) k_sem_give(&g_poll_sem); #endif - err = k_sem_take(&sync_sem, HCI_CMD_TIMEOUT); + err = k_sem_take(&sync_sem, HCI_CMD_TIMEOUT); #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS k_sem_delete(&sync_sem); #endif - __ASSERT(err == 0, "k_sem_take failed with err %d", err); + __ASSERT(err == 0, "k_sem_take failed with err %d", err); - BT_DBG("opcode 0x%04x status 0x%02x", opcode, cmd(buf)->status); + BT_DBG("opcode 0x%04x status 0x%02x", opcode, cmd(buf)->status); - if (cmd(buf)->status) { - switch (cmd(buf)->status) { - case BT_HCI_ERR_CONN_LIMIT_EXCEEDED: - err = -ECONNREFUSED; - break; - #if defined(BFLB_BLE) - case 0xff: - err = -ETIME; + if (cmd(buf)->status) { + switch (cmd(buf)->status) { + case BT_HCI_ERR_CONN_LIMIT_EXCEEDED: + err = -ECONNREFUSED; + break; + #if defined(BFLB_BLE) + case 0xff: + err = -ETIME; BT_ERR("k_sem_take timeout with opcode 0x%04x", opcode); BT_ASSERT(err == 0); - break; - #endif - default: - err = -EIO; - break; - } + break; + #endif + default: + err = -EIO; + break; + } - net_buf_unref(buf); - } else { - err = 0; - if (rsp) { - *rsp = buf; - } else { - net_buf_unref(buf); - } - } + net_buf_unref(buf); + } else { + err = 0; + if (rsp) { + *rsp = buf; + } else { + net_buf_unref(buf); + } + } - return err; + return err; } #if defined(CONFIG_BT_OBSERVER) || defined(CONFIG_BT_CONN) const bt_addr_le_t *bt_lookup_id_addr(u8_t id, const bt_addr_le_t *addr) { - if (IS_ENABLED(CONFIG_BT_SMP)) { - struct bt_keys *keys; + if (IS_ENABLED(CONFIG_BT_SMP)) { + struct bt_keys *keys; - keys = bt_keys_find_irk(id, addr); - if (keys) { - BT_DBG("Identity %s matched RPA %s", - bt_addr_le_str(&keys->addr), - bt_addr_le_str(addr)); - return &keys->addr; - } - } + keys = bt_keys_find_irk(id, addr); + if (keys) { + BT_DBG("Identity %s matched RPA %s", + bt_addr_le_str(&keys->addr), + bt_addr_le_str(addr)); + return &keys->addr; + } + } - return addr; + return addr; } #endif /* CONFIG_BT_OBSERVER || CONFIG_BT_CONN */ static int set_advertise_enable(bool enable) { - struct net_buf *buf; - struct cmd_state_set state; - int err; + struct net_buf *buf; + struct cmd_state_set state; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1); + if (!buf) { + return -ENOBUFS; + } - if (enable) { - net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE); - } else { - net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE); - } + if (enable) { + net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE); + } else { + net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE); + } - cmd_state_set_init(&state, bt_dev.flags, BT_DEV_ADVERTISING, enable); - cmd(buf)->state = &state; + cmd_state_set_init(&state, bt_dev.flags, BT_DEV_ADVERTISING, enable); + cmd(buf)->state = &state; - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL); + if (err) { + return err; + } - return 0; + return 0; } static int set_random_address(const bt_addr_t *addr) { - struct net_buf *buf; - int err; + struct net_buf *buf; + int err; #if defined(CONFIG_BT_STACK_PTS) BT_PTS("set random address %s", bt_addr_str(addr)); #else - BT_DBG("%s", bt_addr_str(addr)); + BT_DBG("%s", bt_addr_str(addr)); #endif - /* Do nothing if we already have the right address */ - if (!bt_addr_cmp(addr, &bt_dev.random_addr.a)) { - return 0; - } + /* Do nothing if we already have the right address */ + if (!bt_addr_cmp(addr, &bt_dev.random_addr.a)) { + return 0; + } - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr)); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_mem(buf, addr, sizeof(*addr)); + net_buf_add_mem(buf, addr, sizeof(*addr)); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL); + if (err) { + return err; + } - bt_addr_copy(&bt_dev.random_addr.a, addr); - bt_dev.random_addr.type = BT_ADDR_LE_RANDOM; + bt_addr_copy(&bt_dev.random_addr.a, addr); + bt_dev.random_addr.type = BT_ADDR_LE_RANDOM; - return 0; + return 0; } int bt_addr_from_str(const char *str, bt_addr_t *addr) { - int i, j; - u8_t tmp; + int i, j; + u8_t tmp; - if (strlen(str) != 17U) { - return -EINVAL; - } + if (strlen(str) != 17U) { + return -EINVAL; + } - for (i = 5, j = 1; *str != '\0'; str++, j++) { - if (!(j % 3) && (*str != ':')) { - return -EINVAL; - } else if (*str == ':') { - i--; - continue; - } + for (i = 5, j = 1; *str != '\0'; str++, j++) { + if (!(j % 3) && (*str != ':')) { + return -EINVAL; + } else if (*str == ':') { + i--; + continue; + } - addr->val[i] = addr->val[i] << 4; + addr->val[i] = addr->val[i] << 4; - if (char2hex(*str, &tmp) < 0) { - return -EINVAL; - } + if (char2hex(*str, &tmp) < 0) { + return -EINVAL; + } - addr->val[i] |= tmp; - } + addr->val[i] |= tmp; + } - return 0; + return 0; } int bt_addr_le_from_str(const char *str, const char *type, bt_addr_le_t *addr) { - int err; + int err; - err = bt_addr_from_str(str, &addr->a); - if (err < 0) { - return err; - } + err = bt_addr_from_str(str, &addr->a); + if (err < 0) { + return err; + } - if (!strcmp(type, "public") || !strcmp(type, "(public)")) { - addr->type = BT_ADDR_LE_PUBLIC; - } else if (!strcmp(type, "random") || !strcmp(type, "(random)")) { - addr->type = BT_ADDR_LE_RANDOM; - } else if (!strcmp(type, "public-id") || !strcmp(type, "(public-id)")) { - addr->type = BT_ADDR_LE_PUBLIC_ID; - } else if (!strcmp(type, "random-id") || !strcmp(type, "(random-id)")) { - addr->type = BT_ADDR_LE_RANDOM_ID; - } else { - return -EINVAL; - } + if (!strcmp(type, "public") || !strcmp(type, "(public)")) { + addr->type = BT_ADDR_LE_PUBLIC; + } else if (!strcmp(type, "random") || !strcmp(type, "(random)")) { + addr->type = BT_ADDR_LE_RANDOM; + } else if (!strcmp(type, "public-id") || !strcmp(type, "(public-id)")) { + addr->type = BT_ADDR_LE_PUBLIC_ID; + } else if (!strcmp(type, "random-id") || !strcmp(type, "(random-id)")) { + addr->type = BT_ADDR_LE_RANDOM_ID; + } else { + return -EINVAL; + } - return 0; + return 0; } #if defined(CONFIG_BT_PRIVACY) /* this function sets new RPA only if current one is no longer valid */ static int le_set_private_addr(u8_t id) { - bt_addr_t rpa; - int err; + bt_addr_t rpa; + int err; - /* check if RPA is valid */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) { - return 0; - } + /* check if RPA is valid */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) { + return 0; + } - err = bt_rpa_create(bt_dev.irk[id], &rpa); - if (!err) { - err = set_random_address(&rpa); - if (!err) { - atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID); - } - } + err = bt_rpa_create(bt_dev.irk[id], &rpa); + if (!err) { + err = set_random_address(&rpa); + if (!err) { + atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID); + } + } - /* restart timer even if failed to set new RPA */ - k_delayed_work_submit(&bt_dev.rpa_update, RPA_TIMEOUT); + /* restart timer even if failed to set new RPA */ + k_delayed_work_submit(&bt_dev.rpa_update, RPA_TIMEOUT); - return err; + return err; } static void rpa_timeout(struct k_work *work) { - int err_adv = 0, err_scan = 0; + int err_adv = 0, err_scan = 0; - BT_DBG(""); + BT_DBG(""); - /* Invalidate RPA */ - atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); + /* Invalidate RPA */ + atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); - /* - * we need to update rpa only if advertising is ongoing, with - * BT_DEV_KEEP_ADVERTISING flag is handled in disconnected event - */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - /* make sure new address is used */ - set_advertise_enable(false); - err_adv = le_set_private_addr(bt_dev.adv_id); - set_advertise_enable(true); - } + /* + * we need to update rpa only if advertising is ongoing, with + * BT_DEV_KEEP_ADVERTISING flag is handled in disconnected event + */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + /* make sure new address is used */ + set_advertise_enable(false); + err_adv = le_set_private_addr(bt_dev.adv_id); + set_advertise_enable(true); + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) { - /* TODO do we need to toggle scan? */ - err_scan = le_set_private_addr(BT_ID_DEFAULT); - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) { + /* TODO do we need to toggle scan? */ + err_scan = le_set_private_addr(BT_ID_DEFAULT); + } - /* If both advertising and scanning is active, le_set_private_addr - * will fail. In this case, set back RPA_VALID so that if either of - * advertising or scanning was restarted by application then - * le_set_private_addr in the public API call path will not retry - * set_random_address. This is needed so as to be able to stop and - * restart either of the role by the application after rpa_timeout. - */ - if (err_adv || err_scan) { - atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID); - } + /* If both advertising and scanning is active, le_set_private_addr + * will fail. In this case, set back RPA_VALID so that if either of + * advertising or scanning was restarted by application then + * le_set_private_addr in the public API call path will not retry + * set_random_address. This is needed so as to be able to stop and + * restart either of the role by the application after rpa_timeout. + */ + if (err_adv || err_scan) { + atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID); + } } #if defined(CONFIG_BT_STACK_PTS) static int le_set_non_resolv_private_addr(u8_t id) { - bt_addr_t nrpa; - int err; + bt_addr_t nrpa; + int err; - err = bt_rand(nrpa.val, sizeof(nrpa.val)); - if (err) { - return err; - } + err = bt_rand(nrpa.val, sizeof(nrpa.val)); + if (err) { + return err; + } - nrpa.val[5] &= 0x3f; + nrpa.val[5] &= 0x3f; atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); - return set_random_address(&nrpa); + return set_random_address(&nrpa); } #endif @@ -652,462 +652,462 @@ static int le_set_non_resolv_private_addr(u8_t id) #else static int le_set_private_addr(u8_t id) { - bt_addr_t nrpa; - int err; + bt_addr_t nrpa; + int err; - err = bt_rand(nrpa.val, sizeof(nrpa.val)); - if (err) { - return err; - } + err = bt_rand(nrpa.val, sizeof(nrpa.val)); + if (err) { + return err; + } - nrpa.val[5] &= 0x3f; + nrpa.val[5] &= 0x3f; - return set_random_address(&nrpa); + return set_random_address(&nrpa); } #endif #if defined(CONFIG_BT_OBSERVER) static int set_le_scan_enable(u8_t enable) { - struct bt_hci_cp_le_set_scan_enable *cp; - struct net_buf *buf; - struct cmd_state_set state; - int err; + struct bt_hci_cp_le_set_scan_enable *cp; + struct net_buf *buf; + struct cmd_state_set state; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); - if (enable == BT_HCI_LE_SCAN_ENABLE) { - cp->filter_dup = atomic_test_bit(bt_dev.flags, - BT_DEV_SCAN_FILTER_DUP); - } else { - cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE; - } + if (enable == BT_HCI_LE_SCAN_ENABLE) { + cp->filter_dup = atomic_test_bit(bt_dev.flags, + BT_DEV_SCAN_FILTER_DUP); + } else { + cp->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE; + } - cp->enable = enable; + cp->enable = enable; - cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING, - enable == BT_HCI_LE_SCAN_ENABLE); - cmd(buf)->state = &state; + cmd_state_set_init(&state, bt_dev.flags, BT_DEV_SCANNING, + enable == BT_HCI_LE_SCAN_ENABLE); + cmd(buf)->state = &state; - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, NULL); + if (err) { + return err; + } - return 0; + return 0; } #endif /* CONFIG_BT_OBSERVER */ #if defined(CONFIG_BT_CONN) static void hci_acl(struct net_buf *buf) { - struct bt_hci_acl_hdr *hdr; - u16_t handle, len; - struct bt_conn *conn; - u8_t flags; + struct bt_hci_acl_hdr *hdr; + u16_t handle, len; + struct bt_conn *conn; + u8_t flags; - BT_DBG("buf %p", buf); + BT_DBG("buf %p", buf); - BT_ASSERT(buf->len >= sizeof(*hdr)); + BT_ASSERT(buf->len >= sizeof(*hdr)); - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - len = sys_le16_to_cpu(hdr->len); - handle = sys_le16_to_cpu(hdr->handle); - flags = bt_acl_flags(handle); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + len = sys_le16_to_cpu(hdr->len); + handle = sys_le16_to_cpu(hdr->handle); + flags = bt_acl_flags(handle); - acl(buf)->handle = bt_acl_handle(handle); - acl(buf)->id = BT_CONN_ID_INVALID; + acl(buf)->handle = bt_acl_handle(handle); + acl(buf)->id = BT_CONN_ID_INVALID; - BT_DBG("handle %u len %u flags %u", acl(buf)->handle, len, flags); + BT_DBG("handle %u len %u flags %u", acl(buf)->handle, len, flags); - if (buf->len != len) { - BT_ERR("ACL data length mismatch (%u != %u)", buf->len, len); - net_buf_unref(buf); - return; - } + if (buf->len != len) { + BT_ERR("ACL data length mismatch (%u != %u)", buf->len, len); + net_buf_unref(buf); + return; + } - conn = bt_conn_lookup_handle(acl(buf)->handle); - if (!conn) { - BT_ERR("Unable to find conn for handle %u", acl(buf)->handle); - net_buf_unref(buf); - return; - } + conn = bt_conn_lookup_handle(acl(buf)->handle); + if (!conn) { + BT_ERR("Unable to find conn for handle %u", acl(buf)->handle); + net_buf_unref(buf); + return; + } - acl(buf)->id = bt_conn_index(conn); + acl(buf)->id = bt_conn_index(conn); - bt_conn_recv(conn, buf, flags); - bt_conn_unref(conn); + bt_conn_recv(conn, buf, flags); + bt_conn_unref(conn); } static void hci_data_buf_overflow(struct net_buf *buf) { - struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data; + struct bt_hci_evt_data_buf_overflow *evt = (void *)buf->data; - BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type); + BT_WARN("Data buffer overflow (link type 0x%02x)", evt->link_type); // avoid compiler warning if BT_WARN is empty (void) evt; } static void hci_num_completed_packets(struct net_buf *buf) { - struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data; - int i; + struct bt_hci_evt_num_completed_packets *evt = (void *)buf->data; + int i; - BT_DBG("num_handles %u", evt->num_handles); + BT_DBG("num_handles %u", evt->num_handles); - for (i = 0; i < evt->num_handles; i++) { - u16_t handle, count; - struct bt_conn *conn; - unsigned int key; + for (i = 0; i < evt->num_handles; i++) { + u16_t handle, count; + struct bt_conn *conn; + unsigned int key; - handle = sys_le16_to_cpu(evt->h[i].handle); - count = sys_le16_to_cpu(evt->h[i].count); + handle = sys_le16_to_cpu(evt->h[i].handle); + count = sys_le16_to_cpu(evt->h[i].count); - BT_DBG("handle %u count %u", handle, count); + BT_DBG("handle %u count %u", handle, count); - key = irq_lock(); + key = irq_lock(); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - irq_unlock(key); - BT_ERR("No connection for handle %u", handle); - continue; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + irq_unlock(key); + BT_ERR("No connection for handle %u", handle); + continue; + } - irq_unlock(key); + irq_unlock(key); - while (count--) { - struct bt_conn_tx *tx; - sys_snode_t *node; + while (count--) { + struct bt_conn_tx *tx; + sys_snode_t *node; - key = irq_lock(); + key = irq_lock(); - if (conn->pending_no_cb) { - conn->pending_no_cb--; - irq_unlock(key); - k_sem_give(bt_conn_get_pkts(conn)); - continue; - } + if (conn->pending_no_cb) { + conn->pending_no_cb--; + irq_unlock(key); + k_sem_give(bt_conn_get_pkts(conn)); + continue; + } - node = sys_slist_get(&conn->tx_pending); - irq_unlock(key); + node = sys_slist_get(&conn->tx_pending); + irq_unlock(key); - if (!node) { - BT_ERR("packets count mismatch"); - break; - } + if (!node) { + BT_ERR("packets count mismatch"); + break; + } - tx = CONTAINER_OF(node, struct bt_conn_tx, node); + tx = CONTAINER_OF(node, struct bt_conn_tx, node); - key = irq_lock(); - conn->pending_no_cb = tx->pending_no_cb; - tx->pending_no_cb = 0U; - sys_slist_append(&conn->tx_complete, &tx->node); - irq_unlock(key); + key = irq_lock(); + conn->pending_no_cb = tx->pending_no_cb; + tx->pending_no_cb = 0U; + sys_slist_append(&conn->tx_complete, &tx->node); + irq_unlock(key); - k_work_submit(&conn->tx_complete_work); - k_sem_give(bt_conn_get_pkts(conn)); + k_work_submit(&conn->tx_complete_work); + k_sem_give(bt_conn_get_pkts(conn)); #if defined(BFLB_BLE) k_sem_give(&g_poll_sem); #endif - } + } - bt_conn_unref(conn); - } + bt_conn_unref(conn); + } } #if defined(CONFIG_BT_CENTRAL) #if defined(CONFIG_BT_WHITELIST) int bt_le_auto_conn(const struct bt_le_conn_param *conn_param) { - struct net_buf *buf; - struct cmd_state_set state; - struct bt_hci_cp_le_create_conn *cp; - u8_t own_addr_type; - int err; + struct net_buf *buf; + struct cmd_state_set state; + struct bt_hci_cp_le_create_conn *cp; + u8_t own_addr_type; + int err; - if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { - err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); - if (err) { - return err; - } - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { + err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); + if (err) { + return err; + } + } - #if defined(CONFIG_BT_STACK_PTS) - if(conn_param->own_address_type != BT_ADDR_LE_PUBLIC){ - #endif - - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - err = le_set_private_addr(BT_ID_DEFAULT); - if (err) { - return err; - } - if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - } else { - own_addr_type = BT_ADDR_LE_RANDOM; - } - } else { - const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT]; + #if defined(CONFIG_BT_STACK_PTS) + if(conn_param->own_address_type != BT_ADDR_LE_PUBLIC){ + #endif - /* If Static Random address is used as Identity address we - * need to restore it before creating connection. Otherwise - * NRPA used for active scan could be used for connection. - */ - if (addr->type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&addr->a); - if (err) { - return err; - } - } + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + err = le_set_private_addr(BT_ID_DEFAULT); + if (err) { + return err; + } + if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { + own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + } else { + own_addr_type = BT_ADDR_LE_RANDOM; + } + } else { + const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT]; - own_addr_type = addr->type; - } - - #if defined(CONFIG_BT_STACK_PTS) - }else{ - own_addr_type = conn_param->own_address_type; - } - #endif - - buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + /* If Static Random address is used as Identity address we + * need to restore it before creating connection. Otherwise + * NRPA used for active scan could be used for connection. + */ + if (addr->type == BT_ADDR_LE_RANDOM) { + err = set_random_address(&addr->a); + if (err) { + return err; + } + } - cp = net_buf_add(buf, sizeof(*cp)); - (void)memset(cp, 0, sizeof(*cp)); + own_addr_type = addr->type; + } - cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST; - cp->own_addr_type = own_addr_type; + #if defined(CONFIG_BT_STACK_PTS) + }else{ + own_addr_type = conn_param->own_address_type; + } + #endif - /* User Initiated procedure use fast scan parameters. */ - cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL); - cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW); + buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp->conn_interval_min = sys_cpu_to_le16(conn_param->interval_min); - cp->conn_interval_max = sys_cpu_to_le16(conn_param->interval_max); - cp->conn_latency = sys_cpu_to_le16(conn_param->latency); - cp->supervision_timeout = sys_cpu_to_le16(conn_param->timeout); + cp = net_buf_add(buf, sizeof(*cp)); + (void)memset(cp, 0, sizeof(*cp)); - cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, true); - cmd(buf)->state = &state; + cp->filter_policy = BT_HCI_LE_CREATE_CONN_FP_WHITELIST; + cp->own_addr_type = own_addr_type; - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL); + /* User Initiated procedure use fast scan parameters. */ + cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL); + cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW); + + cp->conn_interval_min = sys_cpu_to_le16(conn_param->interval_min); + cp->conn_interval_max = sys_cpu_to_le16(conn_param->interval_max); + cp->conn_latency = sys_cpu_to_le16(conn_param->latency); + cp->supervision_timeout = sys_cpu_to_le16(conn_param->timeout); + + cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, true); + cmd(buf)->state = &state; + + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL); } int bt_le_auto_conn_cancel(void) { - struct net_buf *buf; - struct cmd_state_set state; + struct net_buf *buf; + struct cmd_state_set state; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN_CANCEL, 0); + buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN_CANCEL, 0); - cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, false); - cmd(buf)->state = &state; + cmd_state_set_init(&state, bt_dev.flags, BT_DEV_AUTO_CONN, false); + cmd(buf)->state = &state; - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN_CANCEL, buf, NULL); } #endif /* defined(CONFIG_BT_WHITELIST) */ static int hci_le_create_conn(const struct bt_conn *conn) { - struct net_buf *buf; - struct bt_hci_cp_le_create_conn *cp; - u8_t own_addr_type; - const bt_addr_le_t *peer_addr; - int err; + struct net_buf *buf; + struct bt_hci_cp_le_create_conn *cp; + u8_t own_addr_type; + const bt_addr_le_t *peer_addr; + int err; #if defined(CONFIG_BT_STACK_PTS) - if(conn->le.own_adder_type == BT_ADDR_LE_PUBLIC || conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) - { - own_addr_type = conn->le.own_adder_type; - goto start_connect; - } - + if(conn->le.own_adder_type == BT_ADDR_LE_PUBLIC || conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) + { + own_addr_type = conn->le.own_adder_type; + goto start_connect; + } + #endif - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - err = le_set_private_addr(conn->id); - if (err) { - return err; - } + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + err = le_set_private_addr(conn->id); + if (err) { + return err; + } #if defined(BFLB_BLE) /*Use random type at the first time*/ own_addr_type = BT_ADDR_LE_RANDOM; - #if defined(CONFIG_BT_STACK_PTS) - if(conn->le.own_adder_type == BT_ADDR_LE_RANDOM_ID){ - own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - } - #endif - #else - if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - } else { - own_addr_type = BT_ADDR_LE_RANDOM; - } + #if defined(CONFIG_BT_STACK_PTS) + if(conn->le.own_adder_type == BT_ADDR_LE_RANDOM_ID){ + own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + } #endif - } else { - /* If Static Random address is used as Identity address we - * need to restore it before creating connection. Otherwise - * NRPA used for active scan could be used for connection. - */ - const bt_addr_le_t *own_addr = &bt_dev.id_addr[conn->id]; + #else + if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { + own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + } else { + own_addr_type = BT_ADDR_LE_RANDOM; + } + #endif + } else { + /* If Static Random address is used as Identity address we + * need to restore it before creating connection. Otherwise + * NRPA used for active scan could be used for connection. + */ + const bt_addr_le_t *own_addr = &bt_dev.id_addr[conn->id]; - if (own_addr->type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&own_addr->a); - if (err) { - return err; - } - } + if (own_addr->type == BT_ADDR_LE_RANDOM) { + err = set_random_address(&own_addr->a); + if (err) { + return err; + } + } - own_addr_type = own_addr->type; - } - -#if defined(CONFIG_BT_STACK_PTS) -start_connect: -#endif - buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } - - cp = net_buf_add(buf, sizeof(*cp)); - (void)memset(cp, 0, sizeof(*cp)); - - /* Interval == window for continuous scanning */ - cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL); - cp->scan_window = cp->scan_interval; - - peer_addr = &conn->le.dst; - -#if defined(CONFIG_BT_SMP) - if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { - /* Host resolving is used, use the RPA directly. */ - peer_addr = &conn->le.resp_addr; - } -#endif - - bt_addr_le_copy(&cp->peer_addr, peer_addr); - cp->own_addr_type = own_addr_type; - cp->conn_interval_min = sys_cpu_to_le16(conn->le.interval_min); - cp->conn_interval_max = sys_cpu_to_le16(conn->le.interval_max); - cp->conn_latency = sys_cpu_to_le16(conn->le.latency); - cp->supervision_timeout = sys_cpu_to_le16(conn->le.timeout); + own_addr_type = own_addr->type; + } #if defined(CONFIG_BT_STACK_PTS) - if(event_flag == dir_connect_req) - { - bt_addr_le_copy(&cp->peer_addr,&pts_addr); - - cp->filter_policy = 0; - cp->own_addr_type = BT_ADDR_LE_PUBLIC; - - /* User Initiated procedure use fast scan parameters. */ - cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL); - cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW); - } +start_connect: #endif - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL); + buf = bt_hci_cmd_create(BT_HCI_OP_LE_CREATE_CONN, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } + + cp = net_buf_add(buf, sizeof(*cp)); + (void)memset(cp, 0, sizeof(*cp)); + + /* Interval == window for continuous scanning */ + cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL); + cp->scan_window = cp->scan_interval; + + peer_addr = &conn->le.dst; + +#if defined(CONFIG_BT_SMP) + if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { + /* Host resolving is used, use the RPA directly. */ + peer_addr = &conn->le.resp_addr; + } +#endif + + bt_addr_le_copy(&cp->peer_addr, peer_addr); + cp->own_addr_type = own_addr_type; + cp->conn_interval_min = sys_cpu_to_le16(conn->le.interval_min); + cp->conn_interval_max = sys_cpu_to_le16(conn->le.interval_max); + cp->conn_latency = sys_cpu_to_le16(conn->le.latency); + cp->supervision_timeout = sys_cpu_to_le16(conn->le.timeout); + +#if defined(CONFIG_BT_STACK_PTS) + if(event_flag == dir_connect_req) + { + bt_addr_le_copy(&cp->peer_addr,&pts_addr); + + cp->filter_policy = 0; + cp->own_addr_type = BT_ADDR_LE_PUBLIC; + + /* User Initiated procedure use fast scan parameters. */ + cp->scan_interval = sys_cpu_to_le16(BT_GAP_SCAN_FAST_INTERVAL); + cp->scan_window = sys_cpu_to_le16(BT_GAP_SCAN_FAST_WINDOW); + } +#endif + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_CREATE_CONN, buf, NULL); } #endif /* CONFIG_BT_CENTRAL */ static void hci_disconn_complete(struct net_buf *buf) { - struct bt_hci_evt_disconn_complete *evt = (void *)buf->data; - u16_t handle = sys_le16_to_cpu(evt->handle); - struct bt_conn *conn; + struct bt_hci_evt_disconn_complete *evt = (void *)buf->data; + u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_conn *conn; - BT_DBG("status 0x%02x handle %u reason 0x%02x", evt->status, handle, - evt->reason); + BT_DBG("status 0x%02x handle %u reason 0x%02x", evt->status, handle, + evt->reason); - if (evt->status) { - return; - } + if (evt->status) { + return; + } - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to look up conn with handle %u", handle); - goto advertise; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to look up conn with handle %u", handle); + goto advertise; + } - conn->err = evt->reason; + conn->err = evt->reason; - /* Check stacks usage */ + /* Check stacks usage */ #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) - STACK_ANALYZE("rx stack", rx_thread_stack); + STACK_ANALYZE("rx stack", rx_thread_stack); #endif #if !defined(BFLB_BLE) - STACK_ANALYZE("tx stack", tx_thread_stack); + STACK_ANALYZE("tx stack", tx_thread_stack); #endif - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); - conn->handle = 0U; + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + conn->handle = 0U; - if (conn->type != BT_CONN_TYPE_LE) { + if (conn->type != BT_CONN_TYPE_LE) { #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_SCO) { - bt_sco_cleanup(conn); - return; - } - /* - * If only for one connection session bond was set, clear keys - * database row for this connection. - */ - if (conn->type == BT_CONN_TYPE_BR && - atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_NOBOND)) { - bt_keys_link_key_clear(conn->br.link_key); - } + if (conn->type == BT_CONN_TYPE_SCO) { + bt_sco_cleanup(conn); + return; + } + /* + * If only for one connection session bond was set, clear keys + * database row for this connection. + */ + if (conn->type == BT_CONN_TYPE_BR && + atomic_test_and_clear_bit(conn->flags, BT_CONN_BR_NOBOND)) { + bt_keys_link_key_clear(conn->br.link_key); + } #endif - bt_conn_unref(conn); - return; - } + bt_conn_unref(conn); + return; + } #if defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST) - if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { - bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); - bt_le_scan_update(false); - } + if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) { + bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN); + bt_le_scan_update(false); + } #endif /* defined(CONFIG_BT_CENTRAL) && !defined(CONFIG_BT_WHITELIST) */ - bt_conn_unref(conn); + bt_conn_unref(conn); #if defined(BFLB_BLE_PATCH_CLEAN_UP_CONNECT_REF) - atomic_clear(&conn->ref); + atomic_clear(&conn->ref); #endif advertise: - if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && - !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - le_set_private_addr(bt_dev.adv_id); - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && + !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + le_set_private_addr(bt_dev.adv_id); + } - set_advertise_enable(true); - } + set_advertise_enable(true); + } } static int hci_le_read_remote_features(struct bt_conn *conn) { - struct bt_hci_cp_le_read_remote_features *cp; - struct net_buf *buf; + struct bt_hci_cp_le_read_remote_features *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES, - sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_READ_REMOTE_FEATURES, + sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(conn->handle); - bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(conn->handle); + bt_hci_cmd_send(BT_HCI_OP_LE_READ_REMOTE_FEATURES, buf); - return 0; + return 0; } /* LE Data Length Change Event is optional so this function just ignore @@ -1115,824 +1115,824 @@ static int hci_le_read_remote_features(struct bt_conn *conn) */ static void hci_le_set_data_len(struct bt_conn *conn) { - struct bt_hci_rp_le_read_max_data_len *rp; - struct bt_hci_cp_le_set_data_len *cp; - struct net_buf *buf, *rsp; - u16_t tx_octets, tx_time; - int err; + struct bt_hci_rp_le_read_max_data_len *rp; + struct bt_hci_cp_le_set_data_len *cp; + struct net_buf *buf, *rsp; + u16_t tx_octets, tx_time; + int err; - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp); - if (err) { - BT_ERR("Failed to read DLE max data len"); - return; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, &rsp); + if (err) { + BT_ERR("Failed to read DLE max data len"); + return; + } - rp = (void *)rsp->data; - tx_octets = sys_le16_to_cpu(rp->max_tx_octets); - tx_time = sys_le16_to_cpu(rp->max_tx_time); - net_buf_unref(rsp); + rp = (void *)rsp->data; + tx_octets = sys_le16_to_cpu(rp->max_tx_octets); + tx_time = sys_le16_to_cpu(rp->max_tx_time); + net_buf_unref(rsp); - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp)); - if (!buf) { - BT_ERR("Failed to create LE Set Data Length Command"); - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp)); + if (!buf) { + BT_ERR("Failed to create LE Set Data Length Command"); + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(conn->handle); - cp->tx_octets = sys_cpu_to_le16(tx_octets); - cp->tx_time = sys_cpu_to_le16(tx_time); - err = bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf); - if (err) { - BT_ERR("Failed to send LE Set Data Length Command"); - } + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(conn->handle); + cp->tx_octets = sys_cpu_to_le16(tx_octets); + cp->tx_time = sys_cpu_to_le16(tx_time); + err = bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf); + if (err) { + BT_ERR("Failed to send LE Set Data Length Command"); + } } int bt_le_set_data_len(struct bt_conn *conn, u16_t tx_octets, u16_t tx_time) { - struct bt_hci_cp_le_set_data_len *cp; - struct net_buf *buf; + struct bt_hci_cp_le_set_data_len *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp)); - if (!buf) { - BT_ERR("bt_le_set_data_len, Failed to create LE Set Data Length Command"); - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_DATA_LEN, sizeof(*cp)); + if (!buf) { + BT_ERR("bt_le_set_data_len, Failed to create LE Set Data Length Command"); + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(conn->handle); - cp->tx_octets = sys_cpu_to_le16(tx_octets); - cp->tx_time = sys_cpu_to_le16(tx_time); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(conn->handle); + cp->tx_octets = sys_cpu_to_le16(tx_octets); + cp->tx_time = sys_cpu_to_le16(tx_time); - return bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf); + return bt_hci_cmd_send(BT_HCI_OP_LE_SET_DATA_LEN, buf); } static int hci_le_set_phy(struct bt_conn *conn) { - struct bt_hci_cp_le_set_phy *cp; - struct net_buf *buf; + struct bt_hci_cp_le_set_phy *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PHY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(conn->handle); - cp->all_phys = 0U; - cp->tx_phys = BT_HCI_LE_PHY_PREFER_2M; - cp->rx_phys = BT_HCI_LE_PHY_PREFER_2M; - cp->phy_opts = BT_HCI_LE_PHY_CODED_ANY; - bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(conn->handle); + cp->all_phys = 0U; + cp->tx_phys = BT_HCI_LE_PHY_PREFER_2M; + cp->rx_phys = BT_HCI_LE_PHY_PREFER_2M; + cp->phy_opts = BT_HCI_LE_PHY_CODED_ANY; + bt_hci_cmd_send(BT_HCI_OP_LE_SET_PHY, buf); - return 0; + return 0; } static void slave_update_conn_param(struct bt_conn *conn) { - if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - return; - } + if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + return; + } - /* don't start timer again on PHY update etc */ - if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) { - return; - } + /* don't start timer again on PHY update etc */ + if (atomic_test_bit(conn->flags, BT_CONN_SLAVE_PARAM_UPDATE)) { + return; + } - /* - * Core 4.2 Vol 3, Part C, 9.3.12.2 - * The Peripheral device should not perform a Connection Parameter - * Update procedure within 5 s after establishing a connection. - */ - k_delayed_work_submit(&conn->update_work, CONN_UPDATE_TIMEOUT); + /* + * Core 4.2 Vol 3, Part C, 9.3.12.2 + * The Peripheral device should not perform a Connection Parameter + * Update procedure within 5 s after establishing a connection. + */ + k_delayed_work_submit(&conn->update_work, CONN_UPDATE_TIMEOUT); } #if defined(CONFIG_BT_SMP) static void update_pending_id(struct bt_keys *keys, void *data) { - if (keys->flags & BT_KEYS_ID_PENDING_ADD) { - keys->flags &= ~BT_KEYS_ID_PENDING_ADD; - bt_id_add(keys); - return; - } + if (keys->flags & BT_KEYS_ID_PENDING_ADD) { + keys->flags &= ~BT_KEYS_ID_PENDING_ADD; + bt_id_add(keys); + return; + } - if (keys->flags & BT_KEYS_ID_PENDING_DEL) { - keys->flags &= ~BT_KEYS_ID_PENDING_DEL; - bt_id_del(keys); - return; - } + if (keys->flags & BT_KEYS_ID_PENDING_DEL) { + keys->flags &= ~BT_KEYS_ID_PENDING_DEL; + bt_id_del(keys); + return; + } } #endif static struct bt_conn *find_pending_connect(bt_addr_le_t *peer_addr) { - struct bt_conn *conn; + struct bt_conn *conn; - /* - * Make lookup to check if there's a connection object in - * CONNECT or DIR_ADV state associated with passed peer LE address. - */ - conn = bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT); - if (conn) { - return conn; - } + /* + * Make lookup to check if there's a connection object in + * CONNECT or DIR_ADV state associated with passed peer LE address. + */ + conn = bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT); + if (conn) { + return conn; + } - return bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT_DIR_ADV); + return bt_conn_lookup_state_le(peer_addr, BT_CONN_CONNECT_DIR_ADV); } static void enh_conn_complete(struct bt_hci_evt_le_enh_conn_complete *evt) { - u16_t handle = sys_le16_to_cpu(evt->handle); - bt_addr_le_t peer_addr, id_addr; - struct bt_conn *conn; - int err; + u16_t handle = sys_le16_to_cpu(evt->handle); + bt_addr_le_t peer_addr, id_addr; + struct bt_conn *conn; + int err; - BT_DBG("status 0x%02x handle %u role %u %s", evt->status, handle, - evt->role, bt_addr_le_str(&evt->peer_addr)); + BT_DBG("status 0x%02x handle %u role %u %s", evt->status, handle, + evt->role, bt_addr_le_str(&evt->peer_addr)); #if defined(CONFIG_BT_SMP) - if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) { - bt_keys_foreach(BT_KEYS_IRK, update_pending_id, NULL); - } + if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) { + bt_keys_foreach(BT_KEYS_IRK, update_pending_id, NULL); + } #endif - if (evt->status) { - /* - * If there was an error we are only interested in pending - * connection. There is no need to check ID address as - * only one connection can be in that state. - * - * Depending on error code address might not be valid anyway. - */ - conn = find_pending_connect(NULL); - if (!conn) { - return; - } + if (evt->status) { + /* + * If there was an error we are only interested in pending + * connection. There is no need to check ID address as + * only one connection can be in that state. + * + * Depending on error code address might not be valid anyway. + */ + conn = find_pending_connect(NULL); + if (!conn) { + return; + } - conn->err = evt->status; + conn->err = evt->status; - if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - /* - * Handle advertising timeout after high duty directed - * advertising. - */ - if (conn->err == BT_HCI_ERR_ADV_TIMEOUT) { - atomic_clear_bit(bt_dev.flags, - BT_DEV_ADVERTISING); - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + /* + * Handle advertising timeout after high duty directed + * advertising. + */ + if (conn->err == BT_HCI_ERR_ADV_TIMEOUT) { + atomic_clear_bit(bt_dev.flags, + BT_DEV_ADVERTISING); + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); - goto done; - } - } + goto done; + } + } - if (IS_ENABLED(CONFIG_BT_CENTRAL)) { - /* - * Handle cancellation of outgoing connection attempt. - */ - if (conn->err == BT_HCI_ERR_UNKNOWN_CONN_ID) { - /* We notify before checking autoconnect flag - * as application may choose to change it from - * callback. - */ - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + if (IS_ENABLED(CONFIG_BT_CENTRAL)) { + /* + * Handle cancellation of outgoing connection attempt. + */ + if (conn->err == BT_HCI_ERR_UNKNOWN_CONN_ID) { + /* We notify before checking autoconnect flag + * as application may choose to change it from + * callback. + */ + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); #if !defined(CONFIG_BT_WHITELIST) - /* Check if device is marked for autoconnect. */ - if (atomic_test_bit(conn->flags, - BT_CONN_AUTO_CONNECT)) { - bt_conn_set_state(conn, - BT_CONN_CONNECT_SCAN); - } + /* Check if device is marked for autoconnect. */ + if (atomic_test_bit(conn->flags, + BT_CONN_AUTO_CONNECT)) { + bt_conn_set_state(conn, + BT_CONN_CONNECT_SCAN); + } #endif /* !defined(CONFIG_BT_WHITELIST) */ - goto done; - } - } + goto done; + } + } - BT_WARN("Unexpected status 0x%02x", evt->status); + BT_WARN("Unexpected status 0x%02x", evt->status); - bt_conn_unref(conn); + bt_conn_unref(conn); - return; - } + return; + } - bt_addr_le_copy(&id_addr, &evt->peer_addr); + bt_addr_le_copy(&id_addr, &evt->peer_addr); - /* Translate "enhanced" identity address type to normal one */ - if (id_addr.type == BT_ADDR_LE_PUBLIC_ID || - id_addr.type == BT_ADDR_LE_RANDOM_ID) { - id_addr.type -= BT_ADDR_LE_PUBLIC_ID; - bt_addr_copy(&peer_addr.a, &evt->peer_rpa); - peer_addr.type = BT_ADDR_LE_RANDOM; - } else { - bt_addr_le_copy(&peer_addr, &evt->peer_addr); - } + /* Translate "enhanced" identity address type to normal one */ + if (id_addr.type == BT_ADDR_LE_PUBLIC_ID || + id_addr.type == BT_ADDR_LE_RANDOM_ID) { + id_addr.type -= BT_ADDR_LE_PUBLIC_ID; + bt_addr_copy(&peer_addr.a, &evt->peer_rpa); + peer_addr.type = BT_ADDR_LE_RANDOM; + } else { + bt_addr_le_copy(&peer_addr, &evt->peer_addr); + } - conn = find_pending_connect(&id_addr); + conn = find_pending_connect(&id_addr); - if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && - evt->role == BT_HCI_ROLE_SLAVE) { - /* - * clear advertising even if we are not able to add connection - * object to keep host in sync with controller state - */ - atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING); + if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && + evt->role == BT_HCI_ROLE_SLAVE) { + /* + * clear advertising even if we are not able to add connection + * object to keep host in sync with controller state + */ + atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING); - /* for slave we may need to add new connection */ - if (!conn) { - conn = bt_conn_add_le(bt_dev.adv_id, &id_addr); - } - } + /* for slave we may need to add new connection */ + if (!conn) { + conn = bt_conn_add_le(bt_dev.adv_id, &id_addr); + } + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - IS_ENABLED(CONFIG_BT_WHITELIST) && - evt->role == BT_HCI_ROLE_MASTER) { - /* for whitelist initiator me may need to add new connection. */ - if (!conn) { - conn = bt_conn_add_le(BT_ID_DEFAULT, &id_addr); - } - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + IS_ENABLED(CONFIG_BT_WHITELIST) && + evt->role == BT_HCI_ROLE_MASTER) { + /* for whitelist initiator me may need to add new connection. */ + if (!conn) { + conn = bt_conn_add_le(BT_ID_DEFAULT, &id_addr); + } + } - if (!conn) { - BT_ERR("Unable to add new conn for handle %u", handle); - return; - } + if (!conn) { + BT_ERR("Unable to add new conn for handle %u", handle); + return; + } - conn->handle = handle; - bt_addr_le_copy(&conn->le.dst, &id_addr); - conn->le.interval = sys_le16_to_cpu(evt->interval); - conn->le.latency = sys_le16_to_cpu(evt->latency); - conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout); - conn->role = evt->role; - conn->err = 0U; + conn->handle = handle; + bt_addr_le_copy(&conn->le.dst, &id_addr); + conn->le.interval = sys_le16_to_cpu(evt->interval); + conn->le.latency = sys_le16_to_cpu(evt->latency); + conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout); + conn->role = evt->role; + conn->err = 0U; - /* - * Use connection address (instead of identity address) as initiator - * or responder address. Only slave needs to be updated. For master all - * was set during outgoing connection creation. - */ - if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && - conn->role == BT_HCI_ROLE_SLAVE) { - bt_addr_le_copy(&conn->le.init_addr, &peer_addr); + /* + * Use connection address (instead of identity address) as initiator + * or responder address. Only slave needs to be updated. For master all + * was set during outgoing connection creation. + */ + if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && + conn->role == BT_HCI_ROLE_SLAVE) { + bt_addr_le_copy(&conn->le.init_addr, &peer_addr); - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED) if(memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t))) bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa); else bt_addr_copy(&conn->le.resp_addr.a, &bt_dev.random_addr.a); #else - bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa); + bt_addr_copy(&conn->le.resp_addr.a, &evt->local_rpa); #endif - conn->le.resp_addr.type = BT_ADDR_LE_RANDOM; - } else { - bt_addr_le_copy(&conn->le.resp_addr, - &bt_dev.id_addr[conn->id]); - } + conn->le.resp_addr.type = BT_ADDR_LE_RANDOM; + } else { + bt_addr_le_copy(&conn->le.resp_addr, + &bt_dev.id_addr[conn->id]); + } - #if defined(CONFIG_BT_STACK_PTS) - if(atomic_test_and_clear_bit(bt_dev.flags,BT_DEV_ADV_ADDRESS_IS_PUBLIC)) - { - bt_addr_le_copy(&conn->le.resp_addr,&bt_dev.id_addr[conn->id]); - } - #endif + #if defined(CONFIG_BT_STACK_PTS) + if(atomic_test_and_clear_bit(bt_dev.flags,BT_DEV_ADV_ADDRESS_IS_PUBLIC)) + { + bt_addr_le_copy(&conn->le.resp_addr,&bt_dev.id_addr[conn->id]); + } + #endif - /* if the controller supports, lets advertise for another - * slave connection. - * check for connectable advertising state is sufficient as - * this is how this le connection complete for slave occurred. - */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && - BT_LE_STATES_SLAVE_CONN_ADV(bt_dev.le.states)) { - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - le_set_private_addr(bt_dev.adv_id); - } + /* if the controller supports, lets advertise for another + * slave connection. + * check for connectable advertising state is sufficient as + * this is how this le connection complete for slave occurred. + */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING) && + BT_LE_STATES_SLAVE_CONN_ADV(bt_dev.le.states)) { + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + le_set_private_addr(bt_dev.adv_id); + } - set_advertise_enable(true); - } - } + set_advertise_enable(true); + } + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_HCI_ROLE_MASTER) { - - if (IS_ENABLED(CONFIG_BT_WHITELIST) && - atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { - conn->id = BT_ID_DEFAULT; - atomic_clear_bit(bt_dev.flags, BT_DEV_AUTO_CONN); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_HCI_ROLE_MASTER) { - bt_addr_le_copy(&conn->le.resp_addr, &peer_addr); - - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + if (IS_ENABLED(CONFIG_BT_WHITELIST) && + atomic_test_bit(bt_dev.flags, BT_DEV_AUTO_CONN)) { + conn->id = BT_ID_DEFAULT; + atomic_clear_bit(bt_dev.flags, BT_DEV_AUTO_CONN); + } + + bt_addr_le_copy(&conn->le.resp_addr, &peer_addr); + + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { #if defined(BFLB_BLE_PATCH_DHKEY_CHECK_FAILED) if(memcmp(&evt->local_rpa, BT_ADDR_ANY, sizeof(bt_addr_t))) bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa); else bt_addr_copy(&conn->le.init_addr.a, &bt_dev.random_addr.a); #else - bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa); + bt_addr_copy(&conn->le.init_addr.a, &evt->local_rpa); #endif - conn->le.init_addr.type = BT_ADDR_LE_RANDOM; - } else { - bt_addr_le_copy(&conn->le.init_addr, - &bt_dev.id_addr[conn->id]); - } - - #if defined(CONFIG_BT_STACK_PTS) - if(conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) - { - bt_addr_le_copy(&conn->le.init_addr,&bt_dev.id_addr[conn->id]); - } - #endif - } - + conn->le.init_addr.type = BT_ADDR_LE_RANDOM; + } else { + bt_addr_le_copy(&conn->le.init_addr, + &bt_dev.id_addr[conn->id]); + } - bt_conn_set_state(conn, BT_CONN_CONNECTED); + #if defined(CONFIG_BT_STACK_PTS) + if(conn->le.own_adder_type == BT_ADDR_LE_PUBLIC_ID) + { + bt_addr_le_copy(&conn->le.init_addr,&bt_dev.id_addr[conn->id]); + } + #endif + } - /* - * it is possible that connection was disconnected directly from - * connected callback so we must check state before doing connection - * parameters update - */ - if (conn->state != BT_CONN_CONNECTED) { - goto done; - } - if ((evt->role == BT_HCI_ROLE_MASTER) || - BT_FEAT_LE_SLAVE_FEATURE_XCHG(bt_dev.le.features)) { - err = hci_le_read_remote_features(conn); - if (!err) { - goto done; - } - } + bt_conn_set_state(conn, BT_CONN_CONNECTED); - if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && - BT_FEAT_LE_PHY_2M(bt_dev.le.features)) { - err = hci_le_set_phy(conn); - if (!err) { - atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE); - goto done; - } - } + /* + * it is possible that connection was disconnected directly from + * connected callback so we must check state before doing connection + * parameters update + */ + if (conn->state != BT_CONN_CONNECTED) { + goto done; + } - if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && - BT_FEAT_LE_DLE(bt_dev.le.features)) { - hci_le_set_data_len(conn); - } + if ((evt->role == BT_HCI_ROLE_MASTER) || + BT_FEAT_LE_SLAVE_FEATURE_XCHG(bt_dev.le.features)) { + err = hci_le_read_remote_features(conn); + if (!err) { + goto done; + } + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && - conn->role == BT_CONN_ROLE_SLAVE) { - slave_update_conn_param(conn); - } + if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && + BT_FEAT_LE_PHY_2M(bt_dev.le.features)) { + err = hci_le_set_phy(conn); + if (!err) { + atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE); + goto done; + } + } + + if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && + BT_FEAT_LE_DLE(bt_dev.le.features)) { + hci_le_set_data_len(conn); + } + + if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && + conn->role == BT_CONN_ROLE_SLAVE) { + slave_update_conn_param(conn); + } done: - bt_conn_unref(conn); - if (IS_ENABLED(CONFIG_BT_CENTRAL)) { - bt_le_scan_update(false); - } + bt_conn_unref(conn); + if (IS_ENABLED(CONFIG_BT_CENTRAL)) { + bt_le_scan_update(false); + } } static void le_enh_conn_complete(struct net_buf *buf) { - enh_conn_complete((void *)buf->data); + enh_conn_complete((void *)buf->data); } static void le_legacy_conn_complete(struct net_buf *buf) { - struct bt_hci_evt_le_conn_complete *evt = (void *)buf->data; - struct bt_hci_evt_le_enh_conn_complete enh; - const bt_addr_le_t *id_addr; + struct bt_hci_evt_le_conn_complete *evt = (void *)buf->data; + struct bt_hci_evt_le_enh_conn_complete enh; + const bt_addr_le_t *id_addr; - BT_DBG("status 0x%02x role %u %s", evt->status, evt->role, - bt_addr_le_str(&evt->peer_addr)); + BT_DBG("status 0x%02x role %u %s", evt->status, evt->role, + bt_addr_le_str(&evt->peer_addr)); - enh.status = evt->status; - enh.handle = evt->handle; - enh.role = evt->role; - enh.interval = evt->interval; - enh.latency = evt->latency; - enh.supv_timeout = evt->supv_timeout; - enh.clock_accuracy = evt->clock_accuracy; + enh.status = evt->status; + enh.handle = evt->handle; + enh.role = evt->role; + enh.interval = evt->interval; + enh.latency = evt->latency; + enh.supv_timeout = evt->supv_timeout; + enh.clock_accuracy = evt->clock_accuracy; - bt_addr_le_copy(&enh.peer_addr, &evt->peer_addr); + bt_addr_le_copy(&enh.peer_addr, &evt->peer_addr); - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - bt_addr_copy(&enh.local_rpa, &bt_dev.random_addr.a); - } else { - bt_addr_copy(&enh.local_rpa, BT_ADDR_ANY); - } + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + bt_addr_copy(&enh.local_rpa, &bt_dev.random_addr.a); + } else { + bt_addr_copy(&enh.local_rpa, BT_ADDR_ANY); + } - if (evt->role == BT_HCI_ROLE_SLAVE) { - id_addr = bt_lookup_id_addr(bt_dev.adv_id, &enh.peer_addr); - } else { - id_addr = bt_lookup_id_addr(BT_ID_DEFAULT, &enh.peer_addr); - } + if (evt->role == BT_HCI_ROLE_SLAVE) { + id_addr = bt_lookup_id_addr(bt_dev.adv_id, &enh.peer_addr); + } else { + id_addr = bt_lookup_id_addr(BT_ID_DEFAULT, &enh.peer_addr); + } - if (id_addr != &enh.peer_addr) { - bt_addr_copy(&enh.peer_rpa, &enh.peer_addr.a); - bt_addr_le_copy(&enh.peer_addr, id_addr); - enh.peer_addr.type += BT_ADDR_LE_PUBLIC_ID; - } else { - bt_addr_copy(&enh.peer_rpa, BT_ADDR_ANY); - } + if (id_addr != &enh.peer_addr) { + bt_addr_copy(&enh.peer_rpa, &enh.peer_addr.a); + bt_addr_le_copy(&enh.peer_addr, id_addr); + enh.peer_addr.type += BT_ADDR_LE_PUBLIC_ID; + } else { + bt_addr_copy(&enh.peer_rpa, BT_ADDR_ANY); + } - enh_conn_complete(&enh); + enh_conn_complete(&enh); } static void le_remote_feat_complete(struct net_buf *buf) { - struct bt_hci_evt_le_remote_feat_complete *evt = (void *)buf->data; - u16_t handle = sys_le16_to_cpu(evt->handle); - struct bt_conn *conn; + struct bt_hci_evt_le_remote_feat_complete *evt = (void *)buf->data; + u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_conn *conn; - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to lookup conn for handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to lookup conn for handle %u", handle); + return; + } - if (!evt->status) { - memcpy(conn->le.features, evt->features, - sizeof(conn->le.features)); - } + if (!evt->status) { + memcpy(conn->le.features, evt->features, + sizeof(conn->le.features)); + } - if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && - BT_FEAT_LE_PHY_2M(bt_dev.le.features) && - BT_FEAT_LE_PHY_2M(conn->le.features)) { - int err; + if (IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) && + BT_FEAT_LE_PHY_2M(bt_dev.le.features) && + BT_FEAT_LE_PHY_2M(conn->le.features)) { + int err; - err = hci_le_set_phy(conn); - if (!err) { - atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE); - goto done; - } - } + err = hci_le_set_phy(conn); + if (!err) { + atomic_set_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE); + goto done; + } + } + + if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && + BT_FEAT_LE_DLE(bt_dev.le.features) && + BT_FEAT_LE_DLE(conn->le.features)) { + hci_le_set_data_len(conn); + } - if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && - BT_FEAT_LE_DLE(bt_dev.le.features) && - BT_FEAT_LE_DLE(conn->le.features)) { - hci_le_set_data_len(conn); - } - #if !defined(CONFIG_BT_STACK_PTS) - if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && - conn->role == BT_CONN_ROLE_SLAVE) { - slave_update_conn_param(conn); - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && + conn->role == BT_CONN_ROLE_SLAVE) { + slave_update_conn_param(conn); + } #endif done: - bt_conn_unref(conn); + bt_conn_unref(conn); } #if defined(CONFIG_BT_DATA_LEN_UPDATE) static void le_data_len_change(struct net_buf *buf) { - struct bt_hci_evt_le_data_len_change *evt = (void *)buf->data; - u16_t max_tx_octets = sys_le16_to_cpu(evt->max_tx_octets); - u16_t max_rx_octets = sys_le16_to_cpu(evt->max_rx_octets); - u16_t max_tx_time = sys_le16_to_cpu(evt->max_tx_time); - u16_t max_rx_time = sys_le16_to_cpu(evt->max_rx_time); - u16_t handle = sys_le16_to_cpu(evt->handle); - struct bt_conn *conn; + struct bt_hci_evt_le_data_len_change *evt = (void *)buf->data; + u16_t max_tx_octets = sys_le16_to_cpu(evt->max_tx_octets); + u16_t max_rx_octets = sys_le16_to_cpu(evt->max_rx_octets); + u16_t max_tx_time = sys_le16_to_cpu(evt->max_tx_time); + u16_t max_rx_time = sys_le16_to_cpu(evt->max_rx_time); + u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_conn *conn; UNUSED(max_tx_octets); UNUSED(max_rx_octets); UNUSED(max_tx_time); UNUSED(max_rx_time); - - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to lookup conn for handle %u", handle); - return; - } - BT_DBG("max. tx: %u (%uus), max. rx: %u (%uus)", max_tx_octets, - max_tx_time, max_rx_octets, max_rx_time); + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to lookup conn for handle %u", handle); + return; + } - /* TODO use those */ + BT_DBG("max. tx: %u (%uus), max. rx: %u (%uus)", max_tx_octets, + max_tx_time, max_rx_octets, max_rx_time); - bt_conn_unref(conn); + /* TODO use those */ + + bt_conn_unref(conn); } #endif /* CONFIG_BT_DATA_LEN_UPDATE */ #if defined(CONFIG_BT_PHY_UPDATE) static void le_phy_update_complete(struct net_buf *buf) { - struct bt_hci_evt_le_phy_update_complete *evt = (void *)buf->data; - u16_t handle = sys_le16_to_cpu(evt->handle); - struct bt_conn *conn; + struct bt_hci_evt_le_phy_update_complete *evt = (void *)buf->data; + u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_conn *conn; - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to lookup conn for handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to lookup conn for handle %u", handle); + return; + } - BT_DBG("PHY updated: status: 0x%02x, tx: %u, rx: %u", - evt->status, evt->tx_phy, evt->rx_phy); + BT_DBG("PHY updated: status: 0x%02x, tx: %u, rx: %u", + evt->status, evt->tx_phy, evt->rx_phy); - if (!IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) || - !atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE)) { - goto done; - } + if (!IS_ENABLED(CONFIG_BT_AUTO_PHY_UPDATE) || + !atomic_test_and_clear_bit(conn->flags, BT_CONN_AUTO_PHY_UPDATE)) { + goto done; + } - if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && - BT_FEAT_LE_DLE(bt_dev.le.features) && - BT_FEAT_LE_DLE(conn->le.features)) { - hci_le_set_data_len(conn); - } + if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && + BT_FEAT_LE_DLE(bt_dev.le.features) && + BT_FEAT_LE_DLE(conn->le.features)) { + hci_le_set_data_len(conn); + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && - conn->role == BT_CONN_ROLE_SLAVE) { - slave_update_conn_param(conn); - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && + conn->role == BT_CONN_ROLE_SLAVE) { + slave_update_conn_param(conn); + } done: - bt_conn_unref(conn); + bt_conn_unref(conn); } #endif /* CONFIG_BT_PHY_UPDATE */ bool bt_le_conn_params_valid(const struct bt_le_conn_param *param) { - /* All limits according to BT Core spec 5.0 [Vol 2, Part E, 7.8.12] */ + /* All limits according to BT Core spec 5.0 [Vol 2, Part E, 7.8.12] */ - if (param->interval_min > param->interval_max || - param->interval_min < 6 || param->interval_max > 3200) { - return false; - } + if (param->interval_min > param->interval_max || + param->interval_min < 6 || param->interval_max > 3200) { + return false; + } - if (param->latency > 499) { - return false; - } + if (param->latency > 499) { + return false; + } - if (param->timeout < 10 || param->timeout > 3200 || - ((param->timeout * 4U) <= - ((1 + param->latency) * param->interval_max))) { - return false; - } + if (param->timeout < 10 || param->timeout > 3200 || + ((param->timeout * 4U) <= + ((1 + param->latency) * param->interval_max))) { + return false; + } - return true; + return true; } static void le_conn_param_neg_reply(u16_t handle, u8_t reason) { - struct bt_hci_cp_le_conn_param_req_neg_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_le_conn_param_req_neg_reply *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, - sizeof(*cp)); - if (!buf) { - BT_ERR("Unable to allocate buffer"); - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, + sizeof(*cp)); + if (!buf) { + BT_ERR("Unable to allocate buffer"); + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(handle); - cp->reason = sys_cpu_to_le16(reason); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(handle); + cp->reason = sys_cpu_to_le16(reason); - bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf); + bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY, buf); } static int le_conn_param_req_reply(u16_t handle, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - struct bt_hci_cp_le_conn_param_req_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_le_conn_param_req_reply *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - (void)memset(cp, 0, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); + (void)memset(cp, 0, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(handle); - cp->interval_min = sys_cpu_to_le16(param->interval_min); - cp->interval_max = sys_cpu_to_le16(param->interval_max); - cp->latency = sys_cpu_to_le16(param->latency); - cp->timeout = sys_cpu_to_le16(param->timeout); + cp->handle = sys_cpu_to_le16(handle); + cp->interval_min = sys_cpu_to_le16(param->interval_min); + cp->interval_max = sys_cpu_to_le16(param->interval_max); + cp->latency = sys_cpu_to_le16(param->latency); + cp->timeout = sys_cpu_to_le16(param->timeout); - return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf); + return bt_hci_cmd_send(BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY, buf); } static void le_conn_param_req(struct net_buf *buf) { - struct bt_hci_evt_le_conn_param_req *evt = (void *)buf->data; - struct bt_le_conn_param param; - struct bt_conn *conn; - u16_t handle; + struct bt_hci_evt_le_conn_param_req *evt = (void *)buf->data; + struct bt_le_conn_param param; + struct bt_conn *conn; + u16_t handle; - handle = sys_le16_to_cpu(evt->handle); - param.interval_min = sys_le16_to_cpu(evt->interval_min); - param.interval_max = sys_le16_to_cpu(evt->interval_max); - param.latency = sys_le16_to_cpu(evt->latency); - param.timeout = sys_le16_to_cpu(evt->timeout); + handle = sys_le16_to_cpu(evt->handle); + param.interval_min = sys_le16_to_cpu(evt->interval_min); + param.interval_max = sys_le16_to_cpu(evt->interval_max); + param.latency = sys_le16_to_cpu(evt->latency); + param.timeout = sys_le16_to_cpu(evt->timeout); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to lookup conn for handle %u", handle); - le_conn_param_neg_reply(handle, BT_HCI_ERR_UNKNOWN_CONN_ID); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to lookup conn for handle %u", handle); + le_conn_param_neg_reply(handle, BT_HCI_ERR_UNKNOWN_CONN_ID); + return; + } - if (!le_param_req(conn, ¶m)) { - le_conn_param_neg_reply(handle, BT_HCI_ERR_INVALID_LL_PARAM); - } else { - le_conn_param_req_reply(handle, ¶m); - } + if (!le_param_req(conn, ¶m)) { + le_conn_param_neg_reply(handle, BT_HCI_ERR_INVALID_LL_PARAM); + } else { + le_conn_param_req_reply(handle, ¶m); + } - bt_conn_unref(conn); + bt_conn_unref(conn); } static void le_conn_update_complete(struct net_buf *buf) { - struct bt_hci_evt_le_conn_update_complete *evt = (void *)buf->data; - struct bt_conn *conn; - u16_t handle; + struct bt_hci_evt_le_conn_update_complete *evt = (void *)buf->data; + struct bt_conn *conn; + u16_t handle; - handle = sys_le16_to_cpu(evt->handle); + handle = sys_le16_to_cpu(evt->handle); - BT_DBG("status 0x%02x, handle %u", evt->status, handle); + BT_DBG("status 0x%02x, handle %u", evt->status, handle); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to lookup conn for handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to lookup conn for handle %u", handle); + return; + } - if (!evt->status) { - conn->le.interval = sys_le16_to_cpu(evt->interval); - conn->le.latency = sys_le16_to_cpu(evt->latency); - conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout); - notify_le_param_updated(conn); - } else if (evt->status == BT_HCI_ERR_UNSUPP_REMOTE_FEATURE && - conn->role == BT_HCI_ROLE_SLAVE && - !atomic_test_and_set_bit(conn->flags, - BT_CONN_SLAVE_PARAM_L2CAP)) { - /* CPR not supported, let's try L2CAP CPUP instead */ - struct bt_le_conn_param param; + if (!evt->status) { + conn->le.interval = sys_le16_to_cpu(evt->interval); + conn->le.latency = sys_le16_to_cpu(evt->latency); + conn->le.timeout = sys_le16_to_cpu(evt->supv_timeout); + notify_le_param_updated(conn); + } else if (evt->status == BT_HCI_ERR_UNSUPP_REMOTE_FEATURE && + conn->role == BT_HCI_ROLE_SLAVE && + !atomic_test_and_set_bit(conn->flags, + BT_CONN_SLAVE_PARAM_L2CAP)) { + /* CPR not supported, let's try L2CAP CPUP instead */ + struct bt_le_conn_param param; - param.interval_min = conn->le.interval_min; - param.interval_max = conn->le.interval_max; - param.latency = conn->le.pending_latency; - param.timeout = conn->le.pending_timeout; + param.interval_min = conn->le.interval_min; + param.interval_max = conn->le.interval_max; + param.latency = conn->le.pending_latency; + param.timeout = conn->le.pending_timeout; - bt_l2cap_update_conn_param(conn, ¶m); - } + bt_l2cap_update_conn_param(conn, ¶m); + } - bt_conn_unref(conn); + bt_conn_unref(conn); } #if defined(CONFIG_BT_CENTRAL) static void check_pending_conn(const bt_addr_le_t *id_addr, - const bt_addr_le_t *addr, u8_t evtype) + const bt_addr_le_t *addr, u8_t evtype) { - struct bt_conn *conn; + struct bt_conn *conn; - /* No connections are allowed during explicit scanning */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { - return; - } + /* No connections are allowed during explicit scanning */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { + return; + } - /* Return if event is not connectable */ - if (evtype != BT_LE_ADV_IND && evtype != BT_LE_ADV_DIRECT_IND) { - return; - } + /* Return if event is not connectable */ + if (evtype != BT_LE_ADV_IND && evtype != BT_LE_ADV_DIRECT_IND) { + return; + } - conn = bt_conn_lookup_state_le(id_addr, BT_CONN_CONNECT_SCAN); - if (!conn) { - return; - } + conn = bt_conn_lookup_state_le(id_addr, BT_CONN_CONNECT_SCAN); + if (!conn) { + return; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && - set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE)) { - goto failed; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && + set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE)) { + goto failed; + } - bt_addr_le_copy(&conn->le.resp_addr, addr); - if (hci_le_create_conn(conn)) { - goto failed; - } - - bt_conn_set_state(conn, BT_CONN_CONNECT); - bt_conn_unref(conn); - return; + bt_addr_le_copy(&conn->le.resp_addr, addr); + if (hci_le_create_conn(conn)) { + goto failed; + } + + bt_conn_set_state(conn, BT_CONN_CONNECT); + bt_conn_unref(conn); + return; failed: - conn->err = BT_HCI_ERR_UNSPECIFIED; - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); - bt_conn_unref(conn); - bt_le_scan_update(false); + conn->err = BT_HCI_ERR_UNSPECIFIED; + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + bt_conn_unref(conn); + bt_le_scan_update(false); } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) static int set_flow_control(void) { - struct bt_hci_cp_host_buffer_size *hbs; - struct net_buf *buf; - int err; + struct bt_hci_cp_host_buffer_size *hbs; + struct net_buf *buf; + int err; - /* Check if host flow control is actually supported */ - if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) { - BT_WARN("Controller to host flow control not supported"); - return 0; - } + /* Check if host flow control is actually supported */ + if (!BT_CMD_TEST(bt_dev.supported_commands, 10, 5)) { + BT_WARN("Controller to host flow control not supported"); + return 0; + } - buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE, - sizeof(*hbs)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_HOST_BUFFER_SIZE, + sizeof(*hbs)); + if (!buf) { + return -ENOBUFS; + } - hbs = net_buf_add(buf, sizeof(*hbs)); - (void)memset(hbs, 0, sizeof(*hbs)); - hbs->acl_mtu = sys_cpu_to_le16(CONFIG_BT_L2CAP_RX_MTU + - sizeof(struct bt_l2cap_hdr)); - hbs->acl_pkts = sys_cpu_to_le16(CONFIG_BT_ACL_RX_COUNT); + hbs = net_buf_add(buf, sizeof(*hbs)); + (void)memset(hbs, 0, sizeof(*hbs)); + hbs->acl_mtu = sys_cpu_to_le16(CONFIG_BT_L2CAP_RX_MTU + + sizeof(struct bt_l2cap_hdr)); + hbs->acl_pkts = sys_cpu_to_le16(CONFIG_BT_ACL_RX_COUNT); - err = bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_HOST_BUFFER_SIZE, buf, NULL); + if (err) { + return err; + } - buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, 1); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_u8(buf, BT_HCI_CTL_TO_HOST_FLOW_ENABLE); - return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL); + net_buf_add_u8(buf, BT_HCI_CTL_TO_HOST_FLOW_ENABLE); + return bt_hci_cmd_send_sync(BT_HCI_OP_SET_CTL_TO_HOST_FLOW, buf, NULL); } #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */ static int bt_clear_all_pairings(u8_t id) { - bt_conn_disconnect_all(id); + bt_conn_disconnect_all(id); - if (IS_ENABLED(CONFIG_BT_SMP)) { - bt_keys_clear_all(id); - } + if (IS_ENABLED(CONFIG_BT_SMP)) { + bt_keys_clear_all(id); + } - if (IS_ENABLED(CONFIG_BT_BREDR)) { - bt_keys_link_key_clear_addr(NULL); - } + if (IS_ENABLED(CONFIG_BT_BREDR)) { + bt_keys_link_key_clear_addr(NULL); + } - return 0; + return 0; } int bt_unpair(u8_t id, const bt_addr_le_t *addr) { - struct bt_keys *keys = NULL; - struct bt_conn *conn; + struct bt_keys *keys = NULL; + struct bt_conn *conn; - if (id >= CONFIG_BT_ID_MAX) { - return -EINVAL; - } + if (id >= CONFIG_BT_ID_MAX) { + return -EINVAL; + } - if (!addr || !bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { - return bt_clear_all_pairings(id); - } + if (!addr || !bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { + return bt_clear_all_pairings(id); + } - conn = bt_conn_lookup_addr_le(id, addr); - if (conn) { - /* Clear the conn->le.keys pointer since we'll invalidate it, - * and don't want any subsequent code (like disconnected - * callbacks) accessing it. - */ - if (conn->type == BT_CONN_TYPE_LE) { - keys = conn->le.keys; - conn->le.keys = NULL; - } + conn = bt_conn_lookup_addr_le(id, addr); + if (conn) { + /* Clear the conn->le.keys pointer since we'll invalidate it, + * and don't want any subsequent code (like disconnected + * callbacks) accessing it. + */ + if (conn->type == BT_CONN_TYPE_LE) { + keys = conn->le.keys; + conn->le.keys = NULL; + } - bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); - bt_conn_unref(conn); - } + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + bt_conn_unref(conn); + } - if (IS_ENABLED(CONFIG_BT_BREDR)) { - /* LE Public may indicate BR/EDR as well */ - if (addr->type == BT_ADDR_LE_PUBLIC) { - bt_keys_link_key_clear_addr(&addr->a); - } - } + if (IS_ENABLED(CONFIG_BT_BREDR)) { + /* LE Public may indicate BR/EDR as well */ + if (addr->type == BT_ADDR_LE_PUBLIC) { + bt_keys_link_key_clear_addr(&addr->a); + } + } - if (IS_ENABLED(CONFIG_BT_SMP)) { - if (!keys) { - keys = bt_keys_find_addr(id, addr); - } + if (IS_ENABLED(CONFIG_BT_SMP)) { + if (!keys) { + keys = bt_keys_find_addr(id, addr); + } - if (keys) { - bt_keys_clear(keys); - } - } + if (keys) { + bt_keys_clear(keys); + } + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_gatt_clear(id, addr); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_gatt_clear(id, addr); + } - return 0; + return 0; } #endif /* CONFIG_BT_CONN */ @@ -1940,1137 +1940,1137 @@ int bt_unpair(u8_t id, const bt_addr_le_t *addr) #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) static enum bt_security_err security_err_get(u8_t hci_err) { - switch (hci_err) { - case BT_HCI_ERR_SUCCESS: - return BT_SECURITY_ERR_SUCCESS; - case BT_HCI_ERR_AUTH_FAIL: - return BT_SECURITY_ERR_AUTH_FAIL; - case BT_HCI_ERR_PIN_OR_KEY_MISSING: - return BT_SECURITY_ERR_PIN_OR_KEY_MISSING; - case BT_HCI_ERR_PAIRING_NOT_SUPPORTED: - return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED; - case BT_HCI_ERR_PAIRING_NOT_ALLOWED: - return BT_SECURITY_ERR_PAIR_NOT_ALLOWED; - case BT_HCI_ERR_INVALID_PARAM: - return BT_SECURITY_ERR_INVALID_PARAM; - default: - return BT_SECURITY_ERR_UNSPECIFIED; - } + switch (hci_err) { + case BT_HCI_ERR_SUCCESS: + return BT_SECURITY_ERR_SUCCESS; + case BT_HCI_ERR_AUTH_FAIL: + return BT_SECURITY_ERR_AUTH_FAIL; + case BT_HCI_ERR_PIN_OR_KEY_MISSING: + return BT_SECURITY_ERR_PIN_OR_KEY_MISSING; + case BT_HCI_ERR_PAIRING_NOT_SUPPORTED: + return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED; + case BT_HCI_ERR_PAIRING_NOT_ALLOWED: + return BT_SECURITY_ERR_PAIR_NOT_ALLOWED; + case BT_HCI_ERR_INVALID_PARAM: + return BT_SECURITY_ERR_INVALID_PARAM; + default: + return BT_SECURITY_ERR_UNSPECIFIED; + } } static void reset_pairing(struct bt_conn *conn) { #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING); - atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR); - atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE); - } + if (conn->type == BT_CONN_TYPE_BR) { + atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING); + atomic_clear_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR); + atomic_clear_bit(conn->flags, BT_CONN_BR_LEGACY_SECURE); + } #endif /* CONFIG_BT_BREDR */ - /* Reset required security level to current operational */ - conn->required_sec_level = conn->sec_level; + /* Reset required security level to current operational */ + conn->required_sec_level = conn->sec_level; } #endif /* defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) */ #if defined(CONFIG_BT_BREDR) static int reject_conn(const bt_addr_t *bdaddr, u8_t reason) { - struct bt_hci_cp_reject_conn_req *cp; - struct net_buf *buf; - int err; + struct bt_hci_cp_reject_conn_req *cp; + struct net_buf *buf; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_REJECT_CONN_REQ, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_REJECT_CONN_REQ, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, bdaddr); - cp->reason = reason; + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, bdaddr); + cp->reason = reason; - err = bt_hci_cmd_send_sync(BT_HCI_OP_REJECT_CONN_REQ, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_REJECT_CONN_REQ, buf, NULL); + if (err) { + return err; + } - return 0; + return 0; } static int accept_sco_conn(const bt_addr_t *bdaddr, struct bt_conn *sco_conn) { - struct bt_hci_cp_accept_sync_conn_req *cp; - struct net_buf *buf; - int err; + struct bt_hci_cp_accept_sync_conn_req *cp; + struct net_buf *buf; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, bdaddr); - cp->pkt_type = sco_conn->sco.pkt_type; - cp->tx_bandwidth = 0x00001f40; - cp->rx_bandwidth = 0x00001f40; - cp->max_latency = 0x0007; - cp->retrans_effort = 0x01; - cp->content_format = BT_VOICE_CVSD_16BIT; + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, bdaddr); + cp->pkt_type = sco_conn->sco.pkt_type; + cp->tx_bandwidth = 0x00001f40; + cp->rx_bandwidth = 0x00001f40; + cp->max_latency = 0x0007; + cp->retrans_effort = 0x01; + cp->content_format = BT_VOICE_CVSD_16BIT; - err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_SYNC_CONN_REQ, buf, NULL); + if (err) { + return err; + } - return 0; + return 0; } static int accept_conn(const bt_addr_t *bdaddr) { - struct bt_hci_cp_accept_conn_req *cp; - struct net_buf *buf; - int err; + struct bt_hci_cp_accept_conn_req *cp; + struct net_buf *buf; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_CONN_REQ, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_ACCEPT_CONN_REQ, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, bdaddr); - cp->role = BT_HCI_ROLE_SLAVE; + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, bdaddr); + cp->role = BT_HCI_ROLE_SLAVE; - err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_CONN_REQ, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_ACCEPT_CONN_REQ, buf, NULL); + if (err) { + return err; + } - return 0; + return 0; } static void bt_esco_conn_req(struct bt_hci_evt_conn_request *evt) { - struct bt_conn *sco_conn; + struct bt_conn *sco_conn; - sco_conn = bt_conn_add_sco(&evt->bdaddr, evt->link_type); - if (!sco_conn) { - reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES); - return; - } + sco_conn = bt_conn_add_sco(&evt->bdaddr, evt->link_type); + if (!sco_conn) { + reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES); + return; + } - if (accept_sco_conn(&evt->bdaddr, sco_conn)) { - BT_ERR("Error accepting connection from %s", - bt_addr_str(&evt->bdaddr)); - reject_conn(&evt->bdaddr, BT_HCI_ERR_UNSPECIFIED); - bt_sco_cleanup(sco_conn); - return; - } + if (accept_sco_conn(&evt->bdaddr, sco_conn)) { + BT_ERR("Error accepting connection from %s", + bt_addr_str(&evt->bdaddr)); + reject_conn(&evt->bdaddr, BT_HCI_ERR_UNSPECIFIED); + bt_sco_cleanup(sco_conn); + return; + } - sco_conn->role = BT_HCI_ROLE_SLAVE; - bt_conn_set_state(sco_conn, BT_CONN_CONNECT); - bt_conn_unref(sco_conn); + sco_conn->role = BT_HCI_ROLE_SLAVE; + bt_conn_set_state(sco_conn, BT_CONN_CONNECT); + bt_conn_unref(sco_conn); } static void conn_req(struct net_buf *buf) { - struct bt_hci_evt_conn_request *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_conn_request *evt = (void *)buf->data; + struct bt_conn *conn; - BT_DBG("conn req from %s, type 0x%02x", bt_addr_str(&evt->bdaddr), - evt->link_type); + BT_DBG("conn req from %s, type 0x%02x", bt_addr_str(&evt->bdaddr), + evt->link_type); - if (evt->link_type != BT_HCI_ACL) { - bt_esco_conn_req(evt); - return; - } + if (evt->link_type != BT_HCI_ACL) { + bt_esco_conn_req(evt); + return; + } - conn = bt_conn_add_br(&evt->bdaddr); - if (!conn) { - reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES); - return; - } + conn = bt_conn_add_br(&evt->bdaddr); + if (!conn) { + reject_conn(&evt->bdaddr, BT_HCI_ERR_INSUFFICIENT_RESOURCES); + return; + } - accept_conn(&evt->bdaddr); - conn->role = BT_HCI_ROLE_SLAVE; - bt_conn_set_state(conn, BT_CONN_CONNECT); - bt_conn_unref(conn); + accept_conn(&evt->bdaddr); + conn->role = BT_HCI_ROLE_SLAVE; + bt_conn_set_state(conn, BT_CONN_CONNECT); + bt_conn_unref(conn); } static bool br_sufficient_key_size(struct bt_conn *conn) { - struct bt_hci_cp_read_encryption_key_size *cp; - struct bt_hci_rp_read_encryption_key_size *rp; - struct net_buf *buf, *rsp; - u8_t key_size; - int err; + struct bt_hci_cp_read_encryption_key_size *cp; + struct bt_hci_rp_read_encryption_key_size *rp; + struct net_buf *buf, *rsp; + u8_t key_size; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, - sizeof(*cp)); - if (!buf) { - BT_ERR("Failed to allocate command buffer"); - return false; - } + buf = bt_hci_cmd_create(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, + sizeof(*cp)); + if (!buf) { + BT_ERR("Failed to allocate command buffer"); + return false; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(conn->handle); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(conn->handle); - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, - buf, &rsp); - if (err) { - BT_ERR("Failed to read encryption key size (err %d)", err); - return false; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE, + buf, &rsp); + if (err) { + BT_ERR("Failed to read encryption key size (err %d)", err); + return false; + } - if (rsp->len < sizeof(*rp)) { - BT_ERR("Too small command complete for encryption key size"); - net_buf_unref(rsp); - return false; - } + if (rsp->len < sizeof(*rp)) { + BT_ERR("Too small command complete for encryption key size"); + net_buf_unref(rsp); + return false; + } - rp = (void *)rsp->data; - key_size = rp->key_size; - net_buf_unref(rsp); + rp = (void *)rsp->data; + key_size = rp->key_size; + net_buf_unref(rsp); - BT_DBG("Encryption key size is %u", key_size); + BT_DBG("Encryption key size is %u", key_size); - if (conn->sec_level == BT_SECURITY_L4) { - return key_size == BT_HCI_ENCRYPTION_KEY_SIZE_MAX; - } + if (conn->sec_level == BT_SECURITY_L4) { + return key_size == BT_HCI_ENCRYPTION_KEY_SIZE_MAX; + } - return key_size >= BT_HCI_ENCRYPTION_KEY_SIZE_MIN; + return key_size >= BT_HCI_ENCRYPTION_KEY_SIZE_MIN; } static bool update_sec_level_br(struct bt_conn *conn) { - if (!conn->encrypt) { - conn->sec_level = BT_SECURITY_L1; - return true; - } + if (!conn->encrypt) { + conn->sec_level = BT_SECURITY_L1; + return true; + } - if (conn->br.link_key) { - if (conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) { - if (conn->encrypt == 0x02) { - conn->sec_level = BT_SECURITY_L4; - } else { - conn->sec_level = BT_SECURITY_L3; - } - } else { - conn->sec_level = BT_SECURITY_L2; - } - } else { - BT_WARN("No BR/EDR link key found"); - conn->sec_level = BT_SECURITY_L2; - } + if (conn->br.link_key) { + if (conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) { + if (conn->encrypt == 0x02) { + conn->sec_level = BT_SECURITY_L4; + } else { + conn->sec_level = BT_SECURITY_L3; + } + } else { + conn->sec_level = BT_SECURITY_L2; + } + } else { + BT_WARN("No BR/EDR link key found"); + conn->sec_level = BT_SECURITY_L2; + } - if (!br_sufficient_key_size(conn)) { - BT_ERR("Encryption key size is not sufficient"); - bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); - return false; - } + if (!br_sufficient_key_size(conn)) { + BT_ERR("Encryption key size is not sufficient"); + bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); + return false; + } - if (conn->required_sec_level > conn->sec_level) { - BT_ERR("Failed to set required security level"); - bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); - return false; - } + if (conn->required_sec_level > conn->sec_level) { + BT_ERR("Failed to set required security level"); + bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); + return false; + } - return true; + return true; } static void synchronous_conn_complete(struct net_buf *buf) { - struct bt_hci_evt_sync_conn_complete *evt = (void *)buf->data; - struct bt_conn *sco_conn; - u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_hci_evt_sync_conn_complete *evt = (void *)buf->data; + struct bt_conn *sco_conn; + u16_t handle = sys_le16_to_cpu(evt->handle); - BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, - evt->link_type); + BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, + evt->link_type); - sco_conn = bt_conn_lookup_addr_sco(&evt->bdaddr); - if (!sco_conn) { - BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + sco_conn = bt_conn_lookup_addr_sco(&evt->bdaddr); + if (!sco_conn) { + BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - if (evt->status) { - sco_conn->err = evt->status; - bt_conn_set_state(sco_conn, BT_CONN_DISCONNECTED); - bt_conn_unref(sco_conn); - return; - } + if (evt->status) { + sco_conn->err = evt->status; + bt_conn_set_state(sco_conn, BT_CONN_DISCONNECTED); + bt_conn_unref(sco_conn); + return; + } - sco_conn->handle = handle; - bt_conn_set_state(sco_conn, BT_CONN_CONNECTED); - bt_conn_unref(sco_conn); + sco_conn->handle = handle; + bt_conn_set_state(sco_conn, BT_CONN_CONNECTED); + bt_conn_unref(sco_conn); } static void conn_complete(struct net_buf *buf) { - struct bt_hci_evt_conn_complete *evt = (void *)buf->data; - struct bt_conn *conn; - struct bt_hci_cp_read_remote_features *cp; - u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_hci_evt_conn_complete *evt = (void *)buf->data; + struct bt_conn *conn; + struct bt_hci_cp_read_remote_features *cp; + u16_t handle = sys_le16_to_cpu(evt->handle); - BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, - evt->link_type); + BT_DBG("status 0x%02x, handle %u, type 0x%02x", evt->status, handle, + evt->link_type); - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - if (evt->status) { - conn->err = evt->status; - bt_conn_set_state(conn, BT_CONN_DISCONNECTED); - bt_conn_unref(conn); - return; - } + if (evt->status) { + conn->err = evt->status; + bt_conn_set_state(conn, BT_CONN_DISCONNECTED); + bt_conn_unref(conn); + return; + } - conn->handle = handle; - conn->err = 0U; - conn->encrypt = evt->encr_enabled; + conn->handle = handle; + conn->err = 0U; + conn->encrypt = evt->encr_enabled; - if (!update_sec_level_br(conn)) { - bt_conn_unref(conn); - return; - } + if (!update_sec_level_br(conn)) { + bt_conn_unref(conn); + return; + } - bt_conn_set_state(conn, BT_CONN_CONNECTED); - bt_conn_unref(conn); + bt_conn_set_state(conn, BT_CONN_CONNECTED); + bt_conn_unref(conn); - buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_FEATURES, sizeof(*cp)); - if (!buf) { - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_FEATURES, sizeof(*cp)); + if (!buf) { + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = evt->handle; + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = evt->handle; - bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_FEATURES, buf, NULL); + bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_FEATURES, buf, NULL); } static void pin_code_req(struct net_buf *buf) { - struct bt_hci_evt_pin_code_req *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_pin_code_req *evt = (void *)buf->data; + struct bt_conn *conn; - BT_DBG(""); + BT_DBG(""); - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - bt_conn_pin_code_req(conn); - bt_conn_unref(conn); + bt_conn_pin_code_req(conn); + bt_conn_unref(conn); } static void link_key_notify(struct net_buf *buf) { - struct bt_hci_evt_link_key_notify *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_link_key_notify *evt = (void *)buf->data; + struct bt_conn *conn; - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - BT_DBG("%s, link type 0x%02x", bt_addr_str(&evt->bdaddr), evt->key_type); + BT_DBG("%s, link type 0x%02x", bt_addr_str(&evt->bdaddr), evt->key_type); - if (!conn->br.link_key) { - conn->br.link_key = bt_keys_get_link_key(&evt->bdaddr); - } - if (!conn->br.link_key) { - BT_ERR("Can't update keys for %s", bt_addr_str(&evt->bdaddr)); - bt_conn_unref(conn); - return; - } + if (!conn->br.link_key) { + conn->br.link_key = bt_keys_get_link_key(&evt->bdaddr); + } + if (!conn->br.link_key) { + BT_ERR("Can't update keys for %s", bt_addr_str(&evt->bdaddr)); + bt_conn_unref(conn); + return; + } - /* clear any old Link Key flags */ - conn->br.link_key->flags = 0U; + /* clear any old Link Key flags */ + conn->br.link_key->flags = 0U; - switch (evt->key_type) { - case BT_LK_COMBINATION: - /* - * Setting Combination Link Key as AUTHENTICATED means it was - * successfully generated by 16 digits wide PIN code. - */ - if (atomic_test_and_clear_bit(conn->flags, - BT_CONN_BR_LEGACY_SECURE)) { - conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; - } - memcpy(conn->br.link_key->val, evt->link_key, 16); - break; - case BT_LK_AUTH_COMBINATION_P192: - conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; - /* fall through */ - __attribute__ ((fallthrough)); - case BT_LK_UNAUTH_COMBINATION_P192: - /* Mark no-bond so that link-key is removed on disconnection */ - if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) { - atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND); - } + switch (evt->key_type) { + case BT_LK_COMBINATION: + /* + * Setting Combination Link Key as AUTHENTICATED means it was + * successfully generated by 16 digits wide PIN code. + */ + if (atomic_test_and_clear_bit(conn->flags, + BT_CONN_BR_LEGACY_SECURE)) { + conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; + } + memcpy(conn->br.link_key->val, evt->link_key, 16); + break; + case BT_LK_AUTH_COMBINATION_P192: + conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; + /* fall through */ + __attribute__ ((fallthrough)); + case BT_LK_UNAUTH_COMBINATION_P192: + /* Mark no-bond so that link-key is removed on disconnection */ + if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) { + atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND); + } - memcpy(conn->br.link_key->val, evt->link_key, 16); - break; - case BT_LK_AUTH_COMBINATION_P256: - conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; - /* fall through */ - __attribute__ ((fallthrough)); - case BT_LK_UNAUTH_COMBINATION_P256: - conn->br.link_key->flags |= BT_LINK_KEY_SC; + memcpy(conn->br.link_key->val, evt->link_key, 16); + break; + case BT_LK_AUTH_COMBINATION_P256: + conn->br.link_key->flags |= BT_LINK_KEY_AUTHENTICATED; + /* fall through */ + __attribute__ ((fallthrough)); + case BT_LK_UNAUTH_COMBINATION_P256: + conn->br.link_key->flags |= BT_LINK_KEY_SC; - /* Mark no-bond so that link-key is removed on disconnection */ - if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) { - atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND); - } + /* Mark no-bond so that link-key is removed on disconnection */ + if (bt_conn_ssp_get_auth(conn) < BT_HCI_DEDICATED_BONDING) { + atomic_set_bit(conn->flags, BT_CONN_BR_NOBOND); + } - memcpy(conn->br.link_key->val, evt->link_key, 16); - break; - default: - BT_WARN("Unsupported Link Key type %u", evt->key_type); - (void)memset(conn->br.link_key->val, 0, - sizeof(conn->br.link_key->val)); - break; - } + memcpy(conn->br.link_key->val, evt->link_key, 16); + break; + default: + BT_WARN("Unsupported Link Key type %u", evt->key_type); + (void)memset(conn->br.link_key->val, 0, + sizeof(conn->br.link_key->val)); + break; + } - bt_conn_unref(conn); + bt_conn_unref(conn); } static void link_key_neg_reply(const bt_addr_t *bdaddr) { - struct bt_hci_cp_link_key_neg_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_link_key_neg_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_NEG_REPLY, sizeof(*cp)); - if (!buf) { - BT_ERR("Out of command buffers"); - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_NEG_REPLY, sizeof(*cp)); + if (!buf) { + BT_ERR("Out of command buffers"); + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, bdaddr); - bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_NEG_REPLY, buf, NULL); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, bdaddr); + bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_NEG_REPLY, buf, NULL); } static void link_key_reply(const bt_addr_t *bdaddr, const u8_t *lk) { - struct bt_hci_cp_link_key_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_link_key_reply *cp; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_REPLY, sizeof(*cp)); - if (!buf) { - BT_ERR("Out of command buffers"); - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LINK_KEY_REPLY, sizeof(*cp)); + if (!buf) { + BT_ERR("Out of command buffers"); + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, bdaddr); - memcpy(cp->link_key, lk, 16); - bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_REPLY, buf, NULL); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, bdaddr); + memcpy(cp->link_key, lk, 16); + bt_hci_cmd_send_sync(BT_HCI_OP_LINK_KEY_REPLY, buf, NULL); } static void link_key_req(struct net_buf *buf) { - struct bt_hci_evt_link_key_req *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_link_key_req *evt = (void *)buf->data; + struct bt_conn *conn; - BT_DBG("%s", bt_addr_str(&evt->bdaddr)); + BT_DBG("%s", bt_addr_str(&evt->bdaddr)); - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - link_key_neg_reply(&evt->bdaddr); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + link_key_neg_reply(&evt->bdaddr); + return; + } - if (!conn->br.link_key) { - conn->br.link_key = bt_keys_find_link_key(&evt->bdaddr); - } + if (!conn->br.link_key) { + conn->br.link_key = bt_keys_find_link_key(&evt->bdaddr); + } - if (!conn->br.link_key) { - link_key_neg_reply(&evt->bdaddr); - bt_conn_unref(conn); - return; - } + if (!conn->br.link_key) { + link_key_neg_reply(&evt->bdaddr); + bt_conn_unref(conn); + return; + } - /* - * Enforce regenerate by controller stronger link key since found one - * in database not covers requested security level. - */ - if (!(conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) && - conn->required_sec_level > BT_SECURITY_L2) { - link_key_neg_reply(&evt->bdaddr); - bt_conn_unref(conn); - return; - } + /* + * Enforce regenerate by controller stronger link key since found one + * in database not covers requested security level. + */ + if (!(conn->br.link_key->flags & BT_LINK_KEY_AUTHENTICATED) && + conn->required_sec_level > BT_SECURITY_L2) { + link_key_neg_reply(&evt->bdaddr); + bt_conn_unref(conn); + return; + } - link_key_reply(&evt->bdaddr, conn->br.link_key->val); - bt_conn_unref(conn); + link_key_reply(&evt->bdaddr, conn->br.link_key->val); + bt_conn_unref(conn); } static void io_capa_neg_reply(const bt_addr_t *bdaddr, const u8_t reason) { - struct bt_hci_cp_io_capability_neg_reply *cp; - struct net_buf *resp_buf; + struct bt_hci_cp_io_capability_neg_reply *cp; + struct net_buf *resp_buf; - resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, - sizeof(*cp)); - if (!resp_buf) { - BT_ERR("Out of command buffers"); - return; - } + resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, + sizeof(*cp)); + if (!resp_buf) { + BT_ERR("Out of command buffers"); + return; + } - cp = net_buf_add(resp_buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, bdaddr); - cp->reason = reason; - bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, resp_buf, NULL); + cp = net_buf_add(resp_buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, bdaddr); + cp->reason = reason; + bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_NEG_REPLY, resp_buf, NULL); } static void io_capa_resp(struct net_buf *buf) { - struct bt_hci_evt_io_capa_resp *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_io_capa_resp *evt = (void *)buf->data; + struct bt_conn *conn; - BT_DBG("remote %s, IOcapa 0x%02x, auth 0x%02x", - bt_addr_str(&evt->bdaddr), evt->capability, evt->authentication); + BT_DBG("remote %s, IOcapa 0x%02x, auth 0x%02x", + bt_addr_str(&evt->bdaddr), evt->capability, evt->authentication); - if (evt->authentication > BT_HCI_GENERAL_BONDING_MITM) { - BT_ERR("Invalid remote authentication requirements"); - io_capa_neg_reply(&evt->bdaddr, - BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL); - return; - } + if (evt->authentication > BT_HCI_GENERAL_BONDING_MITM) { + BT_ERR("Invalid remote authentication requirements"); + io_capa_neg_reply(&evt->bdaddr, + BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL); + return; + } - if (evt->capability > BT_IO_NO_INPUT_OUTPUT) { - BT_ERR("Invalid remote io capability requirements"); - io_capa_neg_reply(&evt->bdaddr, - BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL); - return; - } + if (evt->capability > BT_IO_NO_INPUT_OUTPUT) { + BT_ERR("Invalid remote io capability requirements"); + io_capa_neg_reply(&evt->bdaddr, + BT_HCI_ERR_UNSUPP_FEATURE_PARAM_VAL); + return; + } - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Unable to find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - conn->br.remote_io_capa = evt->capability; - conn->br.remote_auth = evt->authentication; - atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING); - bt_conn_unref(conn); + conn->br.remote_io_capa = evt->capability; + conn->br.remote_auth = evt->authentication; + atomic_set_bit(conn->flags, BT_CONN_BR_PAIRING); + bt_conn_unref(conn); } static void io_capa_req(struct net_buf *buf) { - struct bt_hci_evt_io_capa_req *evt = (void *)buf->data; - struct net_buf *resp_buf; - struct bt_conn *conn; - struct bt_hci_cp_io_capability_reply *cp; - u8_t auth; + struct bt_hci_evt_io_capa_req *evt = (void *)buf->data; + struct net_buf *resp_buf; + struct bt_conn *conn; + struct bt_hci_cp_io_capability_reply *cp; + u8_t auth; - BT_DBG(""); + BT_DBG(""); - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_REPLY, - sizeof(*cp)); - if (!resp_buf) { - BT_ERR("Out of command buffers"); - bt_conn_unref(conn); - return; - } + resp_buf = bt_hci_cmd_create(BT_HCI_OP_IO_CAPABILITY_REPLY, + sizeof(*cp)); + if (!resp_buf) { + BT_ERR("Out of command buffers"); + bt_conn_unref(conn); + return; + } - /* - * Set authentication requirements when acting as pairing initiator to - * 'dedicated bond' with MITM protection set if local IO capa - * potentially allows it, and for acceptor, based on local IO capa and - * remote's authentication set. - */ - if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) { - if (bt_conn_get_io_capa() != BT_IO_NO_INPUT_OUTPUT) { - auth = BT_HCI_DEDICATED_BONDING_MITM; - } else { - auth = BT_HCI_DEDICATED_BONDING; - } - } else { - auth = bt_conn_ssp_get_auth(conn); - } + /* + * Set authentication requirements when acting as pairing initiator to + * 'dedicated bond' with MITM protection set if local IO capa + * potentially allows it, and for acceptor, based on local IO capa and + * remote's authentication set. + */ + if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING_INITIATOR)) { + if (bt_conn_get_io_capa() != BT_IO_NO_INPUT_OUTPUT) { + auth = BT_HCI_DEDICATED_BONDING_MITM; + } else { + auth = BT_HCI_DEDICATED_BONDING; + } + } else { + auth = bt_conn_ssp_get_auth(conn); + } - cp = net_buf_add(resp_buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, &evt->bdaddr); - cp->capability = bt_conn_get_io_capa(); - cp->authentication = auth; - cp->oob_data = 0U; - bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_REPLY, resp_buf, NULL); - bt_conn_unref(conn); + cp = net_buf_add(resp_buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, &evt->bdaddr); + cp->capability = bt_conn_get_io_capa(); + cp->authentication = auth; + cp->oob_data = 0U; + bt_hci_cmd_send_sync(BT_HCI_OP_IO_CAPABILITY_REPLY, resp_buf, NULL); + bt_conn_unref(conn); } static void ssp_complete(struct net_buf *buf) { - struct bt_hci_evt_ssp_complete *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_ssp_complete *evt = (void *)buf->data; + struct bt_conn *conn; - BT_DBG("status 0x%02x", evt->status); + BT_DBG("status 0x%02x", evt->status); - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - bt_conn_ssp_auth_complete(conn, security_err_get(evt->status)); - if (evt->status) { - bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); - } + bt_conn_ssp_auth_complete(conn, security_err_get(evt->status)); + if (evt->status) { + bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); + } - bt_conn_unref(conn); + bt_conn_unref(conn); } static void user_confirm_req(struct net_buf *buf) { - struct bt_hci_evt_user_confirm_req *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_user_confirm_req *evt = (void *)buf->data; + struct bt_conn *conn; - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey)); - bt_conn_unref(conn); + bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey)); + bt_conn_unref(conn); } static void user_passkey_notify(struct net_buf *buf) { - struct bt_hci_evt_user_passkey_notify *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_user_passkey_notify *evt = (void *)buf->data; + struct bt_conn *conn; - BT_DBG(""); + BT_DBG(""); - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey)); - bt_conn_unref(conn); + bt_conn_ssp_auth(conn, sys_le32_to_cpu(evt->passkey)); + bt_conn_unref(conn); } static void user_passkey_req(struct net_buf *buf) { - struct bt_hci_evt_user_passkey_req *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_user_passkey_req *evt = (void *)buf->data; + struct bt_conn *conn; - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - bt_conn_ssp_auth(conn, 0); - bt_conn_unref(conn); + bt_conn_ssp_auth(conn, 0); + bt_conn_unref(conn); } struct discovery_priv { - u16_t clock_offset; - u8_t pscan_rep_mode; - u8_t resolving; + u16_t clock_offset; + u8_t pscan_rep_mode; + u8_t resolving; } __packed; static int request_name(const bt_addr_t *addr, u8_t pscan, u16_t offset) { - struct bt_hci_cp_remote_name_request *cp; - struct net_buf *buf; + struct bt_hci_cp_remote_name_request *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_REQUEST, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_REQUEST, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, addr); - cp->pscan_rep_mode = pscan; - cp->reserved = 0x00; /* reserver, should be set to 0x00 */ - cp->clock_offset = offset; + bt_addr_copy(&cp->bdaddr, addr); + cp->pscan_rep_mode = pscan; + cp->reserved = 0x00; /* reserver, should be set to 0x00 */ + cp->clock_offset = offset; - return bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_REQUEST, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_REQUEST, buf, NULL); } -#define EIR_SHORT_NAME 0x08 -#define EIR_COMPLETE_NAME 0x09 +#define EIR_SHORT_NAME 0x08 +#define EIR_COMPLETE_NAME 0x09 static bool eir_has_name(const u8_t *eir) { - int len = 240; + int len = 240; - while (len) { - if (len < 2) { - break; - }; + while (len) { + if (len < 2) { + break; + }; - /* Look for early termination */ - if (!eir[0]) { - break; - } + /* Look for early termination */ + if (!eir[0]) { + break; + } - /* Check if field length is correct */ - if (eir[0] > len - 1) { - break; - } + /* Check if field length is correct */ + if (eir[0] > len - 1) { + break; + } - switch (eir[1]) { - case EIR_SHORT_NAME: - case EIR_COMPLETE_NAME: - if (eir[0] > 1) { - return true; - } - break; - default: - break; - } + switch (eir[1]) { + case EIR_SHORT_NAME: + case EIR_COMPLETE_NAME: + if (eir[0] > 1) { + return true; + } + break; + default: + break; + } - /* Parse next AD Structure */ - len -= eir[0] + 1; - eir += eir[0] + 1; - } + /* Parse next AD Structure */ + len -= eir[0] + 1; + eir += eir[0] + 1; + } - return false; + return false; } static void report_discovery_results(void) { - bool resolving_names = false; - int i; + bool resolving_names = false; + int i; - for (i = 0; i < discovery_results_count; i++) { - struct discovery_priv *priv; + for (i = 0; i < discovery_results_count; i++) { + struct discovery_priv *priv; - priv = (struct discovery_priv *)&discovery_results[i]._priv; + priv = (struct discovery_priv *)&discovery_results[i]._priv; - if (eir_has_name(discovery_results[i].eir)) { - continue; - } + if (eir_has_name(discovery_results[i].eir)) { + continue; + } - if (request_name(&discovery_results[i].addr, - priv->pscan_rep_mode, priv->clock_offset)) { - continue; - } + if (request_name(&discovery_results[i].addr, + priv->pscan_rep_mode, priv->clock_offset)) { + continue; + } - priv->resolving = 1U; - resolving_names = true; - } + priv->resolving = 1U; + resolving_names = true; + } - if (resolving_names) { - return; - } + if (resolving_names) { + return; + } - atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); + atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); - discovery_cb(discovery_results, discovery_results_count); + discovery_cb(discovery_results, discovery_results_count); - discovery_cb = NULL; - discovery_results = NULL; - discovery_results_size = 0; - discovery_results_count = 0; + discovery_cb = NULL; + discovery_results = NULL; + discovery_results_size = 0; + discovery_results_count = 0; } static void inquiry_complete(struct net_buf *buf) { - struct bt_hci_evt_inquiry_complete *evt = (void *)buf->data; + struct bt_hci_evt_inquiry_complete *evt = (void *)buf->data; - if (evt->status) { - BT_ERR("Failed to complete inquiry"); - } + if (evt->status) { + BT_ERR("Failed to complete inquiry"); + } - report_discovery_results(); + report_discovery_results(); } static struct bt_br_discovery_result *get_result_slot(const bt_addr_t *addr, - s8_t rssi) + s8_t rssi) { - struct bt_br_discovery_result *result = NULL; - size_t i; + struct bt_br_discovery_result *result = NULL; + size_t i; - /* check if already present in results */ - for (i = 0; i < discovery_results_count; i++) { - if (!bt_addr_cmp(addr, &discovery_results[i].addr)) { - return &discovery_results[i]; - } - } + /* check if already present in results */ + for (i = 0; i < discovery_results_count; i++) { + if (!bt_addr_cmp(addr, &discovery_results[i].addr)) { + return &discovery_results[i]; + } + } - /* Pick a new slot (if available) */ - if (discovery_results_count < discovery_results_size) { - bt_addr_copy(&discovery_results[discovery_results_count].addr, - addr); - return &discovery_results[discovery_results_count++]; - } + /* Pick a new slot (if available) */ + if (discovery_results_count < discovery_results_size) { + bt_addr_copy(&discovery_results[discovery_results_count].addr, + addr); + return &discovery_results[discovery_results_count++]; + } - /* ignore if invalid RSSI */ - if (rssi == 0xff) { - return NULL; - } + /* ignore if invalid RSSI */ + if (rssi == 0xff) { + return NULL; + } - /* - * Pick slot with smallest RSSI that is smaller then passed RSSI - * TODO handle TX if present - */ - for (i = 0; i < discovery_results_size; i++) { - if (discovery_results[i].rssi > rssi) { - continue; - } + /* + * Pick slot with smallest RSSI that is smaller then passed RSSI + * TODO handle TX if present + */ + for (i = 0; i < discovery_results_size; i++) { + if (discovery_results[i].rssi > rssi) { + continue; + } - if (!result || result->rssi > discovery_results[i].rssi) { - result = &discovery_results[i]; - } - } + if (!result || result->rssi > discovery_results[i].rssi) { + result = &discovery_results[i]; + } + } - if (result) { - BT_DBG("Reusing slot (old %s rssi %d dBm)", - bt_addr_str(&result->addr), result->rssi); + if (result) { + BT_DBG("Reusing slot (old %s rssi %d dBm)", + bt_addr_str(&result->addr), result->rssi); - bt_addr_copy(&result->addr, addr); - } + bt_addr_copy(&result->addr, addr); + } - return result; + return result; } static void inquiry_result_with_rssi(struct net_buf *buf) { - u8_t num_reports = net_buf_pull_u8(buf); + u8_t num_reports = net_buf_pull_u8(buf); - if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { - return; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { + return; + } - BT_DBG("number of results: %u", num_reports); + BT_DBG("number of results: %u", num_reports); - while (num_reports--) { - struct bt_hci_evt_inquiry_result_with_rssi *evt; - struct bt_br_discovery_result *result; - struct discovery_priv *priv; + while (num_reports--) { + struct bt_hci_evt_inquiry_result_with_rssi *evt; + struct bt_br_discovery_result *result; + struct discovery_priv *priv; - if (buf->len < sizeof(*evt)) { - BT_ERR("Unexpected end to buffer"); - return; - } + if (buf->len < sizeof(*evt)) { + BT_ERR("Unexpected end to buffer"); + return; + } - evt = net_buf_pull_mem(buf, sizeof(*evt)); - BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi); + evt = net_buf_pull_mem(buf, sizeof(*evt)); + BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi); - result = get_result_slot(&evt->addr, evt->rssi); - if (!result) { - return; - } + result = get_result_slot(&evt->addr, evt->rssi); + if (!result) { + return; + } - priv = (struct discovery_priv *)&result->_priv; - priv->pscan_rep_mode = evt->pscan_rep_mode; - priv->clock_offset = evt->clock_offset; + priv = (struct discovery_priv *)&result->_priv; + priv->pscan_rep_mode = evt->pscan_rep_mode; + priv->clock_offset = evt->clock_offset; - memcpy(result->cod, evt->cod, 3); - result->rssi = evt->rssi; + memcpy(result->cod, evt->cod, 3); + result->rssi = evt->rssi; - /* we could reuse slot so make sure EIR is cleared */ - (void)memset(result->eir, 0, sizeof(result->eir)); - } + /* we could reuse slot so make sure EIR is cleared */ + (void)memset(result->eir, 0, sizeof(result->eir)); + } } static void extended_inquiry_result(struct net_buf *buf) { - struct bt_hci_evt_extended_inquiry_result *evt = (void *)buf->data; - struct bt_br_discovery_result *result; - struct discovery_priv *priv; + struct bt_hci_evt_extended_inquiry_result *evt = (void *)buf->data; + struct bt_br_discovery_result *result; + struct discovery_priv *priv; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { - return; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { + return; + } - BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi); + BT_DBG("%s rssi %d dBm", bt_addr_str(&evt->addr), evt->rssi); - result = get_result_slot(&evt->addr, evt->rssi); - if (!result) { - return; - } + result = get_result_slot(&evt->addr, evt->rssi); + if (!result) { + return; + } - priv = (struct discovery_priv *)&result->_priv; - priv->pscan_rep_mode = evt->pscan_rep_mode; - priv->clock_offset = evt->clock_offset; + priv = (struct discovery_priv *)&result->_priv; + priv->pscan_rep_mode = evt->pscan_rep_mode; + priv->clock_offset = evt->clock_offset; - result->rssi = evt->rssi; - memcpy(result->cod, evt->cod, 3); - memcpy(result->eir, evt->eir, sizeof(result->eir)); + result->rssi = evt->rssi; + memcpy(result->cod, evt->cod, 3); + memcpy(result->eir, evt->eir, sizeof(result->eir)); } static void remote_name_request_complete(struct net_buf *buf) { - struct bt_hci_evt_remote_name_req_complete *evt = (void *)buf->data; - struct bt_br_discovery_result *result; - struct discovery_priv *priv; - int eir_len = 240; - u8_t *eir; - int i; + struct bt_hci_evt_remote_name_req_complete *evt = (void *)buf->data; + struct bt_br_discovery_result *result; + struct discovery_priv *priv; + int eir_len = 240; + u8_t *eir; + int i; - result = get_result_slot(&evt->bdaddr, 0xff); - if (!result) { - return; - } + result = get_result_slot(&evt->bdaddr, 0xff); + if (!result) { + return; + } - priv = (struct discovery_priv *)&result->_priv; - priv->resolving = 0U; + priv = (struct discovery_priv *)&result->_priv; + priv->resolving = 0U; - if (evt->status) { - goto check_names; - } + if (evt->status) { + goto check_names; + } - eir = result->eir; + eir = result->eir; - while (eir_len) { - if (eir_len < 2) { - break; - }; + while (eir_len) { + if (eir_len < 2) { + break; + }; - /* Look for early termination */ - if (!eir[0]) { - size_t name_len; + /* Look for early termination */ + if (!eir[0]) { + size_t name_len; - eir_len -= 2; + eir_len -= 2; - /* name is null terminated */ - name_len = strlen((const char *)evt->name); + /* name is null terminated */ + name_len = strlen((const char *)evt->name); - if (name_len > eir_len) { - eir[0] = eir_len + 1; - eir[1] = EIR_SHORT_NAME; - } else { - eir[0] = name_len + 1; - eir[1] = EIR_SHORT_NAME; - } + if (name_len > eir_len) { + eir[0] = eir_len + 1; + eir[1] = EIR_SHORT_NAME; + } else { + eir[0] = name_len + 1; + eir[1] = EIR_SHORT_NAME; + } - memcpy(&eir[2], evt->name, eir[0] - 1); + memcpy(&eir[2], evt->name, eir[0] - 1); - break; - } + break; + } - /* Check if field length is correct */ - if (eir[0] > eir_len - 1) { - break; - } + /* Check if field length is correct */ + if (eir[0] > eir_len - 1) { + break; + } - /* next EIR Structure */ - eir_len -= eir[0] + 1; - eir += eir[0] + 1; - } + /* next EIR Structure */ + eir_len -= eir[0] + 1; + eir += eir[0] + 1; + } check_names: - /* if still waiting for names */ - for (i = 0; i < discovery_results_count; i++) { - struct discovery_priv *priv; + /* if still waiting for names */ + for (i = 0; i < discovery_results_count; i++) { + struct discovery_priv *priv; - priv = (struct discovery_priv *)&discovery_results[i]._priv; + priv = (struct discovery_priv *)&discovery_results[i]._priv; - if (priv->resolving) { - return; - } - } + if (priv->resolving) { + return; + } + } - /* all names resolved, report discovery results */ - atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); + /* all names resolved, report discovery results */ + atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); - discovery_cb(discovery_results, discovery_results_count); + discovery_cb(discovery_results, discovery_results_count); - discovery_cb = NULL; - discovery_results = NULL; - discovery_results_size = 0; - discovery_results_count = 0; + discovery_cb = NULL; + discovery_results = NULL; + discovery_results_size = 0; + discovery_results_count = 0; } static void link_encr(const u16_t handle) { - struct bt_hci_cp_set_conn_encrypt *encr; - struct net_buf *buf; + struct bt_hci_cp_set_conn_encrypt *encr; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = bt_hci_cmd_create(BT_HCI_OP_SET_CONN_ENCRYPT, sizeof(*encr)); - if (!buf) { - BT_ERR("Out of command buffers"); - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_SET_CONN_ENCRYPT, sizeof(*encr)); + if (!buf) { + BT_ERR("Out of command buffers"); + return; + } - encr = net_buf_add(buf, sizeof(*encr)); - encr->handle = sys_cpu_to_le16(handle); - encr->encrypt = 0x01; + encr = net_buf_add(buf, sizeof(*encr)); + encr->handle = sys_cpu_to_le16(handle); + encr->encrypt = 0x01; - bt_hci_cmd_send_sync(BT_HCI_OP_SET_CONN_ENCRYPT, buf, NULL); + bt_hci_cmd_send_sync(BT_HCI_OP_SET_CONN_ENCRYPT, buf, NULL); } static void auth_complete(struct net_buf *buf) { - struct bt_hci_evt_auth_complete *evt = (void *)buf->data; - struct bt_conn *conn; - u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_hci_evt_auth_complete *evt = (void *)buf->data; + struct bt_conn *conn; + u16_t handle = sys_le16_to_cpu(evt->handle); - BT_DBG("status 0x%02x, handle %u", evt->status, handle); + BT_DBG("status 0x%02x, handle %u", evt->status, handle); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Can't find conn for handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Can't find conn for handle %u", handle); + return; + } - if (evt->status) { - if (conn->state == BT_CONN_CONNECTED) { - /* - * Inform layers above HCI about non-zero authentication - * status to make them able cleanup pending jobs. - */ - bt_l2cap_encrypt_change(conn, evt->status); - } - reset_pairing(conn); - } else { - link_encr(handle); - } + if (evt->status) { + if (conn->state == BT_CONN_CONNECTED) { + /* + * Inform layers above HCI about non-zero authentication + * status to make them able cleanup pending jobs. + */ + bt_l2cap_encrypt_change(conn, evt->status); + } + reset_pairing(conn); + } else { + link_encr(handle); + } - bt_conn_unref(conn); + bt_conn_unref(conn); } static void read_remote_features_complete(struct net_buf *buf) { - struct bt_hci_evt_remote_features *evt = (void *)buf->data; - u16_t handle = sys_le16_to_cpu(evt->handle); - struct bt_hci_cp_read_remote_ext_features *cp; - struct bt_conn *conn; + struct bt_hci_evt_remote_features *evt = (void *)buf->data; + u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_hci_cp_read_remote_ext_features *cp; + struct bt_conn *conn; - BT_DBG("status 0x%02x handle %u", evt->status, handle); + BT_DBG("status 0x%02x handle %u", evt->status, handle); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Can't find conn for handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Can't find conn for handle %u", handle); + return; + } - if (evt->status) { - goto done; - } + if (evt->status) { + goto done; + } - memcpy(conn->br.features[0], evt->features, sizeof(evt->features)); + memcpy(conn->br.features[0], evt->features, sizeof(evt->features)); - if (!BT_FEAT_EXT_FEATURES(conn->br.features)) { - goto done; - } + if (!BT_FEAT_EXT_FEATURES(conn->br.features)) { + goto done; + } - buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, - sizeof(*cp)); - if (!buf) { - goto done; - } + buf = bt_hci_cmd_create(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, + sizeof(*cp)); + if (!buf) { + goto done; + } - /* Read remote host features (page 1) */ - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = evt->handle; - cp->page = 0x01; + /* Read remote host features (page 1) */ + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = evt->handle; + cp->page = 0x01; - bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, buf, NULL); + bt_hci_cmd_send_sync(BT_HCI_OP_READ_REMOTE_EXT_FEATURES, buf, NULL); done: - bt_conn_unref(conn); + bt_conn_unref(conn); } static void read_remote_ext_features_complete(struct net_buf *buf) { - struct bt_hci_evt_remote_ext_features *evt = (void *)buf->data; - u16_t handle = sys_le16_to_cpu(evt->handle); - struct bt_conn *conn; + struct bt_hci_evt_remote_ext_features *evt = (void *)buf->data; + u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_conn *conn; - BT_DBG("status 0x%02x handle %u", evt->status, handle); + BT_DBG("status 0x%02x handle %u", evt->status, handle); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Can't find conn for handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Can't find conn for handle %u", handle); + return; + } - if (!evt->status && evt->page == 0x01) { - memcpy(conn->br.features[1], evt->features, - sizeof(conn->br.features[1])); - } + if (!evt->status && evt->page == 0x01) { + memcpy(conn->br.features[1], evt->features, + sizeof(conn->br.features[1])); + } - bt_conn_unref(conn); + bt_conn_unref(conn); } static void role_change(struct net_buf *buf) { - struct bt_hci_evt_role_change *evt = (void *)buf->data; - struct bt_conn *conn; + struct bt_hci_evt_role_change *evt = (void *)buf->data; + struct bt_conn *conn; - BT_DBG("status 0x%02x role %u addr %s", evt->status, evt->role, - bt_addr_str(&evt->bdaddr)); + BT_DBG("status 0x%02x role %u addr %s", evt->status, evt->role, + bt_addr_str(&evt->bdaddr)); - if (evt->status) { - return; - } + if (evt->status) { + return; + } - conn = bt_conn_lookup_addr_br(&evt->bdaddr); - if (!conn) { - BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); - return; - } + conn = bt_conn_lookup_addr_br(&evt->bdaddr); + if (!conn) { + BT_ERR("Can't find conn for %s", bt_addr_str(&evt->bdaddr)); + return; + } - if (evt->role) { - conn->role = BT_CONN_ROLE_SLAVE; - } else { - conn->role = BT_CONN_ROLE_MASTER; - } + if (evt->role) { + conn->role = BT_CONN_ROLE_SLAVE; + } else { + conn->role = BT_CONN_ROLE_MASTER; + } - bt_conn_unref(conn); + bt_conn_unref(conn); } #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_SMP) static int le_set_privacy_mode(const bt_addr_le_t *addr, u8_t mode) { - struct bt_hci_cp_le_set_privacy_mode cp; - struct net_buf *buf; - int err; + struct bt_hci_cp_le_set_privacy_mode cp; + struct net_buf *buf; + int err; - /* Check if set privacy mode command is supported */ - if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) { - BT_WARN("Set privacy mode command is not supported"); - return 0; - } + /* Check if set privacy mode command is supported */ + if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) { + BT_WARN("Set privacy mode command is not supported"); + return 0; + } - BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode); + BT_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode); - bt_addr_le_copy(&cp.id_addr, addr); - cp.mode = mode; + bt_addr_le_copy(&cp.id_addr, addr); + cp.mode = mode; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp)); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_mem(buf, &cp, sizeof(cp)); + net_buf_add_mem(buf, &cp, sizeof(cp)); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL); + if (err) { + return err; + } - return 0; + return 0; } #if defined(CONFIG_BT_STACK_PTS) int addr_res_enable(u8_t enable) @@ -3078,19 +3078,19 @@ int addr_res_enable(u8_t enable) static int addr_res_enable(u8_t enable) #endif { - struct net_buf *buf; + struct net_buf *buf; - BT_DBG("%s", enable ? "enabled" : "disabled"); + BT_DBG("%s", enable ? "enabled" : "disabled"); - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_u8(buf, enable); + net_buf_add_u8(buf, enable); - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, - buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, + buf, NULL); } @@ -3100,639 +3100,639 @@ int hci_id_add(const bt_addr_le_t *addr, u8_t val[16]) static int hci_id_add(const bt_addr_le_t *addr, u8_t val[16]) #endif { - struct bt_hci_cp_le_add_dev_to_rl *cp; - struct net_buf *buf; + struct bt_hci_cp_le_add_dev_to_rl *cp; + struct net_buf *buf; - BT_DBG("addr %s", bt_addr_le_str(addr)); + BT_DBG("addr %s", bt_addr_le_str(addr)); - buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_le_copy(&cp->peer_id_addr, addr); - memcpy(cp->peer_irk, val, 16); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_le_copy(&cp->peer_id_addr, addr); + memcpy(cp->peer_irk, val, 16); #if defined(CONFIG_BT_PRIVACY) - memcpy(cp->local_irk, bt_dev.irk, 16); + memcpy(cp->local_irk, bt_dev.irk, 16); #else - (void)memset(cp->local_irk, 0, 16); + (void)memset(cp->local_irk, 0, 16); #endif - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL); } void bt_id_add(struct bt_keys *keys) { - bool adv_enabled; + bool adv_enabled; #if defined(CONFIG_BT_OBSERVER) - bool scan_enabled; + bool scan_enabled; #endif /* CONFIG_BT_OBSERVER */ - struct bt_conn *conn; - int err; + struct bt_conn *conn; + int err; - BT_DBG("addr %s", bt_addr_le_str(&keys->addr)); + BT_DBG("addr %s", bt_addr_le_str(&keys->addr)); - /* Nothing to be done if host-side resolving is used */ - if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { - bt_dev.le.rl_entries++; - return; - } + /* Nothing to be done if host-side resolving is used */ + if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) { + bt_dev.le.rl_entries++; + return; + } - conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); - if (conn) { - atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING); - keys->flags |= BT_KEYS_ID_PENDING_ADD; - bt_conn_unref(conn); - return; - } + conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); + if (conn) { + atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING); + keys->flags |= BT_KEYS_ID_PENDING_ADD; + bt_conn_unref(conn); + return; + } - adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING); - if (adv_enabled) { - set_advertise_enable(false); - } + adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING); + if (adv_enabled) { + set_advertise_enable(false); + } #if defined(CONFIG_BT_OBSERVER) - scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING); - if (scan_enabled) { - set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); - } + scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING); + if (scan_enabled) { + set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); + } #endif /* CONFIG_BT_OBSERVER */ - /* If there are any existing entries address resolution will be on */ - if (bt_dev.le.rl_entries) { - err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE); - if (err) { - BT_WARN("Failed to disable address resolution"); - goto done; - } - } + /* If there are any existing entries address resolution will be on */ + if (bt_dev.le.rl_entries) { + err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE); + if (err) { + BT_WARN("Failed to disable address resolution"); + goto done; + } + } - if (bt_dev.le.rl_entries == bt_dev.le.rl_size) { - BT_WARN("Resolving list size exceeded. Switching to host."); + if (bt_dev.le.rl_entries == bt_dev.le.rl_size) { + BT_WARN("Resolving list size exceeded. Switching to host."); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL); - if (err) { - BT_ERR("Failed to clear resolution list"); - goto done; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL); + if (err) { + BT_ERR("Failed to clear resolution list"); + goto done; + } - bt_dev.le.rl_entries++; + bt_dev.le.rl_entries++; - goto done; - } + goto done; + } - err = hci_id_add(&keys->addr, keys->irk.val); - if (err) { - BT_ERR("Failed to add IRK to controller"); - goto done; - } + err = hci_id_add(&keys->addr, keys->irk.val); + if (err) { + BT_ERR("Failed to add IRK to controller"); + goto done; + } - bt_dev.le.rl_entries++; + bt_dev.le.rl_entries++; - /* - * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature - * - * By default, network privacy mode is used when private addresses are - * resolved and generated by the Controller, so advertising packets from - * peer devices that contain private addresses will only be accepted. - * By changing to the device privacy mode device is only concerned about - * its privacy and will accept advertising packets from peer devices - * that contain their identity address as well as ones that contain - * a private address, even if the peer device has distributed its IRK in - * the past. - */ - err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE); - if (err) { - BT_ERR("Failed to set privacy mode"); - goto done; - } + /* + * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature + * + * By default, network privacy mode is used when private addresses are + * resolved and generated by the Controller, so advertising packets from + * peer devices that contain private addresses will only be accepted. + * By changing to the device privacy mode device is only concerned about + * its privacy and will accept advertising packets from peer devices + * that contain their identity address as well as ones that contain + * a private address, even if the peer device has distributed its IRK in + * the past. + */ + err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE); + if (err) { + BT_ERR("Failed to set privacy mode"); + goto done; + } done: - addr_res_enable(BT_HCI_ADDR_RES_ENABLE); + addr_res_enable(BT_HCI_ADDR_RES_ENABLE); #if defined(CONFIG_BT_OBSERVER) - if (scan_enabled) { - set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); - } + if (scan_enabled) { + set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); + } #endif /* CONFIG_BT_OBSERVER */ - if (adv_enabled) { - set_advertise_enable(true); - } + if (adv_enabled) { + set_advertise_enable(true); + } } static void keys_add_id(struct bt_keys *keys, void *data) { - hci_id_add(&keys->addr, keys->irk.val); + hci_id_add(&keys->addr, keys->irk.val); } void bt_id_del(struct bt_keys *keys) { - struct bt_hci_cp_le_rem_dev_from_rl *cp; - bool adv_enabled; + struct bt_hci_cp_le_rem_dev_from_rl *cp; + bool adv_enabled; #if defined(CONFIG_BT_OBSERVER) - bool scan_enabled; + bool scan_enabled; #endif /* CONFIG_BT_OBSERVER */ - struct bt_conn *conn; - struct net_buf *buf; - int err; + struct bt_conn *conn; + struct net_buf *buf; + int err; - BT_DBG("addr %s", bt_addr_le_str(&keys->addr)); + BT_DBG("addr %s", bt_addr_le_str(&keys->addr)); - if (!bt_dev.le.rl_size || - bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) { - bt_dev.le.rl_entries--; - return; - } + if (!bt_dev.le.rl_size || + bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) { + bt_dev.le.rl_entries--; + return; + } - conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); - if (conn) { - atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING); - keys->flags |= BT_KEYS_ID_PENDING_DEL; - bt_conn_unref(conn); - return; - } + conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); + if (conn) { + atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING); + keys->flags |= BT_KEYS_ID_PENDING_DEL; + bt_conn_unref(conn); + return; + } - adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING); - if (adv_enabled) { - set_advertise_enable(false); - } + adv_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING); + if (adv_enabled) { + set_advertise_enable(false); + } #if defined(CONFIG_BT_OBSERVER) - scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING); - if (scan_enabled) { - set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); - } + scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING); + if (scan_enabled) { + set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); + } #endif /* CONFIG_BT_OBSERVER */ - err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE); - if (err) { - BT_ERR("Disabling address resolution failed (err %d)", err); - goto done; - } + err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE); + if (err) { + BT_ERR("Disabling address resolution failed (err %d)", err); + goto done; + } - /* We checked size + 1 earlier, so here we know we can fit again */ - if (bt_dev.le.rl_entries > bt_dev.le.rl_size) { - bt_dev.le.rl_entries--; - keys->keys &= ~BT_KEYS_IRK; - bt_keys_foreach(BT_KEYS_IRK, keys_add_id, NULL); - goto done; - } + /* We checked size + 1 earlier, so here we know we can fit again */ + if (bt_dev.le.rl_entries > bt_dev.le.rl_size) { + bt_dev.le.rl_entries--; + keys->keys &= ~BT_KEYS_IRK; + bt_keys_foreach(BT_KEYS_IRK, keys_add_id, NULL); + goto done; + } - buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp)); - if (!buf) { - goto done; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp)); + if (!buf) { + goto done; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_le_copy(&cp->peer_id_addr, &keys->addr); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_le_copy(&cp->peer_id_addr, &keys->addr); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL); - if (err) { - BT_ERR("Failed to remove IRK from controller"); - goto done; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL); + if (err) { + BT_ERR("Failed to remove IRK from controller"); + goto done; + } - bt_dev.le.rl_entries--; + bt_dev.le.rl_entries--; done: - /* Only re-enable if there are entries to do resolving with */ - if (bt_dev.le.rl_entries) { - addr_res_enable(BT_HCI_ADDR_RES_ENABLE); - } + /* Only re-enable if there are entries to do resolving with */ + if (bt_dev.le.rl_entries) { + addr_res_enable(BT_HCI_ADDR_RES_ENABLE); + } #if defined(CONFIG_BT_OBSERVER) - if (scan_enabled) { - set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); - } + if (scan_enabled) { + set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); + } #endif /* CONFIG_BT_OBSERVER */ - if (adv_enabled) { - set_advertise_enable(true); - } + if (adv_enabled) { + set_advertise_enable(true); + } } static void update_sec_level(struct bt_conn *conn) { - if (!conn->encrypt) { - conn->sec_level = BT_SECURITY_L1; - return; - } + if (!conn->encrypt) { + conn->sec_level = BT_SECURITY_L1; + return; + } - if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { - if (conn->le.keys->flags & BT_KEYS_SC && - conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE) { - conn->sec_level = BT_SECURITY_L4; - } else { - conn->sec_level = BT_SECURITY_L3; - } - } else { - conn->sec_level = BT_SECURITY_L2; - } + if (conn->le.keys && (conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { + if (conn->le.keys->flags & BT_KEYS_SC && + conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE) { + conn->sec_level = BT_SECURITY_L4; + } else { + conn->sec_level = BT_SECURITY_L3; + } + } else { + conn->sec_level = BT_SECURITY_L2; + } - if (conn->required_sec_level > conn->sec_level) { - BT_ERR("Failed to set required security level"); - bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); - } + if (conn->required_sec_level > conn->sec_level) { + BT_ERR("Failed to set required security level"); + bt_conn_disconnect(conn, BT_HCI_ERR_AUTH_FAIL); + } } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) static void hci_encrypt_change(struct net_buf *buf) { - struct bt_hci_evt_encrypt_change *evt = (void *)buf->data; - u16_t handle = sys_le16_to_cpu(evt->handle); - struct bt_conn *conn; + struct bt_hci_evt_encrypt_change *evt = (void *)buf->data; + u16_t handle = sys_le16_to_cpu(evt->handle); + struct bt_conn *conn; - BT_DBG("status 0x%02x handle %u encrypt 0x%02x", evt->status, handle, - evt->encrypt); + BT_DBG("status 0x%02x handle %u encrypt 0x%02x", evt->status, handle, + evt->encrypt); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to look up conn with handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to look up conn with handle %u", handle); + return; + } - if (evt->status) { - reset_pairing(conn); - bt_l2cap_encrypt_change(conn, evt->status); - bt_conn_security_changed(conn, security_err_get(evt->status)); - bt_conn_unref(conn); - return; - } + if (evt->status) { + reset_pairing(conn); + bt_l2cap_encrypt_change(conn, evt->status); + bt_conn_security_changed(conn, security_err_get(evt->status)); + bt_conn_unref(conn); + return; + } - conn->encrypt = evt->encrypt; + conn->encrypt = evt->encrypt; #if defined(CONFIG_BT_SMP) - if (conn->type == BT_CONN_TYPE_LE) { - /* - * we update keys properties only on successful encryption to - * avoid losing valid keys if encryption was not successful. - * - * Update keys with last pairing info for proper sec level - * update. This is done only for LE transport, for BR/EDR keys - * are updated on HCI 'Link Key Notification Event' - */ - if (conn->encrypt) { - bt_smp_update_keys(conn); - } - update_sec_level(conn); - } + if (conn->type == BT_CONN_TYPE_LE) { + /* + * we update keys properties only on successful encryption to + * avoid losing valid keys if encryption was not successful. + * + * Update keys with last pairing info for proper sec level + * update. This is done only for LE transport, for BR/EDR keys + * are updated on HCI 'Link Key Notification Event' + */ + if (conn->encrypt) { + bt_smp_update_keys(conn); + } + update_sec_level(conn); + } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - if (!update_sec_level_br(conn)) { - bt_conn_unref(conn); - return; - } + if (conn->type == BT_CONN_TYPE_BR) { + if (!update_sec_level_br(conn)) { + bt_conn_unref(conn); + return; + } - if (IS_ENABLED(CONFIG_BT_SMP)) { - /* - * Start SMP over BR/EDR if we are pairing and are - * master on the link - */ - if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING) && - conn->role == BT_CONN_ROLE_MASTER) { - bt_smp_br_send_pairing_req(conn); - } - } - } + if (IS_ENABLED(CONFIG_BT_SMP)) { + /* + * Start SMP over BR/EDR if we are pairing and are + * master on the link + */ + if (atomic_test_bit(conn->flags, BT_CONN_BR_PAIRING) && + conn->role == BT_CONN_ROLE_MASTER) { + bt_smp_br_send_pairing_req(conn); + } + } + } #endif /* CONFIG_BT_BREDR */ - reset_pairing(conn); + reset_pairing(conn); - bt_l2cap_encrypt_change(conn, evt->status); - bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS); + bt_l2cap_encrypt_change(conn, evt->status); + bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS); - bt_conn_unref(conn); + bt_conn_unref(conn); } static void hci_encrypt_key_refresh_complete(struct net_buf *buf) { - struct bt_hci_evt_encrypt_key_refresh_complete *evt = (void *)buf->data; - struct bt_conn *conn; - u16_t handle; + struct bt_hci_evt_encrypt_key_refresh_complete *evt = (void *)buf->data; + struct bt_conn *conn; + u16_t handle; - handle = sys_le16_to_cpu(evt->handle); + handle = sys_le16_to_cpu(evt->handle); - BT_DBG("status 0x%02x handle %u", evt->status, handle); + BT_DBG("status 0x%02x handle %u", evt->status, handle); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to look up conn with handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to look up conn with handle %u", handle); + return; + } - if (evt->status) { - reset_pairing(conn); - bt_l2cap_encrypt_change(conn, evt->status); - bt_conn_security_changed(conn, security_err_get(evt->status)); - bt_conn_unref(conn); - return; - } + if (evt->status) { + reset_pairing(conn); + bt_l2cap_encrypt_change(conn, evt->status); + bt_conn_security_changed(conn, security_err_get(evt->status)); + bt_conn_unref(conn); + return; + } - /* - * Update keys with last pairing info for proper sec level update. - * This is done only for LE transport. For BR/EDR transport keys are - * updated on HCI 'Link Key Notification Event', therefore update here - * only security level based on available keys and encryption state. - */ + /* + * Update keys with last pairing info for proper sec level update. + * This is done only for LE transport. For BR/EDR transport keys are + * updated on HCI 'Link Key Notification Event', therefore update here + * only security level based on available keys and encryption state. + */ #if defined(CONFIG_BT_SMP) - if (conn->type == BT_CONN_TYPE_LE) { - bt_smp_update_keys(conn); - update_sec_level(conn); - } + if (conn->type == BT_CONN_TYPE_LE) { + bt_smp_update_keys(conn); + update_sec_level(conn); + } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - if (!update_sec_level_br(conn)) { - bt_conn_unref(conn); - return; - } - } + if (conn->type == BT_CONN_TYPE_BR) { + if (!update_sec_level_br(conn)) { + bt_conn_unref(conn); + return; + } + } #endif /* CONFIG_BT_BREDR */ - reset_pairing(conn); - bt_l2cap_encrypt_change(conn, evt->status); - bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS); - bt_conn_unref(conn); + reset_pairing(conn); + bt_l2cap_encrypt_change(conn, evt->status); + bt_conn_security_changed(conn, BT_SECURITY_ERR_SUCCESS); + bt_conn_unref(conn); } #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ #if defined(CONFIG_BT_SMP) static void le_ltk_neg_reply(u16_t handle) { - struct bt_hci_cp_le_ltk_req_neg_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_le_ltk_req_neg_reply *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp)); - if (!buf) { - BT_ERR("Out of command buffers"); + buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, sizeof(*cp)); + if (!buf) { + BT_ERR("Out of command buffers"); - return; - } + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(handle); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(handle); - bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf); + bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_NEG_REPLY, buf); } static void le_ltk_reply(u16_t handle, u8_t *ltk) { - struct bt_hci_cp_le_ltk_req_reply *cp; - struct net_buf *buf; + struct bt_hci_cp_le_ltk_req_reply *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY, - sizeof(*cp)); - if (!buf) { - BT_ERR("Out of command buffers"); - return; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_LTK_REQ_REPLY, + sizeof(*cp)); + if (!buf) { + BT_ERR("Out of command buffers"); + return; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->handle = sys_cpu_to_le16(handle); - memcpy(cp->ltk, ltk, sizeof(cp->ltk)); + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle = sys_cpu_to_le16(handle); + memcpy(cp->ltk, ltk, sizeof(cp->ltk)); - bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf); + bt_hci_cmd_send(BT_HCI_OP_LE_LTK_REQ_REPLY, buf); } static void le_ltk_request(struct net_buf *buf) { - struct bt_hci_evt_le_ltk_request *evt = (void *)buf->data; - struct bt_conn *conn; - u16_t handle; - u8_t ltk[16]; + struct bt_hci_evt_le_ltk_request *evt = (void *)buf->data; + struct bt_conn *conn; + u16_t handle; + u8_t ltk[16]; - handle = sys_le16_to_cpu(evt->handle); + handle = sys_le16_to_cpu(evt->handle); - BT_DBG("handle %u", handle); + BT_DBG("handle %u", handle); - conn = bt_conn_lookup_handle(handle); - if (!conn) { - BT_ERR("Unable to lookup conn for handle %u", handle); - return; - } + conn = bt_conn_lookup_handle(handle); + if (!conn) { + BT_ERR("Unable to lookup conn for handle %u", handle); + return; + } - if (bt_smp_request_ltk(conn, evt->rand, evt->ediv, ltk)) { - le_ltk_reply(handle, ltk); - } else { - le_ltk_neg_reply(handle); - } + if (bt_smp_request_ltk(conn, evt->rand, evt->ediv, ltk)) { + le_ltk_reply(handle, ltk); + } else { + le_ltk_neg_reply(handle); + } - bt_conn_unref(conn); + bt_conn_unref(conn); } #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_ECC) static void le_pkey_complete(struct net_buf *buf) { - struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data; - struct bt_pub_key_cb *cb; + struct bt_hci_evt_le_p256_public_key_complete *evt = (void *)buf->data; + struct bt_pub_key_cb *cb; - BT_DBG("status: 0x%02x", evt->status); + BT_DBG("status: 0x%02x", evt->status); - atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY); + atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY); - if (!evt->status) { - memcpy(pub_key, evt->key, 64); - atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY); - } + if (!evt->status) { + memcpy(pub_key, evt->key, 64); + atomic_set_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY); + } - for (cb = pub_key_cb; cb; cb = cb->_next) { - cb->func(evt->status ? NULL : pub_key); - } + for (cb = pub_key_cb; cb; cb = cb->_next) { + cb->func(evt->status ? NULL : pub_key); + } - pub_key_cb = NULL; + pub_key_cb = NULL; } static void le_dhkey_complete(struct net_buf *buf) { - struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data; + struct bt_hci_evt_le_generate_dhkey_complete *evt = (void *)buf->data; - BT_DBG("status: 0x%02x", evt->status); + BT_DBG("status: 0x%02x", evt->status); - if (dh_key_cb) { - dh_key_cb(evt->status ? NULL : evt->dhkey); - dh_key_cb = NULL; - } + if (dh_key_cb) { + dh_key_cb(evt->status ? NULL : evt->dhkey); + dh_key_cb = NULL; + } } #endif /* CONFIG_BT_ECC */ static void hci_reset_complete(struct net_buf *buf) { - u8_t status = buf->data[0]; - atomic_t flags; + u8_t status = buf->data[0]; + atomic_t flags; - BT_DBG("status 0x%02x", status); + BT_DBG("status 0x%02x", status); - if (status) { - return; - } + if (status) { + return; + } - scan_dev_found_cb = NULL; + scan_dev_found_cb = NULL; #if defined(CONFIG_BT_BREDR) - discovery_cb = NULL; - discovery_results = NULL; - discovery_results_size = 0; - discovery_results_count = 0; + discovery_cb = NULL; + discovery_results = NULL; + discovery_results_size = 0; + discovery_results_count = 0; #endif /* CONFIG_BT_BREDR */ - flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS); - atomic_set(bt_dev.flags, flags); + flags = (atomic_get(bt_dev.flags) & BT_DEV_PERSISTENT_FLAGS); + atomic_set(bt_dev.flags, flags); } static void hci_cmd_done(u16_t opcode, u8_t status, struct net_buf *buf) { - BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf); + BT_DBG("opcode 0x%04x status 0x%02x buf %p", opcode, status, buf); - if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) { - BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p", - opcode, buf->pool_id, net_buf_pool_get(buf->pool_id), - &hci_cmd_pool); - return; - } + if (net_buf_pool_get(buf->pool_id) != &hci_cmd_pool) { + BT_WARN("opcode 0x%04x pool id %u pool %p != &hci_cmd_pool %p", + opcode, buf->pool_id, net_buf_pool_get(buf->pool_id), + &hci_cmd_pool); + return; + } - if (cmd(buf)->opcode != opcode) { - BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x", - opcode, cmd(buf)->opcode); - } + if (cmd(buf)->opcode != opcode) { + BT_WARN("OpCode 0x%04x completed instead of expected 0x%04x", + opcode, cmd(buf)->opcode); + } - if (cmd(buf)->state && !status) { - struct cmd_state_set *update = cmd(buf)->state; + if (cmd(buf)->state && !status) { + struct cmd_state_set *update = cmd(buf)->state; - atomic_set_bit_to(update->target, update->bit, update->val); - } + atomic_set_bit_to(update->target, update->bit, update->val); + } - /* If the command was synchronous wake up bt_hci_cmd_send_sync() */ - if (cmd(buf)->sync) { - cmd(buf)->status = status; - k_sem_give(cmd(buf)->sync); - } + /* If the command was synchronous wake up bt_hci_cmd_send_sync() */ + if (cmd(buf)->sync) { + cmd(buf)->status = status; + k_sem_give(cmd(buf)->sync); + } } static void hci_cmd_complete(struct net_buf *buf) { - struct bt_hci_evt_cmd_complete *evt; - u8_t status, ncmd; - u16_t opcode; + struct bt_hci_evt_cmd_complete *evt; + u8_t status, ncmd; + u16_t opcode; - evt = net_buf_pull_mem(buf, sizeof(*evt)); - ncmd = evt->ncmd; - opcode = sys_le16_to_cpu(evt->opcode); + evt = net_buf_pull_mem(buf, sizeof(*evt)); + ncmd = evt->ncmd; + opcode = sys_le16_to_cpu(evt->opcode); - BT_DBG("opcode 0x%04x", opcode); + BT_DBG("opcode 0x%04x", opcode); - /* All command return parameters have a 1-byte status in the - * beginning, so we can safely make this generalization. - */ - status = buf->data[0]; + /* All command return parameters have a 1-byte status in the + * beginning, so we can safely make this generalization. + */ + status = buf->data[0]; - hci_cmd_done(opcode, status, buf); + hci_cmd_done(opcode, status, buf); - /* Allow next command to be sent */ - if (ncmd) { - k_sem_give(&bt_dev.ncmd_sem); - } + /* Allow next command to be sent */ + if (ncmd) { + k_sem_give(&bt_dev.ncmd_sem); + } } static void hci_cmd_status(struct net_buf *buf) { - struct bt_hci_evt_cmd_status *evt; - u16_t opcode; - u8_t ncmd; + struct bt_hci_evt_cmd_status *evt; + u16_t opcode; + u8_t ncmd; - evt = net_buf_pull_mem(buf, sizeof(*evt)); - opcode = sys_le16_to_cpu(evt->opcode); - ncmd = evt->ncmd; + evt = net_buf_pull_mem(buf, sizeof(*evt)); + opcode = sys_le16_to_cpu(evt->opcode); + ncmd = evt->ncmd; - BT_DBG("opcode 0x%04x", opcode); + BT_DBG("opcode 0x%04x", opcode); - hci_cmd_done(opcode, evt->status, buf); + hci_cmd_done(opcode, evt->status, buf); - /* Allow next command to be sent */ - if (ncmd) { - k_sem_give(&bt_dev.ncmd_sem); - } + /* Allow next command to be sent */ + if (ncmd) { + k_sem_give(&bt_dev.ncmd_sem); + } } #if defined(CONFIG_BT_OBSERVER) static int start_le_scan(u8_t scan_type, u16_t interval, u16_t window) { - struct bt_hci_cp_le_set_scan_param set_param; - struct net_buf *buf; - int err; + struct bt_hci_cp_le_set_scan_param set_param; + struct net_buf *buf; + int err; - (void)memset(&set_param, 0, sizeof(set_param)); + (void)memset(&set_param, 0, sizeof(set_param)); - set_param.scan_type = scan_type; + set_param.scan_type = scan_type; - /* for the rest parameters apply default values according to - * spec 4.2, vol2, part E, 7.8.10 - */ - set_param.interval = sys_cpu_to_le16(interval); - set_param.window = sys_cpu_to_le16(window); + /* for the rest parameters apply default values according to + * spec 4.2, vol2, part E, 7.8.10 + */ + set_param.interval = sys_cpu_to_le16(interval); + set_param.window = sys_cpu_to_le16(window); - if (IS_ENABLED(CONFIG_BT_WHITELIST) && - atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) { - set_param.filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST; - } else { - set_param.filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST; - } + if (IS_ENABLED(CONFIG_BT_WHITELIST) && + atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_WL)) { + set_param.filter_policy = BT_HCI_LE_SCAN_FP_USE_WHITELIST; + } else { + set_param.filter_policy = BT_HCI_LE_SCAN_FP_NO_WHITELIST; + } - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - err = le_set_private_addr(BT_ID_DEFAULT); - if (err) { - return err; - } + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + err = le_set_private_addr(BT_ID_DEFAULT); + if (err) { + return err; + } - if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - } else { - set_param.addr_type = BT_ADDR_LE_RANDOM; - } - } else { - set_param.addr_type = bt_dev.id_addr[0].type; + if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { + set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + } else { + set_param.addr_type = BT_ADDR_LE_RANDOM; + } + } else { + set_param.addr_type = bt_dev.id_addr[0].type; - /* Use NRPA unless identity has been explicitly requested - * (through Kconfig), or if there is no advertising ongoing. - */ - if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && - scan_type == BT_HCI_LE_SCAN_ACTIVE && - !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - err = le_set_private_addr(BT_ID_DEFAULT); - if (err) { - return err; - } + /* Use NRPA unless identity has been explicitly requested + * (through Kconfig), or if there is no advertising ongoing. + */ + if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) && + scan_type == BT_HCI_LE_SCAN_ACTIVE && + !atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + err = le_set_private_addr(BT_ID_DEFAULT); + if (err) { + return err; + } - set_param.addr_type = BT_ADDR_LE_RANDOM; - } else if (set_param.addr_type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&bt_dev.id_addr[0].a); - if (err) { - return err; - } - } - } + set_param.addr_type = BT_ADDR_LE_RANDOM; + } else if (set_param.addr_type == BT_ADDR_LE_RANDOM) { + err = set_random_address(&bt_dev.id_addr[0].a); + if (err) { + return err; + } + } + } - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAM, sizeof(set_param)); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_mem(buf, &set_param, sizeof(set_param)); + net_buf_add_mem(buf, &set_param, sizeof(set_param)); - bt_hci_cmd_send(BT_HCI_OP_LE_SET_SCAN_PARAM, buf); + bt_hci_cmd_send(BT_HCI_OP_LE_SET_SCAN_PARAM, buf); - err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); - if (err) { - return err; - } + err = set_le_scan_enable(BT_HCI_LE_SCAN_ENABLE); + if (err) { + return err; + } - atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, - scan_type == BT_HCI_LE_SCAN_ACTIVE); + atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, + scan_type == BT_HCI_LE_SCAN_ACTIVE); - return 0; + return 0; } #if defined(CONFIG_BT_STACK_PTS) @@ -3763,8 +3763,8 @@ static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window } if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - if(addre_type == 2) - set_param.addr_type = BT_ADDR_LE_PUBLIC; + if(addre_type == 2) + set_param.addr_type = BT_ADDR_LE_PUBLIC; if(addre_type == 1) set_param.addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; else if(addre_type == 0) @@ -3804,8 +3804,8 @@ static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window return err; } - atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, - scan_type == BT_HCI_LE_SCAN_ACTIVE); + atomic_set_bit_to(bt_dev.flags, BT_DEV_ACTIVE_SCAN, + scan_type == BT_HCI_LE_SCAN_ACTIVE); return 0; @@ -3815,380 +3815,380 @@ static int start_le_scan_with_isrpa(u8_t scan_type, u16_t interval, u16_t window int bt_le_scan_update(bool fast_scan) { - if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { - return 0; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { + return 0; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { - int err; + if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { + int err; - err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); - if (err) { - return err; - } - } + err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); + if (err) { + return err; + } + } - if (IS_ENABLED(CONFIG_BT_CENTRAL)) { - u16_t interval, window; - struct bt_conn *conn; + if (IS_ENABLED(CONFIG_BT_CENTRAL)) { + u16_t interval, window; + struct bt_conn *conn; - /* don't restart scan if we have pending connection */ - conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); - if (conn) { - bt_conn_unref(conn); - return 0; - } + /* don't restart scan if we have pending connection */ + conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT); + if (conn) { + bt_conn_unref(conn); + return 0; + } - conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN); - if (!conn) { - return 0; - } + conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN); + if (!conn) { + return 0; + } - //atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); - atomic_clear_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); + //atomic_set_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); + atomic_clear_bit(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP); - bt_conn_unref(conn); + bt_conn_unref(conn); - if (fast_scan) { - interval = BT_GAP_SCAN_FAST_INTERVAL; - window = BT_GAP_SCAN_FAST_WINDOW; - } else { - interval = CONFIG_BT_BACKGROUND_SCAN_INTERVAL; - window = CONFIG_BT_BACKGROUND_SCAN_WINDOW; - } + if (fast_scan) { + interval = BT_GAP_SCAN_FAST_INTERVAL; + window = BT_GAP_SCAN_FAST_WINDOW; + } else { + interval = CONFIG_BT_BACKGROUND_SCAN_INTERVAL; + window = CONFIG_BT_BACKGROUND_SCAN_WINDOW; + } - return start_le_scan(BT_HCI_LE_SCAN_PASSIVE, interval, window); - } + return start_le_scan(BT_HCI_LE_SCAN_PASSIVE, interval, window); + } - return 0; + return 0; } void bt_data_parse(struct net_buf_simple *ad, - bool (*func)(struct bt_data *data, void *user_data), - void *user_data) + bool (*func)(struct bt_data *data, void *user_data), + void *user_data) { - while (ad->len > 1) { - struct bt_data data; - u8_t len; + while (ad->len > 1) { + struct bt_data data; + u8_t len; - len = net_buf_simple_pull_u8(ad); - if (len == 0U) { - /* Early termination */ - return; - } + len = net_buf_simple_pull_u8(ad); + if (len == 0U) { + /* Early termination */ + return; + } - if (len > ad->len) { - BT_WARN("Malformed data"); - return; - } + if (len > ad->len) { + BT_WARN("Malformed data"); + return; + } - data.type = net_buf_simple_pull_u8(ad); - data.data_len = len - 1; - data.data = ad->data; + data.type = net_buf_simple_pull_u8(ad); + data.data_len = len - 1; + data.data = ad->data; - if (!func(&data, user_data)) { - return; - } + if (!func(&data, user_data)) { + return; + } - net_buf_simple_pull(ad, len - 1); - } + net_buf_simple_pull(ad, len - 1); + } } static void le_adv_report(struct net_buf *buf) { - u8_t num_reports = net_buf_pull_u8(buf); - struct bt_hci_evt_le_advertising_info *info; + u8_t num_reports = net_buf_pull_u8(buf); + struct bt_hci_evt_le_advertising_info *info; - BT_DBG("Adv number of reports %u", num_reports); + BT_DBG("Adv number of reports %u", num_reports); - while (num_reports--) { - bt_addr_le_t id_addr; - s8_t rssi; + while (num_reports--) { + bt_addr_le_t id_addr; + s8_t rssi; - if (buf->len < sizeof(*info)) { - BT_ERR("Unexpected end of buffer"); - break; - } + if (buf->len < sizeof(*info)) { + BT_ERR("Unexpected end of buffer"); + break; + } - info = net_buf_pull_mem(buf, sizeof(*info)); - rssi = info->data[info->length]; + info = net_buf_pull_mem(buf, sizeof(*info)); + rssi = info->data[info->length]; - BT_DBG("%s event %u, len %u, rssi %d dBm", - bt_addr_le_str(&info->addr), - info->evt_type, info->length, rssi); + BT_DBG("%s event %u, len %u, rssi %d dBm", + bt_addr_le_str(&info->addr), + info->evt_type, info->length, rssi); - if (info->addr.type == BT_ADDR_LE_PUBLIC_ID || - info->addr.type == BT_ADDR_LE_RANDOM_ID) { - bt_addr_le_copy(&id_addr, &info->addr); - id_addr.type -= BT_ADDR_LE_PUBLIC_ID; - } else { - bt_addr_le_copy(&id_addr, - bt_lookup_id_addr(bt_dev.adv_id, - &info->addr)); - } + if (info->addr.type == BT_ADDR_LE_PUBLIC_ID || + info->addr.type == BT_ADDR_LE_RANDOM_ID) { + bt_addr_le_copy(&id_addr, &info->addr); + id_addr.type -= BT_ADDR_LE_PUBLIC_ID; + } else { + bt_addr_le_copy(&id_addr, + bt_lookup_id_addr(bt_dev.adv_id, + &info->addr)); + } - if (scan_dev_found_cb) { - struct net_buf_simple_state state; + if (scan_dev_found_cb) { + struct net_buf_simple_state state; - net_buf_simple_save(&buf->b, &state); + net_buf_simple_save(&buf->b, &state); - buf->len = info->length; - scan_dev_found_cb(&id_addr, rssi, info->evt_type, - &buf->b); + buf->len = info->length; + scan_dev_found_cb(&id_addr, rssi, info->evt_type, + &buf->b); - net_buf_simple_restore(&buf->b, &state); - } + net_buf_simple_restore(&buf->b, &state); + } #if defined(CONFIG_BT_CENTRAL) - check_pending_conn(&id_addr, &info->addr, info->evt_type); + check_pending_conn(&id_addr, &info->addr, info->evt_type); #endif /* CONFIG_BT_CENTRAL */ - net_buf_pull(buf, info->length + sizeof(rssi)); - } + net_buf_pull(buf, info->length + sizeof(rssi)); + } } #endif /* CONFIG_BT_OBSERVER */ int bt_hci_get_conn_handle(const struct bt_conn *conn, u16_t *conn_handle) { - if (conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - *conn_handle = conn->handle; - return 0; + *conn_handle = conn->handle; + return 0; } #if defined(CONFIG_BT_HCI_VS_EVT_USER) int bt_hci_register_vnd_evt_cb(bt_hci_vnd_evt_cb_t cb) { - hci_vnd_evt_cb = cb; - return 0; + hci_vnd_evt_cb = cb; + return 0; } #endif /* CONFIG_BT_HCI_VS_EVT_USER */ static void hci_vendor_event(struct net_buf *buf) { - bool handled = false; + bool handled = false; #if defined(CONFIG_BT_HCI_VS_EVT_USER) - if (hci_vnd_evt_cb) { - struct net_buf_simple_state state; + if (hci_vnd_evt_cb) { + struct net_buf_simple_state state; - net_buf_simple_save(&buf->b, &state); + net_buf_simple_save(&buf->b, &state); - handled = (hci_vnd_evt_cb)(&buf->b); + handled = (hci_vnd_evt_cb)(&buf->b); - net_buf_simple_restore(&buf->b, &state); - } + net_buf_simple_restore(&buf->b, &state); + } #endif /* CONFIG_BT_HCI_VS_EVT_USER */ - if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT) && !handled) { - /* do nothing at present time */ - BT_WARN("Unhandled vendor-specific event: %s", - bt_hex(buf->data, buf->len)); - } + if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT) && !handled) { + /* do nothing at present time */ + BT_WARN("Unhandled vendor-specific event: %s", + bt_hex(buf->data, buf->len)); + } } static const struct event_handler meta_events[] = { #if defined(CONFIG_BT_OBSERVER) - EVENT_HANDLER(BT_HCI_EVT_LE_ADVERTISING_REPORT, le_adv_report, - sizeof(struct bt_hci_evt_le_advertising_report)), + EVENT_HANDLER(BT_HCI_EVT_LE_ADVERTISING_REPORT, le_adv_report, + sizeof(struct bt_hci_evt_le_advertising_report)), #endif /* CONFIG_BT_OBSERVER */ #if defined(CONFIG_BT_CONN) - EVENT_HANDLER(BT_HCI_EVT_LE_CONN_COMPLETE, le_legacy_conn_complete, - sizeof(struct bt_hci_evt_le_conn_complete)), - EVENT_HANDLER(BT_HCI_EVT_LE_ENH_CONN_COMPLETE, le_enh_conn_complete, - sizeof(struct bt_hci_evt_le_enh_conn_complete)), - EVENT_HANDLER(BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE, - le_conn_update_complete, - sizeof(struct bt_hci_evt_le_conn_update_complete)), - EVENT_HANDLER(BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE, - le_remote_feat_complete, - sizeof(struct bt_hci_evt_le_remote_feat_complete)), - EVENT_HANDLER(BT_HCI_EVT_LE_CONN_PARAM_REQ, le_conn_param_req, - sizeof(struct bt_hci_evt_le_conn_param_req)), + EVENT_HANDLER(BT_HCI_EVT_LE_CONN_COMPLETE, le_legacy_conn_complete, + sizeof(struct bt_hci_evt_le_conn_complete)), + EVENT_HANDLER(BT_HCI_EVT_LE_ENH_CONN_COMPLETE, le_enh_conn_complete, + sizeof(struct bt_hci_evt_le_enh_conn_complete)), + EVENT_HANDLER(BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE, + le_conn_update_complete, + sizeof(struct bt_hci_evt_le_conn_update_complete)), + EVENT_HANDLER(BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE, + le_remote_feat_complete, + sizeof(struct bt_hci_evt_le_remote_feat_complete)), + EVENT_HANDLER(BT_HCI_EVT_LE_CONN_PARAM_REQ, le_conn_param_req, + sizeof(struct bt_hci_evt_le_conn_param_req)), #if defined(CONFIG_BT_DATA_LEN_UPDATE) - EVENT_HANDLER(BT_HCI_EVT_LE_DATA_LEN_CHANGE, le_data_len_change, - sizeof(struct bt_hci_evt_le_data_len_change)), + EVENT_HANDLER(BT_HCI_EVT_LE_DATA_LEN_CHANGE, le_data_len_change, + sizeof(struct bt_hci_evt_le_data_len_change)), #endif /* CONFIG_BT_DATA_LEN_UPDATE */ #if defined(CONFIG_BT_PHY_UPDATE) - EVENT_HANDLER(BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE, - le_phy_update_complete, - sizeof(struct bt_hci_evt_le_phy_update_complete)), + EVENT_HANDLER(BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE, + le_phy_update_complete, + sizeof(struct bt_hci_evt_le_phy_update_complete)), #endif /* CONFIG_BT_PHY_UPDATE */ #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_SMP) - EVENT_HANDLER(BT_HCI_EVT_LE_LTK_REQUEST, le_ltk_request, - sizeof(struct bt_hci_evt_le_ltk_request)), + EVENT_HANDLER(BT_HCI_EVT_LE_LTK_REQUEST, le_ltk_request, + sizeof(struct bt_hci_evt_le_ltk_request)), #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_ECC) - EVENT_HANDLER(BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE, le_pkey_complete, - sizeof(struct bt_hci_evt_le_p256_public_key_complete)), - EVENT_HANDLER(BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE, le_dhkey_complete, - sizeof(struct bt_hci_evt_le_generate_dhkey_complete)), + EVENT_HANDLER(BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE, le_pkey_complete, + sizeof(struct bt_hci_evt_le_p256_public_key_complete)), + EVENT_HANDLER(BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE, le_dhkey_complete, + sizeof(struct bt_hci_evt_le_generate_dhkey_complete)), #endif /* CONFIG_BT_SMP */ }; static void hci_le_meta_event(struct net_buf *buf) { - struct bt_hci_evt_le_meta_event *evt; + struct bt_hci_evt_le_meta_event *evt; - evt = net_buf_pull_mem(buf, sizeof(*evt)); + evt = net_buf_pull_mem(buf, sizeof(*evt)); - BT_DBG("subevent 0x%02x", evt->subevent); + BT_DBG("subevent 0x%02x", evt->subevent); - handle_event(evt->subevent, buf, meta_events, ARRAY_SIZE(meta_events)); + handle_event(evt->subevent, buf, meta_events, ARRAY_SIZE(meta_events)); } static const struct event_handler normal_events[] = { - EVENT_HANDLER(BT_HCI_EVT_VENDOR, hci_vendor_event, - sizeof(struct bt_hci_evt_vs)), - EVENT_HANDLER(BT_HCI_EVT_LE_META_EVENT, hci_le_meta_event, - sizeof(struct bt_hci_evt_le_meta_event)), + EVENT_HANDLER(BT_HCI_EVT_VENDOR, hci_vendor_event, + sizeof(struct bt_hci_evt_vs)), + EVENT_HANDLER(BT_HCI_EVT_LE_META_EVENT, hci_le_meta_event, + sizeof(struct bt_hci_evt_le_meta_event)), #if defined(CONFIG_BT_BREDR) - EVENT_HANDLER(BT_HCI_EVT_CONN_REQUEST, conn_req, - sizeof(struct bt_hci_evt_conn_request)), - EVENT_HANDLER(BT_HCI_EVT_CONN_COMPLETE, conn_complete, - sizeof(struct bt_hci_evt_conn_complete)), - EVENT_HANDLER(BT_HCI_EVT_PIN_CODE_REQ, pin_code_req, - sizeof(struct bt_hci_evt_pin_code_req)), - EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_NOTIFY, link_key_notify, - sizeof(struct bt_hci_evt_link_key_notify)), - EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_REQ, link_key_req, - sizeof(struct bt_hci_evt_link_key_req)), - EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_RESP, io_capa_resp, - sizeof(struct bt_hci_evt_io_capa_resp)), - EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_REQ, io_capa_req, - sizeof(struct bt_hci_evt_io_capa_req)), - EVENT_HANDLER(BT_HCI_EVT_SSP_COMPLETE, ssp_complete, - sizeof(struct bt_hci_evt_ssp_complete)), - EVENT_HANDLER(BT_HCI_EVT_USER_CONFIRM_REQ, user_confirm_req, - sizeof(struct bt_hci_evt_user_confirm_req)), - EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_NOTIFY, user_passkey_notify, - sizeof(struct bt_hci_evt_user_passkey_notify)), - EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_REQ, user_passkey_req, - sizeof(struct bt_hci_evt_user_passkey_req)), - EVENT_HANDLER(BT_HCI_EVT_INQUIRY_COMPLETE, inquiry_complete, - sizeof(struct bt_hci_evt_inquiry_complete)), - EVENT_HANDLER(BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI, - inquiry_result_with_rssi, - sizeof(struct bt_hci_evt_inquiry_result_with_rssi)), - EVENT_HANDLER(BT_HCI_EVT_EXTENDED_INQUIRY_RESULT, - extended_inquiry_result, - sizeof(struct bt_hci_evt_extended_inquiry_result)), - EVENT_HANDLER(BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE, - remote_name_request_complete, - sizeof(struct bt_hci_evt_remote_name_req_complete)), - EVENT_HANDLER(BT_HCI_EVT_AUTH_COMPLETE, auth_complete, - sizeof(struct bt_hci_evt_auth_complete)), - EVENT_HANDLER(BT_HCI_EVT_REMOTE_FEATURES, - read_remote_features_complete, - sizeof(struct bt_hci_evt_remote_features)), - EVENT_HANDLER(BT_HCI_EVT_REMOTE_EXT_FEATURES, - read_remote_ext_features_complete, - sizeof(struct bt_hci_evt_remote_ext_features)), - EVENT_HANDLER(BT_HCI_EVT_ROLE_CHANGE, role_change, - sizeof(struct bt_hci_evt_role_change)), - EVENT_HANDLER(BT_HCI_EVT_SYNC_CONN_COMPLETE, synchronous_conn_complete, - sizeof(struct bt_hci_evt_sync_conn_complete)), + EVENT_HANDLER(BT_HCI_EVT_CONN_REQUEST, conn_req, + sizeof(struct bt_hci_evt_conn_request)), + EVENT_HANDLER(BT_HCI_EVT_CONN_COMPLETE, conn_complete, + sizeof(struct bt_hci_evt_conn_complete)), + EVENT_HANDLER(BT_HCI_EVT_PIN_CODE_REQ, pin_code_req, + sizeof(struct bt_hci_evt_pin_code_req)), + EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_NOTIFY, link_key_notify, + sizeof(struct bt_hci_evt_link_key_notify)), + EVENT_HANDLER(BT_HCI_EVT_LINK_KEY_REQ, link_key_req, + sizeof(struct bt_hci_evt_link_key_req)), + EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_RESP, io_capa_resp, + sizeof(struct bt_hci_evt_io_capa_resp)), + EVENT_HANDLER(BT_HCI_EVT_IO_CAPA_REQ, io_capa_req, + sizeof(struct bt_hci_evt_io_capa_req)), + EVENT_HANDLER(BT_HCI_EVT_SSP_COMPLETE, ssp_complete, + sizeof(struct bt_hci_evt_ssp_complete)), + EVENT_HANDLER(BT_HCI_EVT_USER_CONFIRM_REQ, user_confirm_req, + sizeof(struct bt_hci_evt_user_confirm_req)), + EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_NOTIFY, user_passkey_notify, + sizeof(struct bt_hci_evt_user_passkey_notify)), + EVENT_HANDLER(BT_HCI_EVT_USER_PASSKEY_REQ, user_passkey_req, + sizeof(struct bt_hci_evt_user_passkey_req)), + EVENT_HANDLER(BT_HCI_EVT_INQUIRY_COMPLETE, inquiry_complete, + sizeof(struct bt_hci_evt_inquiry_complete)), + EVENT_HANDLER(BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI, + inquiry_result_with_rssi, + sizeof(struct bt_hci_evt_inquiry_result_with_rssi)), + EVENT_HANDLER(BT_HCI_EVT_EXTENDED_INQUIRY_RESULT, + extended_inquiry_result, + sizeof(struct bt_hci_evt_extended_inquiry_result)), + EVENT_HANDLER(BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE, + remote_name_request_complete, + sizeof(struct bt_hci_evt_remote_name_req_complete)), + EVENT_HANDLER(BT_HCI_EVT_AUTH_COMPLETE, auth_complete, + sizeof(struct bt_hci_evt_auth_complete)), + EVENT_HANDLER(BT_HCI_EVT_REMOTE_FEATURES, + read_remote_features_complete, + sizeof(struct bt_hci_evt_remote_features)), + EVENT_HANDLER(BT_HCI_EVT_REMOTE_EXT_FEATURES, + read_remote_ext_features_complete, + sizeof(struct bt_hci_evt_remote_ext_features)), + EVENT_HANDLER(BT_HCI_EVT_ROLE_CHANGE, role_change, + sizeof(struct bt_hci_evt_role_change)), + EVENT_HANDLER(BT_HCI_EVT_SYNC_CONN_COMPLETE, synchronous_conn_complete, + sizeof(struct bt_hci_evt_sync_conn_complete)), #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_CONN) - EVENT_HANDLER(BT_HCI_EVT_DISCONN_COMPLETE, hci_disconn_complete, - sizeof(struct bt_hci_evt_disconn_complete)), + EVENT_HANDLER(BT_HCI_EVT_DISCONN_COMPLETE, hci_disconn_complete, + sizeof(struct bt_hci_evt_disconn_complete)), #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) - EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_CHANGE, hci_encrypt_change, - sizeof(struct bt_hci_evt_encrypt_change)), - EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE, - hci_encrypt_key_refresh_complete, - sizeof(struct bt_hci_evt_encrypt_key_refresh_complete)), + EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_CHANGE, hci_encrypt_change, + sizeof(struct bt_hci_evt_encrypt_change)), + EVENT_HANDLER(BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE, + hci_encrypt_key_refresh_complete, + sizeof(struct bt_hci_evt_encrypt_key_refresh_complete)), #endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR */ }; static void hci_event(struct net_buf *buf) { - struct bt_hci_evt_hdr *hdr; + struct bt_hci_evt_hdr *hdr; - BT_ASSERT(buf->len >= sizeof(*hdr)); + BT_ASSERT(buf->len >= sizeof(*hdr)); - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - BT_DBG("event 0x%02x", hdr->evt); - BT_ASSERT(!bt_hci_evt_is_prio(hdr->evt)); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + BT_DBG("event 0x%02x", hdr->evt); + BT_ASSERT(!bt_hci_evt_is_prio(hdr->evt)); - handle_event(hdr->evt, buf, normal_events, ARRAY_SIZE(normal_events)); + handle_event(hdr->evt, buf, normal_events, ARRAY_SIZE(normal_events)); - net_buf_unref(buf); + net_buf_unref(buf); } static void send_cmd(void) { - struct net_buf *buf; - int err; + struct net_buf *buf; + int err; - /* Get next command */ - BT_DBG("calling net_buf_get"); - buf = net_buf_get(&bt_dev.cmd_tx_queue, K_NO_WAIT); - BT_ASSERT(buf); + /* Get next command */ + BT_DBG("calling net_buf_get"); + buf = net_buf_get(&bt_dev.cmd_tx_queue, K_NO_WAIT); + BT_ASSERT(buf); - /* Wait until ncmd > 0 */ - BT_DBG("calling sem_take_wait"); - k_sem_take(&bt_dev.ncmd_sem, K_FOREVER); + /* Wait until ncmd > 0 */ + BT_DBG("calling sem_take_wait"); + k_sem_take(&bt_dev.ncmd_sem, K_FOREVER); - /* Clear out any existing sent command */ - if (bt_dev.sent_cmd) { - BT_ERR("Uncleared pending sent_cmd"); - net_buf_unref(bt_dev.sent_cmd); - bt_dev.sent_cmd = NULL; - } + /* Clear out any existing sent command */ + if (bt_dev.sent_cmd) { + BT_ERR("Uncleared pending sent_cmd"); + net_buf_unref(bt_dev.sent_cmd); + bt_dev.sent_cmd = NULL; + } - bt_dev.sent_cmd = net_buf_ref(buf); + bt_dev.sent_cmd = net_buf_ref(buf); - BT_DBG("Sending command 0x%04x (buf %p) to driver", - cmd(buf)->opcode, buf); + BT_DBG("Sending command 0x%04x (buf %p) to driver", + cmd(buf)->opcode, buf); - err = bt_send(buf); - if (err) { - BT_ERR("Unable to send to driver (err %d)", err); - k_sem_give(&bt_dev.ncmd_sem); - hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, - NULL); - net_buf_unref(bt_dev.sent_cmd); - bt_dev.sent_cmd = NULL; - net_buf_unref(buf); - } + err = bt_send(buf); + if (err) { + BT_ERR("Unable to send to driver (err %d)", err); + k_sem_give(&bt_dev.ncmd_sem); + hci_cmd_done(cmd(buf)->opcode, BT_HCI_ERR_UNSPECIFIED, + NULL); + net_buf_unref(bt_dev.sent_cmd); + bt_dev.sent_cmd = NULL; + net_buf_unref(buf); + } } static void process_events(struct k_poll_event *ev, int count) { - BT_DBG("count %d", count); + BT_DBG("count %d", count); - for (; count; ev++, count--) { - BT_DBG("ev->state %u", ev->state); + for (; count; ev++, count--) { + BT_DBG("ev->state %u", ev->state); - switch (ev->state) { - case K_POLL_STATE_SIGNALED: - break; - case K_POLL_STATE_FIFO_DATA_AVAILABLE: - if (ev->tag == BT_EVENT_CMD_TX) { - send_cmd(); - } else if (IS_ENABLED(CONFIG_BT_CONN)) { - struct bt_conn *conn; + switch (ev->state) { + case K_POLL_STATE_SIGNALED: + break; + case K_POLL_STATE_FIFO_DATA_AVAILABLE: + if (ev->tag == BT_EVENT_CMD_TX) { + send_cmd(); + } else if (IS_ENABLED(CONFIG_BT_CONN)) { + struct bt_conn *conn; - if (ev->tag == BT_EVENT_CONN_TX_QUEUE) { - conn = CONTAINER_OF(ev->fifo, - struct bt_conn, - tx_queue); - bt_conn_process_tx(conn); - } - } - break; - case K_POLL_STATE_NOT_READY: - break; - default: - BT_WARN("Unexpected k_poll event state %u", ev->state); - break; - } - } + if (ev->tag == BT_EVENT_CONN_TX_QUEUE) { + conn = CONTAINER_OF(ev->fifo, + struct bt_conn, + tx_queue); + bt_conn_process_tx(conn); + } + } + break; + case K_POLL_STATE_NOT_READY: + break; + default: + BT_WARN("Unexpected k_poll event state %u", ev->state); + break; + } + } } #if defined(CONFIG_BT_CONN) @@ -4203,25 +4203,25 @@ static void process_events(struct k_poll_event *ev, int count) #if (BFLB_BLE_CO_THREAD) void co_tx_thread() { - static struct k_poll_event events[EV_COUNT] = { - K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, - K_POLL_MODE_NOTIFY_ONLY, - &bt_dev.cmd_tx_queue, - BT_EVENT_CMD_TX), - }; + static struct k_poll_event events[EV_COUNT] = { + K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, + K_POLL_MODE_NOTIFY_ONLY, + &bt_dev.cmd_tx_queue, + BT_EVENT_CMD_TX), + }; - if (k_sem_count_get(&g_poll_sem) > 0) { - int ev_count, err; - events[0].state = K_POLL_STATE_NOT_READY; - ev_count = 1; + if (k_sem_count_get(&g_poll_sem) > 0) { + int ev_count, err; + events[0].state = K_POLL_STATE_NOT_READY; + ev_count = 1; - if (IS_ENABLED(CONFIG_BT_CONN)) { - ev_count += bt_conn_prepare_events(&events[1]); - } + if (IS_ENABLED(CONFIG_BT_CONN)) { + ev_count += bt_conn_prepare_events(&events[1]); + } - err = k_poll(events, ev_count, K_NO_WAIT); - process_events(events, ev_count); - } + err = k_poll(events, ev_count, K_NO_WAIT); + process_events(events, ev_count); + } } #endif @@ -4230,807 +4230,807 @@ static void hci_tx_thread(void *p1) static void hci_tx_thread(void *p1, void *p2, void *p3) #endif { - static struct k_poll_event events[EV_COUNT] = { - K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, - K_POLL_MODE_NOTIFY_ONLY, - &bt_dev.cmd_tx_queue, - BT_EVENT_CMD_TX), - }; + static struct k_poll_event events[EV_COUNT] = { + K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_FIFO_DATA_AVAILABLE, + K_POLL_MODE_NOTIFY_ONLY, + &bt_dev.cmd_tx_queue, + BT_EVENT_CMD_TX), + }; - BT_DBG("Started"); + BT_DBG("Started"); - while (1) { - int ev_count, err; + while (1) { + int ev_count, err; - events[0].state = K_POLL_STATE_NOT_READY; - ev_count = 1; + events[0].state = K_POLL_STATE_NOT_READY; + ev_count = 1; - if (IS_ENABLED(CONFIG_BT_CONN)) { - ev_count += bt_conn_prepare_events(&events[1]); - } + if (IS_ENABLED(CONFIG_BT_CONN)) { + ev_count += bt_conn_prepare_events(&events[1]); + } - BT_DBG("Calling k_poll with %d events", ev_count); + BT_DBG("Calling k_poll with %d events", ev_count); - err = k_poll(events, ev_count, K_FOREVER); - BT_ASSERT(err == 0); + err = k_poll(events, ev_count, K_FOREVER); + BT_ASSERT(err == 0); - process_events(events, ev_count); + process_events(events, ev_count); - /* Make sure we don't hog the CPU if there's all the time - * some ready events. - */ - k_yield(); - } + /* Make sure we don't hog the CPU if there's all the time + * some ready events. + */ + k_yield(); + } } static void read_local_ver_complete(struct net_buf *buf) { - struct bt_hci_rp_read_local_version_info *rp = (void *)buf->data; + struct bt_hci_rp_read_local_version_info *rp = (void *)buf->data; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - bt_dev.hci_version = rp->hci_version; - bt_dev.hci_revision = sys_le16_to_cpu(rp->hci_revision); - bt_dev.lmp_version = rp->lmp_version; - bt_dev.lmp_subversion = sys_le16_to_cpu(rp->lmp_subversion); - bt_dev.manufacturer = sys_le16_to_cpu(rp->manufacturer); + bt_dev.hci_version = rp->hci_version; + bt_dev.hci_revision = sys_le16_to_cpu(rp->hci_revision); + bt_dev.lmp_version = rp->lmp_version; + bt_dev.lmp_subversion = sys_le16_to_cpu(rp->lmp_subversion); + bt_dev.manufacturer = sys_le16_to_cpu(rp->manufacturer); } static void read_bdaddr_complete(struct net_buf *buf) { - struct bt_hci_rp_read_bd_addr *rp = (void *)buf->data; + struct bt_hci_rp_read_bd_addr *rp = (void *)buf->data; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) || - !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) { - BT_DBG("Controller has no public address"); - return; - } + if (!bt_addr_cmp(&rp->bdaddr, BT_ADDR_ANY) || + !bt_addr_cmp(&rp->bdaddr, BT_ADDR_NONE)) { + BT_DBG("Controller has no public address"); + return; + } - bt_addr_copy(&bt_dev.id_addr[0].a, &rp->bdaddr); - bt_dev.id_addr[0].type = BT_ADDR_LE_PUBLIC; - bt_dev.id_count = 1U; + bt_addr_copy(&bt_dev.id_addr[0].a, &rp->bdaddr); + bt_dev.id_addr[0].type = BT_ADDR_LE_PUBLIC; + bt_dev.id_count = 1U; } static void read_le_features_complete(struct net_buf *buf) { - struct bt_hci_rp_le_read_local_features *rp = (void *)buf->data; + struct bt_hci_rp_le_read_local_features *rp = (void *)buf->data; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - memcpy(bt_dev.le.features, rp->features, sizeof(bt_dev.le.features)); + memcpy(bt_dev.le.features, rp->features, sizeof(bt_dev.le.features)); } #if defined(CONFIG_BT_BREDR) static void read_buffer_size_complete(struct net_buf *buf) { - struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data; - u16_t pkts; + struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data; + u16_t pkts; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - bt_dev.br.mtu = sys_le16_to_cpu(rp->acl_max_len); - pkts = sys_le16_to_cpu(rp->acl_max_num); + bt_dev.br.mtu = sys_le16_to_cpu(rp->acl_max_len); + pkts = sys_le16_to_cpu(rp->acl_max_num); - BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.br.mtu); + BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.br.mtu); - k_sem_init(&bt_dev.br.pkts, pkts, pkts); + k_sem_init(&bt_dev.br.pkts, pkts, pkts); } #elif defined(CONFIG_BT_CONN) static void read_buffer_size_complete(struct net_buf *buf) { - struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data; - u16_t pkts; + struct bt_hci_rp_read_buffer_size *rp = (void *)buf->data; + u16_t pkts; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - /* If LE-side has buffers we can ignore the BR/EDR values */ - if (bt_dev.le.mtu) { - return; - } + /* If LE-side has buffers we can ignore the BR/EDR values */ + if (bt_dev.le.mtu) { + return; + } - bt_dev.le.mtu = sys_le16_to_cpu(rp->acl_max_len); - pkts = sys_le16_to_cpu(rp->acl_max_num); + bt_dev.le.mtu = sys_le16_to_cpu(rp->acl_max_len); + pkts = sys_le16_to_cpu(rp->acl_max_num); - BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu); + BT_DBG("ACL BR/EDR buffers: pkts %u mtu %u", pkts, bt_dev.le.mtu); - k_sem_init(&bt_dev.le.pkts, pkts, pkts); + k_sem_init(&bt_dev.le.pkts, pkts, pkts); } #endif #if defined(CONFIG_BT_CONN) static void le_read_buffer_size_complete(struct net_buf *buf) { - struct bt_hci_rp_le_read_buffer_size *rp = (void *)buf->data; + struct bt_hci_rp_le_read_buffer_size *rp = (void *)buf->data; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - bt_dev.le.mtu = sys_le16_to_cpu(rp->le_max_len); - if (!bt_dev.le.mtu) { - return; - } + bt_dev.le.mtu = sys_le16_to_cpu(rp->le_max_len); + if (!bt_dev.le.mtu) { + return; + } - BT_DBG("ACL LE buffers: pkts %u mtu %u", rp->le_max_num, bt_dev.le.mtu); + BT_DBG("ACL LE buffers: pkts %u mtu %u", rp->le_max_num, bt_dev.le.mtu); - k_sem_init(&bt_dev.le.pkts, rp->le_max_num, rp->le_max_num); + k_sem_init(&bt_dev.le.pkts, rp->le_max_num, rp->le_max_num); } #endif static void read_supported_commands_complete(struct net_buf *buf) { - struct bt_hci_rp_read_supported_commands *rp = (void *)buf->data; + struct bt_hci_rp_read_supported_commands *rp = (void *)buf->data; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - memcpy(bt_dev.supported_commands, rp->commands, - sizeof(bt_dev.supported_commands)); + memcpy(bt_dev.supported_commands, rp->commands, + sizeof(bt_dev.supported_commands)); - /* - * Report "LE Read Local P-256 Public Key" and "LE Generate DH Key" as - * supported if TinyCrypt ECC is used for emulation. - */ - if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { - bt_dev.supported_commands[34] |= 0x02; - bt_dev.supported_commands[34] |= 0x04; - } + /* + * Report "LE Read Local P-256 Public Key" and "LE Generate DH Key" as + * supported if TinyCrypt ECC is used for emulation. + */ + if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { + bt_dev.supported_commands[34] |= 0x02; + bt_dev.supported_commands[34] |= 0x04; + } } static void read_local_features_complete(struct net_buf *buf) { - struct bt_hci_rp_read_local_features *rp = (void *)buf->data; + struct bt_hci_rp_read_local_features *rp = (void *)buf->data; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - memcpy(bt_dev.features[0], rp->features, sizeof(bt_dev.features[0])); + memcpy(bt_dev.features[0], rp->features, sizeof(bt_dev.features[0])); } static void le_read_supp_states_complete(struct net_buf *buf) { - struct bt_hci_rp_le_read_supp_states *rp = (void *)buf->data; + struct bt_hci_rp_le_read_supp_states *rp = (void *)buf->data; - BT_DBG("status 0x%02x", rp->status); + BT_DBG("status 0x%02x", rp->status); - bt_dev.le.states = sys_get_le64(rp->le_states); + bt_dev.le.states = sys_get_le64(rp->le_states); } #if defined(CONFIG_BT_SMP) static void le_read_resolving_list_size_complete(struct net_buf *buf) { - struct bt_hci_rp_le_read_rl_size *rp = (void *)buf->data; + struct bt_hci_rp_le_read_rl_size *rp = (void *)buf->data; - BT_DBG("Resolving List size %u", rp->rl_size); + BT_DBG("Resolving List size %u", rp->rl_size); - bt_dev.le.rl_size = rp->rl_size; + bt_dev.le.rl_size = rp->rl_size; } #endif /* defined(CONFIG_BT_SMP) */ #if defined(CONFIG_BT_WHITELIST) static void le_read_wl_size_complete(struct net_buf *buf) { - struct bt_hci_rp_le_read_wl_size *rp = - (struct bt_hci_rp_le_read_wl_size *)buf->data; + struct bt_hci_rp_le_read_wl_size *rp = + (struct bt_hci_rp_le_read_wl_size *)buf->data; - BT_DBG("Whitelist size %u", rp->wl_size); + BT_DBG("Whitelist size %u", rp->wl_size); - bt_dev.le.wl_size = rp->wl_size; + bt_dev.le.wl_size = rp->wl_size; } #endif static int common_init(void) { - struct net_buf *rsp; - int err; + struct net_buf *rsp; + int err; - if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) { - /* Send HCI_RESET */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp); - if (err) { - return err; - } - hci_reset_complete(rsp); - net_buf_unref(rsp); - } + if (!(bt_dev.drv->quirks & BT_QUIRK_NO_RESET)) { + /* Send HCI_RESET */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, &rsp); + if (err) { + return err; + } + hci_reset_complete(rsp); + net_buf_unref(rsp); + } - /* Read Local Supported Features */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp); - if (err) { - return err; - } - read_local_features_complete(rsp); - net_buf_unref(rsp); + /* Read Local Supported Features */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_FEATURES, NULL, &rsp); + if (err) { + return err; + } + read_local_features_complete(rsp); + net_buf_unref(rsp); - /* Read Local Version Information */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL, - &rsp); - if (err) { - return err; - } - read_local_ver_complete(rsp); - net_buf_unref(rsp); + /* Read Local Version Information */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_VERSION_INFO, NULL, + &rsp); + if (err) { + return err; + } + read_local_ver_complete(rsp); + net_buf_unref(rsp); - /* Read Bluetooth Address */ - if (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR)) { - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp); - if (err) { - return err; - } - read_bdaddr_complete(rsp); - net_buf_unref(rsp); - } + /* Read Bluetooth Address */ + if (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR)) { + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp); + if (err) { + return err; + } + read_bdaddr_complete(rsp); + net_buf_unref(rsp); + } - /* Read Local Supported Commands */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL, - &rsp); - if (err) { - return err; - } - read_supported_commands_complete(rsp); - net_buf_unref(rsp); + /* Read Local Supported Commands */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_SUPPORTED_COMMANDS, NULL, + &rsp); + if (err) { + return err; + } + read_supported_commands_complete(rsp); + net_buf_unref(rsp); - if (IS_ENABLED(CONFIG_BT_HOST_CRYPTO)) { - /* Initialize the PRNG so that it is safe to use it later - * on in the initialization process. - */ - err = prng_init(); - if (err) { - return err; - } - } + if (IS_ENABLED(CONFIG_BT_HOST_CRYPTO)) { + /* Initialize the PRNG so that it is safe to use it later + * on in the initialization process. + */ + err = prng_init(); + if (err) { + return err; + } + } #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) - err = set_flow_control(); - if (err) { - return err; - } + err = set_flow_control(); + if (err) { + return err; + } #endif /* CONFIG_BT_HCI_ACL_FLOW_CONTROL */ - return 0; + return 0; } static int le_set_event_mask(void) { - struct bt_hci_cp_le_set_event_mask *cp_mask; - struct net_buf *buf; - u64_t mask = 0U; + struct bt_hci_cp_le_set_event_mask *cp_mask; + struct net_buf *buf; + u64_t mask = 0U; - /* Set LE event mask */ - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask)); - if (!buf) { - return -ENOBUFS; - } + /* Set LE event mask */ + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_EVENT_MASK, sizeof(*cp_mask)); + if (!buf) { + return -ENOBUFS; + } - cp_mask = net_buf_add(buf, sizeof(*cp_mask)); + cp_mask = net_buf_add(buf, sizeof(*cp_mask)); - mask |= BT_EVT_MASK_LE_ADVERTISING_REPORT; + mask |= BT_EVT_MASK_LE_ADVERTISING_REPORT; - if (IS_ENABLED(CONFIG_BT_CONN)) { - if (IS_ENABLED(CONFIG_BT_SMP) && - BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - mask |= BT_EVT_MASK_LE_ENH_CONN_COMPLETE; - } else { - mask |= BT_EVT_MASK_LE_CONN_COMPLETE; - } + if (IS_ENABLED(CONFIG_BT_CONN)) { + if (IS_ENABLED(CONFIG_BT_SMP) && + BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { + mask |= BT_EVT_MASK_LE_ENH_CONN_COMPLETE; + } else { + mask |= BT_EVT_MASK_LE_CONN_COMPLETE; + } - mask |= BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE; - mask |= BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE; + mask |= BT_EVT_MASK_LE_CONN_UPDATE_COMPLETE; + mask |= BT_EVT_MASK_LE_REMOTE_FEAT_COMPLETE; - if (BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features)) { - mask |= BT_EVT_MASK_LE_CONN_PARAM_REQ; - } + if (BT_FEAT_LE_CONN_PARAM_REQ_PROC(bt_dev.le.features)) { + mask |= BT_EVT_MASK_LE_CONN_PARAM_REQ; + } - if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && - BT_FEAT_LE_DLE(bt_dev.le.features)) { - mask |= BT_EVT_MASK_LE_DATA_LEN_CHANGE; - } + if (IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && + BT_FEAT_LE_DLE(bt_dev.le.features)) { + mask |= BT_EVT_MASK_LE_DATA_LEN_CHANGE; + } - if (IS_ENABLED(CONFIG_BT_PHY_UPDATE) && - (BT_FEAT_LE_PHY_2M(bt_dev.le.features) || - BT_FEAT_LE_PHY_CODED(bt_dev.le.features))) { - mask |= BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE; - } - } + if (IS_ENABLED(CONFIG_BT_PHY_UPDATE) && + (BT_FEAT_LE_PHY_2M(bt_dev.le.features) || + BT_FEAT_LE_PHY_CODED(bt_dev.le.features))) { + mask |= BT_EVT_MASK_LE_PHY_UPDATE_COMPLETE; + } + } - if (IS_ENABLED(CONFIG_BT_SMP) && - BT_FEAT_LE_ENCR(bt_dev.le.features)) { - mask |= BT_EVT_MASK_LE_LTK_REQUEST; - } + if (IS_ENABLED(CONFIG_BT_SMP) && + BT_FEAT_LE_ENCR(bt_dev.le.features)) { + mask |= BT_EVT_MASK_LE_LTK_REQUEST; + } - /* - * If "LE Read Local P-256 Public Key" and "LE Generate DH Key" are - * supported we need to enable events generated by those commands. - */ - if (IS_ENABLED(CONFIG_BT_ECC) && - (BT_CMD_TEST(bt_dev.supported_commands, 34, 1)) && - (BT_CMD_TEST(bt_dev.supported_commands, 34, 2))) { - mask |= BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE; - mask |= BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE; - } + /* + * If "LE Read Local P-256 Public Key" and "LE Generate DH Key" are + * supported we need to enable events generated by those commands. + */ + if (IS_ENABLED(CONFIG_BT_ECC) && + (BT_CMD_TEST(bt_dev.supported_commands, 34, 1)) && + (BT_CMD_TEST(bt_dev.supported_commands, 34, 2))) { + mask |= BT_EVT_MASK_LE_P256_PUBLIC_KEY_COMPLETE; + mask |= BT_EVT_MASK_LE_GENERATE_DHKEY_COMPLETE; + } - sys_put_le64(mask, cp_mask->events); - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL); + sys_put_le64(mask, cp_mask->events); + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_EVENT_MASK, buf, NULL); } static int le_init(void) { - struct bt_hci_cp_write_le_host_supp *cp_le; - struct net_buf *buf, *rsp; - int err; + struct bt_hci_cp_write_le_host_supp *cp_le; + struct net_buf *buf, *rsp; + int err; - /* For now we only support LE capable controllers */ - if (!BT_FEAT_LE(bt_dev.features)) { - BT_ERR("Non-LE capable controller detected!"); - return -ENODEV; - } + /* For now we only support LE capable controllers */ + if (!BT_FEAT_LE(bt_dev.features)) { + BT_ERR("Non-LE capable controller detected!"); + return -ENODEV; + } - /* Read Low Energy Supported Features */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL, - &rsp); - if (err) { - return err; - } - read_le_features_complete(rsp); - net_buf_unref(rsp); + /* Read Low Energy Supported Features */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_LOCAL_FEATURES, NULL, + &rsp); + if (err) { + return err; + } + read_le_features_complete(rsp); + net_buf_unref(rsp); #if defined(CONFIG_BT_CONN) - /* Read LE Buffer Size */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE, - NULL, &rsp); - if (err) { - return err; - } - le_read_buffer_size_complete(rsp); - net_buf_unref(rsp); + /* Read LE Buffer Size */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_BUFFER_SIZE, + NULL, &rsp); + if (err) { + return err; + } + le_read_buffer_size_complete(rsp); + net_buf_unref(rsp); #endif - if (BT_FEAT_BREDR(bt_dev.features)) { - buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, - sizeof(*cp_le)); - if (!buf) { - return -ENOBUFS; - } + if (BT_FEAT_BREDR(bt_dev.features)) { + buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, + sizeof(*cp_le)); + if (!buf) { + return -ENOBUFS; + } - cp_le = net_buf_add(buf, sizeof(*cp_le)); + cp_le = net_buf_add(buf, sizeof(*cp_le)); - /* Explicitly enable LE for dual-mode controllers */ - cp_le->le = 0x01; - cp_le->simul = 0x00; - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf, - NULL); - if (err) { - return err; - } - } + /* Explicitly enable LE for dual-mode controllers */ + cp_le->le = 0x01; + cp_le->simul = 0x00; + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_LE_HOST_SUPP, buf, + NULL); + if (err) { + return err; + } + } - /* Read LE Supported States */ - if (BT_CMD_LE_STATES(bt_dev.supported_commands)) { - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL, - &rsp); - if (err) { - return err; - } - le_read_supp_states_complete(rsp); - net_buf_unref(rsp); - } + /* Read LE Supported States */ + if (BT_CMD_LE_STATES(bt_dev.supported_commands)) { + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_SUPP_STATES, NULL, + &rsp); + if (err) { + return err; + } + le_read_supp_states_complete(rsp); + net_buf_unref(rsp); + } - if (IS_ENABLED(CONFIG_BT_CONN) && - IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && - BT_FEAT_LE_DLE(bt_dev.le.features)) { - struct bt_hci_cp_le_write_default_data_len *cp; - struct bt_hci_rp_le_read_max_data_len *rp; - u16_t tx_octets, tx_time; + if (IS_ENABLED(CONFIG_BT_CONN) && + IS_ENABLED(CONFIG_BT_DATA_LEN_UPDATE) && + BT_FEAT_LE_DLE(bt_dev.le.features)) { + struct bt_hci_cp_le_write_default_data_len *cp; + struct bt_hci_rp_le_read_max_data_len *rp; + u16_t tx_octets, tx_time; - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, - &rsp); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_MAX_DATA_LEN, NULL, + &rsp); + if (err) { + return err; + } - rp = (void *)rsp->data; - tx_octets = sys_le16_to_cpu(rp->max_tx_octets); - tx_time = sys_le16_to_cpu(rp->max_tx_time); - net_buf_unref(rsp); + rp = (void *)rsp->data; + tx_octets = sys_le16_to_cpu(rp->max_tx_octets); + tx_time = sys_le16_to_cpu(rp->max_tx_time); + net_buf_unref(rsp); - buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, - sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, + sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->max_tx_octets = sys_cpu_to_le16(tx_octets); - cp->max_tx_time = sys_cpu_to_le16(tx_time); + cp = net_buf_add(buf, sizeof(*cp)); + cp->max_tx_octets = sys_cpu_to_le16(tx_octets); + cp->max_tx_time = sys_cpu_to_le16(tx_time); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, - buf, NULL); - if (err) { - return err; - } - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN, + buf, NULL); + if (err) { + return err; + } + } #if defined(CONFIG_BT_SMP) - if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { + if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { #if defined(CONFIG_BT_PRIVACY) - struct bt_hci_cp_le_set_rpa_timeout *cp; + struct bt_hci_cp_le_set_rpa_timeout *cp; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT, - sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT, + sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->rpa_timeout = sys_cpu_to_le16(CONFIG_BT_RPA_TIMEOUT); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf, - NULL); - if (err) { - return err; - } + cp = net_buf_add(buf, sizeof(*cp)); + cp->rpa_timeout = sys_cpu_to_le16(CONFIG_BT_RPA_TIMEOUT); + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf, + NULL); + if (err) { + return err; + } #endif /* defined(CONFIG_BT_PRIVACY) */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL, - &rsp); - if (err) { - return err; - } - le_read_resolving_list_size_complete(rsp); - net_buf_unref(rsp); - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_RL_SIZE, NULL, + &rsp); + if (err) { + return err; + } + le_read_resolving_list_size_complete(rsp); + net_buf_unref(rsp); + } #endif #if defined(CONFIG_BT_WHITELIST) - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL, - &rsp); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_READ_WL_SIZE, NULL, + &rsp); + if (err) { + return err; + } - le_read_wl_size_complete(rsp); - net_buf_unref(rsp); + le_read_wl_size_complete(rsp); + net_buf_unref(rsp); #endif /* defined(CONFIG_BT_WHITELIST) */ - return le_set_event_mask(); + return le_set_event_mask(); } #if defined(CONFIG_BT_BREDR) static int read_ext_features(void) { - int i; + int i; - /* Read Local Supported Extended Features */ - for (i = 1; i < LMP_FEAT_PAGES_COUNT; i++) { - struct bt_hci_cp_read_local_ext_features *cp; - struct bt_hci_rp_read_local_ext_features *rp; - struct net_buf *buf, *rsp; - int err; + /* Read Local Supported Extended Features */ + for (i = 1; i < LMP_FEAT_PAGES_COUNT; i++) { + struct bt_hci_cp_read_local_ext_features *cp; + struct bt_hci_rp_read_local_ext_features *rp; + struct net_buf *buf, *rsp; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, - sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, + sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - cp->page = i; + cp = net_buf_add(buf, sizeof(*cp)); + cp->page = i; - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, - buf, &rsp); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_LOCAL_EXT_FEATURES, + buf, &rsp); + if (err) { + return err; + } - rp = (void *)rsp->data; + rp = (void *)rsp->data; - memcpy(&bt_dev.features[i], rp->ext_features, - sizeof(bt_dev.features[i])); + memcpy(&bt_dev.features[i], rp->ext_features, + sizeof(bt_dev.features[i])); - if (rp->max_page <= i) { - net_buf_unref(rsp); - break; - } + if (rp->max_page <= i) { + net_buf_unref(rsp); + break; + } - net_buf_unref(rsp); - } + net_buf_unref(rsp); + } - return 0; + return 0; } void device_supported_pkt_type(void) { - /* Device supported features and sco packet types */ - if (BT_FEAT_HV2_PKT(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV2); - } + /* Device supported features and sco packet types */ + if (BT_FEAT_HV2_PKT(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV2); + } - if (BT_FEAT_HV3_PKT(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV3); - } + if (BT_FEAT_HV3_PKT(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_HV3); + } - if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV3); - } + if (BT_FEAT_LMP_ESCO_CAPABLE(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV3); + } - if (BT_FEAT_EV4_PKT(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV4); - } + if (BT_FEAT_EV4_PKT(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV4); + } - if (BT_FEAT_EV5_PKT(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV5); - } + if (BT_FEAT_EV5_PKT(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_EV5); + } - if (BT_FEAT_2EV3_PKT(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV3); - } + if (BT_FEAT_2EV3_PKT(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV3); + } - if (BT_FEAT_3EV3_PKT(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_3EV3); - } + if (BT_FEAT_3EV3_PKT(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_3EV3); + } - if (BT_FEAT_3SLOT_PKT(bt_dev.features)) { - bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV5 | - HCI_PKT_TYPE_ESCO_3EV5); - } + if (BT_FEAT_3SLOT_PKT(bt_dev.features)) { + bt_dev.br.esco_pkt_type |= (HCI_PKT_TYPE_ESCO_2EV5 | + HCI_PKT_TYPE_ESCO_3EV5); + } } static int br_init(void) { - struct net_buf *buf; - struct bt_hci_cp_write_ssp_mode *ssp_cp; - struct bt_hci_cp_write_inquiry_mode *inq_cp; - struct bt_hci_write_local_name *name_cp; - int err; + struct net_buf *buf; + struct bt_hci_cp_write_ssp_mode *ssp_cp; + struct bt_hci_cp_write_inquiry_mode *inq_cp; + struct bt_hci_write_local_name *name_cp; + int err; - /* Read extended local features */ - if (BT_FEAT_EXT_FEATURES(bt_dev.features)) { - err = read_ext_features(); - if (err) { - return err; - } - } + /* Read extended local features */ + if (BT_FEAT_EXT_FEATURES(bt_dev.features)) { + err = read_ext_features(); + if (err) { + return err; + } + } - /* Add local supported packet types to bt_dev */ - device_supported_pkt_type(); + /* Add local supported packet types to bt_dev */ + device_supported_pkt_type(); - /* Get BR/EDR buffer size */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &buf); - if (err) { - return err; - } + /* Get BR/EDR buffer size */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &buf); + if (err) { + return err; + } - read_buffer_size_complete(buf); - net_buf_unref(buf); + read_buffer_size_complete(buf); + net_buf_unref(buf); - /* Set SSP mode */ - buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SSP_MODE, sizeof(*ssp_cp)); - if (!buf) { - return -ENOBUFS; - } + /* Set SSP mode */ + buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SSP_MODE, sizeof(*ssp_cp)); + if (!buf) { + return -ENOBUFS; + } - ssp_cp = net_buf_add(buf, sizeof(*ssp_cp)); - ssp_cp->mode = 0x01; - err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SSP_MODE, buf, NULL); - if (err) { - return err; - } + ssp_cp = net_buf_add(buf, sizeof(*ssp_cp)); + ssp_cp->mode = 0x01; + err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SSP_MODE, buf, NULL); + if (err) { + return err; + } - /* Enable Inquiry results with RSSI or extended Inquiry */ - buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_MODE, sizeof(*inq_cp)); - if (!buf) { - return -ENOBUFS; - } + /* Enable Inquiry results with RSSI or extended Inquiry */ + buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_INQUIRY_MODE, sizeof(*inq_cp)); + if (!buf) { + return -ENOBUFS; + } - inq_cp = net_buf_add(buf, sizeof(*inq_cp)); - inq_cp->mode = 0x02; - err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_MODE, buf, NULL); - if (err) { - return err; - } + inq_cp = net_buf_add(buf, sizeof(*inq_cp)); + inq_cp->mode = 0x02; + err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_INQUIRY_MODE, buf, NULL); + if (err) { + return err; + } - /* Set local name */ - buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_LOCAL_NAME, sizeof(*name_cp)); - if (!buf) { - return -ENOBUFS; - } + /* Set local name */ + buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_LOCAL_NAME, sizeof(*name_cp)); + if (!buf) { + return -ENOBUFS; + } - name_cp = net_buf_add(buf, sizeof(*name_cp)); - strncpy((char *)name_cp->local_name, CONFIG_BT_DEVICE_NAME, - sizeof(name_cp->local_name)); + name_cp = net_buf_add(buf, sizeof(*name_cp)); + strncpy((char *)name_cp->local_name, CONFIG_BT_DEVICE_NAME, + sizeof(name_cp->local_name)); - err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_LOCAL_NAME, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_LOCAL_NAME, buf, NULL); + if (err) { + return err; + } - /* Set page timeout*/ - buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_TIMEOUT, sizeof(u16_t)); - if (!buf) { - return -ENOBUFS; - } + /* Set page timeout*/ + buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_PAGE_TIMEOUT, sizeof(u16_t)); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_le16(buf, CONFIG_BT_PAGE_TIMEOUT); + net_buf_add_le16(buf, CONFIG_BT_PAGE_TIMEOUT); - err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_TIMEOUT, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_PAGE_TIMEOUT, buf, NULL); + if (err) { + return err; + } - /* Enable BR/EDR SC if supported */ - if (BT_FEAT_SC(bt_dev.features)) { - struct bt_hci_cp_write_sc_host_supp *sc_cp; + /* Enable BR/EDR SC if supported */ + if (BT_FEAT_SC(bt_dev.features)) { + struct bt_hci_cp_write_sc_host_supp *sc_cp; - buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SC_HOST_SUPP, - sizeof(*sc_cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SC_HOST_SUPP, + sizeof(*sc_cp)); + if (!buf) { + return -ENOBUFS; + } - sc_cp = net_buf_add(buf, sizeof(*sc_cp)); - sc_cp->sc_support = 0x01; + sc_cp = net_buf_add(buf, sizeof(*sc_cp)); + sc_cp->sc_support = 0x01; - err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SC_HOST_SUPP, buf, - NULL); - if (err) { - return err; - } - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SC_HOST_SUPP, buf, + NULL); + if (err) { + return err; + } + } - return 0; + return 0; } #else static int br_init(void) { #if defined(CONFIG_BT_CONN) - struct net_buf *rsp; - int err; + struct net_buf *rsp; + int err; - if (bt_dev.le.mtu) { - return 0; - } + if (bt_dev.le.mtu) { + return 0; + } - /* Use BR/EDR buffer size if LE reports zero buffers */ - err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp); - if (err) { - return err; - } + /* Use BR/EDR buffer size if LE reports zero buffers */ + err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BUFFER_SIZE, NULL, &rsp); + if (err) { + return err; + } - read_buffer_size_complete(rsp); - net_buf_unref(rsp); + read_buffer_size_complete(rsp); + net_buf_unref(rsp); #endif /* CONFIG_BT_CONN */ - return 0; + return 0; } #endif static int set_event_mask(void) { - struct bt_hci_cp_set_event_mask *ev; - struct net_buf *buf; - u64_t mask = 0U; + struct bt_hci_cp_set_event_mask *ev; + struct net_buf *buf; + u64_t mask = 0U; - buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_SET_EVENT_MASK, sizeof(*ev)); + if (!buf) { + return -ENOBUFS; + } - ev = net_buf_add(buf, sizeof(*ev)); + ev = net_buf_add(buf, sizeof(*ev)); - if (IS_ENABLED(CONFIG_BT_BREDR)) { - /* Since we require LE support, we can count on a - * Bluetooth 4.0 feature set - */ - mask |= BT_EVT_MASK_INQUIRY_COMPLETE; - mask |= BT_EVT_MASK_CONN_COMPLETE; - mask |= BT_EVT_MASK_CONN_REQUEST; - mask |= BT_EVT_MASK_AUTH_COMPLETE; - mask |= BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE; - mask |= BT_EVT_MASK_REMOTE_FEATURES; - mask |= BT_EVT_MASK_ROLE_CHANGE; - mask |= BT_EVT_MASK_PIN_CODE_REQ; - mask |= BT_EVT_MASK_LINK_KEY_REQ; - mask |= BT_EVT_MASK_LINK_KEY_NOTIFY; - mask |= BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI; - mask |= BT_EVT_MASK_REMOTE_EXT_FEATURES; - mask |= BT_EVT_MASK_SYNC_CONN_COMPLETE; - mask |= BT_EVT_MASK_EXTENDED_INQUIRY_RESULT; - mask |= BT_EVT_MASK_IO_CAPA_REQ; - mask |= BT_EVT_MASK_IO_CAPA_RESP; - mask |= BT_EVT_MASK_USER_CONFIRM_REQ; - mask |= BT_EVT_MASK_USER_PASSKEY_REQ; - mask |= BT_EVT_MASK_SSP_COMPLETE; - mask |= BT_EVT_MASK_USER_PASSKEY_NOTIFY; - } + if (IS_ENABLED(CONFIG_BT_BREDR)) { + /* Since we require LE support, we can count on a + * Bluetooth 4.0 feature set + */ + mask |= BT_EVT_MASK_INQUIRY_COMPLETE; + mask |= BT_EVT_MASK_CONN_COMPLETE; + mask |= BT_EVT_MASK_CONN_REQUEST; + mask |= BT_EVT_MASK_AUTH_COMPLETE; + mask |= BT_EVT_MASK_REMOTE_NAME_REQ_COMPLETE; + mask |= BT_EVT_MASK_REMOTE_FEATURES; + mask |= BT_EVT_MASK_ROLE_CHANGE; + mask |= BT_EVT_MASK_PIN_CODE_REQ; + mask |= BT_EVT_MASK_LINK_KEY_REQ; + mask |= BT_EVT_MASK_LINK_KEY_NOTIFY; + mask |= BT_EVT_MASK_INQUIRY_RESULT_WITH_RSSI; + mask |= BT_EVT_MASK_REMOTE_EXT_FEATURES; + mask |= BT_EVT_MASK_SYNC_CONN_COMPLETE; + mask |= BT_EVT_MASK_EXTENDED_INQUIRY_RESULT; + mask |= BT_EVT_MASK_IO_CAPA_REQ; + mask |= BT_EVT_MASK_IO_CAPA_RESP; + mask |= BT_EVT_MASK_USER_CONFIRM_REQ; + mask |= BT_EVT_MASK_USER_PASSKEY_REQ; + mask |= BT_EVT_MASK_SSP_COMPLETE; + mask |= BT_EVT_MASK_USER_PASSKEY_NOTIFY; + } - mask |= BT_EVT_MASK_HARDWARE_ERROR; - mask |= BT_EVT_MASK_DATA_BUFFER_OVERFLOW; - mask |= BT_EVT_MASK_LE_META_EVENT; + mask |= BT_EVT_MASK_HARDWARE_ERROR; + mask |= BT_EVT_MASK_DATA_BUFFER_OVERFLOW; + mask |= BT_EVT_MASK_LE_META_EVENT; - if (IS_ENABLED(CONFIG_BT_CONN)) { - mask |= BT_EVT_MASK_DISCONN_COMPLETE; - mask |= BT_EVT_MASK_REMOTE_VERSION_INFO; - } + if (IS_ENABLED(CONFIG_BT_CONN)) { + mask |= BT_EVT_MASK_DISCONN_COMPLETE; + mask |= BT_EVT_MASK_REMOTE_VERSION_INFO; + } - if (IS_ENABLED(CONFIG_BT_SMP) && - BT_FEAT_LE_ENCR(bt_dev.le.features)) { - mask |= BT_EVT_MASK_ENCRYPT_CHANGE; - mask |= BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE; - } + if (IS_ENABLED(CONFIG_BT_SMP) && + BT_FEAT_LE_ENCR(bt_dev.le.features)) { + mask |= BT_EVT_MASK_ENCRYPT_CHANGE; + mask |= BT_EVT_MASK_ENCRYPT_KEY_REFRESH_COMPLETE; + } - sys_put_le64(mask, ev->events); - return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL); + sys_put_le64(mask, ev->events); + return bt_hci_cmd_send_sync(BT_HCI_OP_SET_EVENT_MASK, buf, NULL); } static inline int create_random_addr(bt_addr_le_t *addr) { - addr->type = BT_ADDR_LE_RANDOM; + addr->type = BT_ADDR_LE_RANDOM; - return bt_rand(addr->a.val, 6); + return bt_rand(addr->a.val, 6); } int bt_addr_le_create_nrpa(bt_addr_le_t *addr) { - int err; + int err; - err = create_random_addr(addr); - if (err) { - return err; - } + err = create_random_addr(addr); + if (err) { + return err; + } - BT_ADDR_SET_NRPA(&addr->a); + BT_ADDR_SET_NRPA(&addr->a); - return 0; + return 0; } int bt_addr_le_create_static(bt_addr_le_t *addr) { - int err; + int err; - err = create_random_addr(addr); - if (err) { - return err; - } + err = create_random_addr(addr); + if (err) { + return err; + } - BT_ADDR_SET_STATIC(&addr->a); + BT_ADDR_SET_STATIC(&addr->a); - return 0; + return 0; } #if defined(CONFIG_BT_DEBUG) #if 0 static const char *ver_str(u8_t ver) { - const char * const str[] = { - "1.0b", "1.1", "1.2", "2.0", "2.1", "3.0", "4.0", "4.1", "4.2", - "5.0", "5.1", - }; + const char * const str[] = { + "1.0b", "1.1", "1.2", "2.0", "2.1", "3.0", "4.0", "4.1", "4.2", + "5.0", "5.1", + }; - if (ver < ARRAY_SIZE(str)) { - return str[ver]; - } + if (ver < ARRAY_SIZE(str)) { + return str[ver]; + } - return "unknown"; + return "unknown"; } #endif static void bt_dev_show_info(void) { #if 0 - int i; + int i; - BT_INFO("Identity%s: %s", bt_dev.id_count > 1 ? "[0]" : "", - bt_addr_le_str(&bt_dev.id_addr[0])); + BT_INFO("Identity%s: %s", bt_dev.id_count > 1 ? "[0]" : "", + bt_addr_le_str(&bt_dev.id_addr[0])); - for (i = 1; i < bt_dev.id_count; i++) { - BT_INFO("Identity[%d]: %s", - i, bt_addr_le_str(&bt_dev.id_addr[i])); - } + for (i = 1; i < bt_dev.id_count; i++) { + BT_INFO("Identity[%d]: %s", + i, bt_addr_le_str(&bt_dev.id_addr[i])); + } - BT_INFO("HCI: version %s (0x%02x) revision 0x%04x, manufacturer 0x%04x", - ver_str(bt_dev.hci_version), bt_dev.hci_version, - bt_dev.hci_revision, bt_dev.manufacturer); - BT_INFO("LMP: version %s (0x%02x) subver 0x%04x", - ver_str(bt_dev.lmp_version), bt_dev.lmp_version, - bt_dev.lmp_subversion); + BT_INFO("HCI: version %s (0x%02x) revision 0x%04x, manufacturer 0x%04x", + ver_str(bt_dev.hci_version), bt_dev.hci_version, + bt_dev.hci_revision, bt_dev.manufacturer); + BT_INFO("LMP: version %s (0x%02x) subver 0x%04x", + ver_str(bt_dev.lmp_version), bt_dev.lmp_version, + bt_dev.lmp_subversion); #endif } #else @@ -5043,266 +5043,266 @@ static inline void bt_dev_show_info(void) #if defined(CONFIG_BT_DEBUG) static const char *vs_hw_platform(u16_t platform) { - static const char * const plat_str[] = { - "reserved", "Intel Corporation", "Nordic Semiconductor", - "NXP Semiconductors" }; + static const char * const plat_str[] = { + "reserved", "Intel Corporation", "Nordic Semiconductor", + "NXP Semiconductors" }; - if (platform < ARRAY_SIZE(plat_str)) { - return plat_str[platform]; - } + if (platform < ARRAY_SIZE(plat_str)) { + return plat_str[platform]; + } - return "unknown"; + return "unknown"; } static const char *vs_hw_variant(u16_t platform, u16_t variant) { - static const char * const nordic_str[] = { - "reserved", "nRF51x", "nRF52x", "nRF53x" - }; + static const char * const nordic_str[] = { + "reserved", "nRF51x", "nRF52x", "nRF53x" + }; - if (platform != BT_HCI_VS_HW_PLAT_NORDIC) { - return "unknown"; - } + if (platform != BT_HCI_VS_HW_PLAT_NORDIC) { + return "unknown"; + } - if (variant < ARRAY_SIZE(nordic_str)) { - return nordic_str[variant]; - } + if (variant < ARRAY_SIZE(nordic_str)) { + return nordic_str[variant]; + } - return "unknown"; + return "unknown"; } static const char *vs_fw_variant(u8_t variant) { - static const char * const var_str[] = { - "Standard Bluetooth controller", - "Vendor specific controller", - "Firmware loader", - "Rescue image", - }; + static const char * const var_str[] = { + "Standard Bluetooth controller", + "Vendor specific controller", + "Firmware loader", + "Rescue image", + }; - if (variant < ARRAY_SIZE(var_str)) { - return var_str[variant]; - } + if (variant < ARRAY_SIZE(var_str)) { + return var_str[variant]; + } - return "unknown"; + return "unknown"; } #endif /* CONFIG_BT_DEBUG */ static void hci_vs_init(void) { - union { - struct bt_hci_rp_vs_read_version_info *info; - struct bt_hci_rp_vs_read_supported_commands *cmds; - struct bt_hci_rp_vs_read_supported_features *feat; - } rp; - struct net_buf *rsp; - int err; + union { + struct bt_hci_rp_vs_read_version_info *info; + struct bt_hci_rp_vs_read_supported_commands *cmds; + struct bt_hci_rp_vs_read_supported_features *feat; + } rp; + struct net_buf *rsp; + int err; - /* If heuristics is enabled, try to guess HCI VS support by looking - * at the HCI version and identity address. We haven't tried to set - * a static random address yet at this point, so the identity will - * either be zeroes or a valid public address. - */ - if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && - (bt_dev.hci_version < BT_HCI_VERSION_5_0 || - (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) && - bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) { - BT_WARN("Controller doesn't seem to support Zephyr vendor HCI"); - return; - } + /* If heuristics is enabled, try to guess HCI VS support by looking + * at the HCI version and identity address. We haven't tried to set + * a static random address yet at this point, so the identity will + * either be zeroes or a valid public address. + */ + if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) && + (bt_dev.hci_version < BT_HCI_VERSION_5_0 || + (!atomic_test_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR) && + bt_addr_le_cmp(&bt_dev.id_addr[0], BT_ADDR_LE_ANY)))) { + BT_WARN("Controller doesn't seem to support Zephyr vendor HCI"); + return; + } - err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp); - if (err) { - BT_WARN("Vendor HCI extensions not available"); - return; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_VERSION_INFO, NULL, &rsp); + if (err) { + BT_WARN("Vendor HCI extensions not available"); + return; + } #if defined(CONFIG_BT_DEBUG) - rp.info = (void *)rsp->data; - BT_INFO("HW Platform: %s (0x%04x)", - vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)), - sys_le16_to_cpu(rp.info->hw_platform)); - BT_INFO("HW Variant: %s (0x%04x)", - vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform), - sys_le16_to_cpu(rp.info->hw_variant)), - sys_le16_to_cpu(rp.info->hw_variant)); - BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u", - vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant, - rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision), - sys_le32_to_cpu(rp.info->fw_build)); + rp.info = (void *)rsp->data; + BT_INFO("HW Platform: %s (0x%04x)", + vs_hw_platform(sys_le16_to_cpu(rp.info->hw_platform)), + sys_le16_to_cpu(rp.info->hw_platform)); + BT_INFO("HW Variant: %s (0x%04x)", + vs_hw_variant(sys_le16_to_cpu(rp.info->hw_platform), + sys_le16_to_cpu(rp.info->hw_variant)), + sys_le16_to_cpu(rp.info->hw_variant)); + BT_INFO("Firmware: %s (0x%02x) Version %u.%u Build %u", + vs_fw_variant(rp.info->fw_variant), rp.info->fw_variant, + rp.info->fw_version, sys_le16_to_cpu(rp.info->fw_revision), + sys_le32_to_cpu(rp.info->fw_build)); #endif /* CONFIG_BT_DEBUG */ - net_buf_unref(rsp); + net_buf_unref(rsp); - err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS, - NULL, &rsp); - if (err) { - BT_WARN("Failed to read supported vendor features"); - return; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS, + NULL, &rsp); + if (err) { + BT_WARN("Failed to read supported vendor features"); + return; + } - rp.cmds = (void *)rsp->data; - memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX); - net_buf_unref(rsp); + rp.cmds = (void *)rsp->data; + memcpy(bt_dev.vs_commands, rp.cmds->commands, BT_DEV_VS_CMDS_MAX); + net_buf_unref(rsp); - err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES, - NULL, &rsp); - if (err) { - BT_WARN("Failed to read supported vendor commands"); - return; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_SUPPORTED_FEATURES, + NULL, &rsp); + if (err) { + BT_WARN("Failed to read supported vendor commands"); + return; + } - rp.feat = (void *)rsp->data; - memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX); - net_buf_unref(rsp); + rp.feat = (void *)rsp->data; + memcpy(bt_dev.vs_features, rp.feat->features, BT_DEV_VS_FEAT_MAX); + net_buf_unref(rsp); } #endif /* CONFIG_BT_HCI_VS_EXT */ static int host_hci_init(void) { - int err; + int err; - err = common_init(); - if (err) { - return err; - } + err = common_init(); + if (err) { + return err; + } - err = le_init(); - if (err) { - return err; - } + err = le_init(); + if (err) { + return err; + } - if (BT_FEAT_BREDR(bt_dev.features)) { - err = br_init(); - if (err) { - return err; - } - } else if (IS_ENABLED(CONFIG_BT_BREDR)) { - BT_ERR("Non-BR/EDR controller detected"); - return -EIO; - } + if (BT_FEAT_BREDR(bt_dev.features)) { + err = br_init(); + if (err) { + return err; + } + } else if (IS_ENABLED(CONFIG_BT_BREDR)) { + BT_ERR("Non-BR/EDR controller detected"); + return -EIO; + } - err = set_event_mask(); - if (err) { - return err; - } + err = set_event_mask(); + if (err) { + return err; + } #if defined(CONFIG_BT_HCI_VS_EXT) - hci_vs_init(); + hci_vs_init(); #endif - if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) { - BT_DBG("No public address. Trying to set static random."); - err = bt_setup_id_addr(); - if (err) { - BT_ERR("Unable to set identity address"); - return err; - } - } + if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) { + BT_DBG("No public address. Trying to set static random."); + err = bt_setup_id_addr(); + if (err) { + BT_ERR("Unable to set identity address"); + return err; + } + } - return 0; + return 0; } int bt_send(struct net_buf *buf) { - BT_DBG("buf %p len %u type %u", buf, buf->len, bt_buf_get_type(buf)); + BT_DBG("buf %p len %u type %u", buf, buf->len, bt_buf_get_type(buf)); #if !defined(BFLB_BLE) - bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); + bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); #endif - if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { - return bt_hci_ecc_send(buf); - } + if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { + return bt_hci_ecc_send(buf); + } - return bt_dev.drv->send(buf); + return bt_dev.drv->send(buf); } int bt_recv(struct net_buf *buf) { - bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); + bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); - BT_DBG("buf %p len %u", buf, buf->len); + BT_DBG("buf %p len %u", buf, buf->len); - switch (bt_buf_get_type(buf)) { + switch (bt_buf_get_type(buf)) { #if defined(CONFIG_BT_CONN) - case BT_BUF_ACL_IN: + case BT_BUF_ACL_IN: #if defined(CONFIG_BT_RECV_IS_RX_THREAD) - hci_acl(buf); + hci_acl(buf); #else - net_buf_put(&bt_dev.rx_queue, buf); + net_buf_put(&bt_dev.rx_queue, buf); #endif - return 0; + return 0; #endif /* BT_CONN */ - case BT_BUF_EVT: + case BT_BUF_EVT: #if defined(CONFIG_BT_RECV_IS_RX_THREAD) - hci_event(buf); + hci_event(buf); #else - net_buf_put(&bt_dev.rx_queue, buf); + net_buf_put(&bt_dev.rx_queue, buf); #endif - return 0; - default: - BT_ERR("Invalid buf type %u", bt_buf_get_type(buf)); - net_buf_unref(buf); - return -EINVAL; - } + return 0; + default: + BT_ERR("Invalid buf type %u", bt_buf_get_type(buf)); + net_buf_unref(buf); + return -EINVAL; + } } static const struct event_handler prio_events[] = { - EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete, - sizeof(struct bt_hci_evt_cmd_complete)), - EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status, - sizeof(struct bt_hci_evt_cmd_status)), + EVENT_HANDLER(BT_HCI_EVT_CMD_COMPLETE, hci_cmd_complete, + sizeof(struct bt_hci_evt_cmd_complete)), + EVENT_HANDLER(BT_HCI_EVT_CMD_STATUS, hci_cmd_status, + sizeof(struct bt_hci_evt_cmd_status)), #if defined(CONFIG_BT_CONN) - EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW, - hci_data_buf_overflow, - sizeof(struct bt_hci_evt_data_buf_overflow)), - EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS, - hci_num_completed_packets, - sizeof(struct bt_hci_evt_num_completed_packets)), + EVENT_HANDLER(BT_HCI_EVT_DATA_BUF_OVERFLOW, + hci_data_buf_overflow, + sizeof(struct bt_hci_evt_data_buf_overflow)), + EVENT_HANDLER(BT_HCI_EVT_NUM_COMPLETED_PACKETS, + hci_num_completed_packets, + sizeof(struct bt_hci_evt_num_completed_packets)), #endif /* CONFIG_BT_CONN */ }; int bt_recv_prio(struct net_buf *buf) { - struct bt_hci_evt_hdr *hdr; + struct bt_hci_evt_hdr *hdr; - bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); + bt_monitor_send(bt_monitor_opcode(buf), buf->data, buf->len); - BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT); - BT_ASSERT(buf->len >= sizeof(*hdr)); + BT_ASSERT(bt_buf_get_type(buf) == BT_BUF_EVT); + BT_ASSERT(buf->len >= sizeof(*hdr)); - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - BT_ASSERT(bt_hci_evt_is_prio(hdr->evt)); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + BT_ASSERT(bt_hci_evt_is_prio(hdr->evt)); - handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events)); + handle_event(hdr->evt, buf, prio_events, ARRAY_SIZE(prio_events)); - net_buf_unref(buf); + net_buf_unref(buf); - return 0; + return 0; } int bt_hci_driver_register(const struct bt_hci_driver *drv) { - if (bt_dev.drv) { - return -EALREADY; - } + if (bt_dev.drv) { + return -EALREADY; + } - if (!drv->open || !drv->send) { - return -EINVAL; - } + if (!drv->open || !drv->send) { + return -EINVAL; + } - bt_dev.drv = drv; + bt_dev.drv = drv; - BT_DBG("Registered %s", drv->name ? drv->name : ""); + BT_DBG("Registered %s", drv->name ? drv->name : ""); - bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus, - BT_ADDR_ANY, drv->name ? drv->name : "bt0"); + bt_monitor_new_index(BT_MONITOR_TYPE_PRIMARY, drv->bus, + BT_ADDR_ANY, drv->name ? drv->name : "bt0"); - return 0; + return 0; } #if defined(CONFIG_BT_PRIVACY) static int irk_init(void) -{ +{ #if (BFLB_FIXED_IRK) //use fixed irk memset(&bt_dev.irk[0], 0x11, 16); @@ -5320,37 +5320,37 @@ static int irk_init(void) return err; #else - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - BT_DBG("Expecting settings to handle local IRK"); - } else { - int err; + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + BT_DBG("Expecting settings to handle local IRK"); + } else { + int err; - err = bt_rand(&bt_dev.irk[0], 16); - if (err) { - return err; - } + err = bt_rand(&bt_dev.irk[0], 16); + if (err) { + return err; + } - BT_WARN("Using temporary IRK"); - } + BT_WARN("Using temporary IRK"); + } - return 0; + return 0; #endif } #endif /* CONFIG_BT_PRIVACY */ void bt_finalize_init(void) { - atomic_set_bit(bt_dev.flags, BT_DEV_READY); + atomic_set_bit(bt_dev.flags, BT_DEV_READY); - if (IS_ENABLED(CONFIG_BT_OBSERVER)) { - bt_le_scan_update(false); - } + if (IS_ENABLED(CONFIG_BT_OBSERVER)) { + bt_le_scan_update(false); + } - bt_dev_show_info(); + bt_dev_show_info(); } static int bt_init(void) { - int err; + int err; #if defined(CONFIG_BT_STACK_PTS) u8_t dbg_irk[16]; #endif @@ -5358,7 +5358,7 @@ static int bt_init(void) #if defined(BFLB_BLE_PATCH_SETTINGS_LOAD) char empty_name[CONFIG_BT_DEVICE_NAME_MAX]; memset(empty_name, 0, CONFIG_BT_DEVICE_NAME_MAX); - + if(!memcmp(bt_dev.name, empty_name, CONFIG_BT_DEVICE_NAME_MAX)) bt_set_name(CONFIG_BT_DEVICE_NAME); #endif @@ -5366,33 +5366,33 @@ static int bt_init(void) #if defined(BFLB_BLE) err = bl_onchiphci_interface_init(); if (err) { - return err; - } + return err; + } #endif - err = host_hci_init(); - if (err) { - return err; - } - if (IS_ENABLED(CONFIG_BT_CONN)) { - err = bt_conn_init(); - if (err) { - return err; - } - } + err = host_hci_init(); + if (err) { + return err; + } + if (IS_ENABLED(CONFIG_BT_CONN)) { + err = bt_conn_init(); + if (err) { + return err; + } + } #if defined(CONFIG_BT_PRIVACY) - err = irk_init(); - if (err) { - return err; - } + err = irk_init(); + if (err) { + return err; + } #if defined(CONFIG_BT_STACK_PTS) reverse_bytearray(bt_dev.irk[0], dbg_irk, sizeof(dbg_irk)); - BT_PTS("Local IRK %s public identity bdaddr %s", + BT_PTS("Local IRK %s public identity bdaddr %s", bt_hex(dbg_irk, 16), bt_addr_str(&(bt_dev.id_addr[0].a))); #endif - k_delayed_work_init(&bt_dev.rpa_update, rpa_timeout); + k_delayed_work_init(&bt_dev.rpa_update, rpa_timeout); #endif @@ -5409,61 +5409,61 @@ static int bt_init(void) #endif //CONFIG_BT_SMP if (IS_ENABLED(CONFIG_BT_SETTINGS)) { if (!bt_dev.id_count) { - BT_INFO("No ID address. App must call settings_load()"); - return 0; + BT_INFO("No ID address. App must call settings_load()"); + return 0; } - atomic_set_bit(bt_dev.flags, BT_DEV_PRESET_ID); - } + atomic_set_bit(bt_dev.flags, BT_DEV_PRESET_ID); + } - bt_finalize_init(); - return 0; + bt_finalize_init(); + return 0; } static void init_work(struct k_work *work) { - int err; + int err; - err = bt_init(); - if (ready_cb) { - ready_cb(err); - } + err = bt_init(); + if (ready_cb) { + ready_cb(err); + } } #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) static void hci_rx_thread(void) { - struct net_buf *buf; + struct net_buf *buf; - BT_DBG("started"); + BT_DBG("started"); - while (1) { - BT_DBG("calling fifo_get_wait"); - buf = net_buf_get(&bt_dev.rx_queue, K_FOREVER); + while (1) { + BT_DBG("calling fifo_get_wait"); + buf = net_buf_get(&bt_dev.rx_queue, K_FOREVER); - BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), - buf->len); + BT_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), + buf->len); - switch (bt_buf_get_type(buf)) { + switch (bt_buf_get_type(buf)) { #if defined(CONFIG_BT_CONN) - case BT_BUF_ACL_IN: - hci_acl(buf); - break; + case BT_BUF_ACL_IN: + hci_acl(buf); + break; #endif /* CONFIG_BT_CONN */ - case BT_BUF_EVT: - hci_event(buf); - break; - default: - BT_ERR("Unknown buf type %u", bt_buf_get_type(buf)); - net_buf_unref(buf); - break; - } + case BT_BUF_EVT: + hci_event(buf); + break; + default: + BT_ERR("Unknown buf type %u", bt_buf_get_type(buf)); + net_buf_unref(buf); + break; + } - /* Make sure we don't hog the CPU if the rx_queue never - * gets empty. - */ - k_yield(); - } + /* Make sure we don't hog the CPU if the rx_queue never + * gets empty. + */ + k_yield(); + } } #endif /* !CONFIG_BT_RECV_IS_RX_THREAD */ @@ -5473,16 +5473,16 @@ bool queue_inited = false; int bt_enable(bt_ready_cb_t cb) { - int err; + int err; - if (!bt_dev.drv) { - BT_ERR("No HCI driver registered"); - return -ENODEV; - } + if (!bt_dev.drv) { + BT_ERR("No HCI driver registered"); + return -ENODEV; + } - if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_ENABLE)) { - return -EALREADY; - } + if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_ENABLE)) { + return -EALREADY; + } #if defined(BFLB_BLE) k_work_init(&bt_dev.init, init_work); @@ -5501,7 +5501,7 @@ int bt_enable(bt_ready_cb_t cb) k_lifo_init(&hci_cmd_pool.free, CONFIG_BT_HCI_CMD_COUNT); k_lifo_init(&hci_rx_pool.free, CONFIG_BT_RX_BUF_COUNT); } - + k_sem_init(&g_poll_sem, 0, 1); #endif @@ -5514,74 +5514,74 @@ int bt_enable(bt_ready_cb_t cb) } #else if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - err = bt_settings_init(); - if (err) { - return err; - } - } else { - bt_set_name(CONFIG_BT_DEVICE_NAME); - } + err = bt_settings_init(); + if (err) { + return err; + } + } else { + bt_set_name(CONFIG_BT_DEVICE_NAME); + } #endif - ready_cb = cb; + ready_cb = cb; - /* TX thread */ + /* TX thread */ #if defined(BFLB_BLE) #if (!BFLB_BLE_CO_THREAD) k_thread_create(&tx_thread_data, "hci_tx_thread", - CONFIG_BT_HCI_TX_STACK_SIZE, - hci_tx_thread, - CONFIG_BT_HCI_TX_PRIO); + CONFIG_BT_HCI_TX_STACK_SIZE, + hci_tx_thread, + CONFIG_BT_HCI_TX_PRIO); #endif #else k_thread_create(&tx_thread_data, tx_thread_stack, - K_THREAD_STACK_SIZEOF(tx_thread_stack), - hci_tx_thread, NULL, NULL, NULL, - K_PRIO_COOP(CONFIG_BT_HCI_TX_PRIO), - 0, K_NO_WAIT); - k_thread_name_set(&tx_thread_data, "BT TX"); + K_THREAD_STACK_SIZEOF(tx_thread_stack), + hci_tx_thread, NULL, NULL, NULL, + K_PRIO_COOP(CONFIG_BT_HCI_TX_PRIO), + 0, K_NO_WAIT); + k_thread_name_set(&tx_thread_data, "BT TX"); #endif #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) - /* RX thread */ + /* RX thread */ #if defined(BFLB_BLE) - k_thread_create(&rx_thread_data, "hci_rx_thread", - CONFIG_BT_HCI_RX_STACK_SIZE/*K_THREAD_STACK_SIZEOF(rx_thread_stack)*/, - (k_thread_entry_t)hci_rx_thread, - CONFIG_BT_RX_PRIO); + k_thread_create(&rx_thread_data, "hci_rx_thread", + CONFIG_BT_HCI_RX_STACK_SIZE/*K_THREAD_STACK_SIZEOF(rx_thread_stack)*/, + (k_thread_entry_t)hci_rx_thread, + CONFIG_BT_RX_PRIO); #else k_thread_create(&rx_thread_data, rx_thread_stack, - K_THREAD_STACK_SIZEOF(rx_thread_stack), - (k_thread_entry_t)hci_rx_thread, NULL, NULL, NULL, - K_PRIO_COOP(CONFIG_BT_RX_PRIO), - 0, K_NO_WAIT); - k_thread_name_set(&rx_thread_data, "BT RX"); + K_THREAD_STACK_SIZEOF(rx_thread_stack), + (k_thread_entry_t)hci_rx_thread, NULL, NULL, NULL, + K_PRIO_COOP(CONFIG_BT_RX_PRIO), + 0, K_NO_WAIT); + k_thread_name_set(&rx_thread_data, "BT RX"); #endif //BFLB_BLE #endif - if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { - bt_hci_ecc_init(); - } + if (IS_ENABLED(CONFIG_BT_TINYCRYPT_ECC)) { + bt_hci_ecc_init(); + } + + err = bt_dev.drv->open(); + if (err) { + BT_ERR("HCI driver open failed (%d)", err); + return err; + } - err = bt_dev.drv->open(); - if (err) { - BT_ERR("HCI driver open failed (%d)", err); - return err; - } - bt_monitor_send(BT_MONITOR_OPEN_INDEX, NULL, 0); #if !defined(BFLB_BLE) - if (!cb) { - return bt_init(); - } + if (!cb) { + return bt_init(); + } #endif - k_work_submit(&bt_dev.init); - return 0; + k_work_submit(&bt_dev.init); + return 0; } struct bt_ad { - const struct bt_data *data; - size_t len; + const struct bt_data *data; + size_t len; }; #if defined(BFLB_BLE) @@ -5622,9 +5622,9 @@ int bt_disable_action(void) #if defined(CONFIG_BT_PRIVACY) k_delayed_work_del_timer(&bt_dev.rpa_update); #endif - + bt_gatt_deinit(); - + //delete task k_thread_delete(&tx_thread_data); k_thread_delete(&recv_thread_data); @@ -5634,9 +5634,9 @@ int bt_disable_action(void) bt_delete_queue(&recv_fifo); bt_delete_queue(&g_work_queue_main.fifo); bt_delete_queue(&bt_dev.cmd_tx_queue); - + k_queue_free((struct k_queue *)&free_tx); - + //delete sem k_sem_delete(&bt_dev.ncmd_sem); k_sem_delete(&g_poll_sem); @@ -5659,7 +5659,7 @@ int bt_disable_action(void) } int bt_disable(void) -{ +{ if(le_check_valid_conn() || atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN) || atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)){ return -1; @@ -5671,82 +5671,82 @@ int bt_disable(void) static int set_ad(u16_t hci_op, const struct bt_ad *ad, size_t ad_len) { - struct bt_hci_cp_le_set_adv_data *set_data; - struct net_buf *buf; - int c, i; + struct bt_hci_cp_le_set_adv_data *set_data; + struct net_buf *buf; + int c, i; - buf = bt_hci_cmd_create(hci_op, sizeof(*set_data)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(hci_op, sizeof(*set_data)); + if (!buf) { + return -ENOBUFS; + } - set_data = net_buf_add(buf, sizeof(*set_data)); + set_data = net_buf_add(buf, sizeof(*set_data)); - (void)memset(set_data, 0, sizeof(*set_data)); + (void)memset(set_data, 0, sizeof(*set_data)); - for (c = 0; c < ad_len; c++) { - const struct bt_data *data = ad[c].data; + for (c = 0; c < ad_len; c++) { + const struct bt_data *data = ad[c].data; - for (i = 0; i < ad[c].len; i++) { - int len = data[i].data_len; - u8_t type = data[i].type; + for (i = 0; i < ad[c].len; i++) { + int len = data[i].data_len; + u8_t type = data[i].type; - /* Check if ad fit in the remaining buffer */ - if (set_data->len + len + 2 > 31) { - len = 31 - (set_data->len + 2); - if (type != BT_DATA_NAME_COMPLETE || !len) { - net_buf_unref(buf); - BT_ERR("Too big advertising data"); - return -EINVAL; - } - type = BT_DATA_NAME_SHORTENED; - } + /* Check if ad fit in the remaining buffer */ + if (set_data->len + len + 2 > 31) { + len = 31 - (set_data->len + 2); + if (type != BT_DATA_NAME_COMPLETE || !len) { + net_buf_unref(buf); + BT_ERR("Too big advertising data"); + return -EINVAL; + } + type = BT_DATA_NAME_SHORTENED; + } - set_data->data[set_data->len++] = len + 1; - set_data->data[set_data->len++] = type; + set_data->data[set_data->len++] = len + 1; + set_data->data[set_data->len++] = type; - memcpy(&set_data->data[set_data->len], data[i].data, - len); - set_data->len += len; - } - } + memcpy(&set_data->data[set_data->len], data[i].data, + len); + set_data->len += len; + } + } - return bt_hci_cmd_send_sync(hci_op, buf, NULL); + return bt_hci_cmd_send_sync(hci_op, buf, NULL); } int bt_set_name(const char *name) { #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) - size_t len = strlen(name); + size_t len = strlen(name); #if !defined(BFLB_BLE) - int err; + int err; #endif - if (len >= sizeof(bt_dev.name)) { - return -ENOMEM; - } + if (len >= sizeof(bt_dev.name)) { + return -ENOMEM; + } - if (!strcmp(bt_dev.name, name)) { - return 0; - } + if (!strcmp(bt_dev.name, name)) { + return 0; + } - strncpy(bt_dev.name, name, sizeof(bt_dev.name)); + strncpy(bt_dev.name, name, sizeof(bt_dev.name)); - /* Update advertising name if in use */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME)) { - struct bt_data data[] = { BT_DATA(BT_DATA_NAME_COMPLETE, name, - strlen(name)) }; - struct bt_ad sd = { data, ARRAY_SIZE(data) }; + /* Update advertising name if in use */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME)) { + struct bt_data data[] = { BT_DATA(BT_DATA_NAME_COMPLETE, name, + strlen(name)) }; + struct bt_ad sd = { data, ARRAY_SIZE(data) }; - set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, &sd, 1); + set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, &sd, 1); - /* Make sure the new name is set */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - set_advertise_enable(false); - set_advertise_enable(true); - } - } + /* Make sure the new name is set */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + set_advertise_enable(false); + set_advertise_enable(true); + } + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { #if defined(BFLB_BLE) #if defined(CFG_SLEEP) if(HBN_Get_Status_Flag() == 0) @@ -5754,252 +5754,252 @@ int bt_set_name(const char *name) bt_settings_save_name(); #else err = settings_save_one("bt/name", bt_dev.name, len); - if (err) { - BT_WARN("Unable to store name"); - } + if (err) { + BT_WARN("Unable to store name"); + } #endif - } + } - return 0; + return 0; #else - return -ENOMEM; + return -ENOMEM; #endif } const char *bt_get_name(void) { #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) - return bt_dev.name; + return bt_dev.name; #else - return CONFIG_BT_DEVICE_NAME; + return CONFIG_BT_DEVICE_NAME; #endif } int bt_set_id_addr(const bt_addr_le_t *addr) { - bt_addr_le_t non_const_addr; + bt_addr_le_t non_const_addr; - if (atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - BT_ERR("Setting identity not allowed after bt_enable()"); - return -EBUSY; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + BT_ERR("Setting identity not allowed after bt_enable()"); + return -EBUSY; + } - bt_addr_le_copy(&non_const_addr, addr); + bt_addr_le_copy(&non_const_addr, addr); - return bt_id_create(&non_const_addr, NULL); + return bt_id_create(&non_const_addr, NULL); } void bt_id_get(bt_addr_le_t *addrs, size_t *count) { - size_t to_copy = MIN(*count, bt_dev.id_count); + size_t to_copy = MIN(*count, bt_dev.id_count); - memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t)); - *count = to_copy; + memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t)); + *count = to_copy; } static int id_find(const bt_addr_le_t *addr) { - u8_t id; + u8_t id; - for (id = 0U; id < bt_dev.id_count; id++) { - if (!bt_addr_le_cmp(addr, &bt_dev.id_addr[id])) { - return id; - } - } + for (id = 0U; id < bt_dev.id_count; id++) { + if (!bt_addr_le_cmp(addr, &bt_dev.id_addr[id])) { + return id; + } + } - return -ENOENT; + return -ENOENT; } static void id_create(u8_t id, bt_addr_le_t *addr, u8_t *irk) { - if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { - bt_addr_le_copy(&bt_dev.id_addr[id], addr); - } else { - bt_addr_le_t new_addr; + if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { + bt_addr_le_copy(&bt_dev.id_addr[id], addr); + } else { + bt_addr_le_t new_addr; - do { - bt_addr_le_create_static(&new_addr); - /* Make sure we didn't generate a duplicate */ - } while (id_find(&new_addr) >= 0); + do { + bt_addr_le_create_static(&new_addr); + /* Make sure we didn't generate a duplicate */ + } while (id_find(&new_addr) >= 0); - bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr); + bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr); - if (addr) { - bt_addr_le_copy(addr, &bt_dev.id_addr[id]); - } - } + if (addr) { + bt_addr_le_copy(addr, &bt_dev.id_addr[id]); + } + } #if defined(CONFIG_BT_PRIVACY) - { - u8_t zero_irk[16] = { 0 }; + { + u8_t zero_irk[16] = { 0 }; - if (irk && memcmp(irk, zero_irk, 16)) { - memcpy(&bt_dev.irk[id], irk, 16); - } else { - bt_rand(&bt_dev.irk[id], 16); - if (irk) { - memcpy(irk, &bt_dev.irk[id], 16); - } - } - } + if (irk && memcmp(irk, zero_irk, 16)) { + memcpy(&bt_dev.irk[id], irk, 16); + } else { + bt_rand(&bt_dev.irk[id], 16); + if (irk) { + memcpy(irk, &bt_dev.irk[id], 16); + } + } + } #endif - /* Only store if stack was already initialized. Before initialization - * we don't know the flash content, so it's potentially harmful to - * try to write anything there. - */ - if (IS_ENABLED(CONFIG_BT_SETTINGS) && - atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - bt_settings_save_id(); - } + /* Only store if stack was already initialized. Before initialization + * we don't know the flash content, so it's potentially harmful to + * try to write anything there. + */ + if (IS_ENABLED(CONFIG_BT_SETTINGS) && + atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + bt_settings_save_id(); + } } int bt_id_create(bt_addr_le_t *addr, u8_t *irk) { - int new_id; + int new_id; - if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { - if (addr->type != BT_ADDR_LE_RANDOM || - !BT_ADDR_IS_STATIC(&addr->a)) { - BT_ERR("Only static random identity address supported"); - return -EINVAL; - } + if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { + if (addr->type != BT_ADDR_LE_RANDOM || + !BT_ADDR_IS_STATIC(&addr->a)) { + BT_ERR("Only static random identity address supported"); + return -EINVAL; + } - if (id_find(addr) >= 0) { - return -EALREADY; - } - } + if (id_find(addr) >= 0) { + return -EALREADY; + } + } - if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) { - return -EINVAL; - } + if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) { + return -EINVAL; + } - if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) { - return -ENOMEM; - } + if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) { + return -ENOMEM; + } - new_id = bt_dev.id_count++; - if (new_id == BT_ID_DEFAULT && - !atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - atomic_set_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR); - } + new_id = bt_dev.id_count++; + if (new_id == BT_ID_DEFAULT && + !atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + atomic_set_bit(bt_dev.flags, BT_DEV_USER_ID_ADDR); + } - id_create(new_id, addr, irk); + id_create(new_id, addr, irk); - return new_id; + return new_id; } int bt_id_reset(u8_t id, bt_addr_le_t *addr, u8_t *irk) { - if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { - if (addr->type != BT_ADDR_LE_RANDOM || - !BT_ADDR_IS_STATIC(&addr->a)) { - BT_ERR("Only static random identity address supported"); - return -EINVAL; - } + if (addr && bt_addr_le_cmp(addr, BT_ADDR_LE_ANY)) { + if (addr->type != BT_ADDR_LE_RANDOM || + !BT_ADDR_IS_STATIC(&addr->a)) { + BT_ERR("Only static random identity address supported"); + return -EINVAL; + } - if (id_find(addr) >= 0) { - return -EALREADY; - } - } + if (id_find(addr) >= 0) { + return -EALREADY; + } + } - if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) { - return -EINVAL; - } + if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) { + return -EINVAL; + } - if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) { - return -EINVAL; - } + if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) { + return -EINVAL; + } - if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, - BT_DEV_ADVERTISING)) { - return -EBUSY; - } + if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, + BT_DEV_ADVERTISING)) { + return -EBUSY; + } - if (IS_ENABLED(CONFIG_BT_CONN) && - bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) { - int err; + if (IS_ENABLED(CONFIG_BT_CONN) && + bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) { + int err; - err = bt_unpair(id, NULL); - if (err) { - return err; - } - } + err = bt_unpair(id, NULL); + if (err) { + return err; + } + } - id_create(id, addr, irk); + id_create(id, addr, irk); - return id; + return id; } int bt_id_delete(u8_t id) { - if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) { - return -EINVAL; - } + if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) { + return -EINVAL; + } - if (!bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) { - return -EALREADY; - } + if (!bt_addr_le_cmp(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) { + return -EALREADY; + } - if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, - BT_DEV_ADVERTISING)) { - return -EBUSY; - } + if (id == bt_dev.adv_id && atomic_test_bit(bt_dev.flags, + BT_DEV_ADVERTISING)) { + return -EBUSY; + } - if (IS_ENABLED(CONFIG_BT_CONN)) { - int err; + if (IS_ENABLED(CONFIG_BT_CONN)) { + int err; - err = bt_unpair(id, NULL); - if (err) { - return err; - } - } + err = bt_unpair(id, NULL); + if (err) { + return err; + } + } #if defined(CONFIG_BT_PRIVACY) - (void)memset(bt_dev.irk[id], 0, 16); + (void)memset(bt_dev.irk[id], 0, 16); #endif - bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY); + bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY); - if (id == bt_dev.id_count - 1) { - bt_dev.id_count--; - } + if (id == bt_dev.id_count - 1) { + bt_dev.id_count--; + } - if (IS_ENABLED(CONFIG_BT_SETTINGS) && - atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - bt_settings_save_id(); - } + if (IS_ENABLED(CONFIG_BT_SETTINGS) && + atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + bt_settings_save_id(); + } - return 0; + return 0; } #if defined(CONFIG_BT_HCI_VS_EXT) static uint8_t bt_read_static_addr(bt_addr_le_t *addr) { - struct bt_hci_rp_vs_read_static_addrs *rp; - struct net_buf *rsp; - int err, i; - u8_t cnt; - if (!(bt_dev.vs_commands[1] & BIT(0))) { - BT_WARN("Read Static Addresses command not available"); - return 0; - } + struct bt_hci_rp_vs_read_static_addrs *rp; + struct net_buf *rsp; + int err, i; + u8_t cnt; + if (!(bt_dev.vs_commands[1] & BIT(0))) { + BT_WARN("Read Static Addresses command not available"); + return 0; + } - err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp); - if (err) { - BT_WARN("Failed to read static addresses"); - return 0; - } - rp = (void *)rsp->data; - cnt = MIN(rp->num_addrs, CONFIG_BT_ID_MAX); + err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp); + if (err) { + BT_WARN("Failed to read static addresses"); + return 0; + } + rp = (void *)rsp->data; + cnt = MIN(rp->num_addrs, CONFIG_BT_ID_MAX); - for (i = 0; i < cnt; i++) { - addr[i].type = BT_ADDR_LE_RANDOM; - bt_addr_copy(&addr[i].a, &rp->a[i].bdaddr); - } - net_buf_unref(rsp); - if (!cnt) { - BT_WARN("No static addresses stored in controller"); - } - return cnt; + for (i = 0; i < cnt; i++) { + addr[i].type = BT_ADDR_LE_RANDOM; + bt_addr_copy(&addr[i].a, &rp->a[i].bdaddr); + } + net_buf_unref(rsp); + if (!cnt) { + BT_WARN("No static addresses stored in controller"); + } + return cnt; } #elif defined(CONFIG_BT_CTLR) uint8_t bt_read_static_addr(bt_addr_le_t *addr); @@ -6008,621 +6008,621 @@ uint8_t bt_read_static_addr(bt_addr_le_t *addr); int bt_setup_id_addr(void) { #if defined(CONFIG_BT_HCI_VS_EXT) || defined(CONFIG_BT_CTLR) - /* Only read the addresses if the user has not already configured one or - * more identities (!bt_dev.id_count). - */ - if (!bt_dev.id_count) { - bt_addr_le_t addrs[CONFIG_BT_ID_MAX]; + /* Only read the addresses if the user has not already configured one or + * more identities (!bt_dev.id_count). + */ + if (!bt_dev.id_count) { + bt_addr_le_t addrs[CONFIG_BT_ID_MAX]; - bt_dev.id_count = bt_read_static_addr(addrs); - if (bt_dev.id_count) { - int i; + bt_dev.id_count = bt_read_static_addr(addrs); + if (bt_dev.id_count) { + int i; - for (i = 0; i < bt_dev.id_count; i++) { - id_create(i, &addrs[i], NULL); - } + for (i = 0; i < bt_dev.id_count; i++) { + id_create(i, &addrs[i], NULL); + } - return set_random_address(&bt_dev.id_addr[0].a); - } - } + return set_random_address(&bt_dev.id_addr[0].a); + } + } #endif - return bt_id_create(NULL, NULL); + return bt_id_create(NULL, NULL); } bool bt_addr_le_is_bonded(u8_t id, const bt_addr_le_t *addr) { - if (IS_ENABLED(CONFIG_BT_SMP)) { - struct bt_keys *keys = bt_keys_find_addr(id, addr); + if (IS_ENABLED(CONFIG_BT_SMP)) { + struct bt_keys *keys = bt_keys_find_addr(id, addr); - /* if there are any keys stored then device is bonded */ - return keys && keys->keys; - } else { - return false; - } + /* if there are any keys stored then device is bonded */ + return keys && keys->keys; + } else { + return false; + } } static bool valid_adv_param(const struct bt_le_adv_param *param, bool dir_adv) { - if (param->id >= bt_dev.id_count || - !bt_addr_le_cmp(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) { - return false; - } + if (param->id >= bt_dev.id_count || + !bt_addr_le_cmp(&bt_dev.id_addr[param->id], BT_ADDR_LE_ANY)) { + return false; + } - if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE)) { - /* - * BT Core 4.2 [Vol 2, Part E, 7.8.5] - * The Advertising_Interval_Min and Advertising_Interval_Max - * shall not be set to less than 0x00A0 (100 ms) if the - * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND. - */ - if (bt_dev.hci_version < BT_HCI_VERSION_5_0 && - param->interval_min < 0x00a0) { - return false; - } - } + if (!(param->options & BT_LE_ADV_OPT_CONNECTABLE)) { + /* + * BT Core 4.2 [Vol 2, Part E, 7.8.5] + * The Advertising_Interval_Min and Advertising_Interval_Max + * shall not be set to less than 0x00A0 (100 ms) if the + * Advertising_Type is set to ADV_SCAN_IND or ADV_NONCONN_IND. + */ + if (bt_dev.hci_version < BT_HCI_VERSION_5_0 && + param->interval_min < 0x00a0) { + return false; + } + } - if (is_wl_empty() && - ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) || - (param->options & BT_LE_ADV_OPT_FILTER_CONN))) { - return false; - } + if (is_wl_empty() && + ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) || + (param->options & BT_LE_ADV_OPT_FILTER_CONN))) { + return false; + } - if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) || !dir_adv) { - if (param->interval_min > param->interval_max || - param->interval_min < 0x0020 || - param->interval_max > 0x4000) { - return false; - } - } + if ((param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) || !dir_adv) { + if (param->interval_min > param->interval_max || + param->interval_min < 0x0020 || + param->interval_max > 0x4000) { + return false; + } + } - return true; + return true; } static inline bool ad_has_name(const struct bt_data *ad, size_t ad_len) { - int i; + int i; - for (i = 0; i < ad_len; i++) { - if (ad[i].type == BT_DATA_NAME_COMPLETE || - ad[i].type == BT_DATA_NAME_SHORTENED) { - return true; - } - } + for (i = 0; i < ad_len; i++) { + if (ad[i].type == BT_DATA_NAME_COMPLETE || + ad[i].type == BT_DATA_NAME_SHORTENED) { + return true; + } + } - return false; + return false; } static int le_adv_update(const struct bt_data *ad, size_t ad_len, - const struct bt_data *sd, size_t sd_len, - bool connectable, bool use_name) + const struct bt_data *sd, size_t sd_len, + bool connectable, bool use_name) { - struct bt_ad d[2] = {}; - struct bt_data data; - int err; + struct bt_ad d[2] = {}; + struct bt_data data; + int err; - d[0].data = ad; - d[0].len = ad_len; + d[0].data = ad; + d[0].len = ad_len; - err = set_ad(BT_HCI_OP_LE_SET_ADV_DATA, d, 1); - if (err) { - return err; - } + err = set_ad(BT_HCI_OP_LE_SET_ADV_DATA, d, 1); + if (err) { + return err; + } - d[0].data = sd; - d[0].len = sd_len; + d[0].data = sd; + d[0].len = sd_len; - if (use_name) { - const char *name; + if (use_name) { + const char *name; - if (sd) { - /* Cannot use name if name is already set */ - if (ad_has_name(sd, sd_len)) { - return -EINVAL; - } - } + if (sd) { + /* Cannot use name if name is already set */ + if (ad_has_name(sd, sd_len)) { + return -EINVAL; + } + } - name = bt_get_name(); - data = (struct bt_data)BT_DATA( - BT_DATA_NAME_COMPLETE, - name, strlen(name)); + name = bt_get_name(); + data = (struct bt_data)BT_DATA( + BT_DATA_NAME_COMPLETE, + name, strlen(name)); - d[1].data = &data; - d[1].len = 1; - } + d[1].data = &data; + d[1].len = 1; + } - /* - * We need to set SCAN_RSP when enabling advertising type that - * allows for Scan Requests. - * - * If any data was not provided but we enable connectable - * undirected advertising sd needs to be cleared from values set - * by previous calls. - * Clearing sd is done by calling set_ad() with NULL data and - * zero len. - * So following condition check is unusual but correct. - */ - if (d[0].data || d[1].data || connectable) { - err = set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, d, 2); - if (err) { - return err; - } - } + /* + * We need to set SCAN_RSP when enabling advertising type that + * allows for Scan Requests. + * + * If any data was not provided but we enable connectable + * undirected advertising sd needs to be cleared from values set + * by previous calls. + * Clearing sd is done by calling set_ad() with NULL data and + * zero len. + * So following condition check is unusual but correct. + */ + if (d[0].data || d[1].data || connectable) { + err = set_ad(BT_HCI_OP_LE_SET_SCAN_RSP_DATA, d, 2); + if (err) { + return err; + } + } - return 0; + return 0; } int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len, - const struct bt_data *sd, size_t sd_len) + const struct bt_data *sd, size_t sd_len) { - bool connectable, use_name; + bool connectable, use_name; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - return -EAGAIN; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + return -EAGAIN; + } - connectable = atomic_test_bit(bt_dev.flags, - BT_DEV_ADVERTISING_CONNECTABLE); - use_name = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME); + connectable = atomic_test_bit(bt_dev.flags, + BT_DEV_ADVERTISING_CONNECTABLE); + use_name = atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING_NAME); - return le_adv_update(ad, ad_len, sd, sd_len, connectable, use_name); + return le_adv_update(ad, ad_len, sd, sd_len, connectable, use_name); } int bt_le_adv_start_internal(const struct bt_le_adv_param *param, - const struct bt_data *ad, size_t ad_len, - const struct bt_data *sd, size_t sd_len, - const bt_addr_le_t *peer) + const struct bt_data *ad, size_t ad_len, + const struct bt_data *sd, size_t sd_len, + const bt_addr_le_t *peer) { - struct bt_hci_cp_le_set_adv_param set_param; - const bt_addr_le_t *id_addr; - struct net_buf *buf; - bool dir_adv = (peer != NULL); - int err = 0; + struct bt_hci_cp_le_set_adv_param set_param; + const bt_addr_le_t *id_addr; + struct net_buf *buf; + bool dir_adv = (peer != NULL); + int err = 0; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - return -EAGAIN; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + return -EAGAIN; + } - if (!valid_adv_param(param, dir_adv)) { - return -EINVAL; - } + if (!valid_adv_param(param, dir_adv)) { + return -EINVAL; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - return -EALREADY; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + return -EALREADY; + } - (void)memset(&set_param, 0, sizeof(set_param)); + (void)memset(&set_param, 0, sizeof(set_param)); - set_param.min_interval = sys_cpu_to_le16(param->interval_min); - set_param.max_interval = sys_cpu_to_le16(param->interval_max); - set_param.channel_map = adv_ch_map; + set_param.min_interval = sys_cpu_to_le16(param->interval_min); + set_param.max_interval = sys_cpu_to_le16(param->interval_max); + set_param.channel_map = adv_ch_map; - if (bt_dev.adv_id != param->id) { - atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); - } + if (bt_dev.adv_id != param->id) { + atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); + } #if defined(CONFIG_BT_WHITELIST) - if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && - (param->options & BT_LE_ADV_OPT_FILTER_CONN)) { - set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH; - } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) { - set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ; - } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) { - set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND; - } else { + if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && + (param->options & BT_LE_ADV_OPT_FILTER_CONN)) { + set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH; + } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) { + set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ; + } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) { + set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND; + } else { #else - { + { #endif /* defined(CONFIG_BT_WHITELIST) */ - set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST; - } + set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST; + } - /* Set which local identity address we're advertising with */ - bt_dev.adv_id = param->id; - id_addr = &bt_dev.id_addr[param->id]; + /* Set which local identity address we're advertising with */ + bt_dev.adv_id = param->id; + id_addr = &bt_dev.id_addr[param->id]; - if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { - if (IS_ENABLED(CONFIG_BT_PRIVACY) && - !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) { - #if defined(CONFIG_BT_STACK_PTS) - if(param->addr_type == BT_ADDR_TYPE_RPA) - err = le_set_private_addr(param->id); - else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) - err = le_set_non_resolv_private_addr(param->id); - #else - err = le_set_private_addr(param->id); - #endif - if (err) { - return err; - } - - if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - #if defined(CONFIG_BT_STACK_PTS) - if(param->addr_type == BT_ADDR_LE_PUBLIC) - set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - if(param->addr_type == BT_ADDR_TYPE_RPA) - set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) - set_param.own_addr_type = BT_ADDR_LE_RANDOM; - #else - set_param.own_addr_type = - BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - #endif - } else { - set_param.own_addr_type = BT_ADDR_LE_RANDOM; - } - } else { - /* - * If Static Random address is used as Identity - * address we need to restore it before advertising - * is enabled. Otherwise NRPA used for active scan - * could be used for advertising. - */ - if (id_addr->type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&id_addr->a); - if (err) { - return err; - } - } - - set_param.own_addr_type = id_addr->type; - } - - if (dir_adv) { - if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) { - set_param.type = BT_LE_ADV_DIRECT_IND_LOW_DUTY; - } else { - set_param.type = BT_LE_ADV_DIRECT_IND; - } - - bt_addr_le_copy(&set_param.direct_addr, peer); - - if (IS_ENABLED(CONFIG_BT_SMP) && - !IS_ENABLED(CONFIG_BT_PRIVACY) && - BT_FEAT_LE_PRIVACY(bt_dev.le.features) && - (param->options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) { - /* This will not use RPA for our own address - * since we have set zeroed out the local IRK. - */ - set_param.own_addr_type |= - BT_HCI_OWN_ADDR_RPA_MASK; - } - } else { - set_param.type = BT_LE_ADV_IND; - } - } else { - if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) { - if (id_addr->type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&id_addr->a); - } - - set_param.own_addr_type = id_addr->type; - } else { - #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH) + if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { + if (IS_ENABLED(CONFIG_BT_PRIVACY) && + !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) { #if defined(CONFIG_BT_STACK_PTS) if(param->addr_type == BT_ADDR_TYPE_RPA) err = le_set_private_addr(param->id); else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) err = le_set_non_resolv_private_addr(param->id); #else - err = le_set_private_addr(param->id); + err = le_set_private_addr(param->id); + #endif + if (err) { + return err; + } + + if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { + #if defined(CONFIG_BT_STACK_PTS) + if(param->addr_type == BT_ADDR_LE_PUBLIC) + set_param.own_addr_type = BT_ADDR_LE_PUBLIC; + if(param->addr_type == BT_ADDR_TYPE_RPA) + set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) + set_param.own_addr_type = BT_ADDR_LE_RANDOM; + #else + set_param.own_addr_type = + BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + #endif + } else { + set_param.own_addr_type = BT_ADDR_LE_RANDOM; + } + } else { + /* + * If Static Random address is used as Identity + * address we need to restore it before advertising + * is enabled. Otherwise NRPA used for active scan + * could be used for advertising. + */ + if (id_addr->type == BT_ADDR_LE_RANDOM) { + err = set_random_address(&id_addr->a); + if (err) { + return err; + } + } + + set_param.own_addr_type = id_addr->type; + } + + if (dir_adv) { + if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) { + set_param.type = BT_LE_ADV_DIRECT_IND_LOW_DUTY; + } else { + set_param.type = BT_LE_ADV_DIRECT_IND; + } + + bt_addr_le_copy(&set_param.direct_addr, peer); + + if (IS_ENABLED(CONFIG_BT_SMP) && + !IS_ENABLED(CONFIG_BT_PRIVACY) && + BT_FEAT_LE_PRIVACY(bt_dev.le.features) && + (param->options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) { + /* This will not use RPA for our own address + * since we have set zeroed out the local IRK. + */ + set_param.own_addr_type |= + BT_HCI_OWN_ADDR_RPA_MASK; + } + } else { + set_param.type = BT_LE_ADV_IND; + } + } else { + if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) { + if (id_addr->type == BT_ADDR_LE_RANDOM) { + err = set_random_address(&id_addr->a); + } + + set_param.own_addr_type = id_addr->type; + } else { + #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH) + #if defined(CONFIG_BT_STACK_PTS) + if(param->addr_type == BT_ADDR_TYPE_RPA) + err = le_set_private_addr(param->id); + else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) + err = le_set_non_resolv_private_addr(param->id); + #else + err = le_set_private_addr(param->id); #endif//CONFIG_BT_STACK_PTS #if defined(CONFIG_BT_STACK_PTS) - if(param->addr_type == BT_ADDR_LE_PUBLIC) - set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - else - #endif - set_param.own_addr_type = BT_ADDR_LE_RANDOM; + if(param->addr_type == BT_ADDR_LE_PUBLIC) + set_param.own_addr_type = BT_ADDR_LE_PUBLIC; + else #endif - } + set_param.own_addr_type = BT_ADDR_LE_RANDOM; + #endif + } - if (err) { - return err; - } + if (err) { + return err; + } - if (sd) { - set_param.type = BT_LE_ADV_SCAN_IND; - } else { - set_param.type = BT_LE_ADV_NONCONN_IND; - } - } + if (sd) { + set_param.type = BT_LE_ADV_SCAN_IND; + } else { + set_param.type = BT_LE_ADV_NONCONN_IND; + } + } - #if defined(CONFIG_BT_STACK_PTS) - if(set_param.own_addr_type == BT_ADDR_LE_PUBLIC) - { - atomic_set_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC); - } - #endif + #if defined(CONFIG_BT_STACK_PTS) + if(set_param.own_addr_type == BT_ADDR_LE_PUBLIC) + { + atomic_set_bit(bt_dev.flags, BT_DEV_ADV_ADDRESS_IS_PUBLIC); + } + #endif - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param)); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_mem(buf, &set_param, sizeof(set_param)); + net_buf_add_mem(buf, &set_param, sizeof(set_param)); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL); + if (err) { + return err; + } - if (!dir_adv) { - err = le_adv_update(ad, ad_len, sd, sd_len, - param->options & BT_LE_ADV_OPT_CONNECTABLE, - param->options & BT_LE_ADV_OPT_USE_NAME); - if (err) { - return err; - } - } + if (!dir_adv) { + err = le_adv_update(ad, ad_len, sd, sd_len, + param->options & BT_LE_ADV_OPT_CONNECTABLE, + param->options & BT_LE_ADV_OPT_USE_NAME); + if (err) { + return err; + } + } - err = set_advertise_enable(true); - if (err) { - return err; - } + err = set_advertise_enable(true); + if (err) { + return err; + } - atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, - !(param->options & BT_LE_ADV_OPT_ONE_TIME)); + atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, + !(param->options & BT_LE_ADV_OPT_ONE_TIME)); - atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, - param->options & BT_LE_ADV_OPT_USE_NAME); + atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, + param->options & BT_LE_ADV_OPT_USE_NAME); - atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, - param->options & BT_LE_ADV_OPT_CONNECTABLE); + atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, + param->options & BT_LE_ADV_OPT_CONNECTABLE); - return 0; + return 0; } #if defined (BFLB_BLE) int bt_le_read_rssi(u16_t handle,int8_t *rssi) { - struct bt_hci_cp_read_rssi *le_rssi; - struct bt_hci_rp_read_rssi *rsp_rssi; - struct net_buf *buf; - struct net_buf *rsp; - int ret; + struct bt_hci_cp_read_rssi *le_rssi; + struct bt_hci_rp_read_rssi *rsp_rssi; + struct net_buf *buf; + struct net_buf *rsp; + int ret; - buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*le_rssi)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*le_rssi)); + if (!buf) { + return -ENOBUFS; + } - le_rssi = net_buf_add(buf, sizeof(*le_rssi)); - memset(le_rssi, 0, sizeof(*le_rssi)); + le_rssi = net_buf_add(buf, sizeof(*le_rssi)); + memset(le_rssi, 0, sizeof(*le_rssi)); - le_rssi->handle = handle; + le_rssi->handle = handle; - ret = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI,buf,&rsp); + ret = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI,buf,&rsp); - if (ret) { - return ret; - } + if (ret) { + return ret; + } - rsp_rssi = (struct bt_hci_rp_read_rssi *) rsp->data; - *rssi = rsp_rssi->rssi; + rsp_rssi = (struct bt_hci_rp_read_rssi *) rsp->data; + *rssi = rsp_rssi->rssi; - net_buf_unref(rsp); + net_buf_unref(rsp); - return ret; + return ret; } int set_adv_enable(bool enable) { - int err; - err = set_advertise_enable(true); - if (err) { - return err; - } + int err; + err = set_advertise_enable(true); + if (err) { + return err; + } - return 0; + return 0; } int set_adv_param(const struct bt_le_adv_param *param) { - struct bt_hci_cp_le_set_adv_param set_param; - const bt_addr_le_t *id_addr; - struct net_buf *buf; - int err = 0; + struct bt_hci_cp_le_set_adv_param set_param; + const bt_addr_le_t *id_addr; + struct net_buf *buf; + int err = 0; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - return -EAGAIN; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + return -EAGAIN; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - return -EALREADY; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + return -EALREADY; + } - (void)memset(&set_param, 0, sizeof(set_param)); + (void)memset(&set_param, 0, sizeof(set_param)); - set_param.min_interval = sys_cpu_to_le16(param->interval_min); - set_param.max_interval = sys_cpu_to_le16(param->interval_max); - set_param.channel_map = 0x07; + set_param.min_interval = sys_cpu_to_le16(param->interval_min); + set_param.max_interval = sys_cpu_to_le16(param->interval_max); + set_param.channel_map = 0x07; - if (bt_dev.adv_id != param->id) { - atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); - } + if (bt_dev.adv_id != param->id) { + atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); + } #if defined(CONFIG_BT_WHITELIST) - if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && - (param->options & BT_LE_ADV_OPT_FILTER_CONN)) { - set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH; - } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) { - set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ; - } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) { - set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND; - } else { + if ((param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) && + (param->options & BT_LE_ADV_OPT_FILTER_CONN)) { + set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_BOTH; + } else if (param->options & BT_LE_ADV_OPT_FILTER_SCAN_REQ) { + set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_SCAN_REQ; + } else if (param->options & BT_LE_ADV_OPT_FILTER_CONN) { + set_param.filter_policy = BT_LE_ADV_FP_WHITELIST_CONN_IND; + } else { #else - { + { #endif /* defined(CONFIG_BT_WHITELIST) */ - set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST; - } + set_param.filter_policy = BT_LE_ADV_FP_NO_WHITELIST; + } - /* Set which local identity address we're advertising with */ - bt_dev.adv_id = param->id; - id_addr = &bt_dev.id_addr[param->id]; + /* Set which local identity address we're advertising with */ + bt_dev.adv_id = param->id; + id_addr = &bt_dev.id_addr[param->id]; - if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { - if (IS_ENABLED(CONFIG_BT_PRIVACY) && - !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) { - #if defined(CONFIG_BT_STACK_PTS) - if(param->addr_type == BT_ADDR_TYPE_RPA) - err = le_set_private_addr(param->id); - else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) - err = le_set_non_resolv_private_addr(param->id); - #else - err = le_set_private_addr(param->id); - #endif - if (err) { - return err; - } - - if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { - #if defined(CONFIG_BT_STACK_PTS) - if(param->addr_type == BT_ADDR_LE_PUBLIC) - set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - if(param->addr_type == BT_ADDR_TYPE_RPA) - set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) - set_param.own_addr_type = BT_ADDR_LE_RANDOM; - #else - set_param.own_addr_type = - BT_HCI_OWN_ADDR_RPA_OR_RANDOM; - #endif - } else { - set_param.own_addr_type = BT_ADDR_LE_RANDOM; - } - } else { - /* - * If Static Random address is used as Identity - * address we need to restore it before advertising - * is enabled. Otherwise NRPA used for active scan - * could be used for advertising. - */ - if (id_addr->type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&id_addr->a); - if (err) { - return err; - } - } - - set_param.own_addr_type = id_addr->type; - } - - set_param.type = BT_LE_ADV_IND; - - } else { - if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) { - if (id_addr->type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&id_addr->a); - } - - set_param.own_addr_type = id_addr->type; - } else { - #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH) + if (param->options & BT_LE_ADV_OPT_CONNECTABLE) { + if (IS_ENABLED(CONFIG_BT_PRIVACY) && + !(param->options & BT_LE_ADV_OPT_USE_IDENTITY)) { #if defined(CONFIG_BT_STACK_PTS) if(param->addr_type == BT_ADDR_TYPE_RPA) err = le_set_private_addr(param->id); else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) err = le_set_non_resolv_private_addr(param->id); #else - err = le_set_private_addr(param->id); + err = le_set_private_addr(param->id); + #endif + if (err) { + return err; + } + + if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) { + #if defined(CONFIG_BT_STACK_PTS) + if(param->addr_type == BT_ADDR_LE_PUBLIC) + set_param.own_addr_type = BT_ADDR_LE_PUBLIC; + if(param->addr_type == BT_ADDR_TYPE_RPA) + set_param.own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) + set_param.own_addr_type = BT_ADDR_LE_RANDOM; + #else + set_param.own_addr_type = + BT_HCI_OWN_ADDR_RPA_OR_RANDOM; + #endif + } else { + set_param.own_addr_type = BT_ADDR_LE_RANDOM; + } + } else { + /* + * If Static Random address is used as Identity + * address we need to restore it before advertising + * is enabled. Otherwise NRPA used for active scan + * could be used for advertising. + */ + if (id_addr->type == BT_ADDR_LE_RANDOM) { + err = set_random_address(&id_addr->a); + if (err) { + return err; + } + } + + set_param.own_addr_type = id_addr->type; + } + + set_param.type = BT_LE_ADV_IND; + + } else { + if (param->options & BT_LE_ADV_OPT_USE_IDENTITY) { + if (id_addr->type == BT_ADDR_LE_RANDOM) { + err = set_random_address(&id_addr->a); + } + + set_param.own_addr_type = id_addr->type; + } else { + #if defined(BFLB_BLE) && !defined(CONFIG_BT_MESH) + #if defined(CONFIG_BT_STACK_PTS) + if(param->addr_type == BT_ADDR_TYPE_RPA) + err = le_set_private_addr(param->id); + else if(param->addr_type == BT_ADDR_TYPE_NON_RPA) + err = le_set_non_resolv_private_addr(param->id); + #else + err = le_set_private_addr(param->id); #endif//CONFIG_BT_STACK_PTS #if defined(CONFIG_BT_STACK_PTS) - if(param->addr_type == BT_ADDR_LE_PUBLIC) - set_param.own_addr_type = BT_ADDR_LE_PUBLIC; - else - #endif - set_param.own_addr_type = BT_ADDR_LE_RANDOM; + if(param->addr_type == BT_ADDR_LE_PUBLIC) + set_param.own_addr_type = BT_ADDR_LE_PUBLIC; + else #endif - } + set_param.own_addr_type = BT_ADDR_LE_RANDOM; + #endif + } - if (err) { - return err; - } + if (err) { + return err; + } - set_param.type = BT_LE_ADV_NONCONN_IND; - - } + set_param.type = BT_LE_ADV_NONCONN_IND; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param)); - if (!buf) { - return -ENOBUFS; - } + } - net_buf_add_mem(buf, &set_param, sizeof(set_param)); + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_PARAM, sizeof(set_param)); + if (!buf) { + return -ENOBUFS; + } - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL); - if (err) { - return err; - } + net_buf_add_mem(buf, &set_param, sizeof(set_param)); - atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, - !(param->options & BT_LE_ADV_OPT_ONE_TIME)); + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_PARAM, buf, NULL); + if (err) { + return err; + } - atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, - param->options & BT_LE_ADV_OPT_USE_NAME); + atomic_set_bit_to(bt_dev.flags, BT_DEV_KEEP_ADVERTISING, + !(param->options & BT_LE_ADV_OPT_ONE_TIME)); - atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, - param->options & BT_LE_ADV_OPT_CONNECTABLE); + atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_NAME, + param->options & BT_LE_ADV_OPT_USE_NAME); - return 0; + atomic_set_bit_to(bt_dev.flags, BT_DEV_ADVERTISING_CONNECTABLE, + param->options & BT_LE_ADV_OPT_CONNECTABLE); + + return 0; } int set_ad_and_rsp_d(u16_t hci_op, u8_t *data, u32_t ad_len) { - struct net_buf *buf; - u32_t len; - u8_t size; + struct net_buf *buf; + u32_t len; + u8_t size; - if(BT_HCI_OP_LE_SET_ADV_DATA == hci_op){ + if(BT_HCI_OP_LE_SET_ADV_DATA == hci_op){ - size = sizeof(struct bt_hci_cp_le_set_adv_data); + size = sizeof(struct bt_hci_cp_le_set_adv_data); - }else if(BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op){ + }else if(BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op){ - size = sizeof(struct bt_hci_cp_le_set_scan_rsp_data); + size = sizeof(struct bt_hci_cp_le_set_scan_rsp_data); - }else - return -ENOTSUP; + }else + return -ENOTSUP; buf = bt_hci_cmd_create(hci_op, size); - if (!buf) { - return -ENOBUFS; - } + if (!buf) { + return -ENOBUFS; + } - if(BT_HCI_OP_LE_SET_ADV_DATA == hci_op){ + if(BT_HCI_OP_LE_SET_ADV_DATA == hci_op){ - struct bt_hci_cp_le_set_adv_data *set_data = net_buf_add(buf, size); - memset(set_data, 0, size); - set_data->len = ad_len; + struct bt_hci_cp_le_set_adv_data *set_data = net_buf_add(buf, size); + memset(set_data, 0, size); + set_data->len = ad_len; - if (set_data->len > 30) { - len = 30 - (set_data->len); - if (!len) { - net_buf_unref(buf); - return -ENOBUFS; - } - } + if (set_data->len > 30) { + len = 30 - (set_data->len); + if (!len) { + net_buf_unref(buf); + return -ENOBUFS; + } + } - memcpy(set_data->data,data,set_data->len); + memcpy(set_data->data,data,set_data->len); - }else if(BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op){ + }else if(BT_HCI_OP_LE_SET_SCAN_RSP_DATA == hci_op){ - struct bt_hci_cp_le_set_scan_rsp_data *set_data = net_buf_add(buf, size); - memset(set_data, 0, size); + struct bt_hci_cp_le_set_scan_rsp_data *set_data = net_buf_add(buf, size); + memset(set_data, 0, size); - set_data->len = ad_len; + set_data->len = ad_len; - if (set_data->len > 30) { - len = 30 - (set_data->len); - if (!len) { - net_buf_unref(buf); - return -ENOBUFS; - } - } + if (set_data->len > 30) { + len = 30 - (set_data->len); + if (!len) { + net_buf_unref(buf); + return -ENOBUFS; + } + } - memcpy(set_data->data,data,set_data->len); + memcpy(set_data->data,data,set_data->len); - }else - return -ENOBUFS; + }else + return -ENOBUFS; return bt_hci_cmd_send_sync(hci_op,buf,NULL); } @@ -6645,59 +6645,59 @@ int set_adv_channel_map(u8_t channel) int bt_get_local_public_address(bt_addr_le_t *adv_addr) { - int err = 0; + int err = 0; - bt_addr_le_copy(adv_addr, bt_dev.id_addr); - return err; + bt_addr_le_copy(adv_addr, bt_dev.id_addr); + return err; } int bt_get_local_ramdon_address(bt_addr_le_t *adv_addr) { - int err = 0; - - bt_addr_le_copy(adv_addr,&bt_dev.random_addr); - return err; + int err = 0; + + bt_addr_le_copy(adv_addr,&bt_dev.random_addr); + return err; } #endif int bt_le_adv_start(const struct bt_le_adv_param *param, - const struct bt_data *ad, size_t ad_len, - const struct bt_data *sd, size_t sd_len) + const struct bt_data *ad, size_t ad_len, + const struct bt_data *sd, size_t sd_len) { - if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) { - return -EINVAL; - } + if (param->options & BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY) { + return -EINVAL; + } - return bt_le_adv_start_internal(param, ad, ad_len, sd, sd_len, NULL); + return bt_le_adv_start_internal(param, ad, ad_len, sd, sd_len, NULL); } int bt_le_adv_stop(void) { - int err; + int err; - /* Make sure advertising is not re-enabled later even if it's not - * currently enabled (i.e. BT_DEV_ADVERTISING is not set). - */ - atomic_clear_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING); + /* Make sure advertising is not re-enabled later even if it's not + * currently enabled (i.e. BT_DEV_ADVERTISING is not set). + */ + atomic_clear_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING); - if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { - return 0; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) { + return 0; + } - err = set_advertise_enable(false); - if (err) { - return err; - } + err = set_advertise_enable(false); + if (err) { + return err; + } - if (!IS_ENABLED(CONFIG_BT_PRIVACY)) { - /* If active scan is ongoing set NRPA */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && - atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) { - le_set_private_addr(bt_dev.adv_id); - } - } + if (!IS_ENABLED(CONFIG_BT_PRIVACY)) { + /* If active scan is ongoing set NRPA */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) && + atomic_test_bit(bt_dev.flags, BT_DEV_ACTIVE_SCAN)) { + le_set_private_addr(bt_dev.adv_id); + } + } - return 0; + return 0; } #if defined(CONFIG_BLE_MULTI_ADV) @@ -6792,11 +6792,11 @@ int bt_le_adv_start_instant(const struct bt_le_adv_param *param, * could be used for advertising. */ if (id_addr->type == BT_ADDR_LE_RANDOM) { - err = set_random_address(&id_addr->a); - if (err) { - return err; - } - } + err = set_random_address(&id_addr->a); + if (err) { + return err; + } + } set_param.own_addr_type = id_addr->type; } @@ -6838,571 +6838,571 @@ int bt_le_adv_start_instant(const struct bt_le_adv_param *param, #if defined(CONFIG_BT_OBSERVER) static bool valid_le_scan_param(const struct bt_le_scan_param *param) { - if (param->type != BT_HCI_LE_SCAN_PASSIVE && - param->type != BT_HCI_LE_SCAN_ACTIVE) { - return false; - } + if (param->type != BT_HCI_LE_SCAN_PASSIVE && + param->type != BT_HCI_LE_SCAN_ACTIVE) { + return false; + } - if (param->filter_dup & - ~(BT_LE_SCAN_FILTER_DUPLICATE | BT_LE_SCAN_FILTER_WHITELIST)) { - return false; - } + if (param->filter_dup & + ~(BT_LE_SCAN_FILTER_DUPLICATE | BT_LE_SCAN_FILTER_WHITELIST)) { + return false; + } - if (is_wl_empty() && - param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST) { - return false; - } + if (is_wl_empty() && + param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST) { + return false; + } - if (param->interval < 0x0004 || param->interval > 0x4000) { - return false; - } + if (param->interval < 0x0004 || param->interval > 0x4000) { + return false; + } - if (param->window < 0x0004 || param->window > 0x4000) { - return false; - } + if (param->window < 0x0004 || param->window > 0x4000) { + return false; + } - if (param->window > param->interval) { - return false; - } + if (param->window > param->interval) { + return false; + } - return true; + return true; } #if defined(CONFIG_BT_STACK_PTS) int bt_le_pts_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb, u8_t addre_type) { - int err; + int err; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - return -EAGAIN; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + return -EAGAIN; + } - /* Check that the parameters have valid values */ - if (!valid_le_scan_param(param)) { - return -EINVAL; - } + /* Check that the parameters have valid values */ + if (!valid_le_scan_param(param)) { + return -EINVAL; + } - /* Return if active scan is already enabled */ - if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { - return -EALREADY; - } + /* Return if active scan is already enabled */ + if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { + return -EALREADY; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { - err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); - if (err) { - atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); - return err; - } - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { + err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); + if (err) { + atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); + return err; + } + } - atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, - param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE); + atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, + param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE); #if defined(CONFIG_BT_WHITELIST) - atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, - param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST); + atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, + param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST); #endif /* defined(CONFIG_BT_WHITELIST) */ err = start_le_scan_with_isrpa(param->type, param->interval, param->window, addre_type); - - if (err) { - atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); - return err; - } - scan_dev_found_cb = cb; + if (err) { + atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); + return err; + } - return 0; + scan_dev_found_cb = cb; + + return 0; } #endif int bt_le_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb) { - int err; + int err; - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - return -EAGAIN; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + return -EAGAIN; + } - /* Check that the parameters have valid values */ - if (!valid_le_scan_param(param)) { - return -EINVAL; - } + /* Check that the parameters have valid values */ + if (!valid_le_scan_param(param)) { + return -EINVAL; + } - /* Return if active scan is already enabled */ - if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { - return -EALREADY; - } + /* Return if active scan is already enabled */ + if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { + return -EALREADY; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { - err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); - if (err) { - atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); - return err; - } - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) { + err = set_le_scan_enable(BT_HCI_LE_SCAN_DISABLE); + if (err) { + atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); + return err; + } + } - atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, - param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE); + atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_FILTER_DUP, + param->filter_dup & BT_LE_SCAN_FILTER_DUPLICATE); #if defined(CONFIG_BT_WHITELIST) - atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, - param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST); + atomic_set_bit_to(bt_dev.flags, BT_DEV_SCAN_WL, + param->filter_dup & BT_LE_SCAN_FILTER_WHITELIST); #endif /* defined(CONFIG_BT_WHITELIST) */ - err = start_le_scan(param->type, param->interval, param->window); - if (err) { - atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); - return err; - } + err = start_le_scan(param->type, param->interval, param->window); + if (err) { + atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN); + return err; + } - scan_dev_found_cb = cb; + scan_dev_found_cb = cb; - return 0; + return 0; } int bt_le_scan_stop(void) { - /* Return if active scanning is already disabled */ - if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { - return -EALREADY; - } + /* Return if active scanning is already disabled */ + if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) { + return -EALREADY; + } - scan_dev_found_cb = NULL; + scan_dev_found_cb = NULL; - return bt_le_scan_update(false); + return bt_le_scan_update(false); } #endif /* CONFIG_BT_OBSERVER */ #if defined(CONFIG_BT_WHITELIST) int bt_le_whitelist_add(const bt_addr_le_t *addr) { - struct bt_hci_cp_le_add_dev_to_wl *cp; - struct net_buf *buf; - int err; + struct bt_hci_cp_le_add_dev_to_wl *cp; + struct net_buf *buf; + int err; - if (!(bt_dev.le.wl_entries < bt_dev.le.wl_size)) { - return -ENOMEM; - } + if (!(bt_dev.le.wl_entries < bt_dev.le.wl_size)) { + return -ENOMEM; + } - buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_WL, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_le_copy(&cp->addr, addr); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_le_copy(&cp->addr, addr); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL); - if (err) { - BT_ERR("Failed to add device to whitelist"); + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_WL, buf, NULL); + if (err) { + BT_ERR("Failed to add device to whitelist"); - return err; - } + return err; + } - bt_dev.le.wl_entries++; + bt_dev.le.wl_entries++; - return 0; + return 0; } int bt_le_whitelist_rem(const bt_addr_le_t *addr) { - struct bt_hci_cp_le_rem_dev_from_wl *cp; - struct net_buf *buf; - int err; + struct bt_hci_cp_le_rem_dev_from_wl *cp; + struct net_buf *buf; + int err; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_WL, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_le_copy(&cp->addr, addr); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_le_copy(&cp->addr, addr); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL); - if (err) { - BT_ERR("Failed to remove device from whitelist"); - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_WL, buf, NULL); + if (err) { + BT_ERR("Failed to remove device from whitelist"); + return err; + } - bt_dev.le.wl_entries--; - return 0; + bt_dev.le.wl_entries--; + return 0; } int bt_le_whitelist_clear(void) { - int err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL); + int err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_WL, NULL, NULL); - if (err) { - BT_ERR("Failed to clear whitelist"); - return err; - } + if (err) { + BT_ERR("Failed to clear whitelist"); + return err; + } - bt_dev.le.wl_entries = 0; - return 0; + bt_dev.le.wl_entries = 0; + return 0; } #endif /* defined(CONFIG_BT_WHITELIST) */ int bt_le_set_chan_map(u8_t chan_map[5]) { - struct bt_hci_cp_le_set_host_chan_classif *cp; - struct net_buf *buf; + struct bt_hci_cp_le_set_host_chan_classif *cp; + struct net_buf *buf; - if (!IS_ENABLED(CONFIG_BT_CENTRAL)) { - return -ENOTSUP; - } + if (!IS_ENABLED(CONFIG_BT_CENTRAL)) { + return -ENOTSUP; + } - if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 3)) { - BT_WARN("Set Host Channel Classification command is " - "not supported"); - return -ENOTSUP; - } + if (!BT_CMD_TEST(bt_dev.supported_commands, 27, 3)) { + BT_WARN("Set Host Channel Classification command is " + "not supported"); + return -ENOTSUP; + } - buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, - sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, + sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); - memcpy(&cp->ch_map[0], &chan_map[0], 4); - cp->ch_map[4] = chan_map[4] & BIT_MASK(5); + memcpy(&cp->ch_map[0], &chan_map[0], 4); + cp->ch_map[4] = chan_map[4] & BIT_MASK(5); - return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, - buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF, + buf, NULL); } #if defined(CONFIG_SET_TX_PWR) int bt_set_tx_pwr(int8_t power) { struct bt_hci_cp_vs_set_tx_pwr set_param; - struct net_buf *buf; - int err; + struct net_buf *buf; + int err; if(power < 0 || power > 20) return BT_HCI_ERR_INVALID_PARAM; - - memset(&set_param, 0, sizeof(set_param)); - set_param.power = power; + memset(&set_param, 0, sizeof(set_param)); - buf = bt_hci_cmd_create(BT_HCI_OP_VS_SET_TX_PWR, sizeof(set_param)); - if (!buf) { - return -ENOBUFS; - } + set_param.power = power; - net_buf_add_mem(buf, &set_param, sizeof(set_param)); + buf = bt_hci_cmd_create(BT_HCI_OP_VS_SET_TX_PWR, sizeof(set_param)); + if (!buf) { + return -ENOBUFS; + } - err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_SET_TX_PWR, buf, NULL); + net_buf_add_mem(buf, &set_param, sizeof(set_param)); - if (err) { - return err; - } - - return 0; + err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_SET_TX_PWR, buf, NULL); + + if (err) { + return err; + } + + return 0; } #endif int bt_buf_get_rx_avail_cnt(void) { - return (k_queue_get_cnt(&hci_rx_pool.free._queue) \ - + hci_rx_pool.uninit_count); + return (k_queue_get_cnt(&hci_rx_pool.free._queue) \ + + hci_rx_pool.uninit_count); } struct net_buf *bt_buf_get_rx(enum bt_buf_type type, s32_t timeout) { - struct net_buf *buf; + struct net_buf *buf; - __ASSERT(type == BT_BUF_EVT || type == BT_BUF_ACL_IN, - "Invalid buffer type requested"); + __ASSERT(type == BT_BUF_EVT || type == BT_BUF_ACL_IN, + "Invalid buffer type requested"); #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) - if (type == BT_BUF_EVT) { - buf = net_buf_alloc(&hci_rx_pool, timeout); - } else { - buf = net_buf_alloc(&acl_in_pool, timeout); - } + if (type == BT_BUF_EVT) { + buf = net_buf_alloc(&hci_rx_pool, timeout); + } else { + buf = net_buf_alloc(&acl_in_pool, timeout); + } #else - buf = net_buf_alloc(&hci_rx_pool, timeout); + buf = net_buf_alloc(&hci_rx_pool, timeout); #endif - if (buf) { - net_buf_reserve(buf, BT_BUF_RESERVE); - bt_buf_set_type(buf, type); - } + if (buf) { + net_buf_reserve(buf, BT_BUF_RESERVE); + bt_buf_set_type(buf, type); + } - return buf; + return buf; } struct net_buf *bt_buf_get_cmd_complete(s32_t timeout) { - struct net_buf *buf; - unsigned int key; + struct net_buf *buf; + unsigned int key; - key = irq_lock(); - buf = bt_dev.sent_cmd; - bt_dev.sent_cmd = NULL; - irq_unlock(key); + key = irq_lock(); + buf = bt_dev.sent_cmd; + bt_dev.sent_cmd = NULL; + irq_unlock(key); - BT_DBG("sent_cmd %p", buf); + BT_DBG("sent_cmd %p", buf); - if (buf) { - bt_buf_set_type(buf, BT_BUF_EVT); - buf->len = 0U; - net_buf_reserve(buf, BT_BUF_RESERVE); + if (buf) { + bt_buf_set_type(buf, BT_BUF_EVT); + buf->len = 0U; + net_buf_reserve(buf, BT_BUF_RESERVE); - return buf; - } + return buf; + } - return bt_buf_get_rx(BT_BUF_EVT, timeout); + return bt_buf_get_rx(BT_BUF_EVT, timeout); } struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, s32_t timeout) { - switch (evt) { + switch (evt) { #if defined(CONFIG_BT_CONN) - case BT_HCI_EVT_NUM_COMPLETED_PACKETS: - { - struct net_buf *buf; + case BT_HCI_EVT_NUM_COMPLETED_PACKETS: + { + struct net_buf *buf; - buf = net_buf_alloc(&num_complete_pool, timeout); - if (buf) { - net_buf_reserve(buf, BT_BUF_RESERVE); - bt_buf_set_type(buf, BT_BUF_EVT); - } + buf = net_buf_alloc(&num_complete_pool, timeout); + if (buf) { + net_buf_reserve(buf, BT_BUF_RESERVE); + bt_buf_set_type(buf, BT_BUF_EVT); + } - return buf; - } + return buf; + } #endif /* CONFIG_BT_CONN */ - case BT_HCI_EVT_CMD_COMPLETE: - case BT_HCI_EVT_CMD_STATUS: - return bt_buf_get_cmd_complete(timeout); - default: + case BT_HCI_EVT_CMD_COMPLETE: + case BT_HCI_EVT_CMD_STATUS: + return bt_buf_get_cmd_complete(timeout); + default: #if defined(CONFIG_BT_DISCARDABLE_BUF_COUNT) - if (discardable) { - struct net_buf *buf; + if (discardable) { + struct net_buf *buf; - buf = net_buf_alloc(&discardable_pool, timeout); - if (buf) { - net_buf_reserve(buf, BT_BUF_RESERVE); - bt_buf_set_type(buf, BT_BUF_EVT); - } + buf = net_buf_alloc(&discardable_pool, timeout); + if (buf) { + net_buf_reserve(buf, BT_BUF_RESERVE); + bt_buf_set_type(buf, BT_BUF_EVT); + } - return buf; - } + return buf; + } #endif /* CONFIG_BT_DISCARDABLE_BUF_COUNT */ - return bt_buf_get_rx(BT_BUF_EVT, timeout); - } + return bt_buf_get_rx(BT_BUF_EVT, timeout); + } } #if defined(CONFIG_BT_BREDR) static int br_start_inquiry(const struct bt_br_discovery_param *param) { - const u8_t iac[3] = { 0x33, 0x8b, 0x9e }; - struct bt_hci_op_inquiry *cp; - struct net_buf *buf; + const u8_t iac[3] = { 0x33, 0x8b, 0x9e }; + struct bt_hci_op_inquiry *cp; + struct net_buf *buf; - buf = bt_hci_cmd_create(BT_HCI_OP_INQUIRY, sizeof(*cp)); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_INQUIRY, sizeof(*cp)); + if (!buf) { + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); + cp = net_buf_add(buf, sizeof(*cp)); - cp->length = param->length; - cp->num_rsp = 0xff; /* we limit discovery only by time */ + cp->length = param->length; + cp->num_rsp = 0xff; /* we limit discovery only by time */ - memcpy(cp->lap, iac, 3); - if (param->limited) { - cp->lap[0] = 0x00; - } + memcpy(cp->lap, iac, 3); + if (param->limited) { + cp->lap[0] = 0x00; + } - return bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY, buf, NULL); + return bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY, buf, NULL); } static bool valid_br_discov_param(const struct bt_br_discovery_param *param, - size_t num_results) + size_t num_results) { - if (!num_results || num_results > 255) { - return false; - } + if (!num_results || num_results > 255) { + return false; + } - if (!param->length || param->length > 0x30) { - return false; - } + if (!param->length || param->length > 0x30) { + return false; + } - return true; + return true; } int bt_br_discovery_start(const struct bt_br_discovery_param *param, - struct bt_br_discovery_result *results, size_t cnt, - bt_br_discovery_cb_t cb) + struct bt_br_discovery_result *results, size_t cnt, + bt_br_discovery_cb_t cb) { - int err; + int err; - BT_DBG(""); + BT_DBG(""); - if (!valid_br_discov_param(param, cnt)) { - return -EINVAL; - } + if (!valid_br_discov_param(param, cnt)) { + return -EINVAL; + } - if (atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { - return -EALREADY; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { + return -EALREADY; + } - err = br_start_inquiry(param); - if (err) { - return err; - } + err = br_start_inquiry(param); + if (err) { + return err; + } - atomic_set_bit(bt_dev.flags, BT_DEV_INQUIRY); + atomic_set_bit(bt_dev.flags, BT_DEV_INQUIRY); - (void)memset(results, 0, sizeof(*results) * cnt); + (void)memset(results, 0, sizeof(*results) * cnt); - discovery_cb = cb; - discovery_results = results; - discovery_results_size = cnt; - discovery_results_count = 0; + discovery_cb = cb; + discovery_results = results; + discovery_results_size = cnt; + discovery_results_count = 0; - return 0; + return 0; } int bt_br_discovery_stop(void) { - int err; - int i; + int err; + int i; - BT_DBG(""); + BT_DBG(""); - if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { - return -EALREADY; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_INQUIRY)) { + return -EALREADY; + } - err = bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY_CANCEL, NULL, NULL); - if (err) { - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_INQUIRY_CANCEL, NULL, NULL); + if (err) { + return err; + } - for (i = 0; i < discovery_results_count; i++) { - struct discovery_priv *priv; - struct bt_hci_cp_remote_name_cancel *cp; - struct net_buf *buf; + for (i = 0; i < discovery_results_count; i++) { + struct discovery_priv *priv; + struct bt_hci_cp_remote_name_cancel *cp; + struct net_buf *buf; - priv = (struct discovery_priv *)&discovery_results[i]._priv; + priv = (struct discovery_priv *)&discovery_results[i]._priv; - if (!priv->resolving) { - continue; - } + if (!priv->resolving) { + continue; + } - buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_CANCEL, - sizeof(*cp)); - if (!buf) { - continue; - } + buf = bt_hci_cmd_create(BT_HCI_OP_REMOTE_NAME_CANCEL, + sizeof(*cp)); + if (!buf) { + continue; + } - cp = net_buf_add(buf, sizeof(*cp)); - bt_addr_copy(&cp->bdaddr, &discovery_results[i].addr); + cp = net_buf_add(buf, sizeof(*cp)); + bt_addr_copy(&cp->bdaddr, &discovery_results[i].addr); - bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_CANCEL, buf, NULL); - } + bt_hci_cmd_send_sync(BT_HCI_OP_REMOTE_NAME_CANCEL, buf, NULL); + } - atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); + atomic_clear_bit(bt_dev.flags, BT_DEV_INQUIRY); - discovery_cb = NULL; - discovery_results = NULL; - discovery_results_size = 0; - discovery_results_count = 0; + discovery_cb = NULL; + discovery_results = NULL; + discovery_results_size = 0; + discovery_results_count = 0; - return 0; + return 0; } static int write_scan_enable(u8_t scan) { - struct net_buf *buf; - int err; + struct net_buf *buf; + int err; - BT_DBG("type %u", scan); + BT_DBG("type %u", scan); - buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SCAN_ENABLE, 1); - if (!buf) { - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_WRITE_SCAN_ENABLE, 1); + if (!buf) { + return -ENOBUFS; + } - net_buf_add_u8(buf, scan); - err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SCAN_ENABLE, buf, NULL); - if (err) { - return err; - } + net_buf_add_u8(buf, scan); + err = bt_hci_cmd_send_sync(BT_HCI_OP_WRITE_SCAN_ENABLE, buf, NULL); + if (err) { + return err; + } - atomic_set_bit_to(bt_dev.flags, BT_DEV_ISCAN, - (scan & BT_BREDR_SCAN_INQUIRY)); - atomic_set_bit_to(bt_dev.flags, BT_DEV_PSCAN, - (scan & BT_BREDR_SCAN_PAGE)); + atomic_set_bit_to(bt_dev.flags, BT_DEV_ISCAN, + (scan & BT_BREDR_SCAN_INQUIRY)); + atomic_set_bit_to(bt_dev.flags, BT_DEV_PSCAN, + (scan & BT_BREDR_SCAN_PAGE)); - return 0; + return 0; } int bt_br_set_connectable(bool enable) { - if (enable) { - if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { - return -EALREADY; - } else { - return write_scan_enable(BT_BREDR_SCAN_PAGE); - } - } else { - if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { - return -EALREADY; - } else { - return write_scan_enable(BT_BREDR_SCAN_DISABLED); - } - } + if (enable) { + if (atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { + return -EALREADY; + } else { + return write_scan_enable(BT_BREDR_SCAN_PAGE); + } + } else { + if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { + return -EALREADY; + } else { + return write_scan_enable(BT_BREDR_SCAN_DISABLED); + } + } } int bt_br_set_discoverable(bool enable) { - if (enable) { - if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) { - return -EALREADY; - } + if (enable) { + if (atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) { + return -EALREADY; + } - if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { - return -EPERM; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_PSCAN)) { + return -EPERM; + } - return write_scan_enable(BT_BREDR_SCAN_INQUIRY | - BT_BREDR_SCAN_PAGE); - } else { - if (!atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) { - return -EALREADY; - } + return write_scan_enable(BT_BREDR_SCAN_INQUIRY | + BT_BREDR_SCAN_PAGE); + } else { + if (!atomic_test_bit(bt_dev.flags, BT_DEV_ISCAN)) { + return -EALREADY; + } - return write_scan_enable(BT_BREDR_SCAN_PAGE); - } + return write_scan_enable(BT_BREDR_SCAN_PAGE); + } } #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_ECC) int bt_pub_key_gen(struct bt_pub_key_cb *new_cb) { - int err; + int err; - /* - * We check for both "LE Read Local P-256 Public Key" and - * "LE Generate DH Key" support here since both commands are needed for - * ECC support. If "LE Generate DH Key" is not supported then there - * is no point in reading local public key. - */ - if (!BT_CMD_TEST(bt_dev.supported_commands, 34, 1) || - !BT_CMD_TEST(bt_dev.supported_commands, 34, 2)) { - BT_WARN("ECC HCI commands not available"); - return -ENOTSUP; - } + /* + * We check for both "LE Read Local P-256 Public Key" and + * "LE Generate DH Key" support here since both commands are needed for + * ECC support. If "LE Generate DH Key" is not supported then there + * is no point in reading local public key. + */ + if (!BT_CMD_TEST(bt_dev.supported_commands, 34, 1) || + !BT_CMD_TEST(bt_dev.supported_commands, 34, 2)) { + BT_WARN("ECC HCI commands not available"); + return -ENOTSUP; + } #if defined(BFLB_BLE_PATCH_AVOID_DUPLI_PUBKEY_CB) - struct bt_pub_key_cb *cb; + struct bt_pub_key_cb *cb; struct bt_pub_key_cb *valid_cb; bool existed = false; @@ -7418,7 +7418,7 @@ int bt_pub_key_gen(struct bt_pub_key_cb *new_cb) valid_cb = cb; cb = cb->_next; } - + if(!existed){ valid_cb->_next = new_cb; } @@ -7426,125 +7426,125 @@ int bt_pub_key_gen(struct bt_pub_key_cb *new_cb) pub_key_cb = new_cb; } #else - new_cb->_next = pub_key_cb; - pub_key_cb = new_cb; + new_cb->_next = pub_key_cb; + pub_key_cb = new_cb; #endif - - if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) { - return 0; - } - atomic_clear_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY); + if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) { + return 0; + } - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL); - if (err) { - BT_ERR("Sending LE P256 Public Key command failed"); - atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY); - pub_key_cb = NULL; - return err; - } + atomic_clear_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY); - return 0; + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_P256_PUBLIC_KEY, NULL, NULL); + if (err) { + BT_ERR("Sending LE P256 Public Key command failed"); + atomic_clear_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY); + pub_key_cb = NULL; + return err; + } + + return 0; } const u8_t *bt_pub_key_get(void) { - if (atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) { - return pub_key; - } + if (atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) { + return pub_key; + } - return NULL; + return NULL; } int bt_dh_key_gen(const u8_t remote_pk[64], bt_dh_key_cb_t cb) { - struct bt_hci_cp_le_generate_dhkey *cp; - struct net_buf *buf; - int err; + struct bt_hci_cp_le_generate_dhkey *cp; + struct net_buf *buf; + int err; - if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) { - return -EBUSY; - } + if (dh_key_cb || atomic_test_bit(bt_dev.flags, BT_DEV_PUB_KEY_BUSY)) { + return -EBUSY; + } - if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) { - return -EADDRNOTAVAIL; - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_HAS_PUB_KEY)) { + return -EADDRNOTAVAIL; + } - dh_key_cb = cb; + dh_key_cb = cb; - buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp)); - if (!buf) { - dh_key_cb = NULL; - return -ENOBUFS; - } + buf = bt_hci_cmd_create(BT_HCI_OP_LE_GENERATE_DHKEY, sizeof(*cp)); + if (!buf) { + dh_key_cb = NULL; + return -ENOBUFS; + } - cp = net_buf_add(buf, sizeof(*cp)); - memcpy(cp->key, remote_pk, sizeof(cp->key)); + cp = net_buf_add(buf, sizeof(*cp)); + memcpy(cp->key, remote_pk, sizeof(cp->key)); - err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL); - if (err) { - dh_key_cb = NULL; - return err; - } + err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_GENERATE_DHKEY, buf, NULL); + if (err) { + dh_key_cb = NULL; + return err; + } - return 0; + return 0; } #endif /* CONFIG_BT_ECC */ #if defined(CONFIG_BT_BREDR) int bt_br_oob_get_local(struct bt_br_oob *oob) { - bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a); + bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a); - return 0; + return 0; } #endif /* CONFIG_BT_BREDR */ int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob) { - int err; + int err; - if (id >= CONFIG_BT_ID_MAX) { - return -EINVAL; - } + if (id >= CONFIG_BT_ID_MAX) { + return -EINVAL; + } - if (IS_ENABLED(CONFIG_BT_PRIVACY)) { - /* Invalidate RPA so a new one is generated */ - atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); + if (IS_ENABLED(CONFIG_BT_PRIVACY)) { + /* Invalidate RPA so a new one is generated */ + atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID); - err = le_set_private_addr(id); - if (err) { - return err; - } + err = le_set_private_addr(id); + if (err) { + return err; + } - bt_addr_le_copy(&oob->addr, &bt_dev.random_addr); - } else { - bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]); - } + bt_addr_le_copy(&oob->addr, &bt_dev.random_addr); + } else { + bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]); + } - if (IS_ENABLED(CONFIG_BT_SMP)) { - err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data); - if (err) { - return err; - } - } + if (IS_ENABLED(CONFIG_BT_SMP)) { + err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data); + if (err) { + return err; + } + } - return 0; + return 0; } #if defined(CONFIG_BT_SMP) int bt_le_oob_set_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data *oobd_local, - const struct bt_le_oob_sc_data *oobd_remote) + const struct bt_le_oob_sc_data *oobd_local, + const struct bt_le_oob_sc_data *oobd_remote) { - return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote); + return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote); } int bt_le_oob_get_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data **oobd_local, - const struct bt_le_oob_sc_data **oobd_remote) + const struct bt_le_oob_sc_data **oobd_local, + const struct bt_le_oob_sc_data **oobd_remote) { - return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote); + return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote); } #endif diff --git a/components/network/ble/blestack/src/host/hci_core.h b/components/network/ble/blestack/src/host/hci_core.h index abe2a47f..ecf3df2e 100644 --- a/components/network/ble/blestack/src/host/hci_core.h +++ b/components/network/ble/blestack/src/host/hci_core.h @@ -7,13 +7,13 @@ */ /* LL connection parameters */ -#define LE_CONN_LATENCY 0x0000 -#define LE_CONN_TIMEOUT 0x002a +#define LE_CONN_LATENCY 0x0000 +#define LE_CONN_TIMEOUT 0x002a #if defined(CONFIG_BT_BREDR) -#define LMP_FEAT_PAGES_COUNT 3 +#define LMP_FEAT_PAGES_COUNT 3 #else -#define LMP_FEAT_PAGES_COUNT 1 +#define LMP_FEAT_PAGES_COUNT 1 #endif /* SCO settings */ @@ -21,88 +21,88 @@ /* k_poll event tags */ enum { - BT_EVENT_CMD_TX, - BT_EVENT_CONN_TX_QUEUE, + BT_EVENT_CMD_TX, + BT_EVENT_CONN_TX_QUEUE, }; /* bt_dev flags: the flags defined here represent BT controller state */ enum { - BT_DEV_ENABLE, - BT_DEV_READY, - BT_DEV_PRESET_ID, - BT_DEV_USER_ID_ADDR, - BT_DEV_HAS_PUB_KEY, - BT_DEV_PUB_KEY_BUSY, + BT_DEV_ENABLE, + BT_DEV_READY, + BT_DEV_PRESET_ID, + BT_DEV_USER_ID_ADDR, + BT_DEV_HAS_PUB_KEY, + BT_DEV_PUB_KEY_BUSY, - BT_DEV_ADVERTISING, - BT_DEV_ADVERTISING_NAME, - BT_DEV_ADVERTISING_CONNECTABLE, - BT_DEV_KEEP_ADVERTISING, - BT_DEV_SCANNING, - BT_DEV_EXPLICIT_SCAN, - BT_DEV_ACTIVE_SCAN, - BT_DEV_SCAN_FILTER_DUP, - BT_DEV_SCAN_WL, - BT_DEV_AUTO_CONN, + BT_DEV_ADVERTISING, + BT_DEV_ADVERTISING_NAME, + BT_DEV_ADVERTISING_CONNECTABLE, + BT_DEV_KEEP_ADVERTISING, + BT_DEV_SCANNING, + BT_DEV_EXPLICIT_SCAN, + BT_DEV_ACTIVE_SCAN, + BT_DEV_SCAN_FILTER_DUP, + BT_DEV_SCAN_WL, + BT_DEV_AUTO_CONN, - BT_DEV_RPA_VALID, + BT_DEV_RPA_VALID, - BT_DEV_ID_PENDING, + BT_DEV_ID_PENDING, #if defined(CONFIG_BT_BREDR) - BT_DEV_ISCAN, - BT_DEV_PSCAN, - BT_DEV_INQUIRY, + BT_DEV_ISCAN, + BT_DEV_PSCAN, + BT_DEV_INQUIRY, #endif /* CONFIG_BT_BREDR */ #if defined(CONFIG_BT_STACK_PTS) - BT_DEV_ADV_ADDRESS_IS_PUBLIC, + BT_DEV_ADV_ADDRESS_IS_PUBLIC, #endif - /* Total number of flags - must be at the end of the enum */ - BT_DEV_NUM_FLAGS, + /* Total number of flags - must be at the end of the enum */ + BT_DEV_NUM_FLAGS, }; /* Flags which should not be cleared upon HCI_Reset */ #define BT_DEV_PERSISTENT_FLAGS (BIT(BT_DEV_ENABLE) | \ - BIT(BT_DEV_PRESET_ID) | \ - BIT(BT_DEV_USER_ID_ADDR)) + BIT(BT_DEV_PRESET_ID) | \ + BIT(BT_DEV_USER_ID_ADDR)) struct bt_dev_le { - /* LE features */ - u8_t features[8]; - /* LE states */ - u64_t states; + /* LE features */ + u8_t features[8]; + /* LE states */ + u64_t states; #if defined(CONFIG_BT_CONN) - /* Controller buffer information */ - u16_t mtu; - struct k_sem pkts; + /* Controller buffer information */ + u16_t mtu; + struct k_sem pkts; #endif /* CONFIG_BT_CONN */ #if defined(CONFIG_BT_SMP) - /* Size of the the controller resolving list */ - u8_t rl_size; - /* Number of entries in the resolving list. rl_entries > rl_size - * means that host-side resolving is used. - */ - u8_t rl_entries; + /* Size of the the controller resolving list */ + u8_t rl_size; + /* Number of entries in the resolving list. rl_entries > rl_size + * means that host-side resolving is used. + */ + u8_t rl_entries; #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_WHITELIST) - /* Size of the controller whitelist. */ - u8_t wl_size; - /* Number of entries in the resolving list. */ - u8_t wl_entries; + /* Size of the controller whitelist. */ + u8_t wl_size; + /* Number of entries in the resolving list. */ + u8_t wl_entries; #endif /* CONFIG_BT_WHITELIST */ }; #if defined(CONFIG_BT_BREDR) struct bt_dev_br { - /* Max controller's acceptable ACL packet length */ - u16_t mtu; - struct k_sem pkts; - u16_t esco_pkt_type; + /* Max controller's acceptable ACL packet length */ + u16_t mtu; + struct k_sem pkts; + u16_t esco_pkt_type; }; #endif @@ -116,101 +116,101 @@ struct bt_dev_br { /* State tracking for the local Bluetooth controller */ struct bt_dev { - /* Local Identity Address(es) */ - bt_addr_le_t id_addr[CONFIG_BT_ID_MAX]; - u8_t id_count; + /* Local Identity Address(es) */ + bt_addr_le_t id_addr[CONFIG_BT_ID_MAX]; + u8_t id_count; - /* ID Address used for advertising */ - u8_t adv_id; + /* ID Address used for advertising */ + u8_t adv_id; - /* Current local Random Address */ - bt_addr_le_t random_addr; + /* Current local Random Address */ + bt_addr_le_t random_addr; - /* Controller version & manufacturer information */ - u8_t hci_version; - u8_t lmp_version; - u16_t hci_revision; - u16_t lmp_subversion; - u16_t manufacturer; + /* Controller version & manufacturer information */ + u8_t hci_version; + u8_t lmp_version; + u16_t hci_revision; + u16_t lmp_subversion; + u16_t manufacturer; - /* LMP features (pages 0, 1, 2) */ - u8_t features[LMP_FEAT_PAGES_COUNT][8]; + /* LMP features (pages 0, 1, 2) */ + u8_t features[LMP_FEAT_PAGES_COUNT][8]; - /* Supported commands */ - u8_t supported_commands[64]; + /* Supported commands */ + u8_t supported_commands[64]; #if defined(CONFIG_BT_HCI_VS_EXT) - /* Vendor HCI support */ - u8_t vs_features[BT_DEV_VS_FEAT_MAX]; - u8_t vs_commands[BT_DEV_VS_CMDS_MAX]; + /* Vendor HCI support */ + u8_t vs_features[BT_DEV_VS_FEAT_MAX]; + u8_t vs_commands[BT_DEV_VS_CMDS_MAX]; #endif - struct k_work init; + struct k_work init; - ATOMIC_DEFINE(flags, BT_DEV_NUM_FLAGS); + ATOMIC_DEFINE(flags, BT_DEV_NUM_FLAGS); - /* LE controller specific features */ - struct bt_dev_le le; + /* LE controller specific features */ + struct bt_dev_le le; #if defined(CONFIG_BT_BREDR) - /* BR/EDR controller specific features */ - struct bt_dev_br br; + /* BR/EDR controller specific features */ + struct bt_dev_br br; #endif - /* Number of commands controller can accept */ - struct k_sem ncmd_sem; + /* Number of commands controller can accept */ + struct k_sem ncmd_sem; - /* Last sent HCI command */ - struct net_buf *sent_cmd; + /* Last sent HCI command */ + struct net_buf *sent_cmd; #if !defined(CONFIG_BT_RECV_IS_RX_THREAD) - /* Queue for incoming HCI events & ACL data */ - struct k_fifo rx_queue; + /* Queue for incoming HCI events & ACL data */ + struct k_fifo rx_queue; #endif - /* Queue for outgoing HCI commands */ - struct k_fifo cmd_tx_queue; + /* Queue for outgoing HCI commands */ + struct k_fifo cmd_tx_queue; - /* Registered HCI driver */ - const struct bt_hci_driver *drv; + /* Registered HCI driver */ + const struct bt_hci_driver *drv; #if defined(CONFIG_BT_PRIVACY) - /* Local Identity Resolving Key */ - u8_t irk[CONFIG_BT_ID_MAX][16]; + /* Local Identity Resolving Key */ + u8_t irk[CONFIG_BT_ID_MAX][16]; - /* Work used for RPA rotation */ - struct k_delayed_work rpa_update; + /* Work used for RPA rotation */ + struct k_delayed_work rpa_update; #endif - /* Local Name */ + /* Local Name */ #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) - char name[CONFIG_BT_DEVICE_NAME_MAX + 1]; + char name[CONFIG_BT_DEVICE_NAME_MAX + 1]; #endif }; #if defined (CONFIG_BT_STACK_PTS) typedef enum __packed{ - dir_connect_req = 0x01, /*Send a direct connection require while the Lower test enters direct mode .*/ + dir_connect_req = 0x01, /*Send a direct connection require while the Lower test enters direct mode .*/ - ad_type_service_uuid = 0x02, - ad_type_local_name = 0x03, - ad_type_flags = 0x04, - ad_type_manu_data = 0x05, - ad_type_tx_power_level = 0x06, - ad_type_service_data = 0x07, - ad_type_appearance = 0x08, + ad_type_service_uuid = 0x02, + ad_type_local_name = 0x03, + ad_type_flags = 0x04, + ad_type_manu_data = 0x05, + ad_type_tx_power_level = 0x06, + ad_type_service_data = 0x07, + ad_type_appearance = 0x08, - gatt_discover_chara = 0x09, - gatt_exec_write_req = 0x0a, - gatt_cancel_write_req = 0x0b, - att_read_by_group_type_ind = 0x0c, /* CASE : GATT/SR/GAD/BV-01-C. Indicate PTS sends a GATT discover all primary services request to iut */ - att_find_by_type_value_ind = 0x0d, /* CASE : GATT/SR/GAD/BV-02-C. Indicate PTS sends a request to iut for discover it contains Primary Services by Service UUID */ - att_read_by_type_ind = 0x0e, /* CASE : GATT/SR/GAD/BV-04-C. Indicate PTS sends a request to iut for discover all characteristics of a specified service.*/ + gatt_discover_chara = 0x09, + gatt_exec_write_req = 0x0a, + gatt_cancel_write_req = 0x0b, + att_read_by_group_type_ind = 0x0c, /* CASE : GATT/SR/GAD/BV-01-C. Indicate PTS sends a GATT discover all primary services request to iut */ + att_find_by_type_value_ind = 0x0d, /* CASE : GATT/SR/GAD/BV-02-C. Indicate PTS sends a request to iut for discover it contains Primary Services by Service UUID */ + att_read_by_type_ind = 0x0e, /* CASE : GATT/SR/GAD/BV-04-C. Indicate PTS sends a request to iut for discover all characteristics of a specified service.*/ - own_addr_type_random = 0x0f + own_addr_type_random = 0x0f }event_id; -#endif +#endif extern struct bt_dev bt_dev; #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) @@ -238,9 +238,9 @@ int bt_setup_id_addr(void); void bt_finalize_init(void); int bt_le_adv_start_internal(const struct bt_le_adv_param *param, - const struct bt_data *ad, size_t ad_len, - const struct bt_data *sd, size_t sd_len, - const bt_addr_le_t *peer); + const struct bt_data *ad, size_t ad_len, + const struct bt_data *sd, size_t sd_len, + const bt_addr_le_t *peer); #if defined(CONFIG_BLE_MULTI_ADV) int bt_le_adv_start_instant(const struct bt_le_adv_param *param, const uint8_t *ad_data, size_t ad_len, diff --git a/components/network/ble/blestack/src/host/hci_ecc.c b/components/network/ble/blestack/src/host/hci_ecc.c index ac3fa8b1..3a8e7a72 100644 --- a/components/network/ble/blestack/src/host/hci_ecc.c +++ b/components/network/ble/blestack/src/host/hci_ecc.c @@ -42,27 +42,27 @@ static BT_STACK_NOINIT(ecc_thread_stack, 1024); /* based on Core Specification 4.2 Vol 3. Part H 2.3.5.6.1 */ static const u32_t debug_private_key[8] = { - 0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3, - 0xa3c55f38, 0x3f49f6d4 + 0xcd3c1abd, 0x5899b8a6, 0xeb40b799, 0x4aff607b, 0xd2103f50, 0x74c9b3e3, + 0xa3c55f38, 0x3f49f6d4 }; #if defined(CONFIG_BT_USE_DEBUG_KEYS) static const u8_t debug_public_key[64] = { - 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, - 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, - 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, - 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, - 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, - 0x49, 0x9c, 0x80, 0xdc + 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, + 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, + 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, + 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, + 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, + 0x49, 0x9c, 0x80, 0xdc }; #endif enum { - PENDING_PUB_KEY, - PENDING_DHKEY, + PENDING_PUB_KEY, + PENDING_DHKEY, - /* Total number of flags - must be at the end of the enum */ - NUM_FLAGS, + /* Total number of flags - must be at the end of the enum */ + NUM_FLAGS, }; static ATOMIC_DEFINE(flags, NUM_FLAGS); @@ -70,140 +70,140 @@ static ATOMIC_DEFINE(flags, NUM_FLAGS); static K_SEM_DEFINE(cmd_sem, 0, 1); static struct { - u8_t private_key[32]; + u8_t private_key[32]; - union { - u8_t pk[64]; - u8_t dhkey[32]; - }; + union { + u8_t pk[64]; + u8_t dhkey[32]; + }; } ecc; static void send_cmd_status(u16_t opcode, u8_t status) { - struct bt_hci_evt_cmd_status *evt; - struct bt_hci_evt_hdr *hdr; - struct net_buf *buf; + struct bt_hci_evt_cmd_status *evt; + struct bt_hci_evt_hdr *hdr; + struct net_buf *buf; - BT_DBG("opcode %x status %x", opcode, status); + BT_DBG("opcode %x status %x", opcode, status); - buf = bt_buf_get_evt(BT_HCI_EVT_CMD_STATUS, false, K_FOREVER); - bt_buf_set_type(buf, BT_BUF_EVT); + buf = bt_buf_get_evt(BT_HCI_EVT_CMD_STATUS, false, K_FOREVER); + bt_buf_set_type(buf, BT_BUF_EVT); - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->evt = BT_HCI_EVT_CMD_STATUS; - hdr->len = sizeof(*evt); + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->evt = BT_HCI_EVT_CMD_STATUS; + hdr->len = sizeof(*evt); - evt = net_buf_add(buf, sizeof(*evt)); - evt->ncmd = 1U; - evt->opcode = sys_cpu_to_le16(opcode); - evt->status = status; + evt = net_buf_add(buf, sizeof(*evt)); + evt->ncmd = 1U; + evt->opcode = sys_cpu_to_le16(opcode); + evt->status = status; - bt_recv_prio(buf); + bt_recv_prio(buf); } static u8_t generate_keys(void) { #if !defined(CONFIG_BT_USE_DEBUG_KEYS) - do { - int rc; + do { + int rc; - rc = uECC_make_key(ecc.pk, ecc.private_key, &curve_secp256r1); - if (rc == TC_CRYPTO_FAIL) { - BT_ERR("Failed to create ECC public/private pair"); - return BT_HCI_ERR_UNSPECIFIED; - } + rc = uECC_make_key(ecc.pk, ecc.private_key, &curve_secp256r1); + if (rc == TC_CRYPTO_FAIL) { + BT_ERR("Failed to create ECC public/private pair"); + return BT_HCI_ERR_UNSPECIFIED; + } - /* make sure generated key isn't debug key */ - } while (memcmp(ecc.private_key, debug_private_key, 32) == 0); + /* make sure generated key isn't debug key */ + } while (memcmp(ecc.private_key, debug_private_key, 32) == 0); #else - sys_memcpy_swap(&ecc.pk, debug_public_key, 32); - sys_memcpy_swap(&ecc.pk[32], &debug_public_key[32], 32); - sys_memcpy_swap(ecc.private_key, debug_private_key, 32); + sys_memcpy_swap(&ecc.pk, debug_public_key, 32); + sys_memcpy_swap(&ecc.pk[32], &debug_public_key[32], 32); + sys_memcpy_swap(ecc.private_key, debug_private_key, 32); #endif - return 0; + return 0; } static void emulate_le_p256_public_key_cmd(void) { - struct bt_hci_evt_le_p256_public_key_complete *evt; - struct bt_hci_evt_le_meta_event *meta; - struct bt_hci_evt_hdr *hdr; - struct net_buf *buf; - u8_t status; + struct bt_hci_evt_le_p256_public_key_complete *evt; + struct bt_hci_evt_le_meta_event *meta; + struct bt_hci_evt_hdr *hdr; + struct net_buf *buf; + u8_t status; - BT_DBG(""); + BT_DBG(""); - status = generate_keys(); + status = generate_keys(); - buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); + buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->evt = BT_HCI_EVT_LE_META_EVENT; - hdr->len = sizeof(*meta) + sizeof(*evt); + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->evt = BT_HCI_EVT_LE_META_EVENT; + hdr->len = sizeof(*meta) + sizeof(*evt); - meta = net_buf_add(buf, sizeof(*meta)); - meta->subevent = BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE; + meta = net_buf_add(buf, sizeof(*meta)); + meta->subevent = BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE; - evt = net_buf_add(buf, sizeof(*evt)); - evt->status = status; + evt = net_buf_add(buf, sizeof(*evt)); + evt->status = status; - if (status) { - (void)memset(evt->key, 0, sizeof(evt->key)); - } else { - /* Convert X and Y coordinates from big-endian (provided - * by crypto API) to little endian HCI. - */ - sys_memcpy_swap(evt->key, ecc.pk, 32); - sys_memcpy_swap(&evt->key[32], &ecc.pk[32], 32); - } + if (status) { + (void)memset(evt->key, 0, sizeof(evt->key)); + } else { + /* Convert X and Y coordinates from big-endian (provided + * by crypto API) to little endian HCI. + */ + sys_memcpy_swap(evt->key, ecc.pk, 32); + sys_memcpy_swap(&evt->key[32], &ecc.pk[32], 32); + } - atomic_clear_bit(flags, PENDING_PUB_KEY); + atomic_clear_bit(flags, PENDING_PUB_KEY); - bt_recv(buf); + bt_recv(buf); } static void emulate_le_generate_dhkey(void) { - struct bt_hci_evt_le_generate_dhkey_complete *evt; - struct bt_hci_evt_le_meta_event *meta; - struct bt_hci_evt_hdr *hdr; - struct net_buf *buf; - int ret; + struct bt_hci_evt_le_generate_dhkey_complete *evt; + struct bt_hci_evt_le_meta_event *meta; + struct bt_hci_evt_hdr *hdr; + struct net_buf *buf; + int ret; - ret = uECC_valid_public_key(ecc.pk, &curve_secp256r1); - if (ret < 0) { - BT_ERR("public key is not valid (ret %d)", ret); - ret = TC_CRYPTO_FAIL; - } else { - ret = uECC_shared_secret(ecc.pk, ecc.private_key, ecc.dhkey, - &curve_secp256r1); - } + ret = uECC_valid_public_key(ecc.pk, &curve_secp256r1); + if (ret < 0) { + BT_ERR("public key is not valid (ret %d)", ret); + ret = TC_CRYPTO_FAIL; + } else { + ret = uECC_shared_secret(ecc.pk, ecc.private_key, ecc.dhkey, + &curve_secp256r1); + } - buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); + buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER); - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->evt = BT_HCI_EVT_LE_META_EVENT; - hdr->len = sizeof(*meta) + sizeof(*evt); + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->evt = BT_HCI_EVT_LE_META_EVENT; + hdr->len = sizeof(*meta) + sizeof(*evt); - meta = net_buf_add(buf, sizeof(*meta)); - meta->subevent = BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE; + meta = net_buf_add(buf, sizeof(*meta)); + meta->subevent = BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE; - evt = net_buf_add(buf, sizeof(*evt)); + evt = net_buf_add(buf, sizeof(*evt)); - if (ret == TC_CRYPTO_FAIL) { - evt->status = BT_HCI_ERR_UNSPECIFIED; - (void)memset(evt->dhkey, 0, sizeof(evt->dhkey)); - } else { - evt->status = 0U; - /* Convert from big-endian (provided by crypto API) to - * little-endian HCI. - */ - sys_memcpy_swap(evt->dhkey, ecc.dhkey, sizeof(ecc.dhkey)); - } + if (ret == TC_CRYPTO_FAIL) { + evt->status = BT_HCI_ERR_UNSPECIFIED; + (void)memset(evt->dhkey, 0, sizeof(evt->dhkey)); + } else { + evt->status = 0U; + /* Convert from big-endian (provided by crypto API) to + * little-endian HCI. + */ + sys_memcpy_swap(evt->dhkey, ecc.dhkey, sizeof(ecc.dhkey)); + } - atomic_clear_bit(flags, PENDING_DHKEY); + atomic_clear_bit(flags, PENDING_DHKEY); - bt_recv(buf); + bt_recv(buf); } #if defined(BFLB_BLE) @@ -212,116 +212,116 @@ static void ecc_thread(void *p1) static void ecc_thread(void *p1, void *p2, void *p3) #endif { - while (true) { - k_sem_take(&cmd_sem, K_FOREVER); + while (true) { + k_sem_take(&cmd_sem, K_FOREVER); - if (atomic_test_bit(flags, PENDING_PUB_KEY)) { - emulate_le_p256_public_key_cmd(); - } else if (atomic_test_bit(flags, PENDING_DHKEY)) { - emulate_le_generate_dhkey(); - } else { - __ASSERT(0, "Unhandled ECC command"); - } + if (atomic_test_bit(flags, PENDING_PUB_KEY)) { + emulate_le_p256_public_key_cmd(); + } else if (atomic_test_bit(flags, PENDING_DHKEY)) { + emulate_le_generate_dhkey(); + } else { + __ASSERT(0, "Unhandled ECC command"); + } #if !defined(BFLB_BLE) - STACK_ANALYZE("ecc stack", ecc_thread_stack); + STACK_ANALYZE("ecc stack", ecc_thread_stack); #endif - } + } } static void clear_ecc_events(struct net_buf *buf) { - struct bt_hci_cp_le_set_event_mask *cmd; + struct bt_hci_cp_le_set_event_mask *cmd; - cmd = (void *)(buf->data + sizeof(struct bt_hci_cmd_hdr)); + cmd = (void *)(buf->data + sizeof(struct bt_hci_cmd_hdr)); - /* - * don't enable controller ECC events as those will be generated from - * emulation code - */ - cmd->events[0] &= ~0x80; /* LE Read Local P-256 PKey Compl */ - cmd->events[1] &= ~0x01; /* LE Generate DHKey Compl Event */ + /* + * don't enable controller ECC events as those will be generated from + * emulation code + */ + cmd->events[0] &= ~0x80; /* LE Read Local P-256 PKey Compl */ + cmd->events[1] &= ~0x01; /* LE Generate DHKey Compl Event */ } static void le_gen_dhkey(struct net_buf *buf) { - struct bt_hci_cp_le_generate_dhkey *cmd; - u8_t status; + struct bt_hci_cp_le_generate_dhkey *cmd; + u8_t status; - if (atomic_test_bit(flags, PENDING_PUB_KEY)) { - status = BT_HCI_ERR_CMD_DISALLOWED; - goto send_status; - } + if (atomic_test_bit(flags, PENDING_PUB_KEY)) { + status = BT_HCI_ERR_CMD_DISALLOWED; + goto send_status; + } - if (buf->len < sizeof(struct bt_hci_cp_le_generate_dhkey)) { - status = BT_HCI_ERR_INVALID_PARAM; - goto send_status; - } + if (buf->len < sizeof(struct bt_hci_cp_le_generate_dhkey)) { + status = BT_HCI_ERR_INVALID_PARAM; + goto send_status; + } - if (atomic_test_and_set_bit(flags, PENDING_DHKEY)) { - status = BT_HCI_ERR_CMD_DISALLOWED; - goto send_status; - } + if (atomic_test_and_set_bit(flags, PENDING_DHKEY)) { + status = BT_HCI_ERR_CMD_DISALLOWED; + goto send_status; + } - cmd = (void *)buf->data; - /* Convert X and Y coordinates from little-endian HCI to - * big-endian (expected by the crypto API). - */ - sys_memcpy_swap(ecc.pk, cmd->key, 32); - sys_memcpy_swap(&ecc.pk[32], &cmd->key[32], 32); - k_sem_give(&cmd_sem); - status = BT_HCI_ERR_SUCCESS; + cmd = (void *)buf->data; + /* Convert X and Y coordinates from little-endian HCI to + * big-endian (expected by the crypto API). + */ + sys_memcpy_swap(ecc.pk, cmd->key, 32); + sys_memcpy_swap(&ecc.pk[32], &cmd->key[32], 32); + k_sem_give(&cmd_sem); + status = BT_HCI_ERR_SUCCESS; send_status: - net_buf_unref(buf); - send_cmd_status(BT_HCI_OP_LE_GENERATE_DHKEY, status); + net_buf_unref(buf); + send_cmd_status(BT_HCI_OP_LE_GENERATE_DHKEY, status); } static void le_p256_pub_key(struct net_buf *buf) { - u8_t status; + u8_t status; - net_buf_unref(buf); + net_buf_unref(buf); - if (atomic_test_bit(flags, PENDING_DHKEY)) { - status = BT_HCI_ERR_CMD_DISALLOWED; - } else if (atomic_test_and_set_bit(flags, PENDING_PUB_KEY)) { - status = BT_HCI_ERR_CMD_DISALLOWED; - } else { - k_sem_give(&cmd_sem); - status = BT_HCI_ERR_SUCCESS; - } + if (atomic_test_bit(flags, PENDING_DHKEY)) { + status = BT_HCI_ERR_CMD_DISALLOWED; + } else if (atomic_test_and_set_bit(flags, PENDING_PUB_KEY)) { + status = BT_HCI_ERR_CMD_DISALLOWED; + } else { + k_sem_give(&cmd_sem); + status = BT_HCI_ERR_SUCCESS; + } - send_cmd_status(BT_HCI_OP_LE_P256_PUBLIC_KEY, status); + send_cmd_status(BT_HCI_OP_LE_P256_PUBLIC_KEY, status); } int bt_hci_ecc_send(struct net_buf *buf) { - if (bt_buf_get_type(buf) == BT_BUF_CMD) { - struct bt_hci_cmd_hdr *chdr = (void *)buf->data; + if (bt_buf_get_type(buf) == BT_BUF_CMD) { + struct bt_hci_cmd_hdr *chdr = (void *)buf->data; - switch (sys_le16_to_cpu(chdr->opcode)) { - case BT_HCI_OP_LE_P256_PUBLIC_KEY: - net_buf_pull(buf, sizeof(*chdr)); - le_p256_pub_key(buf); - return 0; - case BT_HCI_OP_LE_GENERATE_DHKEY: - net_buf_pull(buf, sizeof(*chdr)); - le_gen_dhkey(buf); - return 0; - case BT_HCI_OP_LE_SET_EVENT_MASK: - clear_ecc_events(buf); - break; - default: - break; - } - } + switch (sys_le16_to_cpu(chdr->opcode)) { + case BT_HCI_OP_LE_P256_PUBLIC_KEY: + net_buf_pull(buf, sizeof(*chdr)); + le_p256_pub_key(buf); + return 0; + case BT_HCI_OP_LE_GENERATE_DHKEY: + net_buf_pull(buf, sizeof(*chdr)); + le_gen_dhkey(buf); + return 0; + case BT_HCI_OP_LE_SET_EVENT_MASK: + clear_ecc_events(buf); + break; + default: + break; + } + } - return bt_dev.drv->send(buf); + return bt_dev.drv->send(buf); } int default_CSPRNG(u8_t *dst, unsigned int len) { - return !bt_rand(dst, len); + return !bt_rand(dst, len); } void bt_hci_ecc_init(void) @@ -333,8 +333,8 @@ void bt_hci_ecc_init(void) CONFIG_BT_WORK_QUEUE_PRIO); #else k_thread_create(&ecc_thread_data, ecc_thread_stack, - K_THREAD_STACK_SIZEOF(ecc_thread_stack), ecc_thread, - NULL, NULL, NULL, K_PRIO_PREEMPT(10), 0, K_NO_WAIT); + K_THREAD_STACK_SIZEOF(ecc_thread_stack), ecc_thread, + NULL, NULL, NULL, K_PRIO_PREEMPT(10), 0, K_NO_WAIT); k_thread_name_set(&ecc_thread_data, "BT ECC"); #endif } diff --git a/components/network/ble/blestack/src/host/keys.c b/components/network/ble/blestack/src/host/keys.c index 6a7fe5c2..35cae792 100644 --- a/components/network/ble/blestack/src/host/keys.c +++ b/components/network/ble/blestack/src/host/keys.c @@ -42,257 +42,257 @@ static struct bt_keys *last_keys_updated; struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr) { - struct bt_keys *keys; - int i; - size_t first_free_slot = ARRAY_SIZE(key_pool); + struct bt_keys *keys; + int i; + size_t first_free_slot = ARRAY_SIZE(key_pool); - BT_DBG("%s", bt_addr_le_str(addr)); + BT_DBG("%s", bt_addr_le_str(addr)); - for (i = 0; i < ARRAY_SIZE(key_pool); i++) { - keys = &key_pool[i]; + for (i = 0; i < ARRAY_SIZE(key_pool); i++) { + keys = &key_pool[i]; - if (keys->id == id && !bt_addr_le_cmp(&keys->addr, addr)) { - return keys; - } + if (keys->id == id && !bt_addr_le_cmp(&keys->addr, addr)) { + return keys; + } - if (first_free_slot == ARRAY_SIZE(key_pool) && - (!bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY) || - !keys->enc_size)) { - first_free_slot = i; - } - } + if (first_free_slot == ARRAY_SIZE(key_pool) && + (!bt_addr_le_cmp(&keys->addr, BT_ADDR_LE_ANY) || + !keys->enc_size)) { + first_free_slot = i; + } + } #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) - if (first_free_slot == ARRAY_SIZE(key_pool)) { - struct bt_keys *oldest = &key_pool[0]; + if (first_free_slot == ARRAY_SIZE(key_pool)) { + struct bt_keys *oldest = &key_pool[0]; - for (i = 1; i < ARRAY_SIZE(key_pool); i++) { - struct bt_keys *current = &key_pool[i]; + for (i = 1; i < ARRAY_SIZE(key_pool); i++) { + struct bt_keys *current = &key_pool[i]; - if (current->aging_counter < oldest->aging_counter) { - oldest = current; - } - } + if (current->aging_counter < oldest->aging_counter) { + oldest = current; + } + } - bt_unpair(oldest->id, &oldest->addr); - if (!bt_addr_le_cmp(&oldest->addr, BT_ADDR_LE_ANY)) { - first_free_slot = oldest - &key_pool[0]; - } - } + bt_unpair(oldest->id, &oldest->addr); + if (!bt_addr_le_cmp(&oldest->addr, BT_ADDR_LE_ANY)) { + first_free_slot = oldest - &key_pool[0]; + } + } #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ - if (first_free_slot < ARRAY_SIZE(key_pool)) { - keys = &key_pool[first_free_slot]; - keys->id = id; - bt_addr_le_copy(&keys->addr, addr); + if (first_free_slot < ARRAY_SIZE(key_pool)) { + keys = &key_pool[first_free_slot]; + keys->id = id; + bt_addr_le_copy(&keys->addr, addr); #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) - keys->aging_counter = ++aging_counter_val; - last_keys_updated = keys; + keys->aging_counter = ++aging_counter_val; + last_keys_updated = keys; #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ - BT_DBG("created %p for %s", keys, bt_addr_le_str(addr)); - return keys; - } + BT_DBG("created %p for %s", keys, bt_addr_le_str(addr)); + return keys; + } - BT_DBG("unable to create keys for %s", bt_addr_le_str(addr)); + BT_DBG("unable to create keys for %s", bt_addr_le_str(addr)); - return NULL; + return NULL; } void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, - void *user_data), - void *user_data) + void *user_data), + void *user_data) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(key_pool); i++) { - struct bt_keys *keys = &key_pool[i]; + for (i = 0; i < ARRAY_SIZE(key_pool); i++) { + struct bt_keys *keys = &key_pool[i]; - if (keys->keys && keys->id == id) { - struct bt_bond_info info; + if (keys->keys && keys->id == id) { + struct bt_bond_info info; - bt_addr_le_copy(&info.addr, &keys->addr); - func(&info, user_data); - } - } + bt_addr_le_copy(&info.addr, &keys->addr); + func(&info, user_data); + } + } } void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data), - void *data) + void *data) { - int i; + int i; - for (i = 0; i < ARRAY_SIZE(key_pool); i++) { - if ((key_pool[i].keys & type)) { - func(&key_pool[i], data); - } - } + for (i = 0; i < ARRAY_SIZE(key_pool); i++) { + if ((key_pool[i].keys & type)) { + func(&key_pool[i], data); + } + } } struct bt_keys *bt_keys_find(int type, u8_t id, const bt_addr_le_t *addr) { - int i; + int i; - BT_DBG("type %d %s", type, bt_addr_le_str(addr)); + BT_DBG("type %d %s", type, bt_addr_le_str(addr)); - for (i = 0; i < ARRAY_SIZE(key_pool); i++) { - if ((key_pool[i].keys & type) && key_pool[i].id == id && - !bt_addr_le_cmp(&key_pool[i].addr, addr)) { - return &key_pool[i]; - } - } + for (i = 0; i < ARRAY_SIZE(key_pool); i++) { + if ((key_pool[i].keys & type) && key_pool[i].id == id && + !bt_addr_le_cmp(&key_pool[i].addr, addr)) { + return &key_pool[i]; + } + } - return NULL; + return NULL; } struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr) { - struct bt_keys *keys; + struct bt_keys *keys; - BT_DBG("type %d %s", type, bt_addr_le_str(addr)); + BT_DBG("type %d %s", type, bt_addr_le_str(addr)); - keys = bt_keys_find(type, id, addr); - if (keys) { - return keys; - } + keys = bt_keys_find(type, id, addr); + if (keys) { + return keys; + } - keys = bt_keys_get_addr(id, addr); - if (!keys) { - return NULL; - } + keys = bt_keys_get_addr(id, addr); + if (!keys) { + return NULL; + } - bt_keys_add_type(keys, type); + bt_keys_add_type(keys, type); - return keys; + return keys; } struct bt_keys *bt_keys_find_irk(u8_t id, const bt_addr_le_t *addr) { - int i; + int i; - BT_DBG("%s", bt_addr_le_str(addr)); + BT_DBG("%s", bt_addr_le_str(addr)); - if (!bt_addr_le_is_rpa(addr)) { - return NULL; - } + if (!bt_addr_le_is_rpa(addr)) { + return NULL; + } - for (i = 0; i < ARRAY_SIZE(key_pool); i++) { - if (!(key_pool[i].keys & BT_KEYS_IRK)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(key_pool); i++) { + if (!(key_pool[i].keys & BT_KEYS_IRK)) { + continue; + } - if (key_pool[i].id == id && - !bt_addr_cmp(&addr->a, &key_pool[i].irk.rpa)) { - BT_DBG("cached RPA %s for %s", - bt_addr_str(&key_pool[i].irk.rpa), - bt_addr_le_str(&key_pool[i].addr)); - return &key_pool[i]; - } - } + if (key_pool[i].id == id && + !bt_addr_cmp(&addr->a, &key_pool[i].irk.rpa)) { + BT_DBG("cached RPA %s for %s", + bt_addr_str(&key_pool[i].irk.rpa), + bt_addr_le_str(&key_pool[i].addr)); + return &key_pool[i]; + } + } - for (i = 0; i < ARRAY_SIZE(key_pool); i++) { - if (!(key_pool[i].keys & BT_KEYS_IRK)) { - continue; - } + for (i = 0; i < ARRAY_SIZE(key_pool); i++) { + if (!(key_pool[i].keys & BT_KEYS_IRK)) { + continue; + } - if (key_pool[i].id != id) { - continue; - } + if (key_pool[i].id != id) { + continue; + } - if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) { - BT_DBG("RPA %s matches %s", - bt_addr_str(&key_pool[i].irk.rpa), - bt_addr_le_str(&key_pool[i].addr)); + if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) { + BT_DBG("RPA %s matches %s", + bt_addr_str(&key_pool[i].irk.rpa), + bt_addr_le_str(&key_pool[i].addr)); - bt_addr_copy(&key_pool[i].irk.rpa, &addr->a); + bt_addr_copy(&key_pool[i].irk.rpa, &addr->a); - return &key_pool[i]; - } - } + return &key_pool[i]; + } + } - BT_DBG("No IRK for %s", bt_addr_le_str(addr)); + BT_DBG("No IRK for %s", bt_addr_le_str(addr)); - return NULL; + return NULL; } struct bt_keys *bt_keys_find_addr(u8_t id, const bt_addr_le_t *addr) { - int i; + int i; - BT_DBG("%s", bt_addr_le_str(addr)); + BT_DBG("%s", bt_addr_le_str(addr)); - for (i = 0; i < ARRAY_SIZE(key_pool); i++) { - if (key_pool[i].id == id && - !bt_addr_le_cmp(&key_pool[i].addr, addr)) { - return &key_pool[i]; - } - } + for (i = 0; i < ARRAY_SIZE(key_pool); i++) { + if (key_pool[i].id == id && + !bt_addr_le_cmp(&key_pool[i].addr, addr)) { + return &key_pool[i]; + } + } - return NULL; + return NULL; } void bt_keys_add_type(struct bt_keys *keys, int type) { - keys->keys |= type; + keys->keys |= type; } void bt_keys_clear(struct bt_keys *keys) { #if defined(BFLB_BLE) if (keys->keys & BT_KEYS_IRK) { - bt_id_del(keys); - } - + bt_id_del(keys); + } + memset(keys, 0, sizeof(*keys)); - + #if defined (CONFIG_BT_SETTINGS) ef_del_env(NV_KEY_POOL); #endif #else - BT_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys); + BT_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys); - if (keys->keys & BT_KEYS_IRK) { - bt_id_del(keys); - } + if (keys->keys & BT_KEYS_IRK) { + bt_id_del(keys); + } - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - char key[BT_SETTINGS_KEY_MAX]; + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + char key[BT_SETTINGS_KEY_MAX]; - /* Delete stored keys from flash */ - if (keys->id) { - char id[4]; + /* Delete stored keys from flash */ + if (keys->id) { + char id[4]; - u8_to_dec(id, sizeof(id), keys->id); - bt_settings_encode_key(key, sizeof(key), "keys", - &keys->addr, id); - } else { - bt_settings_encode_key(key, sizeof(key), "keys", - &keys->addr, NULL); - } + u8_to_dec(id, sizeof(id), keys->id); + bt_settings_encode_key(key, sizeof(key), "keys", + &keys->addr, id); + } else { + bt_settings_encode_key(key, sizeof(key), "keys", + &keys->addr, NULL); + } - BT_DBG("Deleting key %s", log_strdup(key)); - settings_delete(key); - } + BT_DBG("Deleting key %s", log_strdup(key)); + settings_delete(key); + } - (void)memset(keys, 0, sizeof(*keys)); + (void)memset(keys, 0, sizeof(*keys)); #endif } static void keys_clear_id(struct bt_keys *keys, void *data) { - u8_t *id = data; + u8_t *id = data; - if (*id == keys->id) { - if (IS_ENABLED(CONFIG_BT_SETTINGS)) { - bt_gatt_clear(*id, &keys->addr); - } + if (*id == keys->id) { + if (IS_ENABLED(CONFIG_BT_SETTINGS)) { + bt_gatt_clear(*id, &keys->addr); + } - bt_keys_clear(keys); - } + bt_keys_clear(keys); + } } void bt_keys_clear_all(u8_t id) { - bt_keys_foreach(BT_KEYS_ALL, keys_clear_id, &id); + bt_keys_foreach(BT_KEYS_ALL, keys_clear_id, &id); } #if defined(CONFIG_BT_SETTINGS) @@ -300,139 +300,139 @@ int bt_keys_store(struct bt_keys *keys) { #if defined(BFLB_BLE) int err; - err = bt_settings_set_bin(NV_KEY_POOL, (const u8_t *)&key_pool[0], sizeof(key_pool)); + err = bt_settings_set_bin(NV_KEY_POOL, (const u8_t *)&key_pool[0], sizeof(key_pool)); return err; #else - char val[BT_SETTINGS_SIZE(BT_KEYS_STORAGE_LEN)]; - char key[BT_SETTINGS_KEY_MAX]; - char *str; - int err; + char val[BT_SETTINGS_SIZE(BT_KEYS_STORAGE_LEN)]; + char key[BT_SETTINGS_KEY_MAX]; + char *str; + int err; - str = settings_str_from_bytes(keys->storage_start, BT_KEYS_STORAGE_LEN, - val, sizeof(val)); - if (!str) { - BT_ERR("Unable to encode bt_keys as value"); - return -EINVAL; - } + str = settings_str_from_bytes(keys->storage_start, BT_KEYS_STORAGE_LEN, + val, sizeof(val)); + if (!str) { + BT_ERR("Unable to encode bt_keys as value"); + return -EINVAL; + } - if (keys->id) { - char id[4]; + if (keys->id) { + char id[4]; - u8_to_dec(id, sizeof(id), keys->id); - bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, - id); - } else { - bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, - NULL); - } + u8_to_dec(id, sizeof(id), keys->id); + bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, + id); + } else { + bt_settings_encode_key(key, sizeof(key), "keys", &keys->addr, + NULL); + } - err = settings_save_one(key, keys->storage_start, BT_KEYS_STORAGE_LEN); - if (err) { - BT_ERR("Failed to save keys (err %d)", err); - return err; - } + err = settings_save_one(key, keys->storage_start, BT_KEYS_STORAGE_LEN); + if (err) { + BT_ERR("Failed to save keys (err %d)", err); + return err; + } - BT_DBG("Stored keys for %s (%s)", bt_addr_le_str(&keys->addr), - log_strdup(key)); + BT_DBG("Stored keys for %s (%s)", bt_addr_le_str(&keys->addr), + log_strdup(key)); - return 0; + return 0; #endif //BFLB_BLE } #if !defined(BFLB_BLE) static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) { - struct bt_keys *keys; - bt_addr_le_t addr; - u8_t id; - size_t len; - int err; - char val[BT_KEYS_STORAGE_LEN]; - const char *next; + struct bt_keys *keys; + bt_addr_le_t addr; + u8_t id; + size_t len; + int err; + char val[BT_KEYS_STORAGE_LEN]; + const char *next; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -EINVAL; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -EINVAL; + } - len = read_cb(cb_arg, val, sizeof(val)); - if (len < 0) { - BT_ERR("Failed to read value (err %zu)", len); - return -EINVAL; - } + len = read_cb(cb_arg, val, sizeof(val)); + if (len < 0) { + BT_ERR("Failed to read value (err %zu)", len); + return -EINVAL; + } - BT_DBG("name %s val %s", log_strdup(name), - (len) ? bt_hex(val, sizeof(val)) : "(null)"); + BT_DBG("name %s val %s", log_strdup(name), + (len) ? bt_hex(val, sizeof(val)) : "(null)"); - err = bt_settings_decode_key(name, &addr); - if (err) { - BT_ERR("Unable to decode address %s", name); - return -EINVAL; - } + err = bt_settings_decode_key(name, &addr); + if (err) { + BT_ERR("Unable to decode address %s", name); + return -EINVAL; + } - settings_name_next(name, &next); + settings_name_next(name, &next); - if (!next) { - id = BT_ID_DEFAULT; - } else { - id = strtol(next, NULL, 10); - } + if (!next) { + id = BT_ID_DEFAULT; + } else { + id = strtol(next, NULL, 10); + } - if (!len) { - keys = bt_keys_find(BT_KEYS_ALL, id, &addr); - if (keys) { - (void)memset(keys, 0, sizeof(*keys)); - BT_DBG("Cleared keys for %s", bt_addr_le_str(&addr)); - } else { - BT_WARN("Unable to find deleted keys for %s", - bt_addr_le_str(&addr)); - } + if (!len) { + keys = bt_keys_find(BT_KEYS_ALL, id, &addr); + if (keys) { + (void)memset(keys, 0, sizeof(*keys)); + BT_DBG("Cleared keys for %s", bt_addr_le_str(&addr)); + } else { + BT_WARN("Unable to find deleted keys for %s", + bt_addr_le_str(&addr)); + } - return 0; - } + return 0; + } - keys = bt_keys_get_addr(id, &addr); - if (!keys) { - BT_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr)); - return -ENOMEM; - } - if (len != BT_KEYS_STORAGE_LEN) { - do { - /* Load shorter structure for compatibility with old - * records format with no counter. - */ - if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) && - len == BT_KEYS_STORAGE_LEN_COMPAT) { - BT_WARN("Keys for %s have no aging counter", - bt_addr_le_str(&addr)); - memcpy(keys->storage_start, val, len); - continue; - } + keys = bt_keys_get_addr(id, &addr); + if (!keys) { + BT_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr)); + return -ENOMEM; + } + if (len != BT_KEYS_STORAGE_LEN) { + do { + /* Load shorter structure for compatibility with old + * records format with no counter. + */ + if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) && + len == BT_KEYS_STORAGE_LEN_COMPAT) { + BT_WARN("Keys for %s have no aging counter", + bt_addr_le_str(&addr)); + memcpy(keys->storage_start, val, len); + continue; + } - BT_ERR("Invalid key length %zu != %zu", len, - BT_KEYS_STORAGE_LEN); - bt_keys_clear(keys); + BT_ERR("Invalid key length %zu != %zu", len, + BT_KEYS_STORAGE_LEN); + bt_keys_clear(keys); - return -EINVAL; - } while (0); - } else { - memcpy(keys->storage_start, val, len); - } + return -EINVAL; + } while (0); + } else { + memcpy(keys->storage_start, val, len); + } - BT_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr)); + BT_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr)); #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) - if (aging_counter_val < keys->aging_counter) { - aging_counter_val = keys->aging_counter; - } + if (aging_counter_val < keys->aging_counter) { + aging_counter_val = keys->aging_counter; + } #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ - return 0; + return 0; } #endif //!(BFLB_BLE) static void id_add(struct bt_keys *keys, void *user_data) { - bt_id_add(keys); + bt_id_add(keys); } #if defined(BFLB_BLE) @@ -441,24 +441,24 @@ int keys_commit(void) static int keys_commit(void) #endif { - BT_DBG(""); + BT_DBG(""); - /* We do this in commit() rather than add() since add() may get - * called multiple times for the same address, especially if - * the keys were already removed. - */ - bt_keys_foreach(BT_KEYS_IRK, id_add, NULL); + /* We do this in commit() rather than add() since add() may get + * called multiple times for the same address, especially if + * the keys were already removed. + */ + bt_keys_foreach(BT_KEYS_IRK, id_add, NULL); - return 0; + return 0; } //SETTINGS_STATIC_HANDLER_DEFINE(bt_keys, "bt/keys", NULL, keys_set, keys_commit, -// NULL); - +// NULL); + #if defined(BFLB_BLE) int bt_keys_load(void) { - return bt_settings_get_bin(NV_KEY_POOL, (u8_t *)&key_pool[0], sizeof(key_pool), NULL); + return bt_settings_get_bin(NV_KEY_POOL, (u8_t *)&key_pool[0], sizeof(key_pool), NULL); } #endif @@ -467,25 +467,25 @@ int bt_keys_load(void) #if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) void bt_keys_update_usage(u8_t id, const bt_addr_le_t *addr) { - struct bt_keys *keys = bt_keys_find_addr(id, addr); + struct bt_keys *keys = bt_keys_find_addr(id, addr); - if (!keys) { - return; - } + if (!keys) { + return; + } - if (last_keys_updated == keys) { - return; - } + if (last_keys_updated == keys) { + return; + } - keys->aging_counter = ++aging_counter_val; - last_keys_updated = keys; + keys->aging_counter = ++aging_counter_val; + last_keys_updated = keys; - BT_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr), - keys->aging_counter); + BT_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr), + keys->aging_counter); - if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) { - bt_keys_store(keys); - } + if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) { + bt_keys_store(keys); + } } #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ diff --git a/components/network/ble/blestack/src/host/keys.h b/components/network/ble/blestack/src/host/keys.h index 7bfd4ef7..7ec05131 100644 --- a/components/network/ble/blestack/src/host/keys.h +++ b/components/network/ble/blestack/src/host/keys.h @@ -7,72 +7,72 @@ */ enum { - BT_KEYS_SLAVE_LTK = BIT(0), - BT_KEYS_IRK = BIT(1), - BT_KEYS_LTK = BIT(2), - BT_KEYS_LOCAL_CSRK = BIT(3), - BT_KEYS_REMOTE_CSRK = BIT(4), - BT_KEYS_LTK_P256 = BIT(5), + BT_KEYS_SLAVE_LTK = BIT(0), + BT_KEYS_IRK = BIT(1), + BT_KEYS_LTK = BIT(2), + BT_KEYS_LOCAL_CSRK = BIT(3), + BT_KEYS_REMOTE_CSRK = BIT(4), + BT_KEYS_LTK_P256 = BIT(5), - BT_KEYS_ALL = (BT_KEYS_SLAVE_LTK | BT_KEYS_IRK | \ - BT_KEYS_LTK | BT_KEYS_LOCAL_CSRK | \ - BT_KEYS_REMOTE_CSRK | BT_KEYS_LTK_P256), + BT_KEYS_ALL = (BT_KEYS_SLAVE_LTK | BT_KEYS_IRK | \ + BT_KEYS_LTK | BT_KEYS_LOCAL_CSRK | \ + BT_KEYS_REMOTE_CSRK | BT_KEYS_LTK_P256), }; enum { - BT_KEYS_AUTHENTICATED = BIT(0), - BT_KEYS_DEBUG = BIT(1), - BT_KEYS_ID_PENDING_ADD = BIT(2), - BT_KEYS_ID_PENDING_DEL = BIT(3), - BT_KEYS_SC = BIT(4), + BT_KEYS_AUTHENTICATED = BIT(0), + BT_KEYS_DEBUG = BIT(1), + BT_KEYS_ID_PENDING_ADD = BIT(2), + BT_KEYS_ID_PENDING_DEL = BIT(3), + BT_KEYS_SC = BIT(4), }; struct bt_ltk { - u8_t rand[8]; - u8_t ediv[2]; - u8_t val[16]; + u8_t rand[8]; + u8_t ediv[2]; + u8_t val[16]; }; struct bt_irk { - u8_t val[16]; - bt_addr_t rpa; + u8_t val[16]; + bt_addr_t rpa; }; struct bt_csrk { - u8_t val[16]; - u32_t cnt; + u8_t val[16]; + u32_t cnt; }; struct bt_keys { - u8_t id; - bt_addr_le_t addr; + u8_t id; + bt_addr_le_t addr; #if !defined(BFLB_BLE) - u8_t storage_start[0]; + u8_t storage_start[0]; #endif - u8_t enc_size; - u8_t flags; - u16_t keys; - struct bt_ltk ltk; - struct bt_irk irk; + u8_t enc_size; + u8_t flags; + u16_t keys; + struct bt_ltk ltk; + struct bt_irk irk; #if defined(CONFIG_BT_SIGNING) - struct bt_csrk local_csrk; - struct bt_csrk remote_csrk; + struct bt_csrk local_csrk; + struct bt_csrk remote_csrk; #endif /* BT_SIGNING */ #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - struct bt_ltk slave_ltk; + struct bt_ltk slave_ltk; #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ #if (defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)) - u32_t aging_counter; + u32_t aging_counter; #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */ }; #if !defined(BFLB_BLE) #define BT_KEYS_STORAGE_LEN (sizeof(struct bt_keys) - \ - offsetof(struct bt_keys, storage_start)) + offsetof(struct bt_keys, storage_start)) #endif void bt_keys_foreach(int type, void (*func)(struct bt_keys *keys, void *data), - void *data); + void *data); struct bt_keys *bt_keys_get_addr(u8_t id, const bt_addr_le_t *addr); struct bt_keys *bt_keys_get_type(int type, u8_t id, const bt_addr_le_t *addr); @@ -93,20 +93,20 @@ int bt_keys_store(struct bt_keys *keys); #else static inline int bt_keys_store(struct bt_keys *keys) { - return 0; + return 0; } #endif enum { - BT_LINK_KEY_AUTHENTICATED = BIT(0), - BT_LINK_KEY_DEBUG = BIT(1), - BT_LINK_KEY_SC = BIT(2), + BT_LINK_KEY_AUTHENTICATED = BIT(0), + BT_LINK_KEY_DEBUG = BIT(1), + BT_LINK_KEY_SC = BIT(2), }; struct bt_keys_link_key { - bt_addr_t addr; - u8_t flags; - u8_t val[16]; + bt_addr_t addr; + u8_t flags; + u8_t val[16]; }; struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr); diff --git a/components/network/ble/blestack/src/host/l2cap.c b/components/network/ble/blestack/src/host/l2cap.c index 93a2cc58..49e00001 100644 --- a/components/network/ble/blestack/src/host/l2cap.c +++ b/components/network/ble/blestack/src/host/l2cap.c @@ -31,26 +31,26 @@ #define LE_CHAN_RTX(_w) CONTAINER_OF(_w, struct bt_l2cap_le_chan, chan.rtx_work) #define CHAN_RX(_w) CONTAINER_OF(_w, struct bt_l2cap_le_chan, rx_work) -#define L2CAP_LE_MIN_MTU 23 +#define L2CAP_LE_MIN_MTU 23 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) -#define L2CAP_LE_MAX_CREDITS (CONFIG_BT_ACL_RX_COUNT - 1) +#define L2CAP_LE_MAX_CREDITS (CONFIG_BT_ACL_RX_COUNT - 1) #else -#define L2CAP_LE_MAX_CREDITS (CONFIG_BT_RX_BUF_COUNT - 1) +#define L2CAP_LE_MAX_CREDITS (CONFIG_BT_RX_BUF_COUNT - 1) #endif -#define L2CAP_LE_CID_DYN_START 0x0040 -#define L2CAP_LE_CID_DYN_END 0x007f +#define L2CAP_LE_CID_DYN_START 0x0040 +#define L2CAP_LE_CID_DYN_END 0x007f #define L2CAP_LE_CID_IS_DYN(_cid) \ - (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END) + (_cid >= L2CAP_LE_CID_DYN_START && _cid <= L2CAP_LE_CID_DYN_END) #define L2CAP_LE_PSM_FIXED_START 0x0001 #define L2CAP_LE_PSM_FIXED_END 0x007f #define L2CAP_LE_PSM_DYN_START 0x0080 #define L2CAP_LE_PSM_DYN_END 0x00ff -#define L2CAP_CONN_TIMEOUT K_SECONDS(40) -#define L2CAP_DISC_TIMEOUT K_SECONDS(2) +#define L2CAP_CONN_TIMEOUT K_SECONDS(40) +#define L2CAP_DISC_TIMEOUT K_SECONDS(2) #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) static sys_slist_t le_channels; @@ -60,9 +60,9 @@ static sys_slist_t le_channels; /* Size of MTU is based on the maximum amount of data the buffer can hold * excluding ACL and driver headers. */ -#define L2CAP_MAX_LE_MPS BT_L2CAP_RX_MTU +#define L2CAP_MAX_LE_MPS BT_L2CAP_RX_MTU /* For now use MPS - SDU length to disable segmentation */ -#define L2CAP_MAX_LE_MTU (L2CAP_MAX_LE_MPS - 2) +#define L2CAP_MAX_LE_MTU (L2CAP_MAX_LE_MPS - 2) #define l2cap_lookup_ident(conn, ident) __l2cap_lookup_ident(conn, ident, false) #define l2cap_remove_ident(conn, ident) __l2cap_lookup_ident(conn, ident, true) @@ -73,191 +73,191 @@ static sys_slist_t servers; /* L2CAP signalling channel specific context */ struct bt_l2cap { - /* The channel this context is associated with */ - struct bt_l2cap_le_chan chan; + /* The channel this context is associated with */ + struct bt_l2cap_le_chan chan; }; static struct bt_l2cap bt_l2cap_pool[CONFIG_BT_MAX_CONN]; static u8_t get_ident(void) { - static u8_t ident; + static u8_t ident; - ident++; - /* handle integer overflow (0 is not valid) */ - if (!ident) { - ident++; - } + ident++; + /* handle integer overflow (0 is not valid) */ + if (!ident) { + ident++; + } - return ident; + return ident; } #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) void bt_l2cap_le_fixed_chan_register(struct bt_l2cap_fixed_chan *chan) { - BT_DBG("CID 0x%04x", chan->cid); + BT_DBG("CID 0x%04x", chan->cid); - sys_slist_append(&le_channels, &chan->node); + sys_slist_append(&le_channels, &chan->node); } #endif #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static struct bt_l2cap_le_chan *l2cap_chan_alloc_cid(struct bt_conn *conn, - struct bt_l2cap_chan *chan) + struct bt_l2cap_chan *chan) { - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - u16_t cid; + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + u16_t cid; - /* - * No action needed if there's already a CID allocated, e.g. in - * the case of a fixed channel. - */ - if (ch && ch->rx.cid > 0) { - return ch; - } + /* + * No action needed if there's already a CID allocated, e.g. in + * the case of a fixed channel. + */ + if (ch && ch->rx.cid > 0) { + return ch; + } - for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) { - if (ch && !bt_l2cap_le_lookup_rx_cid(conn, cid)) { - ch->rx.cid = cid; - return ch; - } - } + for (cid = L2CAP_LE_CID_DYN_START; cid <= L2CAP_LE_CID_DYN_END; cid++) { + if (ch && !bt_l2cap_le_lookup_rx_cid(conn, cid)) { + ch->rx.cid = cid; + return ch; + } + } - return NULL; + return NULL; } static struct bt_l2cap_le_chan * __l2cap_lookup_ident(struct bt_conn *conn, u16_t ident, bool remove) { - struct bt_l2cap_chan *chan; - sys_snode_t *prev = NULL; + struct bt_l2cap_chan *chan; + sys_snode_t *prev = NULL; - SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { - if (chan->ident == ident) { - if (remove) { - sys_slist_remove(&conn->channels, prev, - &chan->node); - } - return BT_L2CAP_LE_CHAN(chan); - } + SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { + if (chan->ident == ident) { + if (remove) { + sys_slist_remove(&conn->channels, prev, + &chan->node); + } + return BT_L2CAP_LE_CHAN(chan); + } - prev = &chan->node; - } + prev = &chan->node; + } - return NULL; + return NULL; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *ch) { - struct bt_l2cap_chan *chan; - sys_snode_t *prev = NULL; + struct bt_l2cap_chan *chan; + sys_snode_t *prev = NULL; - SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { - if (chan == ch) { - sys_slist_remove(&conn->channels, prev, &chan->node); - return; - } + SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { + if (chan == ch) { + sys_slist_remove(&conn->channels, prev, &chan->node); + return; + } - prev = &chan->node; - } + prev = &chan->node; + } } const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state) { - switch (state) { - case BT_L2CAP_DISCONNECTED: - return "disconnected"; - case BT_L2CAP_CONNECT: - return "connect"; - case BT_L2CAP_CONFIG: - return "config"; - case BT_L2CAP_CONNECTED: - return "connected"; - case BT_L2CAP_DISCONNECT: - return "disconnect"; - default: - return "unknown"; - } + switch (state) { + case BT_L2CAP_DISCONNECTED: + return "disconnected"; + case BT_L2CAP_CONNECT: + return "connect"; + case BT_L2CAP_CONFIG: + return "config"; + case BT_L2CAP_CONNECTED: + return "connected"; + case BT_L2CAP_DISCONNECT: + return "disconnect"; + default: + return "unknown"; + } } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) #if defined(CONFIG_BT_DEBUG_L2CAP) void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan, - bt_l2cap_chan_state_t state, - const char *func, int line) + bt_l2cap_chan_state_t state, + const char *func, int line) { - BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm, - bt_l2cap_chan_state_str(chan->state), - bt_l2cap_chan_state_str(state)); + BT_DBG("chan %p psm 0x%04x %s -> %s", chan, chan->psm, + bt_l2cap_chan_state_str(chan->state), + bt_l2cap_chan_state_str(state)); - /* check transitions validness */ - switch (state) { - case BT_L2CAP_DISCONNECTED: - /* regardless of old state always allows this state */ - break; - case BT_L2CAP_CONNECT: - if (chan->state != BT_L2CAP_DISCONNECTED) { - BT_WARN("%s()%d: invalid transition", func, line); - } - break; - case BT_L2CAP_CONFIG: - if (chan->state != BT_L2CAP_CONNECT) { - BT_WARN("%s()%d: invalid transition", func, line); - } - break; - case BT_L2CAP_CONNECTED: - if (chan->state != BT_L2CAP_CONFIG && - chan->state != BT_L2CAP_CONNECT) { - BT_WARN("%s()%d: invalid transition", func, line); - } - break; - case BT_L2CAP_DISCONNECT: - if (chan->state != BT_L2CAP_CONFIG && - chan->state != BT_L2CAP_CONNECTED) { - BT_WARN("%s()%d: invalid transition", func, line); - } - break; - default: - BT_ERR("%s()%d: unknown (%u) state was set", func, line, state); - return; - } + /* check transitions validness */ + switch (state) { + case BT_L2CAP_DISCONNECTED: + /* regardless of old state always allows this state */ + break; + case BT_L2CAP_CONNECT: + if (chan->state != BT_L2CAP_DISCONNECTED) { + BT_WARN("%s()%d: invalid transition", func, line); + } + break; + case BT_L2CAP_CONFIG: + if (chan->state != BT_L2CAP_CONNECT) { + BT_WARN("%s()%d: invalid transition", func, line); + } + break; + case BT_L2CAP_CONNECTED: + if (chan->state != BT_L2CAP_CONFIG && + chan->state != BT_L2CAP_CONNECT) { + BT_WARN("%s()%d: invalid transition", func, line); + } + break; + case BT_L2CAP_DISCONNECT: + if (chan->state != BT_L2CAP_CONFIG && + chan->state != BT_L2CAP_CONNECTED) { + BT_WARN("%s()%d: invalid transition", func, line); + } + break; + default: + BT_ERR("%s()%d: unknown (%u) state was set", func, line, state); + return; + } - chan->state = state; + chan->state = state; } #else void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan, - bt_l2cap_chan_state_t state) + bt_l2cap_chan_state_t state) { - chan->state = state; + chan->state = state; } #endif /* CONFIG_BT_DEBUG_L2CAP */ #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_del(struct bt_l2cap_chan *chan) { - BT_DBG("conn %p chan %p", chan->conn, chan); + BT_DBG("conn %p chan %p", chan->conn, chan); - if (!chan->conn) { - goto destroy; - } + if (!chan->conn) { + goto destroy; + } - if (chan->ops->disconnected) { - chan->ops->disconnected(chan); - } + if (chan->ops->disconnected) { + chan->ops->disconnected(chan); + } - chan->conn = NULL; + chan->conn = NULL; destroy: #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) - /* Reset internal members of common channel */ - bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED); - chan->psm = 0U; + /* Reset internal members of common channel */ + bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECTED); + chan->psm = 0U; #endif - if (chan->destroy) { - chan->destroy(chan); - } + if (chan->destroy) { + chan->destroy(chan); + } #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS if(chan->rtx_work.timer.timer.hdl) @@ -267,1555 +267,1555 @@ destroy: static void l2cap_rtx_timeout(struct k_work *work) { - struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work); + struct bt_l2cap_le_chan *chan = LE_CHAN_RTX(work); - BT_ERR("chan %p timeout", chan); + BT_ERR("chan %p timeout", chan); - bt_l2cap_chan_remove(chan->chan.conn, &chan->chan); - bt_l2cap_chan_del(&chan->chan); + bt_l2cap_chan_remove(chan->chan.conn, &chan->chan); + bt_l2cap_chan_del(&chan->chan); } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, - struct net_buf *buf); + struct net_buf *buf); static void l2cap_rx_process(struct k_work *work) { - struct bt_l2cap_le_chan *ch = CHAN_RX(work); - struct net_buf *buf; + struct bt_l2cap_le_chan *ch = CHAN_RX(work); + struct net_buf *buf; - while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { - BT_DBG("ch %p buf %p", ch, buf); - l2cap_chan_le_recv(ch, buf); - net_buf_unref(buf); - } + while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { + BT_DBG("ch %p buf %p", ch, buf); + l2cap_chan_le_recv(ch, buf); + net_buf_unref(buf); + } } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, - bt_l2cap_chan_destroy_t destroy) + bt_l2cap_chan_destroy_t destroy) { - /* Attach channel to the connection */ - sys_slist_append(&conn->channels, &chan->node); - chan->conn = conn; - chan->destroy = destroy; + /* Attach channel to the connection */ + sys_slist_append(&conn->channels, &chan->node); + chan->conn = conn; + chan->destroy = destroy; - BT_DBG("conn %p chan %p", conn, chan); + BT_DBG("conn %p chan %p", conn, chan); } static bool l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, - bt_l2cap_chan_destroy_t destroy) + bt_l2cap_chan_destroy_t destroy) { - struct bt_l2cap_le_chan *ch; + struct bt_l2cap_le_chan *ch; #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) - ch = l2cap_chan_alloc_cid(conn, chan); + ch = l2cap_chan_alloc_cid(conn, chan); #else - ch = BT_L2CAP_LE_CHAN(chan); + ch = BT_L2CAP_LE_CHAN(chan); #endif - if (!ch) { - BT_ERR("Unable to allocate L2CAP CID"); - return false; - } + if (!ch) { + BT_ERR("Unable to allocate L2CAP CID"); + return false; + } - k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout); + k_delayed_work_init(&chan->rtx_work, l2cap_rtx_timeout); - bt_l2cap_chan_add(conn, chan, destroy); + bt_l2cap_chan_add(conn, chan, destroy); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) - if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { - k_work_init(&ch->rx_work, l2cap_rx_process); - k_fifo_init(&ch->rx_queue, 20); - bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT); - } + if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { + k_work_init(&ch->rx_work, l2cap_rx_process); + k_fifo_init(&ch->rx_queue, 20); + bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECT); + } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ - return true; + return true; } void bt_l2cap_connected(struct bt_conn *conn) { #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) - struct bt_l2cap_fixed_chan *fchan; + struct bt_l2cap_fixed_chan *fchan; #endif - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - if (IS_ENABLED(CONFIG_BT_BREDR) && - conn->type == BT_CONN_TYPE_BR) { - bt_l2cap_br_connected(conn); - return; - } + if (IS_ENABLED(CONFIG_BT_BREDR) && + conn->type == BT_CONN_TYPE_BR) { + bt_l2cap_br_connected(conn); + return; + } #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) - SYS_SLIST_FOR_EACH_CONTAINER(&le_channels, fchan, node) { - #else + SYS_SLIST_FOR_EACH_CONTAINER(&le_channels, fchan, node) { + #else Z_STRUCT_SECTION_FOREACH(bt_l2cap_fixed_chan, fchan) { #endif - struct bt_l2cap_le_chan *ch; + struct bt_l2cap_le_chan *ch; - if (fchan->accept(conn, &chan) < 0) { - continue; - } + if (fchan->accept(conn, &chan) < 0) { + continue; + } - ch = BT_L2CAP_LE_CHAN(chan); + ch = BT_L2CAP_LE_CHAN(chan); - /* Fill up remaining fixed channel context attached in - * fchan->accept() - */ - ch->rx.cid = fchan->cid; - ch->tx.cid = fchan->cid; + /* Fill up remaining fixed channel context attached in + * fchan->accept() + */ + ch->rx.cid = fchan->cid; + ch->tx.cid = fchan->cid; - if (!l2cap_chan_add(conn, chan, NULL)) { - return; - } + if (!l2cap_chan_add(conn, chan, NULL)) { + return; + } - if (chan->ops->connected) { - chan->ops->connected(chan); - } + if (chan->ops->connected) { + chan->ops->connected(chan); + } - /* Always set output status to fixed channels */ - atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT); + /* Always set output status to fixed channels */ + atomic_set_bit(chan->status, BT_L2CAP_STATUS_OUT); - if (chan->ops->status) { - chan->ops->status(chan, chan->status); - } - } + if (chan->ops->status) { + chan->ops->status(chan, chan->status); + } + } } void bt_l2cap_disconnected(struct bt_conn *conn) { - struct bt_l2cap_chan *chan, *next; + struct bt_l2cap_chan *chan, *next; - SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node) { - bt_l2cap_chan_del(chan); - } + SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&conn->channels, chan, next, node) { + bt_l2cap_chan_del(chan); + } } static struct net_buf *l2cap_create_le_sig_pdu(struct net_buf *buf, - u8_t code, u8_t ident, - u16_t len) + u8_t code, u8_t ident, + u16_t len) { - struct bt_l2cap_sig_hdr *hdr; + struct bt_l2cap_sig_hdr *hdr; - /* Don't wait more than the minimum RTX timeout of 2 seconds */ - buf = bt_l2cap_create_pdu_timeout(NULL, 0, K_SECONDS(2)); - if (!buf) { - /* If it was not possible to allocate a buffer within the - * timeout return NULL. - */ - BT_ERR("Unable to allocate buffer for op 0x%02x", code); - return NULL; - } + /* Don't wait more than the minimum RTX timeout of 2 seconds */ + buf = bt_l2cap_create_pdu_timeout(NULL, 0, K_SECONDS(2)); + if (!buf) { + /* If it was not possible to allocate a buffer within the + * timeout return NULL. + */ + BT_ERR("Unable to allocate buffer for op 0x%02x", code); + return NULL; + } - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->code = code; - hdr->ident = ident; - hdr->len = sys_cpu_to_le16(len); + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->code = code; + hdr->ident = ident; + hdr->len = sys_cpu_to_le16(len); - return buf; + return buf; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_send_req(struct bt_l2cap_le_chan *chan, - struct net_buf *buf, s32_t timeout) + struct net_buf *buf, s32_t timeout) { - /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126: - * - * The value of this timer is implementation-dependent but the minimum - * initial value is 1 second and the maximum initial value is 60 - * seconds. One RTX timer shall exist for each outstanding signaling - * request, including each Echo Request. The timer disappears on the - * final expiration, when the response is received, or the physical - * link is lost. - */ - if (timeout) { - k_delayed_work_submit(&chan->chan.rtx_work, timeout); - } else { - k_delayed_work_cancel(&chan->chan.rtx_work); - } + /* BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part A] page 126: + * + * The value of this timer is implementation-dependent but the minimum + * initial value is 1 second and the maximum initial value is 60 + * seconds. One RTX timer shall exist for each outstanding signaling + * request, including each Echo Request. The timer disappears on the + * final expiration, when the response is received, or the physical + * link is lost. + */ + if (timeout) { + k_delayed_work_submit(&chan->chan.rtx_work, timeout); + } else { + k_delayed_work_cancel(&chan->chan.rtx_work); + } - bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf); + bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf); } static int l2cap_le_conn_req(struct bt_l2cap_le_chan *ch) { - struct net_buf *buf; - struct bt_l2cap_le_conn_req *req; + struct net_buf *buf; + struct bt_l2cap_le_conn_req *req; - ch->chan.ident = get_ident(); + ch->chan.ident = get_ident(); - buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ, - ch->chan.ident, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_LE_CONN_REQ, + ch->chan.ident, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->psm = sys_cpu_to_le16(ch->chan.psm); - req->scid = sys_cpu_to_le16(ch->rx.cid); - req->mtu = sys_cpu_to_le16(ch->rx.mtu); - req->mps = sys_cpu_to_le16(ch->rx.mps); - req->credits = sys_cpu_to_le16(ch->rx.init_credits); + req = net_buf_add(buf, sizeof(*req)); + req->psm = sys_cpu_to_le16(ch->chan.psm); + req->scid = sys_cpu_to_le16(ch->rx.cid); + req->mtu = sys_cpu_to_le16(ch->rx.mtu); + req->mps = sys_cpu_to_le16(ch->rx.mps); + req->credits = sys_cpu_to_le16(ch->rx.init_credits); - l2cap_chan_send_req(ch, buf, L2CAP_CONN_TIMEOUT); + l2cap_chan_send_req(ch, buf, L2CAP_CONN_TIMEOUT); - return 0; + return 0; } static void l2cap_le_encrypt_change(struct bt_l2cap_chan *chan, u8_t status) { - /* Skip channels already connected or with a pending request */ - if (chan->state != BT_L2CAP_CONNECT || chan->ident) { - return; - } + /* Skip channels already connected or with a pending request */ + if (chan->state != BT_L2CAP_CONNECT || chan->ident) { + return; + } - if (status) { - bt_l2cap_chan_remove(chan->conn, chan); - bt_l2cap_chan_del(chan); - return; - } + if (status) { + bt_l2cap_chan_remove(chan->conn, chan); + bt_l2cap_chan_del(chan); + return; + } - /* Retry to connect */ - l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan)); + /* Retry to connect */ + l2cap_le_conn_req(BT_L2CAP_LE_CHAN(chan)); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status) { - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - if (IS_ENABLED(CONFIG_BT_BREDR) && - conn->type == BT_CONN_TYPE_BR) { - l2cap_br_encrypt_change(conn, hci_status); - return; - } + if (IS_ENABLED(CONFIG_BT_BREDR) && + conn->type == BT_CONN_TYPE_BR) { + l2cap_br_encrypt_change(conn, hci_status); + return; + } - SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { + SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) - l2cap_le_encrypt_change(chan, hci_status); + l2cap_le_encrypt_change(chan, hci_status); #endif - if (chan->ops->encrypt_change) { - chan->ops->encrypt_change(chan, hci_status); - } - } + if (chan->ops->encrypt_change) { + chan->ops->encrypt_change(chan, hci_status); + } + } } struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool, - size_t reserve, s32_t timeout) + size_t reserve, s32_t timeout) { - return bt_conn_create_pdu_timeout(pool, - sizeof(struct bt_l2cap_hdr) + reserve, - timeout); + return bt_conn_create_pdu_timeout(pool, + sizeof(struct bt_l2cap_hdr) + reserve, + timeout); } int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf, - bt_conn_tx_cb_t cb, void *user_data) + bt_conn_tx_cb_t cb, void *user_data) { - struct bt_l2cap_hdr *hdr; + struct bt_l2cap_hdr *hdr; - BT_DBG("conn %p cid %u len %zu", conn, cid, net_buf_frags_len(buf)); + BT_DBG("conn %p cid %u len %zu", conn, cid, net_buf_frags_len(buf)); - hdr = net_buf_push(buf, sizeof(*hdr)); - hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); - hdr->cid = sys_cpu_to_le16(cid); + hdr = net_buf_push(buf, sizeof(*hdr)); + hdr->len = sys_cpu_to_le16(buf->len - sizeof(*hdr)); + hdr->cid = sys_cpu_to_le16(cid); - return bt_conn_send_cb(conn, buf, cb, user_data); + return bt_conn_send_cb(conn, buf, cb, user_data); } static void l2cap_send_reject(struct bt_conn *conn, u8_t ident, - u16_t reason, void *data, u8_t data_len) + u16_t reason, void *data, u8_t data_len) { - struct bt_l2cap_cmd_reject *rej; - struct net_buf *buf; + struct bt_l2cap_cmd_reject *rej; + struct net_buf *buf; - buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident, - sizeof(*rej) + data_len); - if (!buf) { - return; - } + buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CMD_REJECT, ident, + sizeof(*rej) + data_len); + if (!buf) { + return; + } - rej = net_buf_add(buf, sizeof(*rej)); - rej->reason = sys_cpu_to_le16(reason); + rej = net_buf_add(buf, sizeof(*rej)); + rej->reason = sys_cpu_to_le16(reason); - if (data) { - net_buf_add_mem(buf, data, data_len); - } + if (data) { + net_buf_add_mem(buf, data, data_len); + } - bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); + bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static void le_conn_param_rsp(struct bt_l2cap *l2cap, struct net_buf *buf) { - struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data; + struct bt_l2cap_conn_param_rsp *rsp = (void *)buf->data; - if (buf->len < sizeof(*rsp)) { - BT_ERR("Too small LE conn param rsp"); - return; - } + if (buf->len < sizeof(*rsp)) { + BT_ERR("Too small LE conn param rsp"); + return; + } - BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result)); + BT_DBG("LE conn param rsp result %u", sys_le16_to_cpu(rsp->result)); } static void le_conn_param_update_req(struct bt_l2cap *l2cap, u8_t ident, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = l2cap->chan.chan.conn; - struct bt_le_conn_param param; - struct bt_l2cap_conn_param_rsp *rsp; - struct bt_l2cap_conn_param_req *req = (void *)buf->data; - bool accepted; + struct bt_conn *conn = l2cap->chan.chan.conn; + struct bt_le_conn_param param; + struct bt_l2cap_conn_param_rsp *rsp; + struct bt_l2cap_conn_param_req *req = (void *)buf->data; + bool accepted; - if (buf->len < sizeof(*req)) { - BT_ERR("Too small LE conn update param req"); - return; - } + if (buf->len < sizeof(*req)) { + BT_ERR("Too small LE conn update param req"); + return; + } - if (conn->role != BT_HCI_ROLE_MASTER) { - l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, - NULL, 0); - return; - } + if (conn->role != BT_HCI_ROLE_MASTER) { + l2cap_send_reject(conn, ident, BT_L2CAP_REJ_NOT_UNDERSTOOD, + NULL, 0); + return; + } - param.interval_min = sys_le16_to_cpu(req->min_interval); - param.interval_max = sys_le16_to_cpu(req->max_interval); - param.latency = sys_le16_to_cpu(req->latency); - param.timeout = sys_le16_to_cpu(req->timeout); + param.interval_min = sys_le16_to_cpu(req->min_interval); + param.interval_max = sys_le16_to_cpu(req->max_interval); + param.latency = sys_le16_to_cpu(req->latency); + param.timeout = sys_le16_to_cpu(req->timeout); - BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x", - param.interval_min, param.interval_max, param.latency, - param.timeout); + BT_DBG("min 0x%04x max 0x%04x latency: 0x%04x timeout: 0x%04x", + param.interval_min, param.interval_max, param.latency, + param.timeout); - buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident, - sizeof(*rsp)); - if (!buf) { - return; - } + buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_CONN_PARAM_RSP, ident, + sizeof(*rsp)); + if (!buf) { + return; + } - accepted = le_param_req(conn, ¶m); + accepted = le_param_req(conn, ¶m); - rsp = net_buf_add(buf, sizeof(*rsp)); - if (accepted) { - rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED); - } else { - rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED); - } + rsp = net_buf_add(buf, sizeof(*rsp)); + if (accepted) { + rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_ACCEPTED); + } else { + rsp->result = sys_cpu_to_le16(BT_L2CAP_CONN_PARAM_REJECTED); + } - bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); + bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); - if (accepted) { - bt_conn_le_conn_update(conn, ¶m); - } + if (accepted) { + bt_conn_le_conn_update(conn, ¶m); + } } struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn, - u16_t cid) + u16_t cid) { - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { - if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) { - return chan; - } - } + SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { + if (BT_L2CAP_LE_CHAN(chan)->tx.cid == cid) { + return chan; + } + } - return NULL; + return NULL; } struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn, - u16_t cid) + u16_t cid) { - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { - if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { - return chan; - } - } + SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { + if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { + return chan; + } + } - return NULL; + return NULL; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static struct bt_l2cap_server *l2cap_server_lookup_psm(u16_t psm) { - struct bt_l2cap_server *server; + struct bt_l2cap_server *server; - SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node) { - if (server->psm == psm) { - return server; - } - } + SYS_SLIST_FOR_EACH_CONTAINER(&servers, server, node) { + if (server->psm == psm) { + return server; + } + } - return NULL; + return NULL; } int bt_l2cap_server_register(struct bt_l2cap_server *server) { - if (!server->accept) { - return -EINVAL; - } + if (!server->accept) { + return -EINVAL; + } - if (server->psm) { - if (server->psm < L2CAP_LE_PSM_FIXED_START || - server->psm > L2CAP_LE_PSM_DYN_END) { - return -EINVAL; - } + if (server->psm) { + if (server->psm < L2CAP_LE_PSM_FIXED_START || + server->psm > L2CAP_LE_PSM_DYN_END) { + return -EINVAL; + } - /* Check if given PSM is already in use */ - if (l2cap_server_lookup_psm(server->psm)) { - BT_DBG("PSM already registered"); - return -EADDRINUSE; - } - } else { - u16_t psm; + /* Check if given PSM is already in use */ + if (l2cap_server_lookup_psm(server->psm)) { + BT_DBG("PSM already registered"); + return -EADDRINUSE; + } + } else { + u16_t psm; - for (psm = L2CAP_LE_PSM_DYN_START; - psm <= L2CAP_LE_PSM_DYN_END; psm++) { - if (!l2cap_server_lookup_psm(psm)) { - break; - } - } + for (psm = L2CAP_LE_PSM_DYN_START; + psm <= L2CAP_LE_PSM_DYN_END; psm++) { + if (!l2cap_server_lookup_psm(psm)) { + break; + } + } - if (psm > L2CAP_LE_PSM_DYN_END) { - BT_WARN("No free dynamic PSMs available"); - return -EADDRNOTAVAIL; - } + if (psm > L2CAP_LE_PSM_DYN_END) { + BT_WARN("No free dynamic PSMs available"); + return -EADDRNOTAVAIL; + } - BT_DBG("Allocated PSM 0x%04x for new server", psm); - server->psm = psm; - } + BT_DBG("Allocated PSM 0x%04x for new server", psm); + server->psm = psm; + } - if (server->sec_level > BT_SECURITY_L4) { - return -EINVAL; - } else if (server->sec_level < BT_SECURITY_L1) { - /* Level 0 is only applicable for BR/EDR */ - server->sec_level = BT_SECURITY_L1; - } + if (server->sec_level > BT_SECURITY_L4) { + return -EINVAL; + } else if (server->sec_level < BT_SECURITY_L1) { + /* Level 0 is only applicable for BR/EDR */ + server->sec_level = BT_SECURITY_L1; + } - BT_DBG("PSM 0x%04x", server->psm); + BT_DBG("PSM 0x%04x", server->psm); - sys_slist_append(&servers, &server->node); + sys_slist_append(&servers, &server->node); - return 0; + return 0; } static void l2cap_chan_rx_init(struct bt_l2cap_le_chan *chan) { - BT_DBG("chan %p", chan); + BT_DBG("chan %p", chan); - /* Use existing MTU if defined */ - if (!chan->rx.mtu) { - chan->rx.mtu = L2CAP_MAX_LE_MTU; - } + /* Use existing MTU if defined */ + if (!chan->rx.mtu) { + chan->rx.mtu = L2CAP_MAX_LE_MTU; + } - /* Use existing credits if defined */ - if (!chan->rx.init_credits) { - if (chan->chan.ops->alloc_buf) { - /* Auto tune credits to receive a full packet */ - chan->rx.init_credits = (chan->rx.mtu + - (L2CAP_MAX_LE_MPS - 1)) / - L2CAP_MAX_LE_MPS; - } else { - chan->rx.init_credits = L2CAP_LE_MAX_CREDITS; - } - } + /* Use existing credits if defined */ + if (!chan->rx.init_credits) { + if (chan->chan.ops->alloc_buf) { + /* Auto tune credits to receive a full packet */ + chan->rx.init_credits = (chan->rx.mtu + + (L2CAP_MAX_LE_MPS - 1)) / + L2CAP_MAX_LE_MPS; + } else { + chan->rx.init_credits = L2CAP_LE_MAX_CREDITS; + } + } - /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot - * be used. - */ - chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS); - k_sem_init(&chan->rx.credits, 0, BT_UINT_MAX); + /* MPS shall not be bigger than MTU + 2 as the remaining bytes cannot + * be used. + */ + chan->rx.mps = MIN(chan->rx.mtu + 2, L2CAP_MAX_LE_MPS); + k_sem_init(&chan->rx.credits, 0, BT_UINT_MAX); - if (BT_DBG_ENABLED && - chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) { - BT_WARN("Not enough credits for a full packet"); - } + if (BT_DBG_ENABLED && + chan->rx.init_credits * chan->rx.mps < chan->rx.mtu + 2) { + BT_WARN("Not enough credits for a full packet"); + } } static void l2cap_chan_tx_init(struct bt_l2cap_le_chan *chan) { - BT_DBG("chan %p", chan); + BT_DBG("chan %p", chan); - (void)memset(&chan->tx, 0, sizeof(chan->tx)); - k_sem_init(&chan->tx.credits, 0, BT_UINT_MAX); - k_fifo_init(&chan->tx_queue, 20); + (void)memset(&chan->tx, 0, sizeof(chan->tx)); + k_sem_init(&chan->tx.credits, 0, BT_UINT_MAX); + k_fifo_init(&chan->tx_queue, 20); } static void l2cap_chan_tx_give_credits(struct bt_l2cap_le_chan *chan, - u16_t credits) + u16_t credits) { - BT_DBG("chan %p credits %u", chan, credits); + BT_DBG("chan %p credits %u", chan, credits); - while (credits--) { - k_sem_give(&chan->tx.credits); - } + while (credits--) { + k_sem_give(&chan->tx.credits); + } - if (atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) && - chan->chan.ops->status) { - chan->chan.ops->status(&chan->chan, chan->chan.status); - } + if (atomic_test_and_set_bit(chan->chan.status, BT_L2CAP_STATUS_OUT) && + chan->chan.ops->status) { + chan->chan.ops->status(&chan->chan, chan->chan.status); + } } static void l2cap_chan_rx_give_credits(struct bt_l2cap_le_chan *chan, - u16_t credits) + u16_t credits) { - BT_DBG("chan %p credits %u", chan, credits); + BT_DBG("chan %p credits %u", chan, credits); - while (credits--) { - k_sem_give(&chan->rx.credits); - } + while (credits--) { + k_sem_give(&chan->rx.credits); + } } static void l2cap_chan_destroy(struct bt_l2cap_chan *chan) { - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - struct net_buf *buf; + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + struct net_buf *buf; - BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid); + BT_DBG("chan %p cid 0x%04x", ch, ch->rx.cid); - /* Cancel ongoing work */ - k_delayed_work_cancel(&chan->rtx_work); + /* Cancel ongoing work */ + k_delayed_work_cancel(&chan->rtx_work); - if (ch->tx_buf) { - net_buf_unref(ch->tx_buf); - ch->tx_buf = NULL; - } + if (ch->tx_buf) { + net_buf_unref(ch->tx_buf); + ch->tx_buf = NULL; + } - /* Remove buffers on the TX queue */ - while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) { - net_buf_unref(buf); - } + /* Remove buffers on the TX queue */ + while ((buf = net_buf_get(&ch->tx_queue, K_NO_WAIT))) { + net_buf_unref(buf); + } - /* Remove buffers on the RX queue */ - while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { - net_buf_unref(buf); - } + /* Remove buffers on the RX queue */ + while ((buf = net_buf_get(&ch->rx_queue, K_NO_WAIT))) { + net_buf_unref(buf); + } - /* Destroy segmented SDU if it exists */ - if (ch->_sdu) { - net_buf_unref(ch->_sdu); - ch->_sdu = NULL; - ch->_sdu_len = 0U; - } + /* Destroy segmented SDU if it exists */ + if (ch->_sdu) { + net_buf_unref(ch->_sdu); + ch->_sdu = NULL; + ch->_sdu_len = 0U; + } } static u16_t le_err_to_result(int err) { - switch (err) { - case -ENOMEM: - return BT_L2CAP_LE_ERR_NO_RESOURCES; - case -EACCES: - return BT_L2CAP_LE_ERR_AUTHORIZATION; - case -EPERM: - return BT_L2CAP_LE_ERR_KEY_SIZE; - case -ENOTSUP: - /* This handle the cases where a fixed channel is registered but - * for some reason (e.g. controller not suporting a feature) - * cannot be used. - */ - return BT_L2CAP_LE_ERR_PSM_NOT_SUPP; - default: - return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS; - } + switch (err) { + case -ENOMEM: + return BT_L2CAP_LE_ERR_NO_RESOURCES; + case -EACCES: + return BT_L2CAP_LE_ERR_AUTHORIZATION; + case -EPERM: + return BT_L2CAP_LE_ERR_KEY_SIZE; + case -ENOTSUP: + /* This handle the cases where a fixed channel is registered but + * for some reason (e.g. controller not suporting a feature) + * cannot be used. + */ + return BT_L2CAP_LE_ERR_PSM_NOT_SUPP; + default: + return BT_L2CAP_LE_ERR_UNACCEPT_PARAMS; + } } static void le_conn_req(struct bt_l2cap *l2cap, u8_t ident, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = l2cap->chan.chan.conn; - struct bt_l2cap_chan *chan; - struct bt_l2cap_server *server; - struct bt_l2cap_le_conn_req *req = (void *)buf->data; - struct bt_l2cap_le_conn_rsp *rsp; - u16_t psm, scid, mtu, mps, credits; - int err; + struct bt_conn *conn = l2cap->chan.chan.conn; + struct bt_l2cap_chan *chan; + struct bt_l2cap_server *server; + struct bt_l2cap_le_conn_req *req = (void *)buf->data; + struct bt_l2cap_le_conn_rsp *rsp; + u16_t psm, scid, mtu, mps, credits; + int err; - if (buf->len < sizeof(*req)) { - BT_ERR("Too small LE conn req packet size"); - return; - } + if (buf->len < sizeof(*req)) { + BT_ERR("Too small LE conn req packet size"); + return; + } - psm = sys_le16_to_cpu(req->psm); - scid = sys_le16_to_cpu(req->scid); - mtu = sys_le16_to_cpu(req->mtu); - mps = sys_le16_to_cpu(req->mps); - credits = sys_le16_to_cpu(req->credits); + psm = sys_le16_to_cpu(req->psm); + scid = sys_le16_to_cpu(req->scid); + mtu = sys_le16_to_cpu(req->mtu); + mps = sys_le16_to_cpu(req->mps); + credits = sys_le16_to_cpu(req->credits); - BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid, - mtu, mps, credits); + BT_DBG("psm 0x%02x scid 0x%04x mtu %u mps %u credits %u", psm, scid, + mtu, mps, credits); - if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) { - BT_ERR("Invalid LE-Conn Req params"); - return; - } + if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MTU) { + BT_ERR("Invalid LE-Conn Req params"); + return; + } - buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident, - sizeof(*rsp)); - if (!buf) { - return; - } + buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CONN_RSP, ident, + sizeof(*rsp)); + if (!buf) { + return; + } - rsp = net_buf_add(buf, sizeof(*rsp)); - (void)memset(rsp, 0, sizeof(*rsp)); + rsp = net_buf_add(buf, sizeof(*rsp)); + (void)memset(rsp, 0, sizeof(*rsp)); - /* Check if there is a server registered */ - server = l2cap_server_lookup_psm(psm); - if (!server) { - rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP); - goto rsp; - } + /* Check if there is a server registered */ + server = l2cap_server_lookup_psm(psm); + if (!server) { + rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_PSM_NOT_SUPP); + goto rsp; + } - /* Check if connection has minimum required security level */ + /* Check if connection has minimum required security level */ #if defined(CONFIG_BT_SMP) - if (conn->sec_level < server->sec_level) { - rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION); - goto rsp; - } + if (conn->sec_level < server->sec_level) { + rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_AUTHENTICATION); + goto rsp; + } #endif - - if (!L2CAP_LE_CID_IS_DYN(scid)) { - rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_INVALID_SCID); - goto rsp; - } - chan = bt_l2cap_le_lookup_tx_cid(conn, scid); - if (chan) { - rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_SCID_IN_USE); - goto rsp; - } + if (!L2CAP_LE_CID_IS_DYN(scid)) { + rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_INVALID_SCID); + goto rsp; + } - /* Request server to accept the new connection and allocate the - * channel. - */ - err = server->accept(conn, &chan); - if (err < 0) { - rsp->result = sys_cpu_to_le16(le_err_to_result(err)); - goto rsp; - } + chan = bt_l2cap_le_lookup_tx_cid(conn, scid); + if (chan) { + rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_SCID_IN_USE); + goto rsp; + } - chan->required_sec_level = server->sec_level; + /* Request server to accept the new connection and allocate the + * channel. + */ + err = server->accept(conn, &chan); + if (err < 0) { + rsp->result = sys_cpu_to_le16(le_err_to_result(err)); + goto rsp; + } - if (l2cap_chan_add(conn, chan, l2cap_chan_destroy)) { - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + chan->required_sec_level = server->sec_level; - /* Init TX parameters */ - l2cap_chan_tx_init(ch); - ch->tx.cid = scid; - ch->tx.mps = mps; - ch->tx.mtu = mtu; - ch->tx.init_credits = credits; - l2cap_chan_tx_give_credits(ch, credits); + if (l2cap_chan_add(conn, chan, l2cap_chan_destroy)) { + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - /* Init RX parameters */ - l2cap_chan_rx_init(ch); - l2cap_chan_rx_give_credits(ch, ch->rx.init_credits); + /* Init TX parameters */ + l2cap_chan_tx_init(ch); + ch->tx.cid = scid; + ch->tx.mps = mps; + ch->tx.mtu = mtu; + ch->tx.init_credits = credits; + l2cap_chan_tx_give_credits(ch, credits); - /* Set channel PSM */ - chan->psm = server->psm; + /* Init RX parameters */ + l2cap_chan_rx_init(ch); + l2cap_chan_rx_give_credits(ch, ch->rx.init_credits); - /* Update state */ - bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED); + /* Set channel PSM */ + chan->psm = server->psm; - if (chan->ops->connected) { - chan->ops->connected(chan); - } + /* Update state */ + bt_l2cap_chan_set_state(chan, BT_L2CAP_CONNECTED); - /* Prepare response protocol data */ - rsp->dcid = sys_cpu_to_le16(ch->rx.cid); - rsp->mps = sys_cpu_to_le16(ch->rx.mps); - rsp->mtu = sys_cpu_to_le16(ch->rx.mtu); - rsp->credits = sys_cpu_to_le16(ch->rx.init_credits); - rsp->result = BT_L2CAP_LE_SUCCESS; - } else { - rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_NO_RESOURCES); - } + if (chan->ops->connected) { + chan->ops->connected(chan); + } + + /* Prepare response protocol data */ + rsp->dcid = sys_cpu_to_le16(ch->rx.cid); + rsp->mps = sys_cpu_to_le16(ch->rx.mps); + rsp->mtu = sys_cpu_to_le16(ch->rx.mtu); + rsp->credits = sys_cpu_to_le16(ch->rx.init_credits); + rsp->result = BT_L2CAP_LE_SUCCESS; + } else { + rsp->result = sys_cpu_to_le16(BT_L2CAP_LE_ERR_NO_RESOURCES); + } rsp: - bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); + bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } static struct bt_l2cap_le_chan *l2cap_remove_rx_cid(struct bt_conn *conn, - u16_t cid) + u16_t cid) { - struct bt_l2cap_chan *chan; - sys_snode_t *prev = NULL; + struct bt_l2cap_chan *chan; + sys_snode_t *prev = NULL; - /* Protect fixed channels against accidental removal */ - if (!L2CAP_LE_CID_IS_DYN(cid)) { - return NULL; - } + /* Protect fixed channels against accidental removal */ + if (!L2CAP_LE_CID_IS_DYN(cid)) { + return NULL; + } - SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { - if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { - sys_slist_remove(&conn->channels, prev, &chan->node); - return BT_L2CAP_LE_CHAN(chan); - } + SYS_SLIST_FOR_EACH_CONTAINER(&conn->channels, chan, node) { + if (BT_L2CAP_LE_CHAN(chan)->rx.cid == cid) { + sys_slist_remove(&conn->channels, prev, &chan->node); + return BT_L2CAP_LE_CHAN(chan); + } - prev = &chan->node; - } + prev = &chan->node; + } - return NULL; + return NULL; } static void le_disconn_req(struct bt_l2cap *l2cap, u8_t ident, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = l2cap->chan.chan.conn; - struct bt_l2cap_le_chan *chan; - struct bt_l2cap_disconn_req *req = (void *)buf->data; - struct bt_l2cap_disconn_rsp *rsp; - u16_t dcid; + struct bt_conn *conn = l2cap->chan.chan.conn; + struct bt_l2cap_le_chan *chan; + struct bt_l2cap_disconn_req *req = (void *)buf->data; + struct bt_l2cap_disconn_rsp *rsp; + u16_t dcid; - if (buf->len < sizeof(*req)) { - BT_ERR("Too small LE conn req packet size"); - return; - } + if (buf->len < sizeof(*req)) { + BT_ERR("Too small LE conn req packet size"); + return; + } - dcid = sys_le16_to_cpu(req->dcid); + dcid = sys_le16_to_cpu(req->dcid); - BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid)); + BT_DBG("dcid 0x%04x scid 0x%04x", dcid, sys_le16_to_cpu(req->scid)); - chan = l2cap_remove_rx_cid(conn, dcid); - if (!chan) { - struct bt_l2cap_cmd_reject_cid_data data; + chan = l2cap_remove_rx_cid(conn, dcid); + if (!chan) { + struct bt_l2cap_cmd_reject_cid_data data; - data.scid = req->scid; - data.dcid = req->dcid; + data.scid = req->scid; + data.dcid = req->dcid; - l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, - sizeof(data)); - return; - } + l2cap_send_reject(conn, ident, BT_L2CAP_REJ_INVALID_CID, &data, + sizeof(data)); + return; + } - buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident, - sizeof(*rsp)); - if (!buf) { - return; - } + buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_DISCONN_RSP, ident, + sizeof(*rsp)); + if (!buf) { + return; + } - rsp = net_buf_add(buf, sizeof(*rsp)); - rsp->dcid = sys_cpu_to_le16(chan->rx.cid); - rsp->scid = sys_cpu_to_le16(chan->tx.cid); + rsp = net_buf_add(buf, sizeof(*rsp)); + rsp->dcid = sys_cpu_to_le16(chan->rx.cid); + rsp->scid = sys_cpu_to_le16(chan->tx.cid); - bt_l2cap_chan_del(&chan->chan); + bt_l2cap_chan_del(&chan->chan); - bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); + bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); } #if defined(CONFIG_BT_SMP) static int l2cap_change_security(struct bt_l2cap_le_chan *chan, u16_t err) { - switch (err) { - case BT_L2CAP_LE_ERR_ENCRYPTION: - if (chan->chan.required_sec_level >= BT_SECURITY_L2) { - return -EALREADY; - } - chan->chan.required_sec_level = BT_SECURITY_L2; - break; - case BT_L2CAP_LE_ERR_AUTHENTICATION: - if (chan->chan.required_sec_level < BT_SECURITY_L2) { - chan->chan.required_sec_level = BT_SECURITY_L2; - } else if (chan->chan.required_sec_level < BT_SECURITY_L3) { - chan->chan.required_sec_level = BT_SECURITY_L3; - } else if (chan->chan.required_sec_level < BT_SECURITY_L4) { - chan->chan.required_sec_level = BT_SECURITY_L4; - } else { - return -EALREADY; - } - break; - default: - return -EINVAL; - } + switch (err) { + case BT_L2CAP_LE_ERR_ENCRYPTION: + if (chan->chan.required_sec_level >= BT_SECURITY_L2) { + return -EALREADY; + } + chan->chan.required_sec_level = BT_SECURITY_L2; + break; + case BT_L2CAP_LE_ERR_AUTHENTICATION: + if (chan->chan.required_sec_level < BT_SECURITY_L2) { + chan->chan.required_sec_level = BT_SECURITY_L2; + } else if (chan->chan.required_sec_level < BT_SECURITY_L3) { + chan->chan.required_sec_level = BT_SECURITY_L3; + } else if (chan->chan.required_sec_level < BT_SECURITY_L4) { + chan->chan.required_sec_level = BT_SECURITY_L4; + } else { + return -EALREADY; + } + break; + default: + return -EINVAL; + } - return bt_conn_set_security(chan->chan.conn, - chan->chan.required_sec_level); + return bt_conn_set_security(chan->chan.conn, + chan->chan.required_sec_level); } #endif //CONFIG_BT_SMP static void le_conn_rsp(struct bt_l2cap *l2cap, u8_t ident, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = l2cap->chan.chan.conn; - struct bt_l2cap_le_chan *chan; - struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data; - u16_t dcid, mtu, mps, credits, result; + struct bt_conn *conn = l2cap->chan.chan.conn; + struct bt_l2cap_le_chan *chan; + struct bt_l2cap_le_conn_rsp *rsp = (void *)buf->data; + u16_t dcid, mtu, mps, credits, result; - if (buf->len < sizeof(*rsp)) { - BT_ERR("Too small LE conn rsp packet size"); - return; - } + if (buf->len < sizeof(*rsp)) { + BT_ERR("Too small LE conn rsp packet size"); + return; + } - dcid = sys_le16_to_cpu(rsp->dcid); - mtu = sys_le16_to_cpu(rsp->mtu); - mps = sys_le16_to_cpu(rsp->mps); - credits = sys_le16_to_cpu(rsp->credits); - result = sys_le16_to_cpu(rsp->result); + dcid = sys_le16_to_cpu(rsp->dcid); + mtu = sys_le16_to_cpu(rsp->mtu); + mps = sys_le16_to_cpu(rsp->mps); + credits = sys_le16_to_cpu(rsp->credits); + result = sys_le16_to_cpu(rsp->result); - BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid, - mtu, mps, credits, result); + BT_DBG("dcid 0x%04x mtu %u mps %u credits %u result 0x%04x", dcid, + mtu, mps, credits, result); - /* Keep the channel in case of security errors */ - if (result == BT_L2CAP_LE_SUCCESS || - result == BT_L2CAP_LE_ERR_AUTHENTICATION || - result == BT_L2CAP_LE_ERR_ENCRYPTION) { - chan = l2cap_lookup_ident(conn, ident); - } else { - chan = l2cap_remove_ident(conn, ident); - } + /* Keep the channel in case of security errors */ + if (result == BT_L2CAP_LE_SUCCESS || + result == BT_L2CAP_LE_ERR_AUTHENTICATION || + result == BT_L2CAP_LE_ERR_ENCRYPTION) { + chan = l2cap_lookup_ident(conn, ident); + } else { + chan = l2cap_remove_ident(conn, ident); + } - if (!chan) { - BT_ERR("Cannot find channel for ident %u", ident); - return; - } + if (!chan) { + BT_ERR("Cannot find channel for ident %u", ident); + return; + } - /* Cancel RTX work */ - k_delayed_work_cancel(&chan->chan.rtx_work); + /* Cancel RTX work */ + k_delayed_work_cancel(&chan->chan.rtx_work); - /* Reset ident since it got a response */ - chan->chan.ident = 0U; + /* Reset ident since it got a response */ + chan->chan.ident = 0U; - switch (result) { - case BT_L2CAP_LE_SUCCESS: - chan->tx.cid = dcid; - chan->tx.mtu = mtu; - chan->tx.mps = mps; + switch (result) { + case BT_L2CAP_LE_SUCCESS: + chan->tx.cid = dcid; + chan->tx.mtu = mtu; + chan->tx.mps = mps; - /* Update state */ - bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED); + /* Update state */ + bt_l2cap_chan_set_state(&chan->chan, BT_L2CAP_CONNECTED); - if (chan->chan.ops->connected) { - chan->chan.ops->connected(&chan->chan); - } + if (chan->chan.ops->connected) { + chan->chan.ops->connected(&chan->chan); + } - /* Give credits */ - l2cap_chan_tx_give_credits(chan, credits); - l2cap_chan_rx_give_credits(chan, chan->rx.init_credits); + /* Give credits */ + l2cap_chan_tx_give_credits(chan, credits); + l2cap_chan_rx_give_credits(chan, chan->rx.init_credits); - break; - case BT_L2CAP_LE_ERR_AUTHENTICATION: - case BT_L2CAP_LE_ERR_ENCRYPTION: + break; + case BT_L2CAP_LE_ERR_AUTHENTICATION: + case BT_L2CAP_LE_ERR_ENCRYPTION: #if defined(CONFIG_BT_SMP) - /* If security needs changing wait it to be completed */ - if (l2cap_change_security(chan, result) == 0) { - return; - } + /* If security needs changing wait it to be completed */ + if (l2cap_change_security(chan, result) == 0) { + return; + } #endif - bt_l2cap_chan_remove(conn, &chan->chan); + bt_l2cap_chan_remove(conn, &chan->chan); __attribute__((fallthrough)); - default: - bt_l2cap_chan_del(&chan->chan); - } + default: + bt_l2cap_chan_del(&chan->chan); + } } static void le_disconn_rsp(struct bt_l2cap *l2cap, u8_t ident, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = l2cap->chan.chan.conn; - struct bt_l2cap_le_chan *chan; - struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data; - u16_t scid; + struct bt_conn *conn = l2cap->chan.chan.conn; + struct bt_l2cap_le_chan *chan; + struct bt_l2cap_disconn_rsp *rsp = (void *)buf->data; + u16_t scid; - if (buf->len < sizeof(*rsp)) { - BT_ERR("Too small LE disconn rsp packet size"); - return; - } + if (buf->len < sizeof(*rsp)) { + BT_ERR("Too small LE disconn rsp packet size"); + return; + } - scid = sys_le16_to_cpu(rsp->scid); + scid = sys_le16_to_cpu(rsp->scid); - BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid); + BT_DBG("dcid 0x%04x scid 0x%04x", sys_le16_to_cpu(rsp->dcid), scid); - chan = l2cap_remove_rx_cid(conn, scid); - if (!chan) { - return; - } + chan = l2cap_remove_rx_cid(conn, scid); + if (!chan) { + return; + } - bt_l2cap_chan_del(&chan->chan); + bt_l2cap_chan_del(&chan->chan); } static inline struct net_buf *l2cap_alloc_seg(struct net_buf *buf) { - struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); - struct net_buf *seg; + struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id); + struct net_buf *seg; - /* Try to use original pool if possible */ - seg = net_buf_alloc(pool, K_NO_WAIT); - if (seg) { - net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE); - return seg; - } + /* Try to use original pool if possible */ + seg = net_buf_alloc(pool, K_NO_WAIT); + if (seg) { + net_buf_reserve(seg, BT_L2CAP_CHAN_SEND_RESERVE); + return seg; + } - /* Fallback to using global connection tx pool */ - return bt_l2cap_create_pdu(NULL, 0); + /* Fallback to using global connection tx pool */ + return bt_l2cap_create_pdu(NULL, 0); } static struct net_buf *l2cap_chan_create_seg(struct bt_l2cap_le_chan *ch, - struct net_buf *buf, - size_t sdu_hdr_len) + struct net_buf *buf, + size_t sdu_hdr_len) { - struct net_buf *seg; - u16_t headroom; - u16_t len; + struct net_buf *seg; + u16_t headroom; + u16_t len; - /* Segment if data (+ data headroom) is bigger than MPS */ - if (buf->len + sdu_hdr_len > ch->tx.mps) { - goto segment; - } + /* Segment if data (+ data headroom) is bigger than MPS */ + if (buf->len + sdu_hdr_len > ch->tx.mps) { + goto segment; + } - headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len; + headroom = BT_L2CAP_CHAN_SEND_RESERVE + sdu_hdr_len; - /* Check if original buffer has enough headroom and don't have any - * fragments. - */ - if (net_buf_headroom(buf) >= headroom && !buf->frags) { - if (sdu_hdr_len) { - /* Push SDU length if set */ - net_buf_push_le16(buf, net_buf_frags_len(buf)); - } - return net_buf_ref(buf); - } + /* Check if original buffer has enough headroom and don't have any + * fragments. + */ + if (net_buf_headroom(buf) >= headroom && !buf->frags) { + if (sdu_hdr_len) { + /* Push SDU length if set */ + net_buf_push_le16(buf, net_buf_frags_len(buf)); + } + return net_buf_ref(buf); + } segment: - seg = l2cap_alloc_seg(buf); - if (!seg) { - return NULL; - } + seg = l2cap_alloc_seg(buf); + if (!seg) { + return NULL; + } - if (sdu_hdr_len) { - net_buf_add_le16(seg, net_buf_frags_len(buf)); - } + if (sdu_hdr_len) { + net_buf_add_le16(seg, net_buf_frags_len(buf)); + } - /* Don't send more that TX MPS including SDU length */ - len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len); - /* Limit if original buffer is smaller than the segment */ - len = MIN(buf->len, len); - net_buf_add_mem(seg, buf->data, len); - net_buf_pull(buf, len); + /* Don't send more that TX MPS including SDU length */ + len = MIN(net_buf_tailroom(seg), ch->tx.mps - sdu_hdr_len); + /* Limit if original buffer is smaller than the segment */ + len = MIN(buf->len, len); + net_buf_add_mem(seg, buf->data, len); + net_buf_pull(buf, len); - BT_DBG("ch %p seg %p len %u", ch, seg, seg->len); + BT_DBG("ch %p seg %p len %u", ch, seg, seg->len); - return seg; + return seg; } void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data) { - struct bt_l2cap_chan *chan = user_data; + struct bt_l2cap_chan *chan = user_data; - BT_DBG("conn %p chan %p", conn, chan); + BT_DBG("conn %p chan %p", conn, chan); - if (chan->ops->sent) { - chan->ops->sent(chan); - } + if (chan->ops->sent) { + chan->ops->sent(chan); + } } static int l2cap_chan_le_send(struct bt_l2cap_le_chan *ch, struct net_buf *buf, - u16_t sdu_hdr_len) + u16_t sdu_hdr_len) { - struct net_buf *seg; - int len; + struct net_buf *seg; + int len; - /* Wait for credits */ - if (k_sem_take(&ch->tx.credits, K_NO_WAIT)) { - BT_DBG("No credits to transmit packet"); - return -EAGAIN; - } + /* Wait for credits */ + if (k_sem_take(&ch->tx.credits, K_NO_WAIT)) { + BT_DBG("No credits to transmit packet"); + return -EAGAIN; + } - seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len); - if (!seg) { - return -ENOMEM; - } + seg = l2cap_chan_create_seg(ch, buf, sdu_hdr_len); + if (!seg) { + return -ENOMEM; + } - /* Channel may have been disconnected while waiting for a buffer */ - if (!ch->chan.conn) { - net_buf_unref(buf); - return -ECONNRESET; - } + /* Channel may have been disconnected while waiting for a buffer */ + if (!ch->chan.conn) { + net_buf_unref(buf); + return -ECONNRESET; + } - BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid, - seg->len, k_sem_count_get(&ch->tx.credits)); + BT_DBG("ch %p cid 0x%04x len %u credits %u", ch, ch->tx.cid, + seg->len, k_sem_count_get(&ch->tx.credits)); - len = seg->len - sdu_hdr_len; + len = seg->len - sdu_hdr_len; - /* Set a callback if there is no data left in the buffer and sent - * callback has been set. - */ - if ((buf == seg || !buf->len) && ch->chan.ops->sent) { - bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, - l2cap_chan_sdu_sent, &ch->chan); - } else { - bt_l2cap_send(ch->chan.conn, ch->tx.cid, seg); - } + /* Set a callback if there is no data left in the buffer and sent + * callback has been set. + */ + if ((buf == seg || !buf->len) && ch->chan.ops->sent) { + bt_l2cap_send_cb(ch->chan.conn, ch->tx.cid, seg, + l2cap_chan_sdu_sent, &ch->chan); + } else { + bt_l2cap_send(ch->chan.conn, ch->tx.cid, seg); + } - /* Check if there is no credits left clear output status and notify its - * change. - */ - if (!k_sem_count_get(&ch->tx.credits)) { - atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT); - if (ch->chan.ops->status) { - ch->chan.ops->status(&ch->chan, ch->chan.status); - } - } + /* Check if there is no credits left clear output status and notify its + * change. + */ + if (!k_sem_count_get(&ch->tx.credits)) { + atomic_clear_bit(ch->chan.status, BT_L2CAP_STATUS_OUT); + if (ch->chan.ops->status) { + ch->chan.ops->status(&ch->chan, ch->chan.status); + } + } - return len; + return len; } static int l2cap_chan_le_send_sdu(struct bt_l2cap_le_chan *ch, - struct net_buf **buf, u16_t sent) + struct net_buf **buf, u16_t sent) { - int ret, total_len; - struct net_buf *frag; + int ret, total_len; + struct net_buf *frag; - total_len = net_buf_frags_len(*buf) + sent; + total_len = net_buf_frags_len(*buf) + sent; - if (total_len > ch->tx.mtu) { - return -EMSGSIZE; - } + if (total_len > ch->tx.mtu) { + return -EMSGSIZE; + } - frag = *buf; - if (!frag->len && frag->frags) { - frag = frag->frags; - } + frag = *buf; + if (!frag->len && frag->frags) { + frag = frag->frags; + } - if (!sent) { - /* Add SDU length for the first segment */ - ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN); - if (ret < 0) { - if (ret == -EAGAIN) { - /* Store sent data into user_data */ - memcpy(net_buf_user_data(frag), &sent, - sizeof(sent)); - } - *buf = frag; - return ret; - } - sent = ret; - } + if (!sent) { + /* Add SDU length for the first segment */ + ret = l2cap_chan_le_send(ch, frag, BT_L2CAP_SDU_HDR_LEN); + if (ret < 0) { + if (ret == -EAGAIN) { + /* Store sent data into user_data */ + memcpy(net_buf_user_data(frag), &sent, + sizeof(sent)); + } + *buf = frag; + return ret; + } + sent = ret; + } - /* Send remaining segments */ - for (ret = 0; sent < total_len; sent += ret) { - /* Proceed to next fragment */ - if (!frag->len) { - frag = net_buf_frag_del(NULL, frag); - } + /* Send remaining segments */ + for (ret = 0; sent < total_len; sent += ret) { + /* Proceed to next fragment */ + if (!frag->len) { + frag = net_buf_frag_del(NULL, frag); + } - ret = l2cap_chan_le_send(ch, frag, 0); - if (ret < 0) { - if (ret == -EAGAIN) { - /* Store sent data into user_data */ - memcpy(net_buf_user_data(frag), &sent, - sizeof(sent)); - } - *buf = frag; - return ret; - } - } + ret = l2cap_chan_le_send(ch, frag, 0); + if (ret < 0) { + if (ret == -EAGAIN) { + /* Store sent data into user_data */ + memcpy(net_buf_user_data(frag), &sent, + sizeof(sent)); + } + *buf = frag; + return ret; + } + } - BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent, - total_len); + BT_DBG("ch %p cid 0x%04x sent %u total_len %u", ch, ch->tx.cid, sent, + total_len); - net_buf_unref(frag); + net_buf_unref(frag); - return ret; + return ret; } static struct net_buf *l2cap_chan_le_get_tx_buf(struct bt_l2cap_le_chan *ch) { - struct net_buf *buf; + struct net_buf *buf; - /* Return current buffer */ - if (ch->tx_buf) { - buf = ch->tx_buf; - ch->tx_buf = NULL; - return buf; - } + /* Return current buffer */ + if (ch->tx_buf) { + buf = ch->tx_buf; + ch->tx_buf = NULL; + return buf; + } - return net_buf_get(&ch->tx_queue, K_NO_WAIT); + return net_buf_get(&ch->tx_queue, K_NO_WAIT); } static void l2cap_chan_le_send_resume(struct bt_l2cap_le_chan *ch) { - struct net_buf *buf; + struct net_buf *buf; - /* Resume tx in case there are buffers in the queue */ - while ((buf = l2cap_chan_le_get_tx_buf(ch))) { - #if defined(BFLB_BLE) - int sent = *((int *)net_buf_user_data(buf)); - #else - u16_t sent = *((u16_t *)net_buf_user_data(buf)); - #endif + /* Resume tx in case there are buffers in the queue */ + while ((buf = l2cap_chan_le_get_tx_buf(ch))) { + #if defined(BFLB_BLE) + int sent = *((int *)net_buf_user_data(buf)); + #else + u16_t sent = *((u16_t *)net_buf_user_data(buf)); + #endif - BT_DBG("buf %p sent %u", buf, sent); - - sent = l2cap_chan_le_send_sdu(ch, &buf, sent); - if (sent < 0) { - if (sent == -EAGAIN) { - ch->tx_buf = buf; - } - break; - } - } + BT_DBG("buf %p sent %u", buf, sent); + + sent = l2cap_chan_le_send_sdu(ch, &buf, sent); + if (sent < 0) { + if (sent == -EAGAIN) { + ch->tx_buf = buf; + } + break; + } + } } static void le_credits(struct bt_l2cap *l2cap, u8_t ident, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = l2cap->chan.chan.conn; - struct bt_l2cap_chan *chan; - struct bt_l2cap_le_credits *ev = (void *)buf->data; - struct bt_l2cap_le_chan *ch; - u16_t credits, cid; + struct bt_conn *conn = l2cap->chan.chan.conn; + struct bt_l2cap_chan *chan; + struct bt_l2cap_le_credits *ev = (void *)buf->data; + struct bt_l2cap_le_chan *ch; + u16_t credits, cid; - if (buf->len < sizeof(*ev)) { - BT_ERR("Too small LE Credits packet size"); - return; - } + if (buf->len < sizeof(*ev)) { + BT_ERR("Too small LE Credits packet size"); + return; + } - cid = sys_le16_to_cpu(ev->cid); - credits = sys_le16_to_cpu(ev->credits); + cid = sys_le16_to_cpu(ev->cid); + credits = sys_le16_to_cpu(ev->credits); - BT_DBG("cid 0x%04x credits %u", cid, credits); + BT_DBG("cid 0x%04x credits %u", cid, credits); - chan = bt_l2cap_le_lookup_tx_cid(conn, cid); - if (!chan) { - BT_ERR("Unable to find channel of LE Credits packet"); - return; - } + chan = bt_l2cap_le_lookup_tx_cid(conn, cid); + if (!chan) { + BT_ERR("Unable to find channel of LE Credits packet"); + return; + } - ch = BT_L2CAP_LE_CHAN(chan); + ch = BT_L2CAP_LE_CHAN(chan); - if (k_sem_count_get(&ch->tx.credits) + credits > UINT16_MAX) { - BT_ERR("Credits overflow"); - bt_l2cap_chan_disconnect(chan); - return; - } + if (k_sem_count_get(&ch->tx.credits) + credits > UINT16_MAX) { + BT_ERR("Credits overflow"); + bt_l2cap_chan_disconnect(chan); + return; + } - l2cap_chan_tx_give_credits(ch, credits); + l2cap_chan_tx_give_credits(ch, credits); - BT_DBG("chan %p total credits %u", ch, - k_sem_count_get(&ch->tx.credits)); + BT_DBG("chan %p total credits %u", ch, + k_sem_count_get(&ch->tx.credits)); - l2cap_chan_le_send_resume(ch); + l2cap_chan_le_send_resume(ch); } static void reject_cmd(struct bt_l2cap *l2cap, u8_t ident, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = l2cap->chan.chan.conn; - struct bt_l2cap_le_chan *chan; + struct bt_conn *conn = l2cap->chan.chan.conn; + struct bt_l2cap_le_chan *chan; - /* Check if there is a outstanding channel */ - chan = l2cap_remove_ident(conn, ident); - if (!chan) { - return; - } + /* Check if there is a outstanding channel */ + chan = l2cap_remove_ident(conn, ident); + if (!chan) { + return; + } - bt_l2cap_chan_del(&chan->chan); + bt_l2cap_chan_del(&chan->chan); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ static int l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { - struct bt_l2cap *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan); - struct bt_l2cap_sig_hdr *hdr; - u16_t len; + struct bt_l2cap *l2cap = CONTAINER_OF(chan, struct bt_l2cap, chan); + struct bt_l2cap_sig_hdr *hdr; + u16_t len; - if (buf->len < sizeof(*hdr)) { - BT_ERR("Too small L2CAP signaling PDU"); - return 0; - } + if (buf->len < sizeof(*hdr)) { + BT_ERR("Too small L2CAP signaling PDU"); + return 0; + } - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - len = sys_le16_to_cpu(hdr->len); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + len = sys_le16_to_cpu(hdr->len); - BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code, - hdr->ident, len); + BT_DBG("Signaling code 0x%02x ident %u len %u", hdr->code, + hdr->ident, len); - if (buf->len != len) { - BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len); - return 0; - } + if (buf->len != len) { + BT_ERR("L2CAP length mismatch (%u != %u)", buf->len, len); + return 0; + } - if (!hdr->ident) { - BT_ERR("Invalid ident value in L2CAP PDU"); - return 0; - } + if (!hdr->ident) { + BT_ERR("Invalid ident value in L2CAP PDU"); + return 0; + } - switch (hdr->code) { - case BT_L2CAP_CONN_PARAM_RSP: - le_conn_param_rsp(l2cap, buf); - break; + switch (hdr->code) { + case BT_L2CAP_CONN_PARAM_RSP: + le_conn_param_rsp(l2cap, buf); + break; #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) - case BT_L2CAP_LE_CONN_REQ: - le_conn_req(l2cap, hdr->ident, buf); - break; - case BT_L2CAP_LE_CONN_RSP: - le_conn_rsp(l2cap, hdr->ident, buf); - break; - case BT_L2CAP_DISCONN_REQ: - le_disconn_req(l2cap, hdr->ident, buf); - break; - case BT_L2CAP_DISCONN_RSP: - le_disconn_rsp(l2cap, hdr->ident, buf); - break; - case BT_L2CAP_LE_CREDITS: - le_credits(l2cap, hdr->ident, buf); - break; - case BT_L2CAP_CMD_REJECT: - reject_cmd(l2cap, hdr->ident, buf); - break; + case BT_L2CAP_LE_CONN_REQ: + le_conn_req(l2cap, hdr->ident, buf); + break; + case BT_L2CAP_LE_CONN_RSP: + le_conn_rsp(l2cap, hdr->ident, buf); + break; + case BT_L2CAP_DISCONN_REQ: + le_disconn_req(l2cap, hdr->ident, buf); + break; + case BT_L2CAP_DISCONN_RSP: + le_disconn_rsp(l2cap, hdr->ident, buf); + break; + case BT_L2CAP_LE_CREDITS: + le_credits(l2cap, hdr->ident, buf); + break; + case BT_L2CAP_CMD_REJECT: + reject_cmd(l2cap, hdr->ident, buf); + break; #else - case BT_L2CAP_CMD_REJECT: - /* Ignored */ - break; + case BT_L2CAP_CMD_REJECT: + /* Ignored */ + break; #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ - case BT_L2CAP_CONN_PARAM_REQ: - if(IS_ENABLED(CONFIG_BT_CENTRAL)) { - le_conn_param_update_req(l2cap, hdr->ident, buf); - break; - } + case BT_L2CAP_CONN_PARAM_REQ: + if(IS_ENABLED(CONFIG_BT_CENTRAL)) { + le_conn_param_update_req(l2cap, hdr->ident, buf); + break; + } #if defined(BFLB_BLE) - __attribute__((fallthrough)); + __attribute__((fallthrough)); #endif - - /* Fall-through */ - default: - BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code); - l2cap_send_reject(chan->conn, hdr->ident, - BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0); - break; - } - return 0; + /* Fall-through */ + default: + BT_WARN("Unknown L2CAP PDU code 0x%02x", hdr->code); + l2cap_send_reject(chan->conn, hdr->ident, + BT_L2CAP_REJ_NOT_UNDERSTOOD, NULL, 0); + break; + } + + return 0; } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static void l2cap_chan_send_credits(struct bt_l2cap_le_chan *chan, - struct net_buf *buf, u16_t credits) + struct net_buf *buf, u16_t credits) { - struct bt_l2cap_le_credits *ev; + struct bt_l2cap_le_credits *ev; - /* Cap the number of credits given */ - if (credits > chan->rx.init_credits) { - credits = chan->rx.init_credits; - } + /* Cap the number of credits given */ + if (credits > chan->rx.init_credits) { + credits = chan->rx.init_credits; + } - l2cap_chan_rx_give_credits(chan, credits); + l2cap_chan_rx_give_credits(chan, credits); - buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(), - sizeof(*ev)); - if (!buf) { - return; - } + buf = l2cap_create_le_sig_pdu(buf, BT_L2CAP_LE_CREDITS, get_ident(), + sizeof(*ev)); + if (!buf) { + return; + } - ev = net_buf_add(buf, sizeof(*ev)); - ev->cid = sys_cpu_to_le16(chan->rx.cid); - ev->credits = sys_cpu_to_le16(credits); + ev = net_buf_add(buf, sizeof(*ev)); + ev->cid = sys_cpu_to_le16(chan->rx.cid); + ev->credits = sys_cpu_to_le16(credits); - bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf); + bt_l2cap_send(chan->chan.conn, BT_L2CAP_CID_LE_SIG, buf); - BT_DBG("chan %p credits %u", chan, k_sem_count_get(&chan->rx.credits)); + BT_DBG("chan %p credits %u", chan, k_sem_count_get(&chan->rx.credits)); } static void l2cap_chan_update_credits(struct bt_l2cap_le_chan *chan, - struct net_buf *buf) + struct net_buf *buf) { - s16_t credits; + s16_t credits; - /* Restore enough credits to complete the sdu */ - credits = ((chan->_sdu_len - net_buf_frags_len(buf)) + - (chan->rx.mps - 1)) / chan->rx.mps; - credits -= k_sem_count_get(&chan->rx.credits); - if (credits <= 0) { - return; - } + /* Restore enough credits to complete the sdu */ + credits = ((chan->_sdu_len - net_buf_frags_len(buf)) + + (chan->rx.mps - 1)) / chan->rx.mps; + credits -= k_sem_count_get(&chan->rx.credits); + if (credits <= 0) { + return; + } - l2cap_chan_send_credits(chan, buf, credits); + l2cap_chan_send_credits(chan, buf, credits); } int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, struct net_buf *buf) { - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - struct bt_conn *conn = chan->conn; - u16_t credits; + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + struct bt_conn *conn = chan->conn; + u16_t credits; - __ASSERT_NO_MSG(chan); - __ASSERT_NO_MSG(buf); + __ASSERT_NO_MSG(chan); + __ASSERT_NO_MSG(buf); - if (!conn) { - return -ENOTCONN; - } + if (!conn) { + return -ENOTCONN; + } - if (conn->type != BT_CONN_TYPE_LE) { - return -ENOTSUP; - } + if (conn->type != BT_CONN_TYPE_LE) { + return -ENOTSUP; + } - BT_DBG("chan %p buf %p", chan, buf); + BT_DBG("chan %p buf %p", chan, buf); - /* Restore credits used by packet */ - memcpy(&credits, net_buf_user_data(buf), sizeof(credits)); + /* Restore credits used by packet */ + memcpy(&credits, net_buf_user_data(buf), sizeof(credits)); - l2cap_chan_send_credits(ch, buf, credits); + l2cap_chan_send_credits(ch, buf, credits); - net_buf_unref(buf); + net_buf_unref(buf); - return 0; + return 0; } static struct net_buf *l2cap_alloc_frag(s32_t timeout, void *user_data) { - struct bt_l2cap_le_chan *chan = user_data; - struct net_buf *frag = NULL; + struct bt_l2cap_le_chan *chan = user_data; + struct net_buf *frag = NULL; - frag = chan->chan.ops->alloc_buf(&chan->chan); - if (!frag) { - return NULL; - } + frag = chan->chan.ops->alloc_buf(&chan->chan); + if (!frag) { + return NULL; + } - BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag)); + BT_DBG("frag %p tailroom %zu", frag, net_buf_tailroom(frag)); - return frag; + return frag; } static void l2cap_chan_le_recv_sdu(struct bt_l2cap_le_chan *chan, - struct net_buf *buf, u16_t seg) + struct net_buf *buf, u16_t seg) { - int err; + int err; - BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf)); + BT_DBG("chan %p len %zu", chan, net_buf_frags_len(buf)); - /* Receiving complete SDU, notify channel and reset SDU buf */ - err = chan->chan.ops->recv(&chan->chan, buf); - if (err < 0) { - if (err != -EINPROGRESS) { - BT_ERR("err %d", err); - bt_l2cap_chan_disconnect(&chan->chan); - net_buf_unref(buf); - } - return; - } + /* Receiving complete SDU, notify channel and reset SDU buf */ + err = chan->chan.ops->recv(&chan->chan, buf); + if (err < 0) { + if (err != -EINPROGRESS) { + BT_ERR("err %d", err); + bt_l2cap_chan_disconnect(&chan->chan); + net_buf_unref(buf); + } + return; + } - l2cap_chan_send_credits(chan, buf, seg); - net_buf_unref(buf); + l2cap_chan_send_credits(chan, buf, seg); + net_buf_unref(buf); } static void l2cap_chan_le_recv_seg(struct bt_l2cap_le_chan *chan, - struct net_buf *buf) + struct net_buf *buf) { - u16_t len; - u16_t seg = 0U; + u16_t len; + u16_t seg = 0U; - len = net_buf_frags_len(chan->_sdu); - if (len) { - memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg)); - } + len = net_buf_frags_len(chan->_sdu); + if (len) { + memcpy(&seg, net_buf_user_data(chan->_sdu), sizeof(seg)); + } - if (len + buf->len > chan->_sdu_len) { - BT_ERR("SDU length mismatch"); - bt_l2cap_chan_disconnect(&chan->chan); - return; - } + if (len + buf->len > chan->_sdu_len) { + BT_ERR("SDU length mismatch"); + bt_l2cap_chan_disconnect(&chan->chan); + return; + } - seg++; - /* Store received segments in user_data */ - memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg)); + seg++; + /* Store received segments in user_data */ + memcpy(net_buf_user_data(chan->_sdu), &seg, sizeof(seg)); - BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf)); + BT_DBG("chan %p seg %d len %zu", chan, seg, net_buf_frags_len(buf)); - /* Append received segment to SDU */ - len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT, - l2cap_alloc_frag, chan); - if (len != buf->len) { - BT_ERR("Unable to store SDU"); - bt_l2cap_chan_disconnect(&chan->chan); - return; - } + /* Append received segment to SDU */ + len = net_buf_append_bytes(chan->_sdu, buf->len, buf->data, K_NO_WAIT, + l2cap_alloc_frag, chan); + if (len != buf->len) { + BT_ERR("Unable to store SDU"); + bt_l2cap_chan_disconnect(&chan->chan); + return; + } - if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) { - /* Give more credits if remote has run out of them, this - * should only happen if the remote cannot fully utilize the - * MPS for some reason. - */ - if (!k_sem_count_get(&chan->rx.credits) && - seg == chan->rx.init_credits) { - l2cap_chan_update_credits(chan, buf); - } - return; - } + if (net_buf_frags_len(chan->_sdu) < chan->_sdu_len) { + /* Give more credits if remote has run out of them, this + * should only happen if the remote cannot fully utilize the + * MPS for some reason. + */ + if (!k_sem_count_get(&chan->rx.credits) && + seg == chan->rx.init_credits) { + l2cap_chan_update_credits(chan, buf); + } + return; + } - buf = chan->_sdu; - chan->_sdu = NULL; - chan->_sdu_len = 0U; + buf = chan->_sdu; + chan->_sdu = NULL; + chan->_sdu_len = 0U; - l2cap_chan_le_recv_sdu(chan, buf, seg); + l2cap_chan_le_recv_sdu(chan, buf, seg); } static void l2cap_chan_le_recv(struct bt_l2cap_le_chan *chan, - struct net_buf *buf) + struct net_buf *buf) { - u16_t sdu_len; - int err; + u16_t sdu_len; + int err; - if (k_sem_take(&chan->rx.credits, K_NO_WAIT)) { - BT_ERR("No credits to receive packet"); - bt_l2cap_chan_disconnect(&chan->chan); - return; - } + if (k_sem_take(&chan->rx.credits, K_NO_WAIT)) { + BT_ERR("No credits to receive packet"); + bt_l2cap_chan_disconnect(&chan->chan); + return; + } - /* Check if segments already exist */ - if (chan->_sdu) { - l2cap_chan_le_recv_seg(chan, buf); - return; - } + /* Check if segments already exist */ + if (chan->_sdu) { + l2cap_chan_le_recv_seg(chan, buf); + return; + } - sdu_len = net_buf_pull_le16(buf); + sdu_len = net_buf_pull_le16(buf); - BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len); + BT_DBG("chan %p len %u sdu_len %u", chan, buf->len, sdu_len); - if (sdu_len > chan->rx.mtu) { - BT_ERR("Invalid SDU length"); - bt_l2cap_chan_disconnect(&chan->chan); - return; - } + if (sdu_len > chan->rx.mtu) { + BT_ERR("Invalid SDU length"); + bt_l2cap_chan_disconnect(&chan->chan); + return; + } - /* Always allocate buffer from the channel if supported. */ - if (chan->chan.ops->alloc_buf) { - chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan); - if (!chan->_sdu) { - BT_ERR("Unable to allocate buffer for SDU"); - bt_l2cap_chan_disconnect(&chan->chan); - return; - } - chan->_sdu_len = sdu_len; - l2cap_chan_le_recv_seg(chan, buf); - return; - } + /* Always allocate buffer from the channel if supported. */ + if (chan->chan.ops->alloc_buf) { + chan->_sdu = chan->chan.ops->alloc_buf(&chan->chan); + if (!chan->_sdu) { + BT_ERR("Unable to allocate buffer for SDU"); + bt_l2cap_chan_disconnect(&chan->chan); + return; + } + chan->_sdu_len = sdu_len; + l2cap_chan_le_recv_seg(chan, buf); + return; + } - err = chan->chan.ops->recv(&chan->chan, buf); - if (err) { - if (err != -EINPROGRESS) { - BT_ERR("err %d", err); - bt_l2cap_chan_disconnect(&chan->chan); - } - return; - } + err = chan->chan.ops->recv(&chan->chan, buf); + if (err) { + if (err != -EINPROGRESS) { + BT_ERR("err %d", err); + bt_l2cap_chan_disconnect(&chan->chan); + } + return; + } - l2cap_chan_send_credits(chan, buf, 1); + l2cap_chan_send_credits(chan, buf, 1); } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ static void l2cap_chan_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) - struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); + struct bt_l2cap_le_chan *ch = BT_L2CAP_LE_CHAN(chan); - if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { - net_buf_put(&ch->rx_queue, net_buf_ref(buf)); - k_work_submit(&ch->rx_work); - return; - } + if (L2CAP_LE_CID_IS_DYN(ch->rx.cid)) { + net_buf_put(&ch->rx_queue, net_buf_ref(buf)); + k_work_submit(&ch->rx_work); + return; + } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ - BT_DBG("chan %p len %u", chan, buf->len); + BT_DBG("chan %p len %u", chan, buf->len); - chan->ops->recv(chan, buf); - net_buf_unref(buf); + chan->ops->recv(chan, buf); + net_buf_unref(buf); } void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf) { - struct bt_l2cap_hdr *hdr; - struct bt_l2cap_chan *chan; - u16_t cid; + struct bt_l2cap_hdr *hdr; + struct bt_l2cap_chan *chan; + u16_t cid; - if (IS_ENABLED(CONFIG_BT_BREDR) && - conn->type == BT_CONN_TYPE_BR) { - bt_l2cap_br_recv(conn, buf); - return; - } + if (IS_ENABLED(CONFIG_BT_BREDR) && + conn->type == BT_CONN_TYPE_BR) { + bt_l2cap_br_recv(conn, buf); + return; + } - if (buf->len < sizeof(*hdr)) { - BT_ERR("Too small L2CAP PDU received"); - net_buf_unref(buf); - return; - } + if (buf->len < sizeof(*hdr)) { + BT_ERR("Too small L2CAP PDU received"); + net_buf_unref(buf); + return; + } - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - cid = sys_le16_to_cpu(hdr->cid); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + cid = sys_le16_to_cpu(hdr->cid); - BT_DBG("Packet for CID %u len %u", cid, buf->len); + BT_DBG("Packet for CID %u len %u", cid, buf->len); - chan = bt_l2cap_le_lookup_rx_cid(conn, cid); - if (!chan) { - BT_WARN("Ignoring data for unknown CID 0x%04x", cid); - net_buf_unref(buf); - return; - } + chan = bt_l2cap_le_lookup_rx_cid(conn, cid); + if (!chan) { + BT_WARN("Ignoring data for unknown CID 0x%04x", cid); + net_buf_unref(buf); + return; + } - l2cap_chan_recv(chan, buf); + l2cap_chan_recv(chan, buf); } int bt_l2cap_update_conn_param(struct bt_conn *conn, - const struct bt_le_conn_param *param) + const struct bt_le_conn_param *param) { - struct bt_l2cap_conn_param_req *req; - struct net_buf *buf; + struct bt_l2cap_conn_param_req *req; + struct net_buf *buf; - buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ, - get_ident(), sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_CONN_PARAM_REQ, + get_ident(), sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->min_interval = sys_cpu_to_le16(param->interval_min); - req->max_interval = sys_cpu_to_le16(param->interval_max); - req->latency = sys_cpu_to_le16(param->latency); - req->timeout = sys_cpu_to_le16(param->timeout); + req = net_buf_add(buf, sizeof(*req)); + req->min_interval = sys_cpu_to_le16(param->interval_min); + req->max_interval = sys_cpu_to_le16(param->interval_max); + req->latency = sys_cpu_to_le16(param->latency); + req->timeout = sys_cpu_to_le16(param->timeout); - bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); + bt_l2cap_send(conn, BT_L2CAP_CID_LE_SIG, buf); - return 0; + return 0; } static void l2cap_connected(struct bt_l2cap_chan *chan) { - BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), - BT_L2CAP_LE_CHAN(chan)->rx.cid); + BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), + BT_L2CAP_LE_CHAN(chan)->rx.cid); } static void l2cap_disconnected(struct bt_l2cap_chan *chan) { - BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), - BT_L2CAP_LE_CHAN(chan)->rx.cid); + BT_DBG("ch %p cid 0x%04x", BT_L2CAP_LE_CHAN(chan), + BT_L2CAP_LE_CHAN(chan)->rx.cid); } static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { - int i; - static struct bt_l2cap_chan_ops ops = { - .connected = l2cap_connected, - .disconnected = l2cap_disconnected, - .recv = l2cap_recv, - }; + int i; + static struct bt_l2cap_chan_ops ops = { + .connected = l2cap_connected, + .disconnected = l2cap_disconnected, + .recv = l2cap_recv, + }; - BT_DBG("conn %p handle %u", conn, conn->handle); + BT_DBG("conn %p handle %u", conn, conn->handle); - for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) { - struct bt_l2cap *l2cap = &bt_l2cap_pool[i]; + for (i = 0; i < ARRAY_SIZE(bt_l2cap_pool); i++) { + struct bt_l2cap *l2cap = &bt_l2cap_pool[i]; - if (l2cap->chan.chan.conn) { - continue; - } + if (l2cap->chan.chan.conn) { + continue; + } - l2cap->chan.chan.ops = &ops; - *chan = &l2cap->chan.chan; + l2cap->chan.chan.ops = &ops; + *chan = &l2cap->chan.chan; - return 0; - } + return 0; + } - BT_ERR("No available L2CAP context for conn %p", conn); + BT_ERR("No available L2CAP context for conn %p", conn); - return -ENOMEM; + return -ENOMEM; } BT_L2CAP_CHANNEL_DEFINE(le_fixed_chan, BT_L2CAP_CID_LE_SIG, l2cap_accept); @@ -1823,133 +1823,133 @@ BT_L2CAP_CHANNEL_DEFINE(le_fixed_chan, BT_L2CAP_CID_LE_SIG, l2cap_accept); void bt_l2cap_init(void) { #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) - static struct bt_l2cap_fixed_chan chan = { - .cid = BT_L2CAP_CID_LE_SIG, - .accept = l2cap_accept, - }; + static struct bt_l2cap_fixed_chan chan = { + .cid = BT_L2CAP_CID_LE_SIG, + .accept = l2cap_accept, + }; - bt_l2cap_le_fixed_chan_register(&chan); + bt_l2cap_le_fixed_chan_register(&chan); #endif - if (IS_ENABLED(CONFIG_BT_BREDR)) { - bt_l2cap_br_init(); - } + if (IS_ENABLED(CONFIG_BT_BREDR)) { + bt_l2cap_br_init(); + } } #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) static int l2cap_le_connect(struct bt_conn *conn, struct bt_l2cap_le_chan *ch, - u16_t psm) + u16_t psm) { - if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) { - return -EINVAL; - } + if (psm < L2CAP_LE_PSM_FIXED_START || psm > L2CAP_LE_PSM_DYN_END) { + return -EINVAL; + } - l2cap_chan_tx_init(ch); - l2cap_chan_rx_init(ch); + l2cap_chan_tx_init(ch); + l2cap_chan_rx_init(ch); - if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) { - return -ENOMEM; - } + if (!l2cap_chan_add(conn, &ch->chan, l2cap_chan_destroy)) { + return -ENOMEM; + } - ch->chan.psm = psm; + ch->chan.psm = psm; - return l2cap_le_conn_req(ch); + return l2cap_le_conn_req(ch); } int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, - u16_t psm) + u16_t psm) { - BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm); + BT_DBG("conn %p chan %p psm 0x%04x", conn, chan, psm); - if (!conn || conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (!conn || conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - if (!chan) { - return -EINVAL; - } + if (!chan) { + return -EINVAL; + } - if (IS_ENABLED(CONFIG_BT_BREDR) && - conn->type == BT_CONN_TYPE_BR) { - return bt_l2cap_br_chan_connect(conn, chan, psm); - } + if (IS_ENABLED(CONFIG_BT_BREDR) && + conn->type == BT_CONN_TYPE_BR) { + return bt_l2cap_br_chan_connect(conn, chan, psm); + } - if (chan->required_sec_level > BT_SECURITY_L4) { - return -EINVAL; - } else if (chan->required_sec_level == BT_SECURITY_L0) { - chan->required_sec_level = BT_SECURITY_L1; - } + if (chan->required_sec_level > BT_SECURITY_L4) { + return -EINVAL; + } else if (chan->required_sec_level == BT_SECURITY_L0) { + chan->required_sec_level = BT_SECURITY_L1; + } - return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm); + return l2cap_le_connect(conn, BT_L2CAP_LE_CHAN(chan), psm); } int bt_l2cap_chan_disconnect(struct bt_l2cap_chan *chan) { - struct bt_conn *conn = chan->conn; - struct net_buf *buf; - struct bt_l2cap_disconn_req *req; - struct bt_l2cap_le_chan *ch; + struct bt_conn *conn = chan->conn; + struct net_buf *buf; + struct bt_l2cap_disconn_req *req; + struct bt_l2cap_le_chan *ch; - if (!conn) { - return -ENOTCONN; - } + if (!conn) { + return -ENOTCONN; + } - if (IS_ENABLED(CONFIG_BT_BREDR) && - conn->type == BT_CONN_TYPE_BR) { - return bt_l2cap_br_chan_disconnect(chan); - } + if (IS_ENABLED(CONFIG_BT_BREDR) && + conn->type == BT_CONN_TYPE_BR) { + return bt_l2cap_br_chan_disconnect(chan); + } - ch = BT_L2CAP_LE_CHAN(chan); + ch = BT_L2CAP_LE_CHAN(chan); - BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid, - ch->tx.cid); + BT_DBG("chan %p scid 0x%04x dcid 0x%04x", chan, ch->rx.cid, + ch->tx.cid); - ch->chan.ident = get_ident(); + ch->chan.ident = get_ident(); - buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ, - ch->chan.ident, sizeof(*req)); - if (!buf) { - return -ENOMEM; - } + buf = l2cap_create_le_sig_pdu(NULL, BT_L2CAP_DISCONN_REQ, + ch->chan.ident, sizeof(*req)); + if (!buf) { + return -ENOMEM; + } - req = net_buf_add(buf, sizeof(*req)); - req->dcid = sys_cpu_to_le16(ch->rx.cid); - req->scid = sys_cpu_to_le16(ch->tx.cid); + req = net_buf_add(buf, sizeof(*req)); + req->dcid = sys_cpu_to_le16(ch->rx.cid); + req->scid = sys_cpu_to_le16(ch->tx.cid); - l2cap_chan_send_req(ch, buf, L2CAP_DISC_TIMEOUT); - bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT); + l2cap_chan_send_req(ch, buf, L2CAP_DISC_TIMEOUT); + bt_l2cap_chan_set_state(chan, BT_L2CAP_DISCONNECT); - return 0; + return 0; } int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf) { - int err; + int err; - if (!buf) { - return -EINVAL; - } + if (!buf) { + return -EINVAL; + } - BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf)); + BT_DBG("chan %p buf %p len %zu", chan, buf, net_buf_frags_len(buf)); - if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) { - return -ENOTCONN; - } + if (!chan->conn || chan->conn->state != BT_CONN_CONNECTED) { + return -ENOTCONN; + } - if (IS_ENABLED(CONFIG_BT_BREDR) && - chan->conn->type == BT_CONN_TYPE_BR) { - return bt_l2cap_br_chan_send(chan, buf); - } + if (IS_ENABLED(CONFIG_BT_BREDR) && + chan->conn->type == BT_CONN_TYPE_BR) { + return bt_l2cap_br_chan_send(chan, buf); + } - err = l2cap_chan_le_send_sdu(BT_L2CAP_LE_CHAN(chan), &buf, 0); - if (err < 0) { - if (err == -EAGAIN) { - /* Queue buffer to be sent later */ - net_buf_put(&(BT_L2CAP_LE_CHAN(chan))->tx_queue, buf); - return *((u16_t *)net_buf_user_data(buf)); - } - BT_ERR("failed to send message %d", err); - } + err = l2cap_chan_le_send_sdu(BT_L2CAP_LE_CHAN(chan), &buf, 0); + if (err < 0) { + if (err == -EAGAIN) { + /* Queue buffer to be sent later */ + net_buf_put(&(BT_L2CAP_LE_CHAN(chan))->tx_queue, buf); + return *((u16_t *)net_buf_user_data(buf)); + } + BT_ERR("failed to send message %d", err); + } - return err; + return err; } #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ diff --git a/components/network/ble/blestack/src/host/l2cap_internal.h b/components/network/ble/blestack/src/host/l2cap_internal.h index 0e5376b2..2b8e44c3 100644 --- a/components/network/ble/blestack/src/host/l2cap_internal.h +++ b/components/network/ble/blestack/src/host/l2cap_internal.h @@ -11,217 +11,217 @@ #include enum l2cap_conn_list_action { - BT_L2CAP_CHAN_LOOKUP, - BT_L2CAP_CHAN_DETACH, + BT_L2CAP_CHAN_LOOKUP, + BT_L2CAP_CHAN_DETACH, }; -#define BT_L2CAP_CID_BR_SIG 0x0001 -#define BT_L2CAP_CID_ATT 0x0004 -#define BT_L2CAP_CID_LE_SIG 0x0005 -#define BT_L2CAP_CID_SMP 0x0006 -#define BT_L2CAP_CID_BR_SMP 0x0007 +#define BT_L2CAP_CID_BR_SIG 0x0001 +#define BT_L2CAP_CID_ATT 0x0004 +#define BT_L2CAP_CID_LE_SIG 0x0005 +#define BT_L2CAP_CID_SMP 0x0006 +#define BT_L2CAP_CID_BR_SMP 0x0007 -#define BT_L2CAP_PSM_RFCOMM 0x0003 +#define BT_L2CAP_PSM_RFCOMM 0x0003 struct bt_l2cap_hdr { - u16_t len; - u16_t cid; + u16_t len; + u16_t cid; } __packed; struct bt_l2cap_sig_hdr { - u8_t code; - u8_t ident; - u16_t len; + u8_t code; + u8_t ident; + u16_t len; } __packed; -#define BT_L2CAP_REJ_NOT_UNDERSTOOD 0x0000 -#define BT_L2CAP_REJ_MTU_EXCEEDED 0x0001 -#define BT_L2CAP_REJ_INVALID_CID 0x0002 +#define BT_L2CAP_REJ_NOT_UNDERSTOOD 0x0000 +#define BT_L2CAP_REJ_MTU_EXCEEDED 0x0001 +#define BT_L2CAP_REJ_INVALID_CID 0x0002 -#define BT_L2CAP_CMD_REJECT 0x01 +#define BT_L2CAP_CMD_REJECT 0x01 struct bt_l2cap_cmd_reject { - u16_t reason; - u8_t data[0]; + u16_t reason; + u8_t data[0]; } __packed; struct bt_l2cap_cmd_reject_cid_data { - u16_t scid; - u16_t dcid; + u16_t scid; + u16_t dcid; } __packed; -#define BT_L2CAP_CONN_REQ 0x02 +#define BT_L2CAP_CONN_REQ 0x02 struct bt_l2cap_conn_req { - u16_t psm; - u16_t scid; + u16_t psm; + u16_t scid; } __packed; /* command statuses in reposnse */ -#define BT_L2CAP_CS_NO_INFO 0x0000 -#define BT_L2CAP_CS_AUTHEN_PEND 0x0001 +#define BT_L2CAP_CS_NO_INFO 0x0000 +#define BT_L2CAP_CS_AUTHEN_PEND 0x0001 /* valid results in conn response on BR/EDR */ -#define BT_L2CAP_BR_SUCCESS 0x0000 -#define BT_L2CAP_BR_PENDING 0x0001 -#define BT_L2CAP_BR_ERR_PSM_NOT_SUPP 0x0002 -#define BT_L2CAP_BR_ERR_SEC_BLOCK 0x0003 -#define BT_L2CAP_BR_ERR_NO_RESOURCES 0x0004 -#define BT_L2CAP_BR_ERR_INVALID_SCID 0x0006 -#define BT_L2CAP_BR_ERR_SCID_IN_USE 0x0007 +#define BT_L2CAP_BR_SUCCESS 0x0000 +#define BT_L2CAP_BR_PENDING 0x0001 +#define BT_L2CAP_BR_ERR_PSM_NOT_SUPP 0x0002 +#define BT_L2CAP_BR_ERR_SEC_BLOCK 0x0003 +#define BT_L2CAP_BR_ERR_NO_RESOURCES 0x0004 +#define BT_L2CAP_BR_ERR_INVALID_SCID 0x0006 +#define BT_L2CAP_BR_ERR_SCID_IN_USE 0x0007 -#define BT_L2CAP_CONN_RSP 0x03 +#define BT_L2CAP_CONN_RSP 0x03 struct bt_l2cap_conn_rsp { - u16_t dcid; - u16_t scid; - u16_t result; - u16_t status; + u16_t dcid; + u16_t scid; + u16_t result; + u16_t status; } __packed; -#define BT_L2CAP_CONF_SUCCESS 0x0000 -#define BT_L2CAP_CONF_UNACCEPT 0x0001 -#define BT_L2CAP_CONF_REJECT 0x0002 +#define BT_L2CAP_CONF_SUCCESS 0x0000 +#define BT_L2CAP_CONF_UNACCEPT 0x0001 +#define BT_L2CAP_CONF_REJECT 0x0002 -#define BT_L2CAP_CONF_REQ 0x04 +#define BT_L2CAP_CONF_REQ 0x04 struct bt_l2cap_conf_req { - u16_t dcid; - u16_t flags; - u8_t data[0]; + u16_t dcid; + u16_t flags; + u8_t data[0]; } __packed; -#define BT_L2CAP_CONF_RSP 0x05 +#define BT_L2CAP_CONF_RSP 0x05 struct bt_l2cap_conf_rsp { - u16_t scid; - u16_t flags; - u16_t result; - u8_t data[0]; + u16_t scid; + u16_t flags; + u16_t result; + u8_t data[0]; } __packed; /* Option type used by MTU config request data */ -#define BT_L2CAP_CONF_OPT_MTU 0x01 +#define BT_L2CAP_CONF_OPT_MTU 0x01 /* Options bits selecting most significant bit (hint) in type field */ -#define BT_L2CAP_CONF_HINT 0x80 -#define BT_L2CAP_CONF_MASK 0x7f +#define BT_L2CAP_CONF_HINT 0x80 +#define BT_L2CAP_CONF_MASK 0x7f struct bt_l2cap_conf_opt { - u8_t type; - u8_t len; - u8_t data[0]; + u8_t type; + u8_t len; + u8_t data[0]; } __packed; -#define BT_L2CAP_DISCONN_REQ 0x06 +#define BT_L2CAP_DISCONN_REQ 0x06 struct bt_l2cap_disconn_req { - u16_t dcid; - u16_t scid; + u16_t dcid; + u16_t scid; } __packed; -#define BT_L2CAP_DISCONN_RSP 0x07 +#define BT_L2CAP_DISCONN_RSP 0x07 struct bt_l2cap_disconn_rsp { - u16_t dcid; - u16_t scid; + u16_t dcid; + u16_t scid; } __packed; -#define BT_L2CAP_INFO_FEAT_MASK 0x0002 -#define BT_L2CAP_INFO_FIXED_CHAN 0x0003 +#define BT_L2CAP_INFO_FEAT_MASK 0x0002 +#define BT_L2CAP_INFO_FIXED_CHAN 0x0003 -#define BT_L2CAP_INFO_REQ 0x0a +#define BT_L2CAP_INFO_REQ 0x0a struct bt_l2cap_info_req { - u16_t type; + u16_t type; } __packed; /* info result */ -#define BT_L2CAP_INFO_SUCCESS 0x0000 -#define BT_L2CAP_INFO_NOTSUPP 0x0001 +#define BT_L2CAP_INFO_SUCCESS 0x0000 +#define BT_L2CAP_INFO_NOTSUPP 0x0001 -#define BT_L2CAP_INFO_RSP 0x0b +#define BT_L2CAP_INFO_RSP 0x0b struct bt_l2cap_info_rsp { - u16_t type; - u16_t result; - u8_t data[0]; + u16_t type; + u16_t result; + u8_t data[0]; } __packed; -#define BT_L2CAP_CONN_PARAM_REQ 0x12 +#define BT_L2CAP_CONN_PARAM_REQ 0x12 struct bt_l2cap_conn_param_req { - u16_t min_interval; - u16_t max_interval; - u16_t latency; - u16_t timeout; + u16_t min_interval; + u16_t max_interval; + u16_t latency; + u16_t timeout; } __packed; -#define BT_L2CAP_CONN_PARAM_ACCEPTED 0x0000 -#define BT_L2CAP_CONN_PARAM_REJECTED 0x0001 +#define BT_L2CAP_CONN_PARAM_ACCEPTED 0x0000 +#define BT_L2CAP_CONN_PARAM_REJECTED 0x0001 -#define BT_L2CAP_CONN_PARAM_RSP 0x13 +#define BT_L2CAP_CONN_PARAM_RSP 0x13 struct bt_l2cap_conn_param_rsp { - u16_t result; + u16_t result; } __packed; -#define BT_L2CAP_LE_CONN_REQ 0x14 +#define BT_L2CAP_LE_CONN_REQ 0x14 struct bt_l2cap_le_conn_req { - u16_t psm; - u16_t scid; - u16_t mtu; - u16_t mps; - u16_t credits; + u16_t psm; + u16_t scid; + u16_t mtu; + u16_t mps; + u16_t credits; } __packed; /* valid results in conn response on LE */ -#define BT_L2CAP_LE_SUCCESS 0x0000 -#define BT_L2CAP_LE_ERR_PSM_NOT_SUPP 0x0002 -#define BT_L2CAP_LE_ERR_NO_RESOURCES 0x0004 -#define BT_L2CAP_LE_ERR_AUTHENTICATION 0x0005 -#define BT_L2CAP_LE_ERR_AUTHORIZATION 0x0006 -#define BT_L2CAP_LE_ERR_KEY_SIZE 0x0007 -#define BT_L2CAP_LE_ERR_ENCRYPTION 0x0008 -#define BT_L2CAP_LE_ERR_INVALID_SCID 0x0009 -#define BT_L2CAP_LE_ERR_SCID_IN_USE 0x000A -#define BT_L2CAP_LE_ERR_UNACCEPT_PARAMS 0x000B +#define BT_L2CAP_LE_SUCCESS 0x0000 +#define BT_L2CAP_LE_ERR_PSM_NOT_SUPP 0x0002 +#define BT_L2CAP_LE_ERR_NO_RESOURCES 0x0004 +#define BT_L2CAP_LE_ERR_AUTHENTICATION 0x0005 +#define BT_L2CAP_LE_ERR_AUTHORIZATION 0x0006 +#define BT_L2CAP_LE_ERR_KEY_SIZE 0x0007 +#define BT_L2CAP_LE_ERR_ENCRYPTION 0x0008 +#define BT_L2CAP_LE_ERR_INVALID_SCID 0x0009 +#define BT_L2CAP_LE_ERR_SCID_IN_USE 0x000A +#define BT_L2CAP_LE_ERR_UNACCEPT_PARAMS 0x000B -#define BT_L2CAP_LE_CONN_RSP 0x15 +#define BT_L2CAP_LE_CONN_RSP 0x15 struct bt_l2cap_le_conn_rsp { - u16_t dcid; - u16_t mtu; - u16_t mps; - u16_t credits; - u16_t result; + u16_t dcid; + u16_t mtu; + u16_t mps; + u16_t credits; + u16_t result; }; -#define BT_L2CAP_LE_CREDITS 0x16 +#define BT_L2CAP_LE_CREDITS 0x16 struct bt_l2cap_le_credits { - u16_t cid; - u16_t credits; + u16_t cid; + u16_t credits; } __packed; -#define BT_L2CAP_SDU_HDR_LEN 2 +#define BT_L2CAP_SDU_HDR_LEN 2 #if defined(CONFIG_BT_HCI_ACL_FLOW_CONTROL) #define BT_L2CAP_RX_MTU CONFIG_BT_L2CAP_RX_MTU #else #define BT_L2CAP_RX_MTU (CONFIG_BT_RX_BUF_LEN - \ - BT_HCI_ACL_HDR_SIZE - BT_L2CAP_HDR_SIZE) + BT_HCI_ACL_HDR_SIZE - BT_L2CAP_HDR_SIZE) #endif struct bt_l2cap_fixed_chan { - u16_t cid; - int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); - sys_snode_t node; + u16_t cid; + int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); + sys_snode_t node; }; -#define BT_L2CAP_CHANNEL_DEFINE(_name, _cid, _accept) \ - const Z_STRUCT_SECTION_ITERABLE(bt_l2cap_fixed_chan, _name) = { \ - .cid = _cid, \ - .accept = _accept, \ - } +#define BT_L2CAP_CHANNEL_DEFINE(_name, _cid, _accept) \ + const Z_STRUCT_SECTION_ITERABLE(bt_l2cap_fixed_chan, _name) = { \ + .cid = _cid, \ + .accept = _accept, \ + } /* Need a name different than bt_l2cap_fixed_chan for a different section */ struct bt_l2cap_br_fixed_chan { - u16_t cid; - int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); + u16_t cid; + int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); }; -#define BT_L2CAP_BR_CHANNEL_DEFINE(_name, _cid, _accept) \ - const Z_STRUCT_SECTION_ITERABLE(bt_l2cap_br_fixed_chan, _name) = { \ - .cid = _cid, \ - .accept = _accept, \ - } +#define BT_L2CAP_BR_CHANNEL_DEFINE(_name, _cid, _accept) \ + const Z_STRUCT_SECTION_ITERABLE(bt_l2cap_br_fixed_chan, _name) = { \ + .cid = _cid, \ + .accept = _accept, \ + } void l2cap_chan_sdu_sent(struct bt_conn *conn, void *user_data); /* Register a fixed L2CAP channel for L2CAP */ @@ -235,7 +235,7 @@ void bt_l2cap_disconnected(struct bt_conn *conn); /* Add channel to the connection */ void bt_l2cap_chan_add(struct bt_conn *conn, struct bt_l2cap_chan *chan, - bt_l2cap_chan_destroy_t destroy); + bt_l2cap_chan_destroy_t destroy); /* Remove channel from the connection */ void bt_l2cap_chan_remove(struct bt_conn *conn, struct bt_l2cap_chan *chan); @@ -247,13 +247,13 @@ const char *bt_l2cap_chan_state_str(bt_l2cap_chan_state_t state); #if defined(CONFIG_BT_DEBUG_L2CAP) void bt_l2cap_chan_set_state_debug(struct bt_l2cap_chan *chan, - bt_l2cap_chan_state_t state, - const char *func, int line); + bt_l2cap_chan_state_t state, + const char *func, int line); #define bt_l2cap_chan_set_state(_chan, _state) \ - bt_l2cap_chan_set_state_debug(_chan, _state, __func__, __LINE__) + bt_l2cap_chan_set_state_debug(_chan, _state, __func__, __LINE__) #else void bt_l2cap_chan_set_state(struct bt_l2cap_chan *chan, - bt_l2cap_chan_state_t state); + bt_l2cap_chan_state_t state); #endif /* CONFIG_BT_DEBUG_L2CAP */ /* @@ -264,10 +264,10 @@ void bt_l2cap_encrypt_change(struct bt_conn *conn, u8_t hci_status); /* Prepare an L2CAP PDU to be sent over a connection */ struct net_buf *bt_l2cap_create_pdu_timeout(struct net_buf_pool *pool, - size_t reserve, s32_t timeout); + size_t reserve, s32_t timeout); #define bt_l2cap_create_pdu(_pool, _reserve) \ - bt_l2cap_create_pdu_timeout(_pool, _reserve, K_FOREVER) + bt_l2cap_create_pdu_timeout(_pool, _reserve, K_FOREVER) /* Prepare a L2CAP Response PDU to be sent over a connection */ struct net_buf *bt_l2cap_create_rsp(struct net_buf *buf, size_t reserve); @@ -281,12 +281,12 @@ struct net_buf *bt_l2cap_create_rsp(struct net_buf *buf, size_t reserve); * ignored. */ int bt_l2cap_send_cb(struct bt_conn *conn, u16_t cid, struct net_buf *buf, - bt_conn_tx_cb_t cb, void *user_data); + bt_conn_tx_cb_t cb, void *user_data); static inline void bt_l2cap_send(struct bt_conn *conn, u16_t cid, - struct net_buf *buf) + struct net_buf *buf) { - bt_l2cap_send_cb(conn, cid, buf, NULL, NULL); + bt_l2cap_send_cb(conn, cid, buf, NULL, NULL); } /* Receive a new L2CAP PDU from a connection */ @@ -294,18 +294,18 @@ void bt_l2cap_recv(struct bt_conn *conn, struct net_buf *buf); /* Perform connection parameter update request */ int bt_l2cap_update_conn_param(struct bt_conn *conn, - const struct bt_le_conn_param *param); + const struct bt_le_conn_param *param); /* Initialize L2CAP and supported channels */ void bt_l2cap_init(void); /* Lookup channel by Transmission CID */ struct bt_l2cap_chan *bt_l2cap_le_lookup_tx_cid(struct bt_conn *conn, - u16_t cid); + u16_t cid); /* Lookup channel by Receiver CID */ struct bt_l2cap_chan *bt_l2cap_le_lookup_rx_cid(struct bt_conn *conn, - u16_t cid); + u16_t cid); /* Initialize BR/EDR L2CAP signal layer */ void bt_l2cap_br_init(void); @@ -318,14 +318,14 @@ void bt_l2cap_br_connected(struct bt_conn *conn); /* Lookup BR/EDR L2CAP channel by Receiver CID */ struct bt_l2cap_chan *bt_l2cap_br_lookup_rx_cid(struct bt_conn *conn, - u16_t cid); + u16_t cid); /* Disconnects dynamic channel */ int bt_l2cap_br_chan_disconnect(struct bt_l2cap_chan *chan); /* Make connection to peer psm server */ int bt_l2cap_br_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, - u16_t psm); + u16_t psm); /* Send packet data to connected peer */ int bt_l2cap_br_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf); diff --git a/components/network/ble/blestack/src/host/monitor.h b/components/network/ble/blestack/src/host/monitor.h index 1e80c1c6..07bb259c 100644 --- a/components/network/ble/blestack/src/host/monitor.h +++ b/components/network/ble/blestack/src/host/monitor.h @@ -10,24 +10,24 @@ #if defined(CONFIG_BT_DEBUG_MONITOR) -#define BT_MONITOR_NEW_INDEX 0 -#define BT_MONITOR_DEL_INDEX 1 -#define BT_MONITOR_COMMAND_PKT 2 -#define BT_MONITOR_EVENT_PKT 3 -#define BT_MONITOR_ACL_TX_PKT 4 -#define BT_MONITOR_ACL_RX_PKT 5 -#define BT_MONITOR_SCO_TX_PKT 6 -#define BT_MONITOR_SCO_RX_PKT 7 -#define BT_MONITOR_OPEN_INDEX 8 -#define BT_MONITOR_CLOSE_INDEX 9 -#define BT_MONITOR_INDEX_INFO 10 -#define BT_MONITOR_VENDOR_DIAG 11 -#define BT_MONITOR_SYSTEM_NOTE 12 -#define BT_MONITOR_USER_LOGGING 13 -#define BT_MONITOR_NOP 255 +#define BT_MONITOR_NEW_INDEX 0 +#define BT_MONITOR_DEL_INDEX 1 +#define BT_MONITOR_COMMAND_PKT 2 +#define BT_MONITOR_EVENT_PKT 3 +#define BT_MONITOR_ACL_TX_PKT 4 +#define BT_MONITOR_ACL_RX_PKT 5 +#define BT_MONITOR_SCO_TX_PKT 6 +#define BT_MONITOR_SCO_RX_PKT 7 +#define BT_MONITOR_OPEN_INDEX 8 +#define BT_MONITOR_CLOSE_INDEX 9 +#define BT_MONITOR_INDEX_INFO 10 +#define BT_MONITOR_VENDOR_DIAG 11 +#define BT_MONITOR_SYSTEM_NOTE 12 +#define BT_MONITOR_USER_LOGGING 13 +#define BT_MONITOR_NOP 255 -#define BT_MONITOR_TYPE_PRIMARY 0 -#define BT_MONITOR_TYPE_AMP 1 +#define BT_MONITOR_TYPE_PRIMARY 0 +#define BT_MONITOR_TYPE_AMP 1 /* Extended header types */ #define BT_MONITOR_COMMAND_DROPS 1 @@ -48,51 +48,51 @@ #endif struct bt_monitor_hdr { - u16_t data_len; - u16_t opcode; - u8_t flags; - u8_t hdr_len; + u16_t data_len; + u16_t opcode; + u8_t flags; + u8_t hdr_len; - u8_t ext[BT_MONITOR_EXT_HDR_MAX]; + u8_t ext[BT_MONITOR_EXT_HDR_MAX]; } __packed; struct bt_monitor_ts32 { - u8_t type; - u32_t ts32; + u8_t type; + u32_t ts32; } __packed; struct bt_monitor_new_index { - u8_t type; - u8_t bus; - u8_t bdaddr[6]; - char name[8]; + u8_t type; + u8_t bus; + u8_t bdaddr[6]; + char name[8]; } __packed; struct bt_monitor_user_logging { - u8_t priority; - u8_t ident_len; + u8_t priority; + u8_t ident_len; } __packed; static inline u8_t bt_monitor_opcode(struct net_buf *buf) { - switch (bt_buf_get_type(buf)) { - case BT_BUF_CMD: - return BT_MONITOR_COMMAND_PKT; - case BT_BUF_EVT: - return BT_MONITOR_EVENT_PKT; - case BT_BUF_ACL_OUT: - return BT_MONITOR_ACL_TX_PKT; - case BT_BUF_ACL_IN: - return BT_MONITOR_ACL_RX_PKT; - default: - return BT_MONITOR_NOP; - } + switch (bt_buf_get_type(buf)) { + case BT_BUF_CMD: + return BT_MONITOR_COMMAND_PKT; + case BT_BUF_EVT: + return BT_MONITOR_EVENT_PKT; + case BT_BUF_ACL_OUT: + return BT_MONITOR_ACL_TX_PKT; + case BT_BUF_ACL_IN: + return BT_MONITOR_ACL_RX_PKT; + default: + return BT_MONITOR_NOP; + } } void bt_monitor_send(u16_t opcode, const void *data, size_t len); void bt_monitor_new_index(u8_t type, u8_t bus, bt_addr_t *addr, - const char *name); + const char *name); #else /* !CONFIG_BT_DEBUG_MONITOR */ diff --git a/components/network/ble/blestack/src/host/multi_adv.c b/components/network/ble/blestack/src/host/multi_adv.c index 4cbef1f0..fcc24bed 100644 --- a/components/network/ble/blestack/src/host/multi_adv.c +++ b/components/network/ble/blestack/src/host/multi_adv.c @@ -23,7 +23,7 @@ int multi_adv_get_instant_num(void) { int i, num = 0; struct multi_adv_instant *inst = &(g_multi_adv_list[0]); - + for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) { if (inst[i].inuse_flag) num++; @@ -50,21 +50,21 @@ int multi_adv_delete_instant_by_id(int instant_id) { int i; struct multi_adv_instant *inst = &(g_multi_adv_list[0]); - + for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) { if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) { inst[i].inuse_flag = 0; return 0; } } - return -1; + return -1; } struct multi_adv_instant *multi_adv_find_instant_by_id(int instant_id) { int i; struct multi_adv_instant *inst = &(g_multi_adv_list[0]); - + for (i = 0; i < MAX_MULTI_ADV_INSTANT; i++) { if ((inst[i].inuse_flag) && (instant_id == (inst[i].instant_id))) { return &(inst[i]); @@ -77,7 +77,7 @@ struct multi_adv_instant *multi_adv_find_instant_by_order(int order) { struct multi_adv_instant *inst = &(g_multi_adv_list[0]); - + if (inst[order].inuse_flag) { return &(inst[order]); } @@ -133,32 +133,32 @@ int calculate_min_multi(int a, int b) y = z; } - return a*b/x; + return a*b/x; } void multi_adv_reorder(int inst_num, uint16_t inst_interval[], uint8_t inst_order[]) { int i, j; - + for (i = 0; i < inst_num; i++) { int max = inst_interval[0]; int max_idx = 0; int temp; - + for (j = 1; j < inst_num-i ; j++) { if (max < inst_interval[j]) { max = inst_interval[j]; max_idx = j; } } - + temp = inst_interval[inst_num-i-1]; inst_interval[inst_num-i-1] = inst_interval[max_idx]; inst_interval[max_idx] = temp; - + temp = inst_order[inst_num-i-1]; inst_order[inst_num-i-1] = inst_order[max_idx]; - inst_order[max_idx] = temp; + inst_order[max_idx] = temp; } } @@ -231,7 +231,7 @@ int multi_adv_start_adv_instant(struct multi_adv_instant *adv_instant) { int ret; - ret = bt_le_adv_start_instant(&adv_instant->param, + ret = bt_le_adv_start_instant(&adv_instant->param, adv_instant->ad, adv_instant->ad_len, adv_instant->sd, adv_instant->sd_len); if (ret) { @@ -268,7 +268,7 @@ int multi_adv_schedule_timer_start(int timeout) k_delayed_work_submit(&g_multi_adv_timer, timeout); adv_scheduler->schedule_timer_active = 1; - + return 1; } @@ -353,8 +353,8 @@ void multi_adv_schedule_timeslot(struct multi_adv_scheduler *adv_scheduler) } next_slot = match*inst_interval[i]+inst_offset[i]; if (next_slot < min_next_slot) { - min_next_slot = next_slot; - } + min_next_slot = next_slot; + } } adv_scheduler->next_slot_offset = 0; adv_scheduler->next_slot_clock = min_next_slot; @@ -375,7 +375,7 @@ void multi_adv_schedule_stop(void) void multi_adv_schedule_start(void) { struct multi_adv_scheduler *adv_scheduler = &g_multi_adv_scheduler; - + /* get all instant and calculate ticks and */ if (adv_scheduler->schedule_state == SCHEDULE_START) { multi_adv_schedule_stop(); @@ -411,7 +411,7 @@ void multi_adv_new_schedule(void) high_duty_instant = adv_instant; break; } - + inst_interval[inst_num] = change_to_tick(adv_instant->param.interval_min, adv_instant->param.interval_max); inst_order[inst_num] = i; inst_num++; @@ -474,18 +474,18 @@ int bt_le_multi_adv_start(const struct bt_le_adv_param *param, adv_instant = multi_adv_alloc_unused_instant(); if (adv_instant == 0) return -1; - + memcpy(&(adv_instant->param), param, sizeof(struct bt_le_adv_param)); adv_instant->ad_len = multi_adv_set_ad_data(adv_instant->ad, ad, ad_len); adv_instant->sd_len = multi_adv_set_ad_data(adv_instant->sd, sd, sd_len); multi_adv_new_schedule(); - + *instant_id = adv_instant->instant_id; return 0; } - + int bt_le_multi_adv_stop(int instant_id) { if (multi_adv_find_instant_by_id(instant_id) == 0) diff --git a/components/network/ble/blestack/src/host/multi_adv.h b/components/network/ble/blestack/src/host/multi_adv.h index 6bdeb1e9..a13b65d0 100644 --- a/components/network/ble/blestack/src/host/multi_adv.h +++ b/components/network/ble/blestack/src/host/multi_adv.h @@ -18,7 +18,7 @@ struct multi_adv_instant { uint8_t inuse_flag; - + /* for parameters */ struct bt_le_adv_param param; uint8_t ad[MAX_AD_DATA_LEN]; @@ -29,7 +29,7 @@ struct multi_adv_instant { /* own address maybe used */ bt_addr_t own_addr; uint8_t own_addr_valid; - + /* for schedule */ int instant_id; int instant_interval; diff --git a/components/network/ble/blestack/src/host/settings.c b/components/network/ble/blestack/src/host/settings.c index 5b675a0f..2a622dd8 100644 --- a/components/network/ble/blestack/src/host/settings.c +++ b/components/network/ble/blestack/src/host/settings.c @@ -28,205 +28,205 @@ #if defined(CONFIG_BT_SETTINGS_USE_PRINTK) void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, - bt_addr_le_t *addr, const char *key) + bt_addr_le_t *addr, const char *key) { - if (key) { - snprintk(path, path_size, - "bt/%s/%02x%02x%02x%02x%02x%02x%u/%s", subsys, - addr->a.val[5], addr->a.val[4], addr->a.val[3], - addr->a.val[2], addr->a.val[1], addr->a.val[0], - addr->type, key); - } else { - snprintk(path, path_size, - "bt/%s/%02x%02x%02x%02x%02x%02x%u", subsys, - addr->a.val[5], addr->a.val[4], addr->a.val[3], - addr->a.val[2], addr->a.val[1], addr->a.val[0], - addr->type); - } + if (key) { + snprintk(path, path_size, + "bt/%s/%02x%02x%02x%02x%02x%02x%u/%s", subsys, + addr->a.val[5], addr->a.val[4], addr->a.val[3], + addr->a.val[2], addr->a.val[1], addr->a.val[0], + addr->type, key); + } else { + snprintk(path, path_size, + "bt/%s/%02x%02x%02x%02x%02x%02x%u", subsys, + addr->a.val[5], addr->a.val[4], addr->a.val[3], + addr->a.val[2], addr->a.val[1], addr->a.val[0], + addr->type); + } - BT_DBG("Encoded path %s", log_strdup(path)); + BT_DBG("Encoded path %s", log_strdup(path)); } #else void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, - bt_addr_le_t *addr, const char *key) + bt_addr_le_t *addr, const char *key) { - size_t len = 3; + size_t len = 3; - /* Skip if path_size is less than 3; strlen("bt/") */ - if (len < path_size) { - /* Key format: - * "bt///", "/" is optional - */ - strcpy(path, "bt/"); - strncpy(&path[len], subsys, path_size - len); - len = strlen(path); - if (len < path_size) { - path[len] = '/'; - len++; - } + /* Skip if path_size is less than 3; strlen("bt/") */ + if (len < path_size) { + /* Key format: + * "bt///", "/" is optional + */ + strcpy(path, "bt/"); + strncpy(&path[len], subsys, path_size - len); + len = strlen(path); + if (len < path_size) { + path[len] = '/'; + len++; + } - for (s8_t i = 5; i >= 0 && len < path_size; i--) { - len += bin2hex(&addr->a.val[i], 1, &path[len], - path_size - len); - } + for (s8_t i = 5; i >= 0 && len < path_size; i--) { + len += bin2hex(&addr->a.val[i], 1, &path[len], + path_size - len); + } - if (len < path_size) { - /* Type can be either BT_ADDR_LE_PUBLIC or - * BT_ADDR_LE_RANDOM (value 0 or 1) - */ - path[len] = '0' + addr->type; - len++; - } + if (len < path_size) { + /* Type can be either BT_ADDR_LE_PUBLIC or + * BT_ADDR_LE_RANDOM (value 0 or 1) + */ + path[len] = '0' + addr->type; + len++; + } - if (key && len < path_size) { - path[len] = '/'; - len++; - strncpy(&path[len], key, path_size - len); - len += strlen(&path[len]); - } + if (key && len < path_size) { + path[len] = '/'; + len++; + strncpy(&path[len], key, path_size - len); + len += strlen(&path[len]); + } - if (len >= path_size) { - /* Truncate string */ - path[path_size - 1] = '\0'; - } - } else if (path_size > 0) { - *path = '\0'; - } + if (len >= path_size) { + /* Truncate string */ + path[path_size - 1] = '\0'; + } + } else if (path_size > 0) { + *path = '\0'; + } - BT_DBG("Encoded path %s", log_strdup(path)); + BT_DBG("Encoded path %s", log_strdup(path)); } #endif #if !defined(BFLB_BLE) int bt_settings_decode_key(const char *key, bt_addr_le_t *addr) { - if (settings_name_next(key, NULL) != 13) { - return -EINVAL; - } + if (settings_name_next(key, NULL) != 13) { + return -EINVAL; + } - if (key[12] == '0') { - addr->type = BT_ADDR_LE_PUBLIC; - } else if (key[12] == '1') { - addr->type = BT_ADDR_LE_RANDOM; - } else { - return -EINVAL; - } + if (key[12] == '0') { + addr->type = BT_ADDR_LE_PUBLIC; + } else if (key[12] == '1') { + addr->type = BT_ADDR_LE_RANDOM; + } else { + return -EINVAL; + } - for (u8_t i = 0; i < 6; i++) { - hex2bin(&key[i * 2], 2, &addr->a.val[5 - i], 1); - } + for (u8_t i = 0; i < 6; i++) { + hex2bin(&key[i * 2], 2, &addr->a.val[5 - i], 1); + } - BT_DBG("Decoded %s as %s", log_strdup(key), bt_addr_le_str(addr)); + BT_DBG("Decoded %s as %s", log_strdup(key), bt_addr_le_str(addr)); - return 0; + return 0; } static int set(const char *name, size_t len_rd, settings_read_cb read_cb, - void *cb_arg) + void *cb_arg) { - ssize_t len; - const char *next; + ssize_t len; + const char *next; - if (!name) { - BT_ERR("Insufficient number of arguments"); - return -ENOENT; - } + if (!name) { + BT_ERR("Insufficient number of arguments"); + return -ENOENT; + } - len = settings_name_next(name, &next); + len = settings_name_next(name, &next); - if (!strncmp(name, "id", len)) { - /* Any previously provided identities supersede flash */ - if (atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) { - BT_WARN("Ignoring identities stored in flash"); - return 0; - } + if (!strncmp(name, "id", len)) { + /* Any previously provided identities supersede flash */ + if (atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) { + BT_WARN("Ignoring identities stored in flash"); + return 0; + } - len = read_cb(cb_arg, &bt_dev.id_addr, sizeof(bt_dev.id_addr)); - if (len < sizeof(bt_dev.id_addr[0])) { - if (len < 0) { - BT_ERR("Failed to read ID address from storage" - " (err %zu)", len); - } else { - BT_ERR("Invalid length ID address in storage"); - BT_HEXDUMP_DBG(&bt_dev.id_addr, len, - "data read"); - } - (void)memset(bt_dev.id_addr, 0, - sizeof(bt_dev.id_addr)); - bt_dev.id_count = 0U; - } else { - int i; + len = read_cb(cb_arg, &bt_dev.id_addr, sizeof(bt_dev.id_addr)); + if (len < sizeof(bt_dev.id_addr[0])) { + if (len < 0) { + BT_ERR("Failed to read ID address from storage" + " (err %zu)", len); + } else { + BT_ERR("Invalid length ID address in storage"); + BT_HEXDUMP_DBG(&bt_dev.id_addr, len, + "data read"); + } + (void)memset(bt_dev.id_addr, 0, + sizeof(bt_dev.id_addr)); + bt_dev.id_count = 0U; + } else { + int i; - bt_dev.id_count = len / sizeof(bt_dev.id_addr[0]); - for (i = 0; i < bt_dev.id_count; i++) { - BT_DBG("ID[%d] %s", i, - bt_addr_le_str(&bt_dev.id_addr[i])); - } - } + bt_dev.id_count = len / sizeof(bt_dev.id_addr[0]); + for (i = 0; i < bt_dev.id_count; i++) { + BT_DBG("ID[%d] %s", i, + bt_addr_le_str(&bt_dev.id_addr[i])); + } + } - return 0; - } + return 0; + } #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) - if (!strncmp(name, "name", len)) { - len = read_cb(cb_arg, &bt_dev.name, sizeof(bt_dev.name) - 1); - if (len < 0) { - BT_ERR("Failed to read device name from storage" - " (err %zu)", len); - } else { - bt_dev.name[len] = '\0'; + if (!strncmp(name, "name", len)) { + len = read_cb(cb_arg, &bt_dev.name, sizeof(bt_dev.name) - 1); + if (len < 0) { + BT_ERR("Failed to read device name from storage" + " (err %zu)", len); + } else { + bt_dev.name[len] = '\0'; - BT_DBG("Name set to %s", log_strdup(bt_dev.name)); - } - return 0; - } + BT_DBG("Name set to %s", log_strdup(bt_dev.name)); + } + return 0; + } #endif #if defined(CONFIG_BT_PRIVACY) - if (!strncmp(name, "irk", len)) { - len = read_cb(cb_arg, bt_dev.irk, sizeof(bt_dev.irk)); - if (len < sizeof(bt_dev.irk[0])) { - if (len < 0) { - BT_ERR("Failed to read IRK from storage" - " (err %zu)", len); - } else { - BT_ERR("Invalid length IRK in storage"); - (void)memset(bt_dev.irk, 0, sizeof(bt_dev.irk)); - } - } else { - int i, count; + if (!strncmp(name, "irk", len)) { + len = read_cb(cb_arg, bt_dev.irk, sizeof(bt_dev.irk)); + if (len < sizeof(bt_dev.irk[0])) { + if (len < 0) { + BT_ERR("Failed to read IRK from storage" + " (err %zu)", len); + } else { + BT_ERR("Invalid length IRK in storage"); + (void)memset(bt_dev.irk, 0, sizeof(bt_dev.irk)); + } + } else { + int i, count; - count = len / sizeof(bt_dev.irk[0]); - for (i = 0; i < count; i++) { - BT_DBG("IRK[%d] %s", i, - bt_hex(bt_dev.irk[i], 16)); - } - } + count = len / sizeof(bt_dev.irk[0]); + for (i = 0; i < count; i++) { + BT_DBG("IRK[%d] %s", i, + bt_hex(bt_dev.irk[i], 16)); + } + } - return 0; - } + return 0; + } #endif /* CONFIG_BT_PRIVACY */ - return -ENOENT; + return -ENOENT; } #define ID_DATA_LEN(array) (bt_dev.id_count * sizeof(array[0])) static void save_id(struct k_work *work) { - int err; - BT_INFO("Saving ID"); - err = settings_save_one("bt/id", &bt_dev.id_addr, - ID_DATA_LEN(bt_dev.id_addr)); - if (err) { - BT_ERR("Failed to save ID (err %d)", err); - } + int err; + BT_INFO("Saving ID"); + err = settings_save_one("bt/id", &bt_dev.id_addr, + ID_DATA_LEN(bt_dev.id_addr)); + if (err) { + BT_ERR("Failed to save ID (err %d)", err); + } #if defined(CONFIG_BT_PRIVACY) - err = settings_save_one("bt/irk", bt_dev.irk, ID_DATA_LEN(bt_dev.irk)); - if (err) { - BT_ERR("Failed to save IRK (err %d)", err); - } + err = settings_save_one("bt/irk", bt_dev.irk, ID_DATA_LEN(bt_dev.irk)); + if (err) { + BT_ERR("Failed to save IRK (err %d)", err); + } #endif } @@ -238,7 +238,7 @@ bool ef_ready_flag = false; int bt_check_if_ef_ready() { int err = 0; - + if(!ef_ready_flag){ err = easyflash_init(); if(!err) @@ -249,7 +249,7 @@ int bt_check_if_ef_ready() } int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length) -{ +{ const char *lookup = "0123456789abcdef"; char *str_value; int err; @@ -261,7 +261,7 @@ int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length) str_value = pvPortMalloc(length*2 + 1); BT_ASSERT(str_value != NULL); - + for(size_t i = 0; i < length; i++){ str_value[(i * 2) + 0] = lookup[(value[i] >> 4) & 0x0F]; str_value[(i * 2) + 1] = lookup[value[i] & 0x0F]; @@ -277,7 +277,7 @@ int bt_settings_set_bin(const char *key, const uint8_t *value, size_t length) int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *real_len) { - char *str_value; + char *str_value; size_t str_value_len; char rand[3]; int err; @@ -286,13 +286,13 @@ int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *re if(err) return err; - + str_value = ef_get_env(key); if(str_value == NULL) { return -1; } - + str_value_len = strlen(str_value); if((str_value_len % 2) != 0 || (exp_len >0 && str_value_len > exp_len*2)) @@ -302,7 +302,7 @@ int bt_settings_get_bin(const char *key, u8_t *value, size_t exp_len, size_t *re if(real_len) *real_len = str_value_len/2; - + for(size_t i = 0; i < str_value_len/2; i++){ strncpy(rand, str_value+2*i, 2); rand[2] = '\0'; @@ -330,13 +330,13 @@ void bt_settings_save_id(void) #if defined(CONFIG_BT_SETTINGS) if(bt_check_if_ef_ready()) return; - bt_settings_set_bin(NV_LOCAL_ID_ADDR, (const u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t)*CONFIG_BT_ID_MAX); + bt_settings_set_bin(NV_LOCAL_ID_ADDR, (const u8_t *)&bt_dev.id_addr[0], sizeof(bt_addr_le_t)*CONFIG_BT_ID_MAX); #if defined(CONFIG_BT_PRIVACY) - bt_settings_set_bin(NV_LOCAL_IRK, (const u8_t *)&bt_dev.irk[0], 16*CONFIG_BT_ID_MAX); + bt_settings_set_bin(NV_LOCAL_IRK, (const u8_t *)&bt_dev.irk[0], 16*CONFIG_BT_ID_MAX); #endif //CONFIG_BT_PRIVACY #endif //CONFIG_BT_SETTINGS -#else - k_work_submit(&save_id_work); +#else + k_work_submit(&save_id_work); #endif } @@ -346,7 +346,7 @@ void bt_settings_save_name(void) { if(bt_check_if_ef_ready()) return; - + ef_set_env(NV_LOCAL_NAME, bt_dev.name); } @@ -374,34 +374,34 @@ void bt_local_info_load(void) #if !defined(BFLB_BLE) static int commit(void) { - BT_DBG(""); + BT_DBG(""); #if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) - if (bt_dev.name[0] == '\0') { - bt_set_name(CONFIG_BT_DEVICE_NAME); - } + if (bt_dev.name[0] == '\0') { + bt_set_name(CONFIG_BT_DEVICE_NAME); + } #endif - if (!bt_dev.id_count) { - int err; + if (!bt_dev.id_count) { + int err; - err = bt_setup_id_addr(); - if (err) { - BT_ERR("Unable to setup an identity address"); - return err; - } - } + err = bt_setup_id_addr(); + if (err) { + BT_ERR("Unable to setup an identity address"); + return err; + } + } - /* Make sure that the identities created by bt_id_create after - * bt_enable is saved to persistent storage. */ - if (!atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) { - bt_settings_save_id(); - } + /* Make sure that the identities created by bt_id_create after + * bt_enable is saved to persistent storage. */ + if (!atomic_test_bit(bt_dev.flags, BT_DEV_PRESET_ID)) { + bt_settings_save_id(); + } - if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { - bt_finalize_init(); - } + if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) { + bt_finalize_init(); + } - return 0; + return 0; } SETTINGS_STATIC_HANDLER_DEFINE(bt, "bt", NULL, set, commit, NULL); @@ -413,16 +413,16 @@ int bt_settings_init(void) #if defined(BFLB_BLE) return 0; #else - int err; + int err; - BT_DBG(""); + BT_DBG(""); - err = settings_subsys_init(); - if (err) { - BT_ERR("settings_subsys_init failed (err %d)", err); - return err; - } + err = settings_subsys_init(); + if (err) { + BT_ERR("settings_subsys_init failed (err %d)", err); + return err; + } - return 0; + return 0; #endif } diff --git a/components/network/ble/blestack/src/host/settings.h b/components/network/ble/blestack/src/host/settings.h index 76806575..1b9476b8 100644 --- a/components/network/ble/blestack/src/host/settings.h +++ b/components/network/ble/blestack/src/host/settings.h @@ -16,7 +16,7 @@ /* Helpers for keys containing a bdaddr */ void bt_settings_encode_key(char *path, size_t path_size, const char *subsys, - bt_addr_le_t *addr, const char *key); + bt_addr_le_t *addr, const char *key); int bt_settings_decode_key(const char *key, bt_addr_le_t *addr); void bt_settings_save_id(void); diff --git a/components/network/ble/blestack/src/host/smp.c b/components/network/ble/blestack/src/host/smp.c index 4b3b98d6..edcf3604 100644 --- a/components/network/ble/blestack/src/host/smp.c +++ b/components/network/ble/blestack/src/host/smp.c @@ -63,7 +63,7 @@ #endif #define RECV_KEYS (BT_SMP_DIST_ENC_KEY | BT_SMP_DIST_ID_KEY | SIGN_DIST |\ - LINK_DIST) + LINK_DIST) #define SEND_KEYS (BT_SMP_DIST_ENC_KEY | ID_DIST | SIGN_DIST | LINK_DIST) #define RECV_KEYS_SC (RECV_KEYS & ~(BT_SMP_DIST_ENC_KEY)) @@ -72,7 +72,7 @@ #define BR_RECV_KEYS_SC (RECV_KEYS & ~(LINK_DIST)) #define BR_SEND_KEYS_SC (SEND_KEYS & ~(LINK_DIST)) -#define BT_SMP_AUTH_MASK 0x07 +#define BT_SMP_AUTH_MASK 0x07 #if defined(CONFIG_BT_BONDABLE) #define BT_SMP_AUTH_BONDING_FLAGS BT_SMP_AUTH_BONDING @@ -82,178 +82,178 @@ #if defined(CONFIG_BT_BREDR) -#define BT_SMP_AUTH_MASK_SC 0x2f +#define BT_SMP_AUTH_MASK_SC 0x2f #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_SC |\ - BT_SMP_AUTH_CT2) + BT_SMP_AUTH_CT2) #else -#define BT_SMP_AUTH_MASK_SC 0x0f +#define BT_SMP_AUTH_MASK_SC 0x0f #define BT_SMP_AUTH_DEFAULT (BT_SMP_AUTH_BONDING_FLAGS | BT_SMP_AUTH_SC) #endif enum pairing_method { - JUST_WORKS, /* JustWorks pairing */ - PASSKEY_INPUT, /* Passkey Entry input */ - PASSKEY_DISPLAY, /* Passkey Entry display */ - PASSKEY_CONFIRM, /* Passkey confirm */ - PASSKEY_ROLE, /* Passkey Entry depends on role */ - LE_SC_OOB, /* LESC Out of Band */ + JUST_WORKS, /* JustWorks pairing */ + PASSKEY_INPUT, /* Passkey Entry input */ + PASSKEY_DISPLAY, /* Passkey Entry display */ + PASSKEY_CONFIRM, /* Passkey confirm */ + PASSKEY_ROLE, /* Passkey Entry depends on role */ + LE_SC_OOB, /* LESC Out of Band */ }; enum { - SMP_FLAG_CFM_DELAYED, /* if confirm should be send when TK is valid */ - SMP_FLAG_ENC_PENDING, /* if waiting for an encryption change event */ - SMP_FLAG_KEYS_DISTR, /* if keys distribution phase is in progress */ - SMP_FLAG_PAIRING, /* if pairing is in progress */ - SMP_FLAG_TIMEOUT, /* if SMP timeout occurred */ - SMP_FLAG_SC, /* if LE Secure Connections is used */ - SMP_FLAG_PKEY_SEND, /* if should send Public Key when available */ - SMP_FLAG_DHKEY_PENDING, /* if waiting for local DHKey */ - SMP_FLAG_DHKEY_SEND, /* if should generate and send DHKey Check */ - SMP_FLAG_USER, /* if waiting for user input */ - SMP_FLAG_DISPLAY, /* if display_passkey() callback was called */ - SMP_FLAG_OOB_PENDING, /* if waiting for OOB data */ - SMP_FLAG_BOND, /* if bonding */ - SMP_FLAG_SC_DEBUG_KEY, /* if Secure Connection are using debug key */ - SMP_FLAG_SEC_REQ, /* if Security Request was sent/received */ - SMP_FLAG_DHCHECK_WAIT, /* if waiting for remote DHCheck (as slave) */ - SMP_FLAG_DERIVE_LK, /* if Link Key should be derived */ - SMP_FLAG_BR_CONNECTED, /* if BR/EDR channel is connected */ - SMP_FLAG_BR_PAIR, /* if should start BR/EDR pairing */ - SMP_FLAG_CT2, /* if should use H7 for keys derivation */ + SMP_FLAG_CFM_DELAYED, /* if confirm should be send when TK is valid */ + SMP_FLAG_ENC_PENDING, /* if waiting for an encryption change event */ + SMP_FLAG_KEYS_DISTR, /* if keys distribution phase is in progress */ + SMP_FLAG_PAIRING, /* if pairing is in progress */ + SMP_FLAG_TIMEOUT, /* if SMP timeout occurred */ + SMP_FLAG_SC, /* if LE Secure Connections is used */ + SMP_FLAG_PKEY_SEND, /* if should send Public Key when available */ + SMP_FLAG_DHKEY_PENDING, /* if waiting for local DHKey */ + SMP_FLAG_DHKEY_SEND, /* if should generate and send DHKey Check */ + SMP_FLAG_USER, /* if waiting for user input */ + SMP_FLAG_DISPLAY, /* if display_passkey() callback was called */ + SMP_FLAG_OOB_PENDING, /* if waiting for OOB data */ + SMP_FLAG_BOND, /* if bonding */ + SMP_FLAG_SC_DEBUG_KEY, /* if Secure Connection are using debug key */ + SMP_FLAG_SEC_REQ, /* if Security Request was sent/received */ + SMP_FLAG_DHCHECK_WAIT, /* if waiting for remote DHCheck (as slave) */ + SMP_FLAG_DERIVE_LK, /* if Link Key should be derived */ + SMP_FLAG_BR_CONNECTED, /* if BR/EDR channel is connected */ + SMP_FLAG_BR_PAIR, /* if should start BR/EDR pairing */ + SMP_FLAG_CT2, /* if should use H7 for keys derivation */ - /* Total number of flags - must be at the end */ - SMP_NUM_FLAGS, + /* Total number of flags - must be at the end */ + SMP_NUM_FLAGS, }; /* SMP channel specific context */ struct bt_smp { - /* The channel this context is associated with */ - struct bt_l2cap_le_chan chan; + /* The channel this context is associated with */ + struct bt_l2cap_le_chan chan; - /* Commands that remote is allowed to send */ - atomic_t allowed_cmds; + /* Commands that remote is allowed to send */ + atomic_t allowed_cmds; - /* Flags for SMP state machine */ - ATOMIC_DEFINE(flags, SMP_NUM_FLAGS); + /* Flags for SMP state machine */ + ATOMIC_DEFINE(flags, SMP_NUM_FLAGS); - /* Type of method used for pairing */ - u8_t method; + /* Type of method used for pairing */ + u8_t method; - /* Pairing Request PDU */ - u8_t preq[7]; + /* Pairing Request PDU */ + u8_t preq[7]; - /* Pairing Response PDU */ - u8_t prsp[7]; + /* Pairing Response PDU */ + u8_t prsp[7]; - /* Pairing Confirm PDU */ - u8_t pcnf[16]; + /* Pairing Confirm PDU */ + u8_t pcnf[16]; - /* Local random number */ - u8_t prnd[16]; + /* Local random number */ + u8_t prnd[16]; - /* Remote random number */ - u8_t rrnd[16]; + /* Remote random number */ + u8_t rrnd[16]; - /* Temporary key */ - u8_t tk[16]; + /* Temporary key */ + u8_t tk[16]; - /* Remote Public Key for LE SC */ - u8_t pkey[64]; + /* Remote Public Key for LE SC */ + u8_t pkey[64]; - /* DHKey */ - u8_t dhkey[32]; + /* DHKey */ + u8_t dhkey[32]; - /* Remote DHKey check */ - u8_t e[16]; + /* Remote DHKey check */ + u8_t e[16]; - /* MacKey */ - u8_t mackey[16]; + /* MacKey */ + u8_t mackey[16]; - /* LE SC passkey */ - u32_t passkey; + /* LE SC passkey */ + u32_t passkey; - /* LE SC passkey round */ - u8_t passkey_round; + /* LE SC passkey round */ + u8_t passkey_round; - /* LE SC local OOB data */ - const struct bt_le_oob_sc_data *oobd_local; + /* LE SC local OOB data */ + const struct bt_le_oob_sc_data *oobd_local; - /* LE SC remote OOB data */ - const struct bt_le_oob_sc_data *oobd_remote; + /* LE SC remote OOB data */ + const struct bt_le_oob_sc_data *oobd_remote; - /* Local key distribution */ - u8_t local_dist; + /* Local key distribution */ + u8_t local_dist; - /* Remote key distribution */ - u8_t remote_dist; + /* Remote key distribution */ + u8_t remote_dist; - /* Delayed work for timeout handling */ - struct k_delayed_work work; + /* Delayed work for timeout handling */ + struct k_delayed_work work; }; static unsigned int fixed_passkey = BT_PASSKEY_INVALID; #define DISPLAY_FIXED(smp) (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && \ - fixed_passkey != BT_PASSKEY_INVALID && \ - (smp)->method == PASSKEY_DISPLAY) + fixed_passkey != BT_PASSKEY_INVALID && \ + (smp)->method == PASSKEY_DISPLAY) #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) /* based on table 2.8 Core Spec 2.3.5.1 Vol. 3 Part H */ static const u8_t gen_method_legacy[5 /* remote */][5 /* local */] = { - { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, - { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, - { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, - PASSKEY_DISPLAY }, - { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, - { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, - PASSKEY_ROLE }, + { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, + { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, + { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, + PASSKEY_DISPLAY }, + { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, + { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, + PASSKEY_ROLE }, }; #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ /* based on table 2.8 Core Spec 2.3.5.1 Vol. 3 Part H */ static const u8_t gen_method_sc[5 /* remote */][5 /* local */] = { - { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, - { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS, - PASSKEY_CONFIRM }, - { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, - PASSKEY_DISPLAY }, - { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, - { PASSKEY_DISPLAY, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS, - PASSKEY_CONFIRM }, + { JUST_WORKS, JUST_WORKS, PASSKEY_INPUT, JUST_WORKS, PASSKEY_INPUT }, + { JUST_WORKS, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS, + PASSKEY_CONFIRM }, + { PASSKEY_DISPLAY, PASSKEY_DISPLAY, PASSKEY_INPUT, JUST_WORKS, + PASSKEY_DISPLAY }, + { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, + { PASSKEY_DISPLAY, PASSKEY_CONFIRM, PASSKEY_INPUT, JUST_WORKS, + PASSKEY_CONFIRM }, }; static const u8_t sc_debug_public_key[64] = { - 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, - 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, - 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, - 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, - 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, - 0x49, 0x9c, 0x80, 0xdc + 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, 0xdb, 0xfd, 0xf4, 0xac, + 0x11, 0x91, 0xf4, 0xef, 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, + 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20, 0x8b, 0xd2, 0x89, 0x15, + 0xd0, 0x8e, 0x1c, 0x74, 0x24, 0x30, 0xed, 0x8f, 0xc2, 0x45, 0x63, 0x76, + 0x5c, 0x15, 0x52, 0x5a, 0xbf, 0x9a, 0x32, 0x63, 0x6d, 0xeb, 0x2a, 0x65, + 0x49, 0x9c, 0x80, 0xdc }; #if defined(CONFIG_BT_BREDR) /* SMP over BR/EDR channel specific context */ struct bt_smp_br { - /* The channel this context is associated with */ - struct bt_l2cap_br_chan chan; + /* The channel this context is associated with */ + struct bt_l2cap_br_chan chan; - /* Commands that remote is allowed to send */ - atomic_t allowed_cmds; + /* Commands that remote is allowed to send */ + atomic_t allowed_cmds; - /* Flags for SMP state machine */ - ATOMIC_DEFINE(flags, SMP_NUM_FLAGS); + /* Flags for SMP state machine */ + ATOMIC_DEFINE(flags, SMP_NUM_FLAGS); - /* Local key distribution */ - u8_t local_dist; + /* Local key distribution */ + u8_t local_dist; - /* Remote key distribution */ - u8_t remote_dist; + /* Remote key distribution */ + u8_t remote_dist; - /* Encryption Key Size used for connection */ - u8_t enc_key_size; + /* Encryption Key Size used for connection */ + u8_t enc_key_size; - /* Delayed work for timeout handling */ - struct k_delayed_work work; + /* Delayed work for timeout handling */ + struct k_delayed_work work; }; static struct bt_smp_br bt_smp_br_pool[CONFIG_BT_MAX_CONN]; @@ -277,57 +277,57 @@ static K_SEM_DEFINE(sc_local_pkey_ready, 0, 1); static u8_t get_io_capa(void) { - if (!bt_auth) { - goto no_callbacks; - } - - #if defined(CONFIG_BT_STACK_PTS) - if(atomic_test_bit(&smp_test_flag, SMP_IO_CAP_DISPLAY_ONLY) || - atomic_test_bit(&smp_test_flag, SMP_AUTH_NO_BONDING_MITM_IO_DISPLAY_ONLY)) { - - return BT_SMP_IO_DISPLAY_ONLY; - - }else if(atomic_test_bit(&smp_test_flag, SMP_IO_KEYBOARD_ONLY)){ - if (bt_auth->passkey_entry){ - return BT_SMP_IO_KEYBOARD_ONLY; - } - }else if(atomic_test_bit(&smp_test_flag, SMP_IO_NO_INPUT_OUTPUT)){ - return BT_SMP_IO_NO_INPUT_OUTPUT; - } - #endif + if (!bt_auth) { + goto no_callbacks; + } - /* Passkey Confirmation is valid only for LE SC */ - if (bt_auth->passkey_display && bt_auth->passkey_entry && - (bt_auth->passkey_confirm || !sc_supported)) { - return BT_SMP_IO_KEYBOARD_DISPLAY; - } + #if defined(CONFIG_BT_STACK_PTS) + if(atomic_test_bit(&smp_test_flag, SMP_IO_CAP_DISPLAY_ONLY) || + atomic_test_bit(&smp_test_flag, SMP_AUTH_NO_BONDING_MITM_IO_DISPLAY_ONLY)) { - /* DisplayYesNo is useful only for LE SC */ - if (sc_supported && bt_auth->passkey_display && - bt_auth->passkey_confirm) { - return BT_SMP_IO_DISPLAY_YESNO; - } + return BT_SMP_IO_DISPLAY_ONLY; - if (bt_auth->passkey_entry) { - if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && - fixed_passkey != BT_PASSKEY_INVALID) { - return BT_SMP_IO_KEYBOARD_DISPLAY; - } else { - return BT_SMP_IO_KEYBOARD_ONLY; - } - } + }else if(atomic_test_bit(&smp_test_flag, SMP_IO_KEYBOARD_ONLY)){ + if (bt_auth->passkey_entry){ + return BT_SMP_IO_KEYBOARD_ONLY; + } + }else if(atomic_test_bit(&smp_test_flag, SMP_IO_NO_INPUT_OUTPUT)){ + return BT_SMP_IO_NO_INPUT_OUTPUT; + } + #endif - if (bt_auth->passkey_display) { - return BT_SMP_IO_DISPLAY_ONLY; - } + /* Passkey Confirmation is valid only for LE SC */ + if (bt_auth->passkey_display && bt_auth->passkey_entry && + (bt_auth->passkey_confirm || !sc_supported)) { + return BT_SMP_IO_KEYBOARD_DISPLAY; + } + + /* DisplayYesNo is useful only for LE SC */ + if (sc_supported && bt_auth->passkey_display && + bt_auth->passkey_confirm) { + return BT_SMP_IO_DISPLAY_YESNO; + } + + if (bt_auth->passkey_entry) { + if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && + fixed_passkey != BT_PASSKEY_INVALID) { + return BT_SMP_IO_KEYBOARD_DISPLAY; + } else { + return BT_SMP_IO_KEYBOARD_ONLY; + } + } + + if (bt_auth->passkey_display) { + return BT_SMP_IO_DISPLAY_ONLY; + } no_callbacks: - if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && - fixed_passkey != BT_PASSKEY_INVALID) { - return BT_SMP_IO_DISPLAY_ONLY; - } else { - return BT_SMP_IO_NO_INPUT_OUTPUT; - } + if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && + fixed_passkey != BT_PASSKEY_INVALID) { + return BT_SMP_IO_DISPLAY_ONLY; + } else { + return BT_SMP_IO_NO_INPUT_OUTPUT; + } } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) @@ -336,129 +336,129 @@ static u8_t legacy_get_pair_method(struct bt_smp *smp, u8_t remote_io); static bool smp_keys_check(struct bt_conn *conn) { - if (atomic_test_bit(conn->flags, BT_CONN_FORCE_PAIR)) { - return false; - } + if (atomic_test_bit(conn->flags, BT_CONN_FORCE_PAIR)) { + return false; + } - if (!conn->le.keys) { - conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, - conn->id, &conn->le.dst); - if (!conn->le.keys) { - conn->le.keys = bt_keys_find(BT_KEYS_LTK, - conn->id, - &conn->le.dst); - } - } + if (!conn->le.keys) { + conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, + conn->id, &conn->le.dst); + if (!conn->le.keys) { + conn->le.keys = bt_keys_find(BT_KEYS_LTK, + conn->id, + &conn->le.dst); + } + } - if (!conn->le.keys || - !(conn->le.keys->keys & (BT_KEYS_LTK | BT_KEYS_LTK_P256))) { - return false; - } + if (!conn->le.keys || + !(conn->le.keys->keys & (BT_KEYS_LTK | BT_KEYS_LTK_P256))) { + return false; + } - if (conn->required_sec_level > BT_SECURITY_L2 && - !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { - return false; - } + if (conn->required_sec_level > BT_SECURITY_L2 && + !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { + return false; + } - if (conn->required_sec_level > BT_SECURITY_L3 && - !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED) && - !(conn->le.keys->keys & BT_KEYS_LTK_P256) && - !(conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE)) { - return false; - } + if (conn->required_sec_level > BT_SECURITY_L3 && + !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED) && + !(conn->le.keys->keys & BT_KEYS_LTK_P256) && + !(conn->le.keys->enc_size == BT_SMP_MAX_ENC_KEY_SIZE)) { + return false; + } - return true; + return true; } static u8_t get_pair_method(struct bt_smp *smp, u8_t remote_io) { - struct bt_smp_pairing *req, *rsp; + struct bt_smp_pairing *req, *rsp; #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - return legacy_get_pair_method(smp, remote_io); - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + return legacy_get_pair_method(smp, remote_io); + } #endif - req = (struct bt_smp_pairing *)&smp->preq[1]; - rsp = (struct bt_smp_pairing *)&smp->prsp[1]; + req = (struct bt_smp_pairing *)&smp->preq[1]; + rsp = (struct bt_smp_pairing *)&smp->prsp[1]; - if ((req->auth_req & rsp->auth_req) & BT_SMP_AUTH_SC) { - /* if one side has OOB data use OOB */ - if ((req->oob_flag | rsp->oob_flag) & BT_SMP_OOB_DATA_MASK) { - return LE_SC_OOB; - } - } + if ((req->auth_req & rsp->auth_req) & BT_SMP_AUTH_SC) { + /* if one side has OOB data use OOB */ + if ((req->oob_flag | rsp->oob_flag) & BT_SMP_OOB_DATA_MASK) { + return LE_SC_OOB; + } + } - if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) { - return JUST_WORKS; - } + if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) { + return JUST_WORKS; + } - /* if none side requires MITM use JustWorks */ - if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) { - return JUST_WORKS; - } + /* if none side requires MITM use JustWorks */ + if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) { + return JUST_WORKS; + } - return gen_method_sc[remote_io][get_io_capa()]; + return gen_method_sc[remote_io][get_io_capa()]; } static enum bt_security_err auth_err_get(u8_t smp_err) { - switch (smp_err) { - case BT_SMP_ERR_PASSKEY_ENTRY_FAILED: - case BT_SMP_ERR_DHKEY_CHECK_FAILED: - case BT_SMP_ERR_NUMERIC_COMP_FAILED: - case BT_SMP_ERR_CONFIRM_FAILED: - return BT_SECURITY_ERR_AUTH_FAIL; - case BT_SMP_ERR_OOB_NOT_AVAIL: - return BT_SECURITY_ERR_OOB_NOT_AVAILABLE; - case BT_SMP_ERR_AUTH_REQUIREMENTS: - case BT_SMP_ERR_ENC_KEY_SIZE: - return BT_SECURITY_ERR_AUTH_REQUIREMENT; - case BT_SMP_ERR_PAIRING_NOTSUPP: - case BT_SMP_ERR_CMD_NOTSUPP: - return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED; - case BT_SMP_ERR_REPEATED_ATTEMPTS: - case BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS: - case BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED: - return BT_SECURITY_ERR_PAIR_NOT_ALLOWED; - case BT_SMP_ERR_INVALID_PARAMS: - return BT_SECURITY_ERR_INVALID_PARAM; - case BT_SMP_ERR_UNSPECIFIED: - default: - return BT_SECURITY_ERR_UNSPECIFIED; - } + switch (smp_err) { + case BT_SMP_ERR_PASSKEY_ENTRY_FAILED: + case BT_SMP_ERR_DHKEY_CHECK_FAILED: + case BT_SMP_ERR_NUMERIC_COMP_FAILED: + case BT_SMP_ERR_CONFIRM_FAILED: + return BT_SECURITY_ERR_AUTH_FAIL; + case BT_SMP_ERR_OOB_NOT_AVAIL: + return BT_SECURITY_ERR_OOB_NOT_AVAILABLE; + case BT_SMP_ERR_AUTH_REQUIREMENTS: + case BT_SMP_ERR_ENC_KEY_SIZE: + return BT_SECURITY_ERR_AUTH_REQUIREMENT; + case BT_SMP_ERR_PAIRING_NOTSUPP: + case BT_SMP_ERR_CMD_NOTSUPP: + return BT_SECURITY_ERR_PAIR_NOT_SUPPORTED; + case BT_SMP_ERR_REPEATED_ATTEMPTS: + case BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS: + case BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED: + return BT_SECURITY_ERR_PAIR_NOT_ALLOWED; + case BT_SMP_ERR_INVALID_PARAMS: + return BT_SECURITY_ERR_INVALID_PARAM; + case BT_SMP_ERR_UNSPECIFIED: + default: + return BT_SECURITY_ERR_UNSPECIFIED; + } } static struct net_buf *smp_create_pdu(struct bt_smp *smp, u8_t op, size_t len) { - struct bt_smp_hdr *hdr; - struct net_buf *buf; - s32_t timeout; + struct bt_smp_hdr *hdr; + struct net_buf *buf; + s32_t timeout; - /* Don't if session had already timed out */ - if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { - timeout = K_NO_WAIT; - } else { - timeout = SMP_TIMEOUT; - } + /* Don't if session had already timed out */ + if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { + timeout = K_NO_WAIT; + } else { + timeout = SMP_TIMEOUT; + } - /* Use smaller timeout if returning an error since that could be - * caused by lack of buffers. - */ - buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout); - if (!buf) { - /* If it was not possible to allocate a buffer within the - * timeout marked it as timed out. - */ - atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); - return NULL; - } + /* Use smaller timeout if returning an error since that could be + * caused by lack of buffers. + */ + buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout); + if (!buf) { + /* If it was not possible to allocate a buffer within the + * timeout marked it as timed out. + */ + atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); + return NULL; + } - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->code = op; + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->code = op; - return buf; + return buf; } /* Cypher based Message Authentication Code (CMAC) with AES 128 bit @@ -469,215 +469,215 @@ static struct net_buf *smp_create_pdu(struct bt_smp *smp, u8_t op, size_t len) * Output : out ( message authentication code ) */ static int bt_smp_aes_cmac(const u8_t *key, const u8_t *in, size_t len, - u8_t *out) + u8_t *out) { - struct tc_aes_key_sched_struct sched; - struct tc_cmac_struct state; + struct tc_aes_key_sched_struct sched; + struct tc_cmac_struct state; - if (tc_cmac_setup(&state, key, &sched) == TC_CRYPTO_FAIL) { - return -EIO; - } + if (tc_cmac_setup(&state, key, &sched) == TC_CRYPTO_FAIL) { + return -EIO; + } - if (tc_cmac_update(&state, in, len) == TC_CRYPTO_FAIL) { - return -EIO; - } + if (tc_cmac_update(&state, in, len) == TC_CRYPTO_FAIL) { + return -EIO; + } - if (tc_cmac_final(out, &state) == TC_CRYPTO_FAIL) { - return -EIO; - } + if (tc_cmac_final(out, &state) == TC_CRYPTO_FAIL) { + return -EIO; + } - return 0; + return 0; } static int smp_f4(const u8_t *u, const u8_t *v, const u8_t *x, - u8_t z, u8_t res[16]) + u8_t z, u8_t res[16]) { - u8_t xs[16]; - u8_t m[65]; - int err; + u8_t xs[16]; + u8_t m[65]; + int err; - BT_DBG("u %s", bt_hex(u, 32)); - BT_DBG("v %s", bt_hex(v, 32)); - BT_DBG("x %s z 0x%x", bt_hex(x, 16), z); + BT_DBG("u %s", bt_hex(u, 32)); + BT_DBG("v %s", bt_hex(v, 32)); + BT_DBG("x %s z 0x%x", bt_hex(x, 16), z); - /* - * U, V and Z are concatenated and used as input m to the function - * AES-CMAC and X is used as the key k. - * - * Core Spec 4.2 Vol 3 Part H 2.2.5 - * - * note: - * bt_smp_aes_cmac uses BE data and smp_f4 accept LE so we swap - */ - sys_memcpy_swap(m, u, 32); - sys_memcpy_swap(m + 32, v, 32); - m[64] = z; + /* + * U, V and Z are concatenated and used as input m to the function + * AES-CMAC and X is used as the key k. + * + * Core Spec 4.2 Vol 3 Part H 2.2.5 + * + * note: + * bt_smp_aes_cmac uses BE data and smp_f4 accept LE so we swap + */ + sys_memcpy_swap(m, u, 32); + sys_memcpy_swap(m + 32, v, 32); + m[64] = z; - sys_memcpy_swap(xs, x, 16); + sys_memcpy_swap(xs, x, 16); - err = bt_smp_aes_cmac(xs, m, sizeof(m), res); - if (err) { - return err; - } + err = bt_smp_aes_cmac(xs, m, sizeof(m), res); + if (err) { + return err; + } - sys_mem_swap(res, 16); + sys_mem_swap(res, 16); - BT_DBG("res %s", bt_hex(res, 16)); + BT_DBG("res %s", bt_hex(res, 16)); - return err; + return err; } static int smp_f5(const u8_t *w, const u8_t *n1, const u8_t *n2, - const bt_addr_le_t *a1, const bt_addr_le_t *a2, u8_t *mackey, - u8_t *ltk) + const bt_addr_le_t *a1, const bt_addr_le_t *a2, u8_t *mackey, + u8_t *ltk) { - static const u8_t salt[16] = { 0x6c, 0x88, 0x83, 0x91, 0xaa, 0xf5, - 0xa5, 0x38, 0x60, 0x37, 0x0b, 0xdb, - 0x5a, 0x60, 0x83, 0xbe }; - u8_t m[53] = { 0x00, /* counter */ - 0x62, 0x74, 0x6c, 0x65, /* keyID */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*n1*/ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*2*/ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a1 */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a2 */ - 0x01, 0x00 /* length */ }; - u8_t t[16], ws[32]; - int err; + static const u8_t salt[16] = { 0x6c, 0x88, 0x83, 0x91, 0xaa, 0xf5, + 0xa5, 0x38, 0x60, 0x37, 0x0b, 0xdb, + 0x5a, 0x60, 0x83, 0xbe }; + u8_t m[53] = { 0x00, /* counter */ + 0x62, 0x74, 0x6c, 0x65, /* keyID */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*n1*/ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*2*/ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a1 */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a2 */ + 0x01, 0x00 /* length */ }; + u8_t t[16], ws[32]; + int err; - BT_DBG("w %s", bt_hex(w, 32)); - BT_DBG("n1 %s", bt_hex(n1, 16)); - BT_DBG("n2 %s", bt_hex(n2, 16)); + BT_DBG("w %s", bt_hex(w, 32)); + BT_DBG("n1 %s", bt_hex(n1, 16)); + BT_DBG("n2 %s", bt_hex(n2, 16)); - sys_memcpy_swap(ws, w, 32); + sys_memcpy_swap(ws, w, 32); - err = bt_smp_aes_cmac(salt, ws, 32, t); - if (err) { - return err; - } + err = bt_smp_aes_cmac(salt, ws, 32, t); + if (err) { + return err; + } - BT_DBG("t %s", bt_hex(t, 16)); + BT_DBG("t %s", bt_hex(t, 16)); - sys_memcpy_swap(m + 5, n1, 16); - sys_memcpy_swap(m + 21, n2, 16); - m[37] = a1->type; - sys_memcpy_swap(m + 38, a1->a.val, 6); - m[44] = a2->type; - sys_memcpy_swap(m + 45, a2->a.val, 6); + sys_memcpy_swap(m + 5, n1, 16); + sys_memcpy_swap(m + 21, n2, 16); + m[37] = a1->type; + sys_memcpy_swap(m + 38, a1->a.val, 6); + m[44] = a2->type; + sys_memcpy_swap(m + 45, a2->a.val, 6); - err = bt_smp_aes_cmac(t, m, sizeof(m), mackey); - if (err) { - return err; - } + err = bt_smp_aes_cmac(t, m, sizeof(m), mackey); + if (err) { + return err; + } - BT_DBG("mackey %1s", bt_hex(mackey, 16)); + BT_DBG("mackey %1s", bt_hex(mackey, 16)); - sys_mem_swap(mackey, 16); + sys_mem_swap(mackey, 16); - /* counter for ltk is 1 */ - m[0] = 0x01; + /* counter for ltk is 1 */ + m[0] = 0x01; - err = bt_smp_aes_cmac(t, m, sizeof(m), ltk); - if (err) { - return err; - } + err = bt_smp_aes_cmac(t, m, sizeof(m), ltk); + if (err) { + return err; + } - BT_DBG("ltk %s", bt_hex(ltk, 16)); + BT_DBG("ltk %s", bt_hex(ltk, 16)); - sys_mem_swap(ltk, 16); + sys_mem_swap(ltk, 16); - return 0; + return 0; } static int smp_f6(const u8_t *w, const u8_t *n1, const u8_t *n2, - const u8_t *r, const u8_t *iocap, const bt_addr_le_t *a1, - const bt_addr_le_t *a2, u8_t *check) + const u8_t *r, const u8_t *iocap, const bt_addr_le_t *a1, + const bt_addr_le_t *a2, u8_t *check) { - u8_t ws[16]; - u8_t m[65]; - int err; + u8_t ws[16]; + u8_t m[65]; + int err; - BT_DBG("w %s", bt_hex(w, 16)); - BT_DBG("n1 %s", bt_hex(n1, 16)); - BT_DBG("n2 %s", bt_hex(n2, 16)); - BT_DBG("r %s", bt_hex(r, 16)); - BT_DBG("io_cap %s", bt_hex(iocap, 3)); - BT_DBG("a1 %s", bt_hex(a1, 7)); - BT_DBG("a2 %s", bt_hex(a2, 7)); + BT_DBG("w %s", bt_hex(w, 16)); + BT_DBG("n1 %s", bt_hex(n1, 16)); + BT_DBG("n2 %s", bt_hex(n2, 16)); + BT_DBG("r %s", bt_hex(r, 16)); + BT_DBG("io_cap %s", bt_hex(iocap, 3)); + BT_DBG("a1 %s", bt_hex(a1, 7)); + BT_DBG("a2 %s", bt_hex(a2, 7)); - sys_memcpy_swap(m, n1, 16); - sys_memcpy_swap(m + 16, n2, 16); - sys_memcpy_swap(m + 32, r, 16); - sys_memcpy_swap(m + 48, iocap, 3); + sys_memcpy_swap(m, n1, 16); + sys_memcpy_swap(m + 16, n2, 16); + sys_memcpy_swap(m + 32, r, 16); + sys_memcpy_swap(m + 48, iocap, 3); - m[51] = a1->type; - memcpy(m + 52, a1->a.val, 6); - sys_memcpy_swap(m + 52, a1->a.val, 6); + m[51] = a1->type; + memcpy(m + 52, a1->a.val, 6); + sys_memcpy_swap(m + 52, a1->a.val, 6); - m[58] = a2->type; - memcpy(m + 59, a2->a.val, 6); - sys_memcpy_swap(m + 59, a2->a.val, 6); + m[58] = a2->type; + memcpy(m + 59, a2->a.val, 6); + sys_memcpy_swap(m + 59, a2->a.val, 6); - sys_memcpy_swap(ws, w, 16); + sys_memcpy_swap(ws, w, 16); - err = bt_smp_aes_cmac(ws, m, sizeof(m), check); - if (err) { - return err; - } + err = bt_smp_aes_cmac(ws, m, sizeof(m), check); + if (err) { + return err; + } - BT_DBG("res %s", bt_hex(check, 16)); + BT_DBG("res %s", bt_hex(check, 16)); - sys_mem_swap(check, 16); + sys_mem_swap(check, 16); - return 0; + return 0; } static int smp_g2(const u8_t u[32], const u8_t v[32], - const u8_t x[16], const u8_t y[16], u32_t *passkey) + const u8_t x[16], const u8_t y[16], u32_t *passkey) { - u8_t m[80], xs[16]; - int err; + u8_t m[80], xs[16]; + int err; - BT_DBG("u %s", bt_hex(u, 32)); - BT_DBG("v %s", bt_hex(v, 32)); - BT_DBG("x %s", bt_hex(x, 16)); - BT_DBG("y %s", bt_hex(y, 16)); + BT_DBG("u %s", bt_hex(u, 32)); + BT_DBG("v %s", bt_hex(v, 32)); + BT_DBG("x %s", bt_hex(x, 16)); + BT_DBG("y %s", bt_hex(y, 16)); - sys_memcpy_swap(m, u, 32); - sys_memcpy_swap(m + 32, v, 32); - sys_memcpy_swap(m + 64, y, 16); + sys_memcpy_swap(m, u, 32); + sys_memcpy_swap(m + 32, v, 32); + sys_memcpy_swap(m + 64, y, 16); - sys_memcpy_swap(xs, x, 16); + sys_memcpy_swap(xs, x, 16); - /* reuse xs (key) as buffer for result */ - err = bt_smp_aes_cmac(xs, m, sizeof(m), xs); - if (err) { - return err; - } - BT_DBG("res %s", bt_hex(xs, 16)); + /* reuse xs (key) as buffer for result */ + err = bt_smp_aes_cmac(xs, m, sizeof(m), xs); + if (err) { + return err; + } + BT_DBG("res %s", bt_hex(xs, 16)); - memcpy(passkey, xs + 12, 4); - *passkey = sys_be32_to_cpu(*passkey) % 1000000; + memcpy(passkey, xs + 12, 4); + *passkey = sys_be32_to_cpu(*passkey) % 1000000; - BT_DBG("passkey %u", *passkey); + BT_DBG("passkey %u", *passkey); - return 0; + return 0; } static u8_t get_encryption_key_size(struct bt_smp *smp) { - struct bt_smp_pairing *req, *rsp; + struct bt_smp_pairing *req, *rsp; - req = (struct bt_smp_pairing *)&smp->preq[1]; - rsp = (struct bt_smp_pairing *)&smp->prsp[1]; + req = (struct bt_smp_pairing *)&smp->preq[1]; + rsp = (struct bt_smp_pairing *)&smp->prsp[1]; - /* - * The smaller value of the initiating and responding devices maximum - * encryption key length parameters shall be used as the encryption key - * size. - */ - return MIN(req->max_key_size, rsp->max_key_size); + /* + * The smaller value of the initiating and responding devices maximum + * encryption key length parameters shall be used as the encryption key + * size. + */ + return MIN(req->max_key_size, rsp->max_key_size); } /* Check that if a new pairing procedure with an existing bond will not lower @@ -685,62 +685,62 @@ static u8_t get_encryption_key_size(struct bt_smp *smp) */ static bool update_keys_check(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; + struct bt_conn *conn = smp->chan.chan.conn; - if (!conn->le.keys) { - conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); - } + if (!conn->le.keys) { + conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); + } - if (!conn->le.keys || - !(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { - return true; - } + if (!conn->le.keys || + !(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { + return true; + } - if (conn->le.keys->enc_size > get_encryption_key_size(smp)) { - return false; - } + if (conn->le.keys->enc_size > get_encryption_key_size(smp)) { + return false; + } - if ((conn->le.keys->keys & BT_KEYS_LTK_P256) && - !atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - return false; - } + if ((conn->le.keys->keys & BT_KEYS_LTK_P256) && + !atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + return false; + } - if ((conn->le.keys->flags & BT_KEYS_AUTHENTICATED) && - smp->method == JUST_WORKS) { - return false; - } + if ((conn->le.keys->flags & BT_KEYS_AUTHENTICATED) && + smp->method == JUST_WORKS) { + return false; + } - if (!IS_ENABLED(CONFIG_BT_SMP_ALLOW_UNAUTH_OVERWRITE) && - (!(conn->le.keys->flags & BT_KEYS_AUTHENTICATED) - && smp->method == JUST_WORKS)) { - return false; - } + if (!IS_ENABLED(CONFIG_BT_SMP_ALLOW_UNAUTH_OVERWRITE) && + (!(conn->le.keys->flags & BT_KEYS_AUTHENTICATED) + && smp->method == JUST_WORKS)) { + return false; + } - return true; + return true; } static bool update_debug_keys_check(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; + struct bt_conn *conn = smp->chan.chan.conn; - if (!conn->le.keys) { - conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); - } + if (!conn->le.keys) { + conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); + } - if (!conn->le.keys || - !(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { - return true; - } + if (!conn->le.keys || + !(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { + return true; + } - if (conn->le.keys->flags & BT_KEYS_DEBUG) { - return false; - } + if (conn->le.keys->flags & BT_KEYS_DEBUG) { + return false; + } - return true; + return true; } #if defined(CONFIG_BT_PRIVACY) || defined(CONFIG_BT_SIGNING) || \ - !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) + !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) /* For TX callbacks */ static void smp_pairing_complete(struct bt_smp *smp, u8_t status); #if defined(CONFIG_BT_BREDR) @@ -749,40 +749,40 @@ static void smp_pairing_br_complete(struct bt_smp_br *smp, u8_t status); static void smp_check_complete(struct bt_conn *conn, u8_t dist_complete) { - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - if (conn->type == BT_CONN_TYPE_LE) { - struct bt_smp *smp; + if (conn->type == BT_CONN_TYPE_LE) { + struct bt_smp *smp; - chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_SMP); - __ASSERT(chan, "No SMP channel found"); + chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_SMP); + __ASSERT(chan, "No SMP channel found"); - smp = CONTAINER_OF(chan, struct bt_smp, chan); - smp->local_dist &= ~dist_complete; + smp = CONTAINER_OF(chan, struct bt_smp, chan); + smp->local_dist &= ~dist_complete; - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_complete(smp, 0); + } - return; - } + return; + } #if defined(CONFIG_BT_BREDR) - if (conn->type == BT_CONN_TYPE_BR) { - struct bt_smp_br *smp; + if (conn->type == BT_CONN_TYPE_BR) { + struct bt_smp_br *smp; - chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_BR_SMP); - __ASSERT(chan, "No SMP channel found"); + chan = bt_l2cap_le_lookup_tx_cid(conn, BT_L2CAP_CID_BR_SMP); + __ASSERT(chan, "No SMP channel found"); - smp = CONTAINER_OF(chan, struct bt_smp_br, chan); - smp->local_dist &= ~dist_complete; + smp = CONTAINER_OF(chan, struct bt_smp_br, chan); + smp->local_dist &= ~dist_complete; - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_br_complete(smp, 0); - } - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_br_complete(smp, 0); + } + } #endif } #endif @@ -790,3442 +790,3442 @@ static void smp_check_complete(struct bt_conn *conn, u8_t dist_complete) #if defined(CONFIG_BT_PRIVACY) static void smp_id_sent(struct bt_conn *conn, void *user_data) { - smp_check_complete(conn, BT_SMP_DIST_ID_KEY); + smp_check_complete(conn, BT_SMP_DIST_ID_KEY); } #endif /* CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_SIGNING) static void smp_sign_info_sent(struct bt_conn *conn, void *user_data) { - smp_check_complete(conn, BT_SMP_DIST_SIGN); + smp_check_complete(conn, BT_SMP_DIST_SIGN); } #endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_BREDR) static int smp_h6(const u8_t w[16], const u8_t key_id[4], u8_t res[16]) { - u8_t ws[16]; - u8_t key_id_s[4]; - int err; + u8_t ws[16]; + u8_t key_id_s[4]; + int err; - BT_DBG("w %s", bt_hex(w, 16)); - BT_DBG("key_id %s", bt_hex(key_id, 4)); + BT_DBG("w %s", bt_hex(w, 16)); + BT_DBG("key_id %s", bt_hex(key_id, 4)); - sys_memcpy_swap(ws, w, 16); - sys_memcpy_swap(key_id_s, key_id, 4); + sys_memcpy_swap(ws, w, 16); + sys_memcpy_swap(key_id_s, key_id, 4); - err = bt_smp_aes_cmac(ws, key_id_s, 4, res); - if (err) { - return err; - } + err = bt_smp_aes_cmac(ws, key_id_s, 4, res); + if (err) { + return err; + } - BT_DBG("res %s", bt_hex(res, 16)); + BT_DBG("res %s", bt_hex(res, 16)); - sys_mem_swap(res, 16); + sys_mem_swap(res, 16); - return 0; + return 0; } static int smp_h7(const u8_t salt[16], const u8_t w[16], u8_t res[16]) { - u8_t ws[16]; - u8_t salt_s[16]; - int err; + u8_t ws[16]; + u8_t salt_s[16]; + int err; - BT_DBG("w %s", bt_hex(w, 16)); - BT_DBG("salt %s", bt_hex(salt, 16)); + BT_DBG("w %s", bt_hex(w, 16)); + BT_DBG("salt %s", bt_hex(salt, 16)); - sys_memcpy_swap(ws, w, 16); - sys_memcpy_swap(salt_s, salt, 16); + sys_memcpy_swap(ws, w, 16); + sys_memcpy_swap(salt_s, salt, 16); - err = bt_smp_aes_cmac(salt_s, ws, 16, res); - if (err) { - return err; - } + err = bt_smp_aes_cmac(salt_s, ws, 16, res); + if (err) { + return err; + } - BT_DBG("res %s", bt_hex(res, 16)); + BT_DBG("res %s", bt_hex(res, 16)); - sys_mem_swap(res, 16); + sys_mem_swap(res, 16); - return 0; + return 0; } static void sc_derive_link_key(struct bt_smp *smp) { - /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ - static const u8_t lebr[4] = { 0x72, 0x62, 0x65, 0x6c }; - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys_link_key *link_key; - u8_t ilk[16]; + /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ + static const u8_t lebr[4] = { 0x72, 0x62, 0x65, 0x6c }; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys_link_key *link_key; + u8_t ilk[16]; - BT_DBG(""); + BT_DBG(""); - /* TODO handle errors? */ + /* TODO handle errors? */ - /* - * At this point remote device identity is known so we can use - * destination address here - */ - link_key = bt_keys_get_link_key(&conn->le.dst.a); - if (!link_key) { - return; - } + /* + * At this point remote device identity is known so we can use + * destination address here + */ + link_key = bt_keys_get_link_key(&conn->le.dst.a); + if (!link_key) { + return; + } - if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) { - /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ - static const u8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00 }; + if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) { + /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ + static const u8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00 }; - if (smp_h7(salt, conn->le.keys->ltk.val, ilk)) { - bt_keys_link_key_clear(link_key); - return; - } - } else { - /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ - static const u8_t tmp1[4] = { 0x31, 0x70, 0x6d, 0x74 }; + if (smp_h7(salt, conn->le.keys->ltk.val, ilk)) { + bt_keys_link_key_clear(link_key); + return; + } + } else { + /* constants as specified in Core Spec Vol.3 Part H 2.4.2.4 */ + static const u8_t tmp1[4] = { 0x31, 0x70, 0x6d, 0x74 }; - if (smp_h6(conn->le.keys->ltk.val, tmp1, ilk)) { - bt_keys_link_key_clear(link_key); - return; - } - } + if (smp_h6(conn->le.keys->ltk.val, tmp1, ilk)) { + bt_keys_link_key_clear(link_key); + return; + } + } - if (smp_h6(ilk, lebr, link_key->val)) { - bt_keys_link_key_clear(link_key); - } + if (smp_h6(ilk, lebr, link_key->val)) { + bt_keys_link_key_clear(link_key); + } - link_key->flags |= BT_LINK_KEY_SC; + link_key->flags |= BT_LINK_KEY_SC; - if (conn->le.keys->flags & BT_KEYS_AUTHENTICATED) { - link_key->flags |= BT_LINK_KEY_AUTHENTICATED; - } else { - link_key->flags &= ~BT_LINK_KEY_AUTHENTICATED; - } + if (conn->le.keys->flags & BT_KEYS_AUTHENTICATED) { + link_key->flags |= BT_LINK_KEY_AUTHENTICATED; + } else { + link_key->flags &= ~BT_LINK_KEY_AUTHENTICATED; + } } static void smp_br_reset(struct bt_smp_br *smp) { - k_delayed_work_cancel(&smp->work); + k_delayed_work_cancel(&smp->work); - atomic_set(smp->flags, 0); - atomic_set(&smp->allowed_cmds, 0); + atomic_set(smp->flags, 0); + atomic_set(&smp->allowed_cmds, 0); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); } static void smp_pairing_br_complete(struct bt_smp_br *smp, u8_t status) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys; - bt_addr_le_t addr; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys; + bt_addr_le_t addr; - BT_DBG("status 0x%x", status); + BT_DBG("status 0x%x", status); - /* For dualmode devices LE address is same as BR/EDR address - * and is of public type. - */ - bt_addr_copy(&addr.a, &conn->br.dst); - addr.type = BT_ADDR_LE_PUBLIC; - keys = bt_keys_find_addr(conn->id, &addr); + /* For dualmode devices LE address is same as BR/EDR address + * and is of public type. + */ + bt_addr_copy(&addr.a, &conn->br.dst); + addr.type = BT_ADDR_LE_PUBLIC; + keys = bt_keys_find_addr(conn->id, &addr); - if (status) { - if (keys) { - bt_keys_clear(keys); - } + if (status) { + if (keys) { + bt_keys_clear(keys); + } - if (bt_auth && bt_auth->pairing_failed) { - bt_auth->pairing_failed(smp->chan.chan.conn, - auth_err_get(status)); - } - } else { - bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND); + if (bt_auth && bt_auth->pairing_failed) { + bt_auth->pairing_failed(smp->chan.chan.conn, + auth_err_get(status)); + } + } else { + bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND); - if (bond_flag && keys) { - bt_keys_store(keys); - } + if (bond_flag && keys) { + bt_keys_store(keys); + } - if (bt_auth && bt_auth->pairing_complete) { - bt_auth->pairing_complete(smp->chan.chan.conn, - bond_flag); - } - } + if (bt_auth && bt_auth->pairing_complete) { + bt_auth->pairing_complete(smp->chan.chan.conn, + bond_flag); + } + } - smp_br_reset(smp); + smp_br_reset(smp); } static void smp_br_timeout(struct k_work *work) { - struct bt_smp_br *smp = CONTAINER_OF(work, struct bt_smp_br, work); + struct bt_smp_br *smp = CONTAINER_OF(work, struct bt_smp_br, work); - BT_ERR("SMP Timeout"); + BT_ERR("SMP Timeout"); - smp_pairing_br_complete(smp, BT_SMP_ERR_UNSPECIFIED); - atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); + smp_pairing_br_complete(smp, BT_SMP_ERR_UNSPECIFIED); + atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); } static void smp_br_send(struct bt_smp_br *smp, struct net_buf *buf, - bt_conn_tx_cb_t cb) + bt_conn_tx_cb_t cb) { - bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_BR_SMP, buf, cb, - NULL); - k_delayed_work_submit(&smp->work, SMP_TIMEOUT); + bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_BR_SMP, buf, cb, + NULL); + k_delayed_work_submit(&smp->work, SMP_TIMEOUT); } static void bt_smp_br_connected(struct bt_l2cap_chan *chan) { - struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); + struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); - BT_DBG("chan %p cid 0x%04x", chan, - CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid); + BT_DBG("chan %p cid 0x%04x", chan, + CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid); - atomic_set_bit(smp->flags, SMP_FLAG_BR_CONNECTED); + atomic_set_bit(smp->flags, SMP_FLAG_BR_CONNECTED); - /* - * if this flag is set it means pairing was requested before channel - * was connected - */ - if (atomic_test_bit(smp->flags, SMP_FLAG_BR_PAIR)) { - bt_smp_br_send_pairing_req(chan->conn); - } + /* + * if this flag is set it means pairing was requested before channel + * was connected + */ + if (atomic_test_bit(smp->flags, SMP_FLAG_BR_PAIR)) { + bt_smp_br_send_pairing_req(chan->conn); + } } static void bt_smp_br_disconnected(struct bt_l2cap_chan *chan) { - struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); + struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); - BT_DBG("chan %p cid 0x%04x", chan, - CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid); + BT_DBG("chan %p cid 0x%04x", chan, + CONTAINER_OF(chan, struct bt_l2cap_br_chan, chan)->tx.cid); - k_delayed_work_cancel(&smp->work); + k_delayed_work_cancel(&smp->work); - (void)memset(smp, 0, sizeof(*smp)); + (void)memset(smp, 0, sizeof(*smp)); } static void smp_br_init(struct bt_smp_br *smp) { - /* Initialize SMP context without clearing L2CAP channel context */ - (void)memset((u8_t *)smp + sizeof(smp->chan), 0, - sizeof(*smp) - (sizeof(smp->chan) + sizeof(smp->work))); + /* Initialize SMP context without clearing L2CAP channel context */ + (void)memset((u8_t *)smp + sizeof(smp->chan), 0, + sizeof(*smp) - (sizeof(smp->chan) + sizeof(smp->work))); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL); } static void smp_br_derive_ltk(struct bt_smp_br *smp) { - /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ - static const u8_t brle[4] = { 0x65, 0x6c, 0x72, 0x62 }; - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys_link_key *link_key = conn->br.link_key; - struct bt_keys *keys; - bt_addr_le_t addr; - u8_t ilk[16]; + /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ + static const u8_t brle[4] = { 0x65, 0x6c, 0x72, 0x62 }; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys_link_key *link_key = conn->br.link_key; + struct bt_keys *keys; + bt_addr_le_t addr; + u8_t ilk[16]; - BT_DBG(""); + BT_DBG(""); - if (!link_key) { - return; - } + if (!link_key) { + return; + } - if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) && conn->encrypt != 0x02) { - BT_WARN("Using P192 Link Key for P256 LTK derivation"); - } + if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) && conn->encrypt != 0x02) { + BT_WARN("Using P192 Link Key for P256 LTK derivation"); + } - /* - * For dualmode devices LE address is same as BR/EDR address and is of - * public type. - */ - bt_addr_copy(&addr.a, &conn->br.dst); - addr.type = BT_ADDR_LE_PUBLIC; + /* + * For dualmode devices LE address is same as BR/EDR address and is of + * public type. + */ + bt_addr_copy(&addr.a, &conn->br.dst); + addr.type = BT_ADDR_LE_PUBLIC; - keys = bt_keys_get_type(BT_KEYS_LTK_P256, conn->id, &addr); - if (!keys) { - BT_ERR("No keys space for %s", bt_addr_le_str(&addr)); - return; - } + keys = bt_keys_get_type(BT_KEYS_LTK_P256, conn->id, &addr); + if (!keys) { + BT_ERR("No keys space for %s", bt_addr_le_str(&addr)); + return; + } - if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) { - /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ - static const u8_t salt[16] = { 0x32, 0x70, 0x6d, 0x74, - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00 }; + if (atomic_test_bit(smp->flags, SMP_FLAG_CT2)) { + /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ + static const u8_t salt[16] = { 0x32, 0x70, 0x6d, 0x74, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00 }; - if (smp_h7(salt, link_key->val, ilk)) { - bt_keys_link_key_clear(link_key); - return; - } - } else { - /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ - static const u8_t tmp2[4] = { 0x32, 0x70, 0x6d, 0x74 }; + if (smp_h7(salt, link_key->val, ilk)) { + bt_keys_link_key_clear(link_key); + return; + } + } else { + /* constants as specified in Core Spec Vol.3 Part H 2.4.2.5 */ + static const u8_t tmp2[4] = { 0x32, 0x70, 0x6d, 0x74 }; - if (smp_h6(link_key->val, tmp2, ilk)) { - bt_keys_clear(keys); - return; - } - } + if (smp_h6(link_key->val, tmp2, ilk)) { + bt_keys_clear(keys); + return; + } + } - if (smp_h6(ilk, brle, keys->ltk.val)) { - bt_keys_clear(keys); - return; - } + if (smp_h6(ilk, brle, keys->ltk.val)) { + bt_keys_clear(keys); + return; + } - (void)memset(keys->ltk.ediv, 0, sizeof(keys->ltk.ediv)); - (void)memset(keys->ltk.rand, 0, sizeof(keys->ltk.rand)); - keys->enc_size = smp->enc_key_size; + (void)memset(keys->ltk.ediv, 0, sizeof(keys->ltk.ediv)); + (void)memset(keys->ltk.rand, 0, sizeof(keys->ltk.rand)); + keys->enc_size = smp->enc_key_size; - if (link_key->flags & BT_LINK_KEY_AUTHENTICATED) { - keys->flags |= BT_KEYS_AUTHENTICATED; - } else { - keys->flags &= ~BT_KEYS_AUTHENTICATED; - } + if (link_key->flags & BT_LINK_KEY_AUTHENTICATED) { + keys->flags |= BT_KEYS_AUTHENTICATED; + } else { + keys->flags &= ~BT_KEYS_AUTHENTICATED; + } - BT_DBG("LTK derived from LinkKey"); + BT_DBG("LTK derived from LinkKey"); } static struct net_buf *smp_br_create_pdu(struct bt_smp_br *smp, u8_t op, - size_t len) + size_t len) { - struct bt_smp_hdr *hdr; - struct net_buf *buf; - s32_t timeout; + struct bt_smp_hdr *hdr; + struct net_buf *buf; + s32_t timeout; - /* Don't if session had already timed out */ - if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { - timeout = K_NO_WAIT; - } else { - timeout = SMP_TIMEOUT; - } + /* Don't if session had already timed out */ + if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { + timeout = K_NO_WAIT; + } else { + timeout = SMP_TIMEOUT; + } - /* Use smaller timeout if returning an error since that could be - * caused by lack of buffers. - */ - buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout); - if (!buf) { - /* If it was not possible to allocate a buffer within the - * timeout marked it as timed out. - */ - atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); - return NULL; - } + /* Use smaller timeout if returning an error since that could be + * caused by lack of buffers. + */ + buf = bt_l2cap_create_pdu_timeout(NULL, 0, timeout); + if (!buf) { + /* If it was not possible to allocate a buffer within the + * timeout marked it as timed out. + */ + atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); + return NULL; + } - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->code = op; + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->code = op; - return buf; + return buf; } static void smp_br_distribute_keys(struct bt_smp_br *smp) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys; - bt_addr_le_t addr; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys; + bt_addr_le_t addr; - /* - * For dualmode devices LE address is same as BR/EDR address and is of - * public type. - */ - bt_addr_copy(&addr.a, &conn->br.dst); - addr.type = BT_ADDR_LE_PUBLIC; + /* + * For dualmode devices LE address is same as BR/EDR address and is of + * public type. + */ + bt_addr_copy(&addr.a, &conn->br.dst); + addr.type = BT_ADDR_LE_PUBLIC; - keys = bt_keys_get_addr(conn->id, &addr); - if (!keys) { - BT_ERR("No keys space for %s", bt_addr_le_str(&addr)); - return; - } + keys = bt_keys_get_addr(conn->id, &addr); + if (!keys) { + BT_ERR("No keys space for %s", bt_addr_le_str(&addr)); + return; + } #if defined(CONFIG_BT_PRIVACY) - if (smp->local_dist & BT_SMP_DIST_ID_KEY) { - struct bt_smp_ident_info *id_info; - struct bt_smp_ident_addr_info *id_addr_info; - struct net_buf *buf; + if (smp->local_dist & BT_SMP_DIST_ID_KEY) { + struct bt_smp_ident_info *id_info; + struct bt_smp_ident_addr_info *id_addr_info; + struct net_buf *buf; - smp->local_dist &= ~BT_SMP_DIST_ID_KEY; + smp->local_dist &= ~BT_SMP_DIST_ID_KEY; - buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_INFO, - sizeof(*id_info)); - if (!buf) { - BT_ERR("Unable to allocate Ident Info buffer"); - return; - } + buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_INFO, + sizeof(*id_info)); + if (!buf) { + BT_ERR("Unable to allocate Ident Info buffer"); + return; + } - id_info = net_buf_add(buf, sizeof(*id_info)); - memcpy(id_info->irk, bt_dev.irk[conn->id], 16); + id_info = net_buf_add(buf, sizeof(*id_info)); + memcpy(id_info->irk, bt_dev.irk[conn->id], 16); - smp_br_send(smp, buf, NULL); + smp_br_send(smp, buf, NULL); - buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO, - sizeof(*id_addr_info)); - if (!buf) { - BT_ERR("Unable to allocate Ident Addr Info buffer"); - return; - } + buf = smp_br_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO, + sizeof(*id_addr_info)); + if (!buf) { + BT_ERR("Unable to allocate Ident Addr Info buffer"); + return; + } - id_addr_info = net_buf_add(buf, sizeof(*id_addr_info)); - bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]); + id_addr_info = net_buf_add(buf, sizeof(*id_addr_info)); + bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]); - smp_br_send(smp, buf, smp_id_sent); - } + smp_br_send(smp, buf, smp_id_sent); + } #endif /* CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_SIGNING) - if (smp->local_dist & BT_SMP_DIST_SIGN) { - struct bt_smp_signing_info *info; - struct net_buf *buf; + if (smp->local_dist & BT_SMP_DIST_SIGN) { + struct bt_smp_signing_info *info; + struct net_buf *buf; - smp->local_dist &= ~BT_SMP_DIST_SIGN; + smp->local_dist &= ~BT_SMP_DIST_SIGN; - buf = smp_br_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO, - sizeof(*info)); - if (!buf) { - BT_ERR("Unable to allocate Signing Info buffer"); - return; - } + buf = smp_br_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO, + sizeof(*info)); + if (!buf) { + BT_ERR("Unable to allocate Signing Info buffer"); + return; + } - info = net_buf_add(buf, sizeof(*info)); + info = net_buf_add(buf, sizeof(*info)); - bt_rand(info->csrk, sizeof(info->csrk)); + bt_rand(info->csrk, sizeof(info->csrk)); - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK); - memcpy(keys->local_csrk.val, info->csrk, 16); - keys->local_csrk.cnt = 0U; - } + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK); + memcpy(keys->local_csrk.val, info->csrk, 16); + keys->local_csrk.cnt = 0U; + } - smp_br_send(smp, buf, smp_sign_info_sent); - } + smp_br_send(smp, buf, smp_sign_info_sent); + } #endif /* CONFIG_BT_SIGNING */ } static bool smp_br_pairing_allowed(struct bt_smp_br *smp) { - if (smp->chan.chan.conn->encrypt == 0x02) { - return true; - } + if (smp->chan.chan.conn->encrypt == 0x02) { + return true; + } - if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) && - smp->chan.chan.conn->encrypt == 0x01) { - BT_WARN("Allowing BR/EDR SMP with P-192 key"); - return true; - } + if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR) && + smp->chan.chan.conn->encrypt == 0x01) { + BT_WARN("Allowing BR/EDR SMP with P-192 key"); + return true; + } - return false; + return false; } static u8_t smp_br_pairing_req(struct bt_smp_br *smp, struct net_buf *buf) { - struct bt_smp_pairing *req = (void *)buf->data; - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_pairing *rsp; - struct net_buf *rsp_buf; - u8_t max_key_size; + struct bt_smp_pairing *req = (void *)buf->data; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_pairing *rsp; + struct net_buf *rsp_buf; + u8_t max_key_size; - BT_DBG(""); + BT_DBG(""); - /* - * If a Pairing Request is received over the BR/EDR transport when - * either cross-transport key derivation/generation is not supported or - * the BR/EDR transport is not encrypted using a Link Key generated - * using P256, a Pairing Failed shall be sent with the error code - * "Cross-transport Key Derivation/Generation not allowed" (0x0E)." - */ - if (!smp_br_pairing_allowed(smp)) { - return BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED; - } + /* + * If a Pairing Request is received over the BR/EDR transport when + * either cross-transport key derivation/generation is not supported or + * the BR/EDR transport is not encrypted using a Link Key generated + * using P256, a Pairing Failed shall be sent with the error code + * "Cross-transport Key Derivation/Generation not allowed" (0x0E)." + */ + if (!smp_br_pairing_allowed(smp)) { + return BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED; + } - max_key_size = bt_conn_enc_key_size(conn); - if (!max_key_size) { - return BT_SMP_ERR_UNSPECIFIED; - } + max_key_size = bt_conn_enc_key_size(conn); + if (!max_key_size) { + return BT_SMP_ERR_UNSPECIFIED; + } - if (req->max_key_size != max_key_size) { - return BT_SMP_ERR_ENC_KEY_SIZE; - } + if (req->max_key_size != max_key_size) { + return BT_SMP_ERR_ENC_KEY_SIZE; + } - rsp_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp)); - if (!rsp_buf) { - return BT_SMP_ERR_UNSPECIFIED; - } + rsp_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp)); + if (!rsp_buf) { + return BT_SMP_ERR_UNSPECIFIED; + } - smp_br_init(smp); - smp->enc_key_size = max_key_size; + smp_br_init(smp); + smp->enc_key_size = max_key_size; - /* - * If Secure Connections pairing has been initiated over BR/EDR, the IO - * Capability, OOB data flag and Auth Req fields of the SM Pairing - * Request/Response PDU shall be set to zero on transmission, and - * ignored on reception. - */ - rsp = net_buf_add(rsp_buf, sizeof(*rsp)); + /* + * If Secure Connections pairing has been initiated over BR/EDR, the IO + * Capability, OOB data flag and Auth Req fields of the SM Pairing + * Request/Response PDU shall be set to zero on transmission, and + * ignored on reception. + */ + rsp = net_buf_add(rsp_buf, sizeof(*rsp)); - rsp->auth_req = 0x00; - rsp->io_capability = 0x00; - rsp->oob_flag = 0x00; - rsp->max_key_size = max_key_size; - rsp->init_key_dist = (req->init_key_dist & BR_RECV_KEYS_SC); - rsp->resp_key_dist = (req->resp_key_dist & BR_RECV_KEYS_SC); + rsp->auth_req = 0x00; + rsp->io_capability = 0x00; + rsp->oob_flag = 0x00; + rsp->max_key_size = max_key_size; + rsp->init_key_dist = (req->init_key_dist & BR_RECV_KEYS_SC); + rsp->resp_key_dist = (req->resp_key_dist & BR_RECV_KEYS_SC); - smp->local_dist = rsp->resp_key_dist; - smp->remote_dist = rsp->init_key_dist; + smp->local_dist = rsp->resp_key_dist; + smp->remote_dist = rsp->init_key_dist; - smp_br_send(smp, rsp_buf, NULL); + smp_br_send(smp, rsp_buf, NULL); - atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); + atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); - /* derive LTK if requested and clear distribution bits */ - if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) && - (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) { - smp_br_derive_ltk(smp); - } - smp->local_dist &= ~BT_SMP_DIST_ENC_KEY; - smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; + /* derive LTK if requested and clear distribution bits */ + if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) && + (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) { + smp_br_derive_ltk(smp); + } + smp->local_dist &= ~BT_SMP_DIST_ENC_KEY; + smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; - /* BR/EDR acceptor is like LE Slave and distributes keys first */ - smp_br_distribute_keys(smp); + /* BR/EDR acceptor is like LE Slave and distributes keys first */ + smp_br_distribute_keys(smp); - if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); - } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); - } + if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); + } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); + } - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_br_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_br_complete(smp, 0); + } - return 0; + return 0; } static u8_t smp_br_pairing_rsp(struct bt_smp_br *smp, struct net_buf *buf) { - struct bt_smp_pairing *rsp = (void *)buf->data; - struct bt_conn *conn = smp->chan.chan.conn; - u8_t max_key_size; + struct bt_smp_pairing *rsp = (void *)buf->data; + struct bt_conn *conn = smp->chan.chan.conn; + u8_t max_key_size; - BT_DBG(""); + BT_DBG(""); - max_key_size = bt_conn_enc_key_size(conn); - if (!max_key_size) { - return BT_SMP_ERR_UNSPECIFIED; - } + max_key_size = bt_conn_enc_key_size(conn); + if (!max_key_size) { + return BT_SMP_ERR_UNSPECIFIED; + } - if (rsp->max_key_size != max_key_size) { - return BT_SMP_ERR_ENC_KEY_SIZE; - } + if (rsp->max_key_size != max_key_size) { + return BT_SMP_ERR_ENC_KEY_SIZE; + } - smp->local_dist &= rsp->init_key_dist; - smp->remote_dist &= rsp->resp_key_dist; + smp->local_dist &= rsp->init_key_dist; + smp->remote_dist &= rsp->resp_key_dist; - smp->local_dist &= SEND_KEYS_SC; - smp->remote_dist &= RECV_KEYS_SC; + smp->local_dist &= SEND_KEYS_SC; + smp->remote_dist &= RECV_KEYS_SC; - /* slave distributes its keys first */ + /* slave distributes its keys first */ - if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); - } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); - } + if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); + } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); + } - /* derive LTK if requested and clear distribution bits */ - if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) && - (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) { - smp_br_derive_ltk(smp); - } - smp->local_dist &= ~BT_SMP_DIST_ENC_KEY; - smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; + /* derive LTK if requested and clear distribution bits */ + if ((smp->local_dist & BT_SMP_DIST_ENC_KEY) && + (smp->remote_dist & BT_SMP_DIST_ENC_KEY)) { + smp_br_derive_ltk(smp); + } + smp->local_dist &= ~BT_SMP_DIST_ENC_KEY; + smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; - /* Pairing acceptor distributes it's keys first */ - if (smp->remote_dist) { - return 0; - } + /* Pairing acceptor distributes it's keys first */ + if (smp->remote_dist) { + return 0; + } - smp_br_distribute_keys(smp); + smp_br_distribute_keys(smp); - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_br_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_br_complete(smp, 0); + } - return 0; + return 0; } static u8_t smp_br_pairing_failed(struct bt_smp_br *smp, struct net_buf *buf) { - struct bt_smp_pairing_fail *req = (void *)buf->data; + struct bt_smp_pairing_fail *req = (void *)buf->data; - BT_ERR("reason 0x%x", req->reason); + BT_ERR("reason 0x%x", req->reason); - smp_pairing_br_complete(smp, req->reason); - smp_br_reset(smp); + smp_pairing_br_complete(smp, req->reason); + smp_br_reset(smp); - /* return no error to avoid sending Pairing Failed in response */ - return 0; + /* return no error to avoid sending Pairing Failed in response */ + return 0; } static u8_t smp_br_ident_info(struct bt_smp_br *smp, struct net_buf *buf) { - struct bt_smp_ident_info *req = (void *)buf->data; - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys; - bt_addr_le_t addr; + struct bt_smp_ident_info *req = (void *)buf->data; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys; + bt_addr_le_t addr; - BT_DBG(""); + BT_DBG(""); - /* TODO should we resolve LE address if matching RPA is connected? */ + /* TODO should we resolve LE address if matching RPA is connected? */ - /* - * For dualmode devices LE address is same as BR/EDR address and is of - * public type. - */ - bt_addr_copy(&addr.a, &conn->br.dst); - addr.type = BT_ADDR_LE_PUBLIC; + /* + * For dualmode devices LE address is same as BR/EDR address and is of + * public type. + */ + bt_addr_copy(&addr.a, &conn->br.dst); + addr.type = BT_ADDR_LE_PUBLIC; - keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &addr); - if (!keys) { - BT_ERR("Unable to get keys for %s", bt_addr_le_str(&addr)); - return BT_SMP_ERR_UNSPECIFIED; - } + keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &addr); + if (!keys) { + BT_ERR("Unable to get keys for %s", bt_addr_le_str(&addr)); + return BT_SMP_ERR_UNSPECIFIED; + } - memcpy(keys->irk.val, req->irk, sizeof(keys->irk.val)); + memcpy(keys->irk.val, req->irk, sizeof(keys->irk.val)); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO); - return 0; + return 0; } static u8_t smp_br_ident_addr_info(struct bt_smp_br *smp, - struct net_buf *buf) + struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_ident_addr_info *req = (void *)buf->data; - bt_addr_le_t addr; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_ident_addr_info *req = (void *)buf->data; + bt_addr_le_t addr; - BT_DBG("identity %s", bt_addr_le_str(&req->addr)); + BT_DBG("identity %s", bt_addr_le_str(&req->addr)); - /* - * For dual mode device identity address must be same as BR/EDR address - * and be of public type. So if received one doesn't match BR/EDR - * address we fail. - */ + /* + * For dual mode device identity address must be same as BR/EDR address + * and be of public type. So if received one doesn't match BR/EDR + * address we fail. + */ - bt_addr_copy(&addr.a, &conn->br.dst); - addr.type = BT_ADDR_LE_PUBLIC; + bt_addr_copy(&addr.a, &conn->br.dst); + addr.type = BT_ADDR_LE_PUBLIC; - if (bt_addr_le_cmp(&addr, &req->addr)) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (bt_addr_le_cmp(&addr, &req->addr)) { + return BT_SMP_ERR_UNSPECIFIED; + } - smp->remote_dist &= ~BT_SMP_DIST_ID_KEY; + smp->remote_dist &= ~BT_SMP_DIST_ID_KEY; - if (smp->remote_dist & BT_SMP_DIST_SIGN) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); - } + if (smp->remote_dist & BT_SMP_DIST_SIGN) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); + } - if (conn->role == BT_CONN_ROLE_MASTER && !smp->remote_dist) { - smp_br_distribute_keys(smp); - } + if (conn->role == BT_CONN_ROLE_MASTER && !smp->remote_dist) { + smp_br_distribute_keys(smp); + } - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_br_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_br_complete(smp, 0); + } - return 0; + return 0; } #if defined(CONFIG_BT_SIGNING) static u8_t smp_br_signing_info(struct bt_smp_br *smp, struct net_buf *buf) { - struct bt_smp_signing_info *req = (void *)buf->data; - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys; - bt_addr_le_t addr; + struct bt_smp_signing_info *req = (void *)buf->data; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys; + bt_addr_le_t addr; - BT_DBG(""); + BT_DBG(""); - /* - * For dualmode devices LE address is same as BR/EDR address and is of - * public type. - */ - bt_addr_copy(&addr.a, &conn->br.dst); - addr.type = BT_ADDR_LE_PUBLIC; + /* + * For dualmode devices LE address is same as BR/EDR address and is of + * public type. + */ + bt_addr_copy(&addr.a, &conn->br.dst); + addr.type = BT_ADDR_LE_PUBLIC; - keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id, &addr); - if (!keys) { - BT_ERR("Unable to get keys for %s", bt_addr_le_str(&addr)); - return BT_SMP_ERR_UNSPECIFIED; - } + keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id, &addr); + if (!keys) { + BT_ERR("Unable to get keys for %s", bt_addr_le_str(&addr)); + return BT_SMP_ERR_UNSPECIFIED; + } - memcpy(keys->remote_csrk.val, req->csrk, sizeof(keys->remote_csrk.val)); + memcpy(keys->remote_csrk.val, req->csrk, sizeof(keys->remote_csrk.val)); - smp->remote_dist &= ~BT_SMP_DIST_SIGN; + smp->remote_dist &= ~BT_SMP_DIST_SIGN; - if (conn->role == BT_CONN_ROLE_MASTER && !smp->remote_dist) { - smp_br_distribute_keys(smp); - } + if (conn->role == BT_CONN_ROLE_MASTER && !smp->remote_dist) { + smp_br_distribute_keys(smp); + } - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_br_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_br_complete(smp, 0); + } - return 0; + return 0; } #else static u8_t smp_br_signing_info(struct bt_smp_br *smp, struct net_buf *buf) { - return BT_SMP_ERR_CMD_NOTSUPP; + return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_SIGNING */ static const struct { - u8_t (*func)(struct bt_smp_br *smp, struct net_buf *buf); - u8_t expect_len; + u8_t (*func)(struct bt_smp_br *smp, struct net_buf *buf); + u8_t expect_len; } br_handlers[] = { - { }, /* No op-code defined for 0x00 */ - { smp_br_pairing_req, sizeof(struct bt_smp_pairing) }, - { smp_br_pairing_rsp, sizeof(struct bt_smp_pairing) }, - { }, /* pairing confirm not used over BR/EDR */ - { }, /* pairing random not used over BR/EDR */ - { smp_br_pairing_failed, sizeof(struct bt_smp_pairing_fail) }, - { }, /* encrypt info not used over BR/EDR */ - { }, /* master ident not used over BR/EDR */ - { smp_br_ident_info, sizeof(struct bt_smp_ident_info) }, - { smp_br_ident_addr_info, sizeof(struct bt_smp_ident_addr_info) }, - { smp_br_signing_info, sizeof(struct bt_smp_signing_info) }, - /* security request not used over BR/EDR */ - /* public key not used over BR/EDR */ - /* DHKey check not used over BR/EDR */ + { }, /* No op-code defined for 0x00 */ + { smp_br_pairing_req, sizeof(struct bt_smp_pairing) }, + { smp_br_pairing_rsp, sizeof(struct bt_smp_pairing) }, + { }, /* pairing confirm not used over BR/EDR */ + { }, /* pairing random not used over BR/EDR */ + { smp_br_pairing_failed, sizeof(struct bt_smp_pairing_fail) }, + { }, /* encrypt info not used over BR/EDR */ + { }, /* master ident not used over BR/EDR */ + { smp_br_ident_info, sizeof(struct bt_smp_ident_info) }, + { smp_br_ident_addr_info, sizeof(struct bt_smp_ident_addr_info) }, + { smp_br_signing_info, sizeof(struct bt_smp_signing_info) }, + /* security request not used over BR/EDR */ + /* public key not used over BR/EDR */ + /* DHKey check not used over BR/EDR */ }; static int smp_br_error(struct bt_smp_br *smp, u8_t reason) { - struct bt_smp_pairing_fail *rsp; - struct net_buf *buf; + struct bt_smp_pairing_fail *rsp; + struct net_buf *buf; - /* reset context and report */ - smp_br_reset(smp); + /* reset context and report */ + smp_br_reset(smp); - buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp)); - if (!buf) { - return -ENOBUFS; - } + buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp)); + if (!buf) { + return -ENOBUFS; + } - rsp = net_buf_add(buf, sizeof(*rsp)); - rsp->reason = reason; + rsp = net_buf_add(buf, sizeof(*rsp)); + rsp->reason = reason; - /* - * SMP timer is not restarted for PairingFailed so don't use - * smp_br_send - */ - bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf); + /* + * SMP timer is not restarted for PairingFailed so don't use + * smp_br_send + */ + bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf); - return 0; + return 0; } static int bt_smp_br_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { - struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); - struct bt_smp_hdr *hdr; - u8_t err; + struct bt_smp_br *smp = CONTAINER_OF(chan, struct bt_smp_br, chan); + struct bt_smp_hdr *hdr; + u8_t err; - if (buf->len < sizeof(*hdr)) { - BT_ERR("Too small SMP PDU received"); - return 0; - } + if (buf->len < sizeof(*hdr)) { + BT_ERR("Too small SMP PDU received"); + return 0; + } - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - BT_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + BT_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len); - /* - * If SMP timeout occurred "no further SMP commands shall be sent over - * the L2CAP Security Manager Channel. A new SM procedure shall only be - * performed when a new physical link has been established." - */ - if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { - BT_WARN("SMP command (code 0x%02x) received after timeout", - hdr->code); - return 0; - } + /* + * If SMP timeout occurred "no further SMP commands shall be sent over + * the L2CAP Security Manager Channel. A new SM procedure shall only be + * performed when a new physical link has been established." + */ + if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { + BT_WARN("SMP command (code 0x%02x) received after timeout", + hdr->code); + return 0; + } - if (hdr->code >= ARRAY_SIZE(br_handlers) || - !br_handlers[hdr->code].func) { - BT_WARN("Unhandled SMP code 0x%02x", hdr->code); - smp_br_error(smp, BT_SMP_ERR_CMD_NOTSUPP); - return 0; - } + if (hdr->code >= ARRAY_SIZE(br_handlers) || + !br_handlers[hdr->code].func) { + BT_WARN("Unhandled SMP code 0x%02x", hdr->code); + smp_br_error(smp, BT_SMP_ERR_CMD_NOTSUPP); + return 0; + } - if (!atomic_test_and_clear_bit(&smp->allowed_cmds, hdr->code)) { - BT_WARN("Unexpected SMP code 0x%02x", hdr->code); - smp_br_error(smp, BT_SMP_ERR_UNSPECIFIED); - return 0; - } + if (!atomic_test_and_clear_bit(&smp->allowed_cmds, hdr->code)) { + BT_WARN("Unexpected SMP code 0x%02x", hdr->code); + smp_br_error(smp, BT_SMP_ERR_UNSPECIFIED); + return 0; + } - if (buf->len != br_handlers[hdr->code].expect_len) { - BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); - smp_br_error(smp, BT_SMP_ERR_INVALID_PARAMS); - return 0; - } + if (buf->len != br_handlers[hdr->code].expect_len) { + BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); + smp_br_error(smp, BT_SMP_ERR_INVALID_PARAMS); + return 0; + } - err = br_handlers[hdr->code].func(smp, buf); - if (err) { - smp_br_error(smp, err); - } + err = br_handlers[hdr->code].func(smp, buf); + if (err) { + smp_br_error(smp, err); + } - return 0; + return 0; } static bool br_sc_supported(void) { - if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR)) { - BT_WARN("Enabling BR/EDR SMP without BR/EDR SC support"); - return true; - } + if (IS_ENABLED(CONFIG_BT_SMP_FORCE_BREDR)) { + BT_WARN("Enabling BR/EDR SMP without BR/EDR SC support"); + return true; + } - return BT_FEAT_SC(bt_dev.features); + return BT_FEAT_SC(bt_dev.features); } static int bt_smp_br_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { - static struct bt_l2cap_chan_ops ops = { - .connected = bt_smp_br_connected, - .disconnected = bt_smp_br_disconnected, - .recv = bt_smp_br_recv, - }; - int i; + static struct bt_l2cap_chan_ops ops = { + .connected = bt_smp_br_connected, + .disconnected = bt_smp_br_disconnected, + .recv = bt_smp_br_recv, + }; + int i; - /* Check BR/EDR SC is supported */ - if (!br_sc_supported()) { - return -ENOTSUP; - } + /* Check BR/EDR SC is supported */ + if (!br_sc_supported()) { + return -ENOTSUP; + } - BT_DBG("conn %p handle %u", conn, conn->handle); + BT_DBG("conn %p handle %u", conn, conn->handle); - for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { - struct bt_smp_br *smp = &bt_smp_br_pool[i]; + for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { + struct bt_smp_br *smp = &bt_smp_br_pool[i]; - if (smp->chan.chan.conn) { - continue; - } + if (smp->chan.chan.conn) { + continue; + } - smp->chan.chan.ops = &ops; + smp->chan.chan.ops = &ops; - *chan = &smp->chan.chan; + *chan = &smp->chan.chan; - k_delayed_work_init(&smp->work, smp_br_timeout); - smp_br_reset(smp); + k_delayed_work_init(&smp->work, smp_br_timeout); + smp_br_reset(smp); - return 0; - } + return 0; + } - BT_ERR("No available SMP context for conn %p", conn); + BT_ERR("No available SMP context for conn %p", conn); - return -ENOMEM; + return -ENOMEM; } static struct bt_smp_br *smp_br_chan_get(struct bt_conn *conn) { - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - chan = bt_l2cap_br_lookup_rx_cid(conn, BT_L2CAP_CID_BR_SMP); - if (!chan) { - BT_ERR("Unable to find SMP channel"); - return NULL; - } + chan = bt_l2cap_br_lookup_rx_cid(conn, BT_L2CAP_CID_BR_SMP); + if (!chan) { + BT_ERR("Unable to find SMP channel"); + return NULL; + } - return CONTAINER_OF(chan, struct bt_smp_br, chan); + return CONTAINER_OF(chan, struct bt_smp_br, chan); } int bt_smp_br_send_pairing_req(struct bt_conn *conn) { - struct bt_smp_pairing *req; - struct net_buf *req_buf; - u8_t max_key_size; - struct bt_smp_br *smp; + struct bt_smp_pairing *req; + struct net_buf *req_buf; + u8_t max_key_size; + struct bt_smp_br *smp; - smp = smp_br_chan_get(conn); - if (!smp) { - return -ENOTCONN; - } + smp = smp_br_chan_get(conn); + if (!smp) { + return -ENOTCONN; + } - /* SMP Timeout */ - if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { - return -EIO; - } + /* SMP Timeout */ + if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { + return -EIO; + } - /* pairing is in progress */ - if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { - return -EBUSY; - } + /* pairing is in progress */ + if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { + return -EBUSY; + } - /* check if we are allowed to start SMP over BR/EDR */ - if (!smp_br_pairing_allowed(smp)) { - return 0; - } + /* check if we are allowed to start SMP over BR/EDR */ + if (!smp_br_pairing_allowed(smp)) { + return 0; + } - /* Channel not yet connected, will start pairing once connected */ - if (!atomic_test_bit(smp->flags, SMP_FLAG_BR_CONNECTED)) { - atomic_set_bit(smp->flags, SMP_FLAG_BR_PAIR); - return 0; - } + /* Channel not yet connected, will start pairing once connected */ + if (!atomic_test_bit(smp->flags, SMP_FLAG_BR_CONNECTED)) { + atomic_set_bit(smp->flags, SMP_FLAG_BR_PAIR); + return 0; + } - max_key_size = bt_conn_enc_key_size(conn); - if (!max_key_size) { - return -EIO; - } + max_key_size = bt_conn_enc_key_size(conn); + if (!max_key_size) { + return -EIO; + } - smp_br_init(smp); - smp->enc_key_size = max_key_size; + smp_br_init(smp); + smp->enc_key_size = max_key_size; - req_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req)); - if (!req_buf) { - return -ENOBUFS; - } + req_buf = smp_br_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req)); + if (!req_buf) { + return -ENOBUFS; + } - req = net_buf_add(req_buf, sizeof(*req)); + req = net_buf_add(req_buf, sizeof(*req)); - /* - * If Secure Connections pairing has been initiated over BR/EDR, the IO - * Capability, OOB data flag and Auth Req fields of the SM Pairing - * Request/Response PDU shall be set to zero on transmission, and - * ignored on reception. - */ + /* + * If Secure Connections pairing has been initiated over BR/EDR, the IO + * Capability, OOB data flag and Auth Req fields of the SM Pairing + * Request/Response PDU shall be set to zero on transmission, and + * ignored on reception. + */ - req->auth_req = 0x00; - req->io_capability = 0x00; - req->oob_flag = 0x00; - req->max_key_size = max_key_size; - req->init_key_dist = BR_SEND_KEYS_SC; - req->resp_key_dist = BR_RECV_KEYS_SC; + req->auth_req = 0x00; + req->io_capability = 0x00; + req->oob_flag = 0x00; + req->max_key_size = max_key_size; + req->init_key_dist = BR_SEND_KEYS_SC; + req->resp_key_dist = BR_RECV_KEYS_SC; - smp_br_send(smp, req_buf, NULL); + smp_br_send(smp, req_buf, NULL); - smp->local_dist = BR_SEND_KEYS_SC; - smp->remote_dist = BR_RECV_KEYS_SC; + smp->local_dist = BR_SEND_KEYS_SC; + smp->remote_dist = BR_RECV_KEYS_SC; - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP); - atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); + atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); - return 0; + return 0; } #endif /* CONFIG_BT_BREDR */ static void smp_reset(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; + struct bt_conn *conn = smp->chan.chan.conn; - k_delayed_work_cancel(&smp->work); + k_delayed_work_cancel(&smp->work); - smp->method = JUST_WORKS; - atomic_set(&smp->allowed_cmds, 0); - atomic_set(smp->flags, 0); + smp->method = JUST_WORKS; + atomic_set(&smp->allowed_cmds, 0); + atomic_set(smp->flags, 0); - if (conn->required_sec_level != conn->sec_level) { - /* TODO report error */ - /* reset required security level in case of error */ - conn->required_sec_level = conn->sec_level; - } + if (conn->required_sec_level != conn->sec_level) { + /* TODO report error */ + /* reset required security level in case of error */ + conn->required_sec_level = conn->sec_level; + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_HCI_ROLE_MASTER) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); - return; - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_HCI_ROLE_MASTER) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); + return; + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); + } } static void smp_pairing_complete(struct bt_smp *smp, u8_t status) { - BT_DBG("status 0x%x", status); + BT_DBG("status 0x%x", status); - if (!status) { + if (!status) { #if defined(CONFIG_BT_BREDR) - /* - * Don't derive if Debug Keys are used. - * TODO should we allow this if BR/EDR is already connected? - */ - if (atomic_test_bit(smp->flags, SMP_FLAG_DERIVE_LK) && - (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) || - IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS))) { - sc_derive_link_key(smp); - } + /* + * Don't derive if Debug Keys are used. + * TODO should we allow this if BR/EDR is already connected? + */ + if (atomic_test_bit(smp->flags, SMP_FLAG_DERIVE_LK) && + (!atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY) || + IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS))) { + sc_derive_link_key(smp); + } #endif /* CONFIG_BT_BREDR */ - bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND); + bool bond_flag = atomic_test_bit(smp->flags, SMP_FLAG_BOND); #if defined(CONFIG_BT_SETTINGS) - if (bond_flag) { - bt_keys_store(smp->chan.chan.conn->le.keys); - } + if (bond_flag) { + bt_keys_store(smp->chan.chan.conn->le.keys); + } #endif - if (bt_auth && bt_auth->pairing_complete) { - bt_auth->pairing_complete(smp->chan.chan.conn, - bond_flag); - } - } else { - u8_t auth_err = auth_err_get(status); + if (bt_auth && bt_auth->pairing_complete) { + bt_auth->pairing_complete(smp->chan.chan.conn, + bond_flag); + } + } else { + u8_t auth_err = auth_err_get(status); - if (!atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) { - bt_conn_security_changed(smp->chan.chan.conn, auth_err); - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR)) { + bt_conn_security_changed(smp->chan.chan.conn, auth_err); + } - if (bt_auth && bt_auth->pairing_failed) { - bt_auth->pairing_failed(smp->chan.chan.conn, auth_err); - } - } + if (bt_auth && bt_auth->pairing_failed) { + bt_auth->pairing_failed(smp->chan.chan.conn, auth_err); + } + } - smp_reset(smp); + smp_reset(smp); } static void smp_timeout(struct k_work *work) { - struct bt_smp *smp = CONTAINER_OF(work, struct bt_smp, work); + struct bt_smp *smp = CONTAINER_OF(work, struct bt_smp, work); - BT_ERR("SMP Timeout"); + BT_ERR("SMP Timeout"); - /* - * If SMP timeout occurred during key distribution we should assume - * pairing failed and don't store any keys from this pairing. - */ - if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR) && - smp->chan.chan.conn->le.keys) { - bt_keys_clear(smp->chan.chan.conn->le.keys); - } + /* + * If SMP timeout occurred during key distribution we should assume + * pairing failed and don't store any keys from this pairing. + */ + if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR) && + smp->chan.chan.conn->le.keys) { + bt_keys_clear(smp->chan.chan.conn->le.keys); + } - atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); + atomic_set_bit(smp->flags, SMP_FLAG_TIMEOUT); - smp_pairing_complete(smp, BT_SMP_ERR_UNSPECIFIED); + smp_pairing_complete(smp, BT_SMP_ERR_UNSPECIFIED); } static void smp_send(struct bt_smp *smp, struct net_buf *buf, - bt_conn_tx_cb_t cb, void *user_data) + bt_conn_tx_cb_t cb, void *user_data) { - bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf, cb, NULL); - k_delayed_work_submit(&smp->work, SMP_TIMEOUT); + bt_l2cap_send_cb(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf, cb, NULL); + k_delayed_work_submit(&smp->work, SMP_TIMEOUT); } static int smp_error(struct bt_smp *smp, u8_t reason) { - struct bt_smp_pairing_fail *rsp; - struct net_buf *buf; + struct bt_smp_pairing_fail *rsp; + struct net_buf *buf; - /* reset context and report */ - smp_pairing_complete(smp, reason); + /* reset context and report */ + smp_pairing_complete(smp, reason); - buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp)); - if (!buf) { - return -ENOBUFS; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_FAIL, sizeof(*rsp)); + if (!buf) { + return -ENOBUFS; + } - rsp = net_buf_add(buf, sizeof(*rsp)); - rsp->reason = reason; + rsp = net_buf_add(buf, sizeof(*rsp)); + rsp->reason = reason; - /* SMP timer is not restarted for PairingFailed so don't use smp_send */ - bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf); + /* SMP timer is not restarted for PairingFailed so don't use smp_send */ + bt_l2cap_send(smp->chan.chan.conn, BT_L2CAP_CID_SMP, buf); - return 0; + return 0; } static u8_t smp_send_pairing_random(struct bt_smp *smp) { - struct bt_smp_pairing_random *req; - struct net_buf *rsp_buf; + struct bt_smp_pairing_random *req; + struct net_buf *rsp_buf; - rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RANDOM, sizeof(*req)); - if (!rsp_buf) { - return BT_SMP_ERR_UNSPECIFIED; - } + rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RANDOM, sizeof(*req)); + if (!rsp_buf) { + return BT_SMP_ERR_UNSPECIFIED; + } - req = net_buf_add(rsp_buf, sizeof(*req)); - memcpy(req->val, smp->prnd, sizeof(req->val)); + req = net_buf_add(rsp_buf, sizeof(*req)); + memcpy(req->val, smp->prnd, sizeof(req->val)); - smp_send(smp, rsp_buf, NULL, NULL); + smp_send(smp, rsp_buf, NULL, NULL); - return 0; + return 0; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) static void xor_128(const u8_t p[16], const u8_t q[16], u8_t r[16]) { - size_t len = 16; + size_t len = 16; - while (len--) { - *r++ = *p++ ^ *q++; - } + while (len--) { + *r++ = *p++ ^ *q++; + } } static int smp_c1(const u8_t k[16], const u8_t r[16], - const u8_t preq[7], const u8_t pres[7], - const bt_addr_le_t *ia, const bt_addr_le_t *ra, - u8_t enc_data[16]) + const u8_t preq[7], const u8_t pres[7], + const bt_addr_le_t *ia, const bt_addr_le_t *ra, + u8_t enc_data[16]) { - u8_t p1[16], p2[16]; - int err; + u8_t p1[16], p2[16]; + int err; - BT_DBG("k %s", bt_hex(k, 16)); - BT_DBG("r %s", bt_hex(r, 16)); - BT_DBG("ia %s", bt_addr_le_str(ia)); - BT_DBG("ra %s", bt_addr_le_str(ra)); - BT_DBG("preq %s", bt_hex(preq, 7)); - BT_DBG("pres %s", bt_hex(pres, 7)); + BT_DBG("k %s", bt_hex(k, 16)); + BT_DBG("r %s", bt_hex(r, 16)); + BT_DBG("ia %s", bt_addr_le_str(ia)); + BT_DBG("ra %s", bt_addr_le_str(ra)); + BT_DBG("preq %s", bt_hex(preq, 7)); + BT_DBG("pres %s", bt_hex(pres, 7)); - /* pres, preq, rat and iat are concatenated to generate p1 */ - p1[0] = ia->type; - p1[1] = ra->type; - memcpy(p1 + 2, preq, 7); - memcpy(p1 + 9, pres, 7); + /* pres, preq, rat and iat are concatenated to generate p1 */ + p1[0] = ia->type; + p1[1] = ra->type; + memcpy(p1 + 2, preq, 7); + memcpy(p1 + 9, pres, 7); - BT_DBG("p1 %s", bt_hex(p1, 16)); + BT_DBG("p1 %s", bt_hex(p1, 16)); - /* c1 = e(k, e(k, r XOR p1) XOR p2) */ + /* c1 = e(k, e(k, r XOR p1) XOR p2) */ - /* Using enc_data as temporary output buffer */ - xor_128(r, p1, enc_data); + /* Using enc_data as temporary output buffer */ + xor_128(r, p1, enc_data); - err = bt_encrypt_le(k, enc_data, enc_data); - if (err) { - return err; - } + err = bt_encrypt_le(k, enc_data, enc_data); + if (err) { + return err; + } - /* ra is concatenated with ia and padding to generate p2 */ - memcpy(p2, ra->a.val, 6); - memcpy(p2 + 6, ia->a.val, 6); - (void)memset(p2 + 12, 0, 4); + /* ra is concatenated with ia and padding to generate p2 */ + memcpy(p2, ra->a.val, 6); + memcpy(p2 + 6, ia->a.val, 6); + (void)memset(p2 + 12, 0, 4); - BT_DBG("p2 %s", bt_hex(p2, 16)); + BT_DBG("p2 %s", bt_hex(p2, 16)); - xor_128(enc_data, p2, enc_data); + xor_128(enc_data, p2, enc_data); - return bt_encrypt_le(k, enc_data, enc_data); + return bt_encrypt_le(k, enc_data, enc_data); } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ static u8_t smp_send_pairing_confirm(struct bt_smp *smp) { - struct bt_smp_pairing_confirm *req; - struct net_buf *buf; - u8_t r; + struct bt_smp_pairing_confirm *req; + struct net_buf *buf; + u8_t r; - switch (smp->method) { - case PASSKEY_CONFIRM: - case JUST_WORKS: - r = 0U; - break; - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - /* - * In the Passkey Entry protocol, the most significant - * bit of Z is set equal to one and the least - * significant bit is made up from one bit of the - * passkey e.g. if the passkey bit is 1, then Z = 0x81 - * and if the passkey bit is 0, then Z = 0x80. - */ - r = (smp->passkey >> smp->passkey_round) & 0x01; - r |= 0x80; - break; - default: - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case PASSKEY_CONFIRM: + case JUST_WORKS: + r = 0U; + break; + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + /* + * In the Passkey Entry protocol, the most significant + * bit of Z is set equal to one and the least + * significant bit is made up from one bit of the + * passkey e.g. if the passkey bit is 1, then Z = 0x81 + * and if the passkey bit is 0, then Z = 0x80. + */ + r = (smp->passkey >> smp->passkey_round) & 0x01; + r |= 0x80; + break; + default: + return BT_SMP_ERR_UNSPECIFIED; + } - buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req)); - if (!buf) { - return BT_SMP_ERR_UNSPECIFIED; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req)); + if (!buf) { + return BT_SMP_ERR_UNSPECIFIED; + } - req = net_buf_add(buf, sizeof(*req)); + req = net_buf_add(buf, sizeof(*req)); - if (smp_f4(sc_public_key, smp->pkey, smp->prnd, r, req->val)) { - net_buf_unref(buf); - return BT_SMP_ERR_UNSPECIFIED; - } + if (smp_f4(sc_public_key, smp->pkey, smp->prnd, r, req->val)) { + net_buf_unref(buf); + return BT_SMP_ERR_UNSPECIFIED; + } - smp_send(smp, buf, NULL, NULL); + smp_send(smp, buf, NULL, NULL); - atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED); + atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED); - return 0; + return 0; } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) static void smp_ident_sent(struct bt_conn *conn, void *user_data) { - smp_check_complete(conn, BT_SMP_DIST_ENC_KEY); + smp_check_complete(conn, BT_SMP_DIST_ENC_KEY); } static void legacy_distribute_keys(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys = conn->le.keys; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys = conn->le.keys; - if (smp->local_dist & BT_SMP_DIST_ENC_KEY) { - struct bt_smp_encrypt_info *info; - struct bt_smp_master_ident *ident; - struct net_buf *buf; - /* Use struct to get randomness in single call to bt_rand */ - struct { - u8_t key[16]; - u8_t rand[8]; - u8_t ediv[2]; - } rand; + if (smp->local_dist & BT_SMP_DIST_ENC_KEY) { + struct bt_smp_encrypt_info *info; + struct bt_smp_master_ident *ident; + struct net_buf *buf; + /* Use struct to get randomness in single call to bt_rand */ + struct { + u8_t key[16]; + u8_t rand[8]; + u8_t ediv[2]; + } rand; - bt_rand((void *)&rand, sizeof(rand)); + bt_rand((void *)&rand, sizeof(rand)); - buf = smp_create_pdu(smp, BT_SMP_CMD_ENCRYPT_INFO, - sizeof(*info)); - if (!buf) { - BT_ERR("Unable to allocate Encrypt Info buffer"); - return; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_ENCRYPT_INFO, + sizeof(*info)); + if (!buf) { + BT_ERR("Unable to allocate Encrypt Info buffer"); + return; + } - info = net_buf_add(buf, sizeof(*info)); + info = net_buf_add(buf, sizeof(*info)); - /* distributed only enc_size bytes of key */ - memcpy(info->ltk, rand.key, keys->enc_size); - if (keys->enc_size < sizeof(info->ltk)) { - (void)memset(info->ltk + keys->enc_size, 0, - sizeof(info->ltk) - keys->enc_size); - } + /* distributed only enc_size bytes of key */ + memcpy(info->ltk, rand.key, keys->enc_size); + if (keys->enc_size < sizeof(info->ltk)) { + (void)memset(info->ltk + keys->enc_size, 0, + sizeof(info->ltk) - keys->enc_size); + } - smp_send(smp, buf, NULL, NULL); + smp_send(smp, buf, NULL, NULL); - buf = smp_create_pdu(smp, BT_SMP_CMD_MASTER_IDENT, - sizeof(*ident)); - if (!buf) { - BT_ERR("Unable to allocate Master Ident buffer"); - return; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_MASTER_IDENT, + sizeof(*ident)); + if (!buf) { + BT_ERR("Unable to allocate Master Ident buffer"); + return; + } - ident = net_buf_add(buf, sizeof(*ident)); - memcpy(ident->rand, rand.rand, sizeof(ident->rand)); - memcpy(ident->ediv, rand.ediv, sizeof(ident->ediv)); + ident = net_buf_add(buf, sizeof(*ident)); + memcpy(ident->rand, rand.rand, sizeof(ident->rand)); + memcpy(ident->ediv, rand.ediv, sizeof(ident->ediv)); - smp_send(smp, buf, smp_ident_sent, NULL); + smp_send(smp, buf, smp_ident_sent, NULL); - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - bt_keys_add_type(keys, BT_KEYS_SLAVE_LTK); + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + bt_keys_add_type(keys, BT_KEYS_SLAVE_LTK); - memcpy(keys->slave_ltk.val, rand.key, - sizeof(keys->slave_ltk.val)); - memcpy(keys->slave_ltk.rand, rand.rand, - sizeof(keys->slave_ltk.rand)); - memcpy(keys->slave_ltk.ediv, rand.ediv, - sizeof(keys->slave_ltk.ediv)); - } - } + memcpy(keys->slave_ltk.val, rand.key, + sizeof(keys->slave_ltk.val)); + memcpy(keys->slave_ltk.rand, rand.rand, + sizeof(keys->slave_ltk.rand)); + memcpy(keys->slave_ltk.ediv, rand.ediv, + sizeof(keys->slave_ltk.ediv)); + } + } } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ static u8_t bt_smp_distribute_keys(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys = conn->le.keys; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys = conn->le.keys; - if (!keys) { - BT_ERR("No keys space for %s", bt_addr_le_str(&conn->le.dst)); - return BT_SMP_ERR_UNSPECIFIED; - } + if (!keys) { + BT_ERR("No keys space for %s", bt_addr_le_str(&conn->le.dst)); + return BT_SMP_ERR_UNSPECIFIED; + } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - /* Distribute legacy pairing specific keys */ - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - legacy_distribute_keys(smp); - } + /* Distribute legacy pairing specific keys */ + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + legacy_distribute_keys(smp); + } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ #if defined(CONFIG_BT_PRIVACY) - if (smp->local_dist & BT_SMP_DIST_ID_KEY) { - struct bt_smp_ident_info *id_info; - struct bt_smp_ident_addr_info *id_addr_info; - struct net_buf *buf; + if (smp->local_dist & BT_SMP_DIST_ID_KEY) { + struct bt_smp_ident_info *id_info; + struct bt_smp_ident_addr_info *id_addr_info; + struct net_buf *buf; - buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_INFO, - sizeof(*id_info)); - if (!buf) { - BT_ERR("Unable to allocate Ident Info buffer"); - return BT_SMP_ERR_UNSPECIFIED; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_INFO, + sizeof(*id_info)); + if (!buf) { + BT_ERR("Unable to allocate Ident Info buffer"); + return BT_SMP_ERR_UNSPECIFIED; + } - id_info = net_buf_add(buf, sizeof(*id_info)); - memcpy(id_info->irk, bt_dev.irk[conn->id], 16); + id_info = net_buf_add(buf, sizeof(*id_info)); + memcpy(id_info->irk, bt_dev.irk[conn->id], 16); - smp_send(smp, buf, NULL, NULL); + smp_send(smp, buf, NULL, NULL); - buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO, - sizeof(*id_addr_info)); - if (!buf) { - BT_ERR("Unable to allocate Ident Addr Info buffer"); - return BT_SMP_ERR_UNSPECIFIED; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_IDENT_ADDR_INFO, + sizeof(*id_addr_info)); + if (!buf) { + BT_ERR("Unable to allocate Ident Addr Info buffer"); + return BT_SMP_ERR_UNSPECIFIED; + } - id_addr_info = net_buf_add(buf, sizeof(*id_addr_info)); - bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]); + id_addr_info = net_buf_add(buf, sizeof(*id_addr_info)); + bt_addr_le_copy(&id_addr_info->addr, &bt_dev.id_addr[conn->id]); - smp_send(smp, buf, smp_id_sent, NULL); - } + smp_send(smp, buf, smp_id_sent, NULL); + } #endif /* CONFIG_BT_PRIVACY */ #if defined(CONFIG_BT_SIGNING) - if (smp->local_dist & BT_SMP_DIST_SIGN) { - struct bt_smp_signing_info *info; - struct net_buf *buf; + if (smp->local_dist & BT_SMP_DIST_SIGN) { + struct bt_smp_signing_info *info; + struct net_buf *buf; - buf = smp_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO, - sizeof(*info)); - if (!buf) { - BT_ERR("Unable to allocate Signing Info buffer"); - return BT_SMP_ERR_UNSPECIFIED; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_SIGNING_INFO, + sizeof(*info)); + if (!buf) { + BT_ERR("Unable to allocate Signing Info buffer"); + return BT_SMP_ERR_UNSPECIFIED; + } - info = net_buf_add(buf, sizeof(*info)); + info = net_buf_add(buf, sizeof(*info)); - bt_rand(info->csrk, sizeof(info->csrk)); + bt_rand(info->csrk, sizeof(info->csrk)); - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK); - memcpy(keys->local_csrk.val, info->csrk, 16); - keys->local_csrk.cnt = 0U; - } + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + bt_keys_add_type(keys, BT_KEYS_LOCAL_CSRK); + memcpy(keys->local_csrk.val, info->csrk, 16); + keys->local_csrk.cnt = 0U; + } - smp_send(smp, buf, smp_sign_info_sent, NULL); - } + smp_send(smp, buf, smp_sign_info_sent, NULL); + } #endif /* CONFIG_BT_SIGNING */ - return 0; + return 0; } #if defined(CONFIG_BT_PERIPHERAL) static u8_t send_pairing_rsp(struct bt_smp *smp) { - struct bt_smp_pairing *rsp; - struct net_buf *rsp_buf; + struct bt_smp_pairing *rsp; + struct net_buf *rsp_buf; - rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp)); - if (!rsp_buf) { - return BT_SMP_ERR_UNSPECIFIED; - } + rsp_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_RSP, sizeof(*rsp)); + if (!rsp_buf) { + return BT_SMP_ERR_UNSPECIFIED; + } - rsp = net_buf_add(rsp_buf, sizeof(*rsp)); - memcpy(rsp, smp->prsp + 1, sizeof(*rsp)); + rsp = net_buf_add(rsp_buf, sizeof(*rsp)); + memcpy(rsp, smp->prsp + 1, sizeof(*rsp)); - smp_send(smp, rsp_buf, NULL, NULL); + smp_send(smp, rsp_buf, NULL, NULL); - return 0; + return 0; } #endif /* CONFIG_BT_PERIPHERAL */ #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) static int smp_s1(const u8_t k[16], const u8_t r1[16], - const u8_t r2[16], u8_t out[16]) + const u8_t r2[16], u8_t out[16]) { - /* The most significant 64-bits of r1 are discarded to generate - * r1' and the most significant 64-bits of r2 are discarded to - * generate r2'. - * r1' is concatenated with r2' to generate r' which is used as - * the 128-bit input parameter plaintextData to security function e: - * - * r' = r1' || r2' - */ - memcpy(out, r2, 8); - memcpy(out + 8, r1, 8); + /* The most significant 64-bits of r1 are discarded to generate + * r1' and the most significant 64-bits of r2 are discarded to + * generate r2'. + * r1' is concatenated with r2' to generate r' which is used as + * the 128-bit input parameter plaintextData to security function e: + * + * r' = r1' || r2' + */ + memcpy(out, r2, 8); + memcpy(out + 8, r1, 8); - /* s1(k, r1 , r2) = e(k, r') */ - return bt_encrypt_le(k, out, out); + /* s1(k, r1 , r2) = e(k, r') */ + return bt_encrypt_le(k, out, out); } static u8_t legacy_get_pair_method(struct bt_smp *smp, u8_t remote_io) { - struct bt_smp_pairing *req, *rsp; - u8_t method; + struct bt_smp_pairing *req, *rsp; + u8_t method; - if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) { - return JUST_WORKS; - } + if (remote_io > BT_SMP_IO_KEYBOARD_DISPLAY) { + return JUST_WORKS; + } - req = (struct bt_smp_pairing *)&smp->preq[1]; - rsp = (struct bt_smp_pairing *)&smp->prsp[1]; + req = (struct bt_smp_pairing *)&smp->preq[1]; + rsp = (struct bt_smp_pairing *)&smp->prsp[1]; - /* if none side requires MITM use JustWorks */ - if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) { - return JUST_WORKS; - } + /* if none side requires MITM use JustWorks */ + if (!((req->auth_req | rsp->auth_req) & BT_SMP_AUTH_MITM)) { + return JUST_WORKS; + } - method = gen_method_legacy[remote_io][get_io_capa()]; + method = gen_method_legacy[remote_io][get_io_capa()]; - /* if both sides have KeyboardDisplay capabilities, initiator displays - * and responder inputs - */ - if (method == PASSKEY_ROLE) { - if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - method = PASSKEY_DISPLAY; - } else { - method = PASSKEY_INPUT; - } - } + /* if both sides have KeyboardDisplay capabilities, initiator displays + * and responder inputs + */ + if (method == PASSKEY_ROLE) { + if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + method = PASSKEY_DISPLAY; + } else { + method = PASSKEY_INPUT; + } + } - return method; + return method; } static u8_t legacy_request_tk(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys; - u32_t passkey; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys; + u32_t passkey; - /* - * Fail if we have keys that are stronger than keys that will be - * distributed in new pairing. This is to avoid replacing authenticated - * keys with unauthenticated ones. - */ - keys = bt_keys_find_addr(conn->id, &conn->le.dst); - if (keys && (keys->flags & BT_KEYS_AUTHENTICATED) && - smp->method == JUST_WORKS) { - BT_ERR("JustWorks failed, authenticated keys present"); - return BT_SMP_ERR_UNSPECIFIED; - } + /* + * Fail if we have keys that are stronger than keys that will be + * distributed in new pairing. This is to avoid replacing authenticated + * keys with unauthenticated ones. + */ + keys = bt_keys_find_addr(conn->id, &conn->le.dst); + if (keys && (keys->flags & BT_KEYS_AUTHENTICATED) && + smp->method == JUST_WORKS) { + BT_ERR("JustWorks failed, authenticated keys present"); + return BT_SMP_ERR_UNSPECIFIED; + } - switch (smp->method) { - case PASSKEY_DISPLAY: - if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && - fixed_passkey != BT_PASSKEY_INVALID) { - passkey = fixed_passkey; - } else { - if (bt_rand(&passkey, sizeof(passkey))) { - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case PASSKEY_DISPLAY: + if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && + fixed_passkey != BT_PASSKEY_INVALID) { + passkey = fixed_passkey; + } else { + if (bt_rand(&passkey, sizeof(passkey))) { + return BT_SMP_ERR_UNSPECIFIED; + } - passkey %= 1000000; - } + passkey %= 1000000; + } - if (bt_auth && bt_auth->passkey_display) { - atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY); - bt_auth->passkey_display(conn, passkey); - } + if (bt_auth && bt_auth->passkey_display) { + atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY); + bt_auth->passkey_display(conn, passkey); + } - sys_put_le32(passkey, smp->tk); + sys_put_le32(passkey, smp->tk); - break; - case PASSKEY_INPUT: - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->passkey_entry(conn); - break; - case JUST_WORKS: - break; - default: - BT_ERR("Unknown pairing method (%u)", smp->method); - return BT_SMP_ERR_UNSPECIFIED; - } + break; + case PASSKEY_INPUT: + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->passkey_entry(conn); + break; + case JUST_WORKS: + break; + default: + BT_ERR("Unknown pairing method (%u)", smp->method); + return BT_SMP_ERR_UNSPECIFIED; + } - return 0; + return 0; } static u8_t legacy_send_pairing_confirm(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_pairing_confirm *req; - struct net_buf *buf; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_pairing_confirm *req; + struct net_buf *buf; - buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req)); - if (!buf) { - return BT_SMP_ERR_UNSPECIFIED; - } + buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_CONFIRM, sizeof(*req)); + if (!buf) { + return BT_SMP_ERR_UNSPECIFIED; + } - req = net_buf_add(buf, sizeof(*req)); + req = net_buf_add(buf, sizeof(*req)); - if (smp_c1(smp->tk, smp->prnd, smp->preq, smp->prsp, - &conn->le.init_addr, &conn->le.resp_addr, req->val)) { - net_buf_unref(buf); - return BT_SMP_ERR_UNSPECIFIED; - } + if (smp_c1(smp->tk, smp->prnd, smp->preq, smp->prsp, + &conn->le.init_addr, &conn->le.resp_addr, req->val)) { + net_buf_unref(buf); + return BT_SMP_ERR_UNSPECIFIED; + } - smp_send(smp, buf, NULL, NULL); + smp_send(smp, buf, NULL, NULL); - atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED); + atomic_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED); - return 0; + return 0; } #if defined(CONFIG_BT_PERIPHERAL) static u8_t legacy_pairing_req(struct bt_smp *smp) { - u8_t ret; + u8_t ret; - BT_DBG(""); + BT_DBG(""); - /* ask for consent if pairing is not due to sending SecReq*/ - if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && - !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && - bt_auth && bt_auth->pairing_confirm) { - - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->pairing_confirm(smp->chan.chan.conn); + /* ask for consent if pairing is not due to sending SecReq*/ + if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && + !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && + bt_auth && bt_auth->pairing_confirm) { - return 0; - } + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->pairing_confirm(smp->chan.chan.conn); - ret = send_pairing_rsp(smp); - if (ret) { - return ret; - } + return 0; + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + ret = send_pairing_rsp(smp); + if (ret) { + return ret; + } - return legacy_request_tk(smp); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + + return legacy_request_tk(smp); } #endif /* CONFIG_BT_PERIPHERAL */ static u8_t legacy_pairing_random(struct bt_smp *smp) { - struct bt_conn *conn = smp->chan.chan.conn; - u8_t tmp[16]; - int err; + struct bt_conn *conn = smp->chan.chan.conn; + u8_t tmp[16]; + int err; - BT_DBG(""); + BT_DBG(""); - /* calculate confirmation */ - err = smp_c1(smp->tk, smp->rrnd, smp->preq, smp->prsp, - &conn->le.init_addr, &conn->le.resp_addr, tmp); - if (err) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* calculate confirmation */ + err = smp_c1(smp->tk, smp->rrnd, smp->preq, smp->prsp, + &conn->le.init_addr, &conn->le.resp_addr, tmp); + if (err) { + return BT_SMP_ERR_UNSPECIFIED; + } - BT_DBG("pcnf %s", bt_hex(smp->pcnf, 16)); - BT_DBG("cfm %s", bt_hex(tmp, 16)); + BT_DBG("pcnf %s", bt_hex(smp->pcnf, 16)); + BT_DBG("cfm %s", bt_hex(tmp, 16)); - if (memcmp(smp->pcnf, tmp, sizeof(smp->pcnf))) { - return BT_SMP_ERR_CONFIRM_FAILED; - } + if (memcmp(smp->pcnf, tmp, sizeof(smp->pcnf))) { + return BT_SMP_ERR_CONFIRM_FAILED; + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_HCI_ROLE_MASTER) { - u8_t ediv[2], rand[8]; + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_HCI_ROLE_MASTER) { + u8_t ediv[2], rand[8]; - /* No need to store master STK */ - err = smp_s1(smp->tk, smp->rrnd, smp->prnd, tmp); - if (err) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* No need to store master STK */ + err = smp_s1(smp->tk, smp->rrnd, smp->prnd, tmp); + if (err) { + return BT_SMP_ERR_UNSPECIFIED; + } - /* Rand and EDiv are 0 for the STK */ - (void)memset(ediv, 0, sizeof(ediv)); - (void)memset(rand, 0, sizeof(rand)); - if (bt_conn_le_start_encryption(conn, rand, ediv, tmp, - get_encryption_key_size(smp))) { - BT_ERR("Failed to start encryption"); - return BT_SMP_ERR_UNSPECIFIED; - } + /* Rand and EDiv are 0 for the STK */ + (void)memset(ediv, 0, sizeof(ediv)); + (void)memset(rand, 0, sizeof(rand)); + if (bt_conn_le_start_encryption(conn, rand, ediv, tmp, + get_encryption_key_size(smp))) { + BT_ERR("Failed to start encryption"); + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return 0; - } + return 0; + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - err = smp_s1(smp->tk, smp->prnd, smp->rrnd, tmp); - if (err) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + err = smp_s1(smp->tk, smp->prnd, smp->rrnd, tmp); + if (err) { + return BT_SMP_ERR_UNSPECIFIED; + } - memcpy(smp->tk, tmp, sizeof(smp->tk)); - BT_DBG("generated STK %s", bt_hex(smp->tk, 16)); + memcpy(smp->tk, tmp, sizeof(smp->tk)); + BT_DBG("generated STK %s", bt_hex(smp->tk, 16)); - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return smp_send_pairing_random(smp); - } + return smp_send_pairing_random(smp); + } - return 0; + return 0; } static u8_t legacy_pairing_confirm(struct bt_smp *smp) { - BT_DBG(""); + BT_DBG(""); - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); - return legacy_send_pairing_confirm(smp); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + return legacy_send_pairing_confirm(smp); + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) { - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PAIRING_RANDOM); - return legacy_send_pairing_confirm(smp); - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) { + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PAIRING_RANDOM); + return legacy_send_pairing_confirm(smp); + } - atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); - } + atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); + } - return 0; + return 0; } static void legacy_passkey_entry(struct bt_smp *smp, unsigned int passkey) { - passkey = sys_cpu_to_le32(passkey); - memcpy(smp->tk, &passkey, sizeof(passkey)); + passkey = sys_cpu_to_le32(passkey); + memcpy(smp->tk, &passkey, sizeof(passkey)); - if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) { - return; - } + if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) { + return; + } - /* if confirm failed ie. due to invalid passkey, cancel pairing */ - if (legacy_pairing_confirm(smp)) { - smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); - return; - } + /* if confirm failed ie. due to invalid passkey, cancel pairing */ + if (legacy_pairing_confirm(smp)) { + smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); + return; + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); - return; - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + return; + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + } } static u8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - struct bt_smp_encrypt_info *req = (void *)buf->data; - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys; + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + struct bt_smp_encrypt_info *req = (void *)buf->data; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys; - keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst); - if (!keys) { - BT_ERR("Unable to get keys for %s", - bt_addr_le_str(&conn->le.dst)); - return BT_SMP_ERR_UNSPECIFIED; - } + keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst); + if (!keys) { + BT_ERR("Unable to get keys for %s", + bt_addr_le_str(&conn->le.dst)); + return BT_SMP_ERR_UNSPECIFIED; + } - memcpy(keys->ltk.val, req->ltk, 16); - } + memcpy(keys->ltk.val, req->ltk, 16); + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_MASTER_IDENT); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_MASTER_IDENT); - return 0; + return 0; } static u8_t smp_master_ident(struct bt_smp *smp, struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - u8_t err; + struct bt_conn *conn = smp->chan.chan.conn; + u8_t err; - BT_DBG(""); + BT_DBG(""); - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - struct bt_smp_master_ident *req = (void *)buf->data; - struct bt_keys *keys; + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + struct bt_smp_master_ident *req = (void *)buf->data; + struct bt_keys *keys; - keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst); - if (!keys) { - BT_ERR("Unable to get keys for %s", - bt_addr_le_str(&conn->le.dst)); - return BT_SMP_ERR_UNSPECIFIED; - } + keys = bt_keys_get_type(BT_KEYS_LTK, conn->id, &conn->le.dst); + if (!keys) { + BT_ERR("Unable to get keys for %s", + bt_addr_le_str(&conn->le.dst)); + return BT_SMP_ERR_UNSPECIFIED; + } - memcpy(keys->ltk.ediv, req->ediv, sizeof(keys->ltk.ediv)); - memcpy(keys->ltk.rand, req->rand, sizeof(req->rand)); + memcpy(keys->ltk.ediv, req->ediv, sizeof(keys->ltk.ediv)); + memcpy(keys->ltk.rand, req->rand, sizeof(req->rand)); - smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; - } + smp->remote_dist &= ~BT_SMP_DIST_ENC_KEY; + } - if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); - } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); - } + if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); + } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { - err = bt_smp_distribute_keys(smp); - if (err) { - return err; - } - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { + err = bt_smp_distribute_keys(smp); + if (err) { + return err; + } + } - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_complete(smp, 0); + } - return 0; + return 0; } #if defined(CONFIG_BT_CENTRAL) static u8_t legacy_pairing_rsp(struct bt_smp *smp) { - u8_t ret; + u8_t ret; - BT_DBG(""); + BT_DBG(""); - /* ask for consent if this is due to received SecReq */ - if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && - atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && - bt_auth && bt_auth->pairing_confirm) { - - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->pairing_confirm(smp->chan.chan.conn); - return 0; - } + /* ask for consent if this is due to received SecReq */ + if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && + atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && + bt_auth && bt_auth->pairing_confirm) { - ret = legacy_request_tk(smp); - if (ret) { - return ret; - } + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->pairing_confirm(smp->chan.chan.conn); + return 0; + } - if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); - return legacy_send_pairing_confirm(smp); - } + ret = legacy_request_tk(smp); + if (ret) { + return ret; + } - atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); + if (!atomic_test_bit(smp->flags, SMP_FLAG_USER)) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + return legacy_send_pairing_confirm(smp); + } - return 0; + atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); + + return 0; } #endif /* CONFIG_BT_CENTRAL */ #else static u8_t smp_encrypt_info(struct bt_smp *smp, struct net_buf *buf) { - return BT_SMP_ERR_CMD_NOTSUPP; + return BT_SMP_ERR_CMD_NOTSUPP; } static u8_t smp_master_ident(struct bt_smp *smp, struct net_buf *buf) { - return BT_SMP_ERR_CMD_NOTSUPP; + return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ static int smp_init(struct bt_smp *smp) { - /* Initialize SMP context without clearing L2CAP channel context */ - (void)memset((u8_t *)smp + sizeof(smp->chan), 0, - sizeof(*smp) - (sizeof(smp->chan) + sizeof(smp->work))); + /* Initialize SMP context without clearing L2CAP channel context */ + (void)memset((u8_t *)smp + sizeof(smp->chan), 0, + sizeof(*smp) - (sizeof(smp->chan) + sizeof(smp->work))); - /* Generate local random number */ - if (bt_rand(smp->prnd, 16)) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* Generate local random number */ + if (bt_rand(smp->prnd, 16)) { + return BT_SMP_ERR_UNSPECIFIED; + } - BT_DBG("prnd %s", bt_hex(smp->prnd, 16)); + BT_DBG("prnd %s", bt_hex(smp->prnd, 16)); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_FAIL); - sc_public_key = bt_pub_key_get(); + sc_public_key = bt_pub_key_get(); #if defined(BFLB_BLE) k_sem_init(&sc_local_pkey_ready, 0, 1); #endif - return 0; + return 0; } void bt_set_bondable(bool enable) { - bondable = enable; + bondable = enable; } #if defined(CONFIG_BT_STACK_PTS) void bt_set_mitm(bool enable) { - mitm = enable; + mitm = enable; } void bt_set_smpflag(smp_test_id id) { - atomic_set_bit(&smp_test_flag, id); + atomic_set_bit(&smp_test_flag, id); } void bt_clear_smpflag(smp_test_id id) { - atomic_clear_bit(&smp_test_flag, id); + atomic_clear_bit(&smp_test_flag, id); } #endif void bt_set_oob_data_flag(bool enable) { - oobd_present = enable; + oobd_present = enable; } static u8_t get_auth(struct bt_conn *conn, u8_t auth) { - if (sc_supported) { - auth &= BT_SMP_AUTH_MASK_SC; - } else { - auth &= BT_SMP_AUTH_MASK; - } + if (sc_supported) { + auth &= BT_SMP_AUTH_MASK_SC; + } else { + auth &= BT_SMP_AUTH_MASK; + } - #if defined(CONFIG_BT_STACK_PTS) - if((get_io_capa() == BT_SMP_IO_NO_INPUT_OUTPUT) || - (!mitm && - (conn->required_sec_level < BT_SECURITY_L3))) { - #else - if ((get_io_capa() == BT_SMP_IO_NO_INPUT_OUTPUT) || - (!IS_ENABLED(CONFIG_BT_SMP_ENFORCE_MITM) && - (conn->required_sec_level < BT_SECURITY_L3))) { - #endif - auth &= ~(BT_SMP_AUTH_MITM); - } else { - auth |= BT_SMP_AUTH_MITM; - } + #if defined(CONFIG_BT_STACK_PTS) + if((get_io_capa() == BT_SMP_IO_NO_INPUT_OUTPUT) || + (!mitm && + (conn->required_sec_level < BT_SECURITY_L3))) { + #else + if ((get_io_capa() == BT_SMP_IO_NO_INPUT_OUTPUT) || + (!IS_ENABLED(CONFIG_BT_SMP_ENFORCE_MITM) && + (conn->required_sec_level < BT_SECURITY_L3))) { + #endif + auth &= ~(BT_SMP_AUTH_MITM); + } else { + auth |= BT_SMP_AUTH_MITM; + } - if (bondable) { - auth |= BT_SMP_AUTH_BONDING; - } else { - auth &= ~BT_SMP_AUTH_BONDING; - } + if (bondable) { + auth |= BT_SMP_AUTH_BONDING; + } else { + auth &= ~BT_SMP_AUTH_BONDING; + } - return auth; + return auth; } static bool sec_level_reachable(struct bt_conn *conn) { - switch (conn->required_sec_level) { - case BT_SECURITY_L1: - case BT_SECURITY_L2: - return true; - case BT_SECURITY_L3: - return get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT || - (bt_auth && bt_auth->oob_data_request && oobd_present); - case BT_SECURITY_L4: - return (get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT || - (bt_auth && bt_auth->oob_data_request && - oobd_present)) && - sc_supported; - default: - return false; - } + switch (conn->required_sec_level) { + case BT_SECURITY_L1: + case BT_SECURITY_L2: + return true; + case BT_SECURITY_L3: + return get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT || + (bt_auth && bt_auth->oob_data_request && oobd_present); + case BT_SECURITY_L4: + return (get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT || + (bt_auth && bt_auth->oob_data_request && + oobd_present)) && + sc_supported; + default: + return false; + } } static struct bt_smp *smp_chan_get(struct bt_conn *conn) { - struct bt_l2cap_chan *chan; + struct bt_l2cap_chan *chan; - chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_SMP); - if (!chan) { - BT_ERR("Unable to find SMP channel"); - return NULL; - } + chan = bt_l2cap_le_lookup_rx_cid(conn, BT_L2CAP_CID_SMP); + if (!chan) { + BT_ERR("Unable to find SMP channel"); + return NULL; + } - return CONTAINER_OF(chan, struct bt_smp, chan); + return CONTAINER_OF(chan, struct bt_smp, chan); } bool bt_smp_request_ltk(struct bt_conn *conn, u64_t rand, u16_t ediv, u8_t *ltk) { - struct bt_smp *smp; - u8_t enc_size; + struct bt_smp *smp; + u8_t enc_size; - smp = smp_chan_get(conn); - if (!smp) { - return false; - } + smp = smp_chan_get(conn); + if (!smp) { + return false; + } - /* - * Both legacy STK and LE SC LTK have rand and ediv equal to zero. - * If pairing is in progress use the TK for encryption. - */ - if (ediv == 0U && rand == 0U && - atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) && - atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { - enc_size = get_encryption_key_size(smp); + /* + * Both legacy STK and LE SC LTK have rand and ediv equal to zero. + * If pairing is in progress use the TK for encryption. + */ + if (ediv == 0U && rand == 0U && + atomic_test_bit(smp->flags, SMP_FLAG_PAIRING) && + atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { + enc_size = get_encryption_key_size(smp); - /* - * We keep both legacy STK and LE SC LTK in TK. - * Also use only enc_size bytes of key for encryption. - */ - memcpy(ltk, smp->tk, enc_size); - if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { - (void)memset(ltk + enc_size, 0, - BT_SMP_MAX_ENC_KEY_SIZE - enc_size); - } + /* + * We keep both legacy STK and LE SC LTK in TK. + * Also use only enc_size bytes of key for encryption. + */ + memcpy(ltk, smp->tk, enc_size); + if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { + (void)memset(ltk + enc_size, 0, + BT_SMP_MAX_ENC_KEY_SIZE - enc_size); + } - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return true; - } + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + return true; + } - if (!conn->le.keys) { - conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id, - &conn->le.dst); - if (!conn->le.keys) { - conn->le.keys = bt_keys_find(BT_KEYS_SLAVE_LTK, - conn->id, &conn->le.dst); - } - } + if (!conn->le.keys) { + conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id, + &conn->le.dst); + if (!conn->le.keys) { + conn->le.keys = bt_keys_find(BT_KEYS_SLAVE_LTK, + conn->id, &conn->le.dst); + } + } - if (ediv == 0U && rand == 0U && - conn->le.keys && (conn->le.keys->keys & BT_KEYS_LTK_P256)) { - enc_size = conn->le.keys->enc_size; + if (ediv == 0U && rand == 0U && + conn->le.keys && (conn->le.keys->keys & BT_KEYS_LTK_P256)) { + enc_size = conn->le.keys->enc_size; - memcpy(ltk, conn->le.keys->ltk.val, enc_size); - if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { - (void)memset(ltk + enc_size, 0, - BT_SMP_MAX_ENC_KEY_SIZE - enc_size); - } + memcpy(ltk, conn->le.keys->ltk.val, enc_size); + if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { + (void)memset(ltk + enc_size, 0, + BT_SMP_MAX_ENC_KEY_SIZE - enc_size); + } - return true; - } + return true; + } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - if (conn->le.keys && (conn->le.keys->keys & BT_KEYS_SLAVE_LTK) && - !memcmp(conn->le.keys->slave_ltk.rand, &rand, 8) && - !memcmp(conn->le.keys->slave_ltk.ediv, &ediv, 2)) { - enc_size = conn->le.keys->enc_size; + if (conn->le.keys && (conn->le.keys->keys & BT_KEYS_SLAVE_LTK) && + !memcmp(conn->le.keys->slave_ltk.rand, &rand, 8) && + !memcmp(conn->le.keys->slave_ltk.ediv, &ediv, 2)) { + enc_size = conn->le.keys->enc_size; - memcpy(ltk, conn->le.keys->slave_ltk.val, enc_size); - if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { - (void)memset(ltk + enc_size, 0, - BT_SMP_MAX_ENC_KEY_SIZE - enc_size); - } + memcpy(ltk, conn->le.keys->slave_ltk.val, enc_size); + if (enc_size < BT_SMP_MAX_ENC_KEY_SIZE) { + (void)memset(ltk + enc_size, 0, + BT_SMP_MAX_ENC_KEY_SIZE - enc_size); + } - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return true; - } + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + return true; + } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ - if (atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) { - /* Notify higher level that security failed if security was - * initiated by slave. - */ - bt_conn_security_changed(smp->chan.chan.conn, - BT_SECURITY_ERR_PIN_OR_KEY_MISSING); + if (atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) { + /* Notify higher level that security failed if security was + * initiated by slave. + */ + bt_conn_security_changed(smp->chan.chan.conn, + BT_SECURITY_ERR_PIN_OR_KEY_MISSING); - } + } - smp_reset(smp); - return false; + smp_reset(smp); + return false; } #if defined(CONFIG_BT_PERIPHERAL) static int smp_send_security_req(struct bt_conn *conn) { - struct bt_smp *smp; - struct bt_smp_security_request *req; - struct net_buf *req_buf; + struct bt_smp *smp; + struct bt_smp_security_request *req; + struct net_buf *req_buf; - BT_DBG(""); - smp = smp_chan_get(conn); - if (!smp) { - return -ENOTCONN; - } + BT_DBG(""); + smp = smp_chan_get(conn); + if (!smp) { + return -ENOTCONN; + } - /* SMP Timeout */ - if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { - return -EIO; - } + /* SMP Timeout */ + if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { + return -EIO; + } - /* pairing is in progress */ - if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { - return -EBUSY; - } + /* pairing is in progress */ + if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { + return -EBUSY; + } - if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { - return -EBUSY; - } + if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { + return -EBUSY; + } - /* early verify if required sec level if reachable */ - if (!(sec_level_reachable(conn) || smp_keys_check(conn))) { - return -EINVAL; - } + /* early verify if required sec level if reachable */ + if (!(sec_level_reachable(conn) || smp_keys_check(conn))) { + return -EINVAL; + } - if (!conn->le.keys) { - conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); - if (!conn->le.keys) { - return -ENOMEM; - } - } + if (!conn->le.keys) { + conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); + if (!conn->le.keys) { + return -ENOMEM; + } + } - if (smp_init(smp) != 0) { - return -ENOBUFS; - } + if (smp_init(smp) != 0) { + return -ENOBUFS; + } - req_buf = smp_create_pdu(smp, BT_SMP_CMD_SECURITY_REQUEST, - sizeof(*req)); - if (!req_buf) { - return -ENOBUFS; - } + req_buf = smp_create_pdu(smp, BT_SMP_CMD_SECURITY_REQUEST, + sizeof(*req)); + if (!req_buf) { + return -ENOBUFS; + } - req = net_buf_add(req_buf, sizeof(*req)); - req->auth_req = get_auth(conn,BT_SMP_AUTH_DEFAULT); + req = net_buf_add(req_buf, sizeof(*req)); + req->auth_req = get_auth(conn,BT_SMP_AUTH_DEFAULT); - /* SMP timer is not restarted for SecRequest so don't use smp_send */ - bt_l2cap_send(conn, BT_L2CAP_CID_SMP, req_buf); + /* SMP timer is not restarted for SecRequest so don't use smp_send */ + bt_l2cap_send(conn, BT_L2CAP_CID_SMP, req_buf); - atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); + atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_REQ); - return 0; + return 0; } static u8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_pairing *req = (void *)buf->data; - struct bt_smp_pairing *rsp; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_pairing *req = (void *)buf->data; + struct bt_smp_pairing *rsp; - BT_DBG(""); + BT_DBG(""); - if ((req->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) || - (req->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) { - return BT_SMP_ERR_ENC_KEY_SIZE; - } + if ((req->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) || + (req->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) { + return BT_SMP_ERR_ENC_KEY_SIZE; + } - if (!conn->le.keys) { - conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); - if (!conn->le.keys) { - return BT_SMP_ERR_UNSPECIFIED; - } - } + if (!conn->le.keys) { + conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); + if (!conn->le.keys) { + return BT_SMP_ERR_UNSPECIFIED; + } + } - /* If we already sent a security request then the SMP context - * is already initialized. - */ - if (!atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) { - int ret = smp_init(smp); + /* If we already sent a security request then the SMP context + * is already initialized. + */ + if (!atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ)) { + int ret = smp_init(smp); - if (ret) { - return ret; - } - } + if (ret) { + return ret; + } + } - /* Store req for later use */ - smp->preq[0] = BT_SMP_CMD_PAIRING_REQ; - memcpy(smp->preq + 1, req, sizeof(*req)); + /* Store req for later use */ + smp->preq[0] = BT_SMP_CMD_PAIRING_REQ; + memcpy(smp->preq + 1, req, sizeof(*req)); - /* create rsp, it will be used later on */ - smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP; - rsp = (struct bt_smp_pairing *)&smp->prsp[1]; + /* create rsp, it will be used later on */ + smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP; + rsp = (struct bt_smp_pairing *)&smp->prsp[1]; - rsp->auth_req = get_auth(conn, req->auth_req); - rsp->io_capability = get_io_capa(); - rsp->oob_flag = oobd_present ? BT_SMP_OOB_PRESENT : - BT_SMP_OOB_NOT_PRESENT; - rsp->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE; - rsp->init_key_dist = (req->init_key_dist & RECV_KEYS); - rsp->resp_key_dist = (req->resp_key_dist & SEND_KEYS); + rsp->auth_req = get_auth(conn, req->auth_req); + rsp->io_capability = get_io_capa(); + rsp->oob_flag = oobd_present ? BT_SMP_OOB_PRESENT : + BT_SMP_OOB_NOT_PRESENT; + rsp->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE; + rsp->init_key_dist = (req->init_key_dist & RECV_KEYS); + rsp->resp_key_dist = (req->resp_key_dist & SEND_KEYS); - if ((rsp->auth_req & BT_SMP_AUTH_SC) && - (req->auth_req & BT_SMP_AUTH_SC)) { - atomic_set_bit(smp->flags, SMP_FLAG_SC); + if ((rsp->auth_req & BT_SMP_AUTH_SC) && + (req->auth_req & BT_SMP_AUTH_SC)) { + atomic_set_bit(smp->flags, SMP_FLAG_SC); - rsp->init_key_dist &= RECV_KEYS_SC; - rsp->resp_key_dist &= SEND_KEYS_SC; - } + rsp->init_key_dist &= RECV_KEYS_SC; + rsp->resp_key_dist &= SEND_KEYS_SC; + } - if ((rsp->auth_req & BT_SMP_AUTH_CT2) && - (req->auth_req & BT_SMP_AUTH_CT2)) { - atomic_set_bit(smp->flags, SMP_FLAG_CT2); - } + if ((rsp->auth_req & BT_SMP_AUTH_CT2) && + (req->auth_req & BT_SMP_AUTH_CT2)) { + atomic_set_bit(smp->flags, SMP_FLAG_CT2); + } - smp->local_dist = rsp->resp_key_dist; - smp->remote_dist = rsp->init_key_dist; + smp->local_dist = rsp->resp_key_dist; + smp->remote_dist = rsp->init_key_dist; - if ((rsp->auth_req & BT_SMP_AUTH_BONDING) && - (req->auth_req & BT_SMP_AUTH_BONDING)) { - atomic_set_bit(smp->flags, SMP_FLAG_BOND); - } + if ((rsp->auth_req & BT_SMP_AUTH_BONDING) && + (req->auth_req & BT_SMP_AUTH_BONDING)) { + atomic_set_bit(smp->flags, SMP_FLAG_BOND); + } - atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); + atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); - smp->method = get_pair_method(smp, req->io_capability); + smp->method = get_pair_method(smp, req->io_capability); - if (!update_keys_check(smp)) { - return BT_SMP_ERR_AUTH_REQUIREMENTS; - } + if (!update_keys_check(smp)) { + return BT_SMP_ERR_AUTH_REQUIREMENTS; + } - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - return BT_SMP_ERR_AUTH_REQUIREMENTS; + return BT_SMP_ERR_AUTH_REQUIREMENTS; #else - return legacy_pairing_req(smp); + return legacy_pairing_req(smp); #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ - } + } - if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || - conn->required_sec_level == BT_SECURITY_L4) && - smp->method == JUST_WORKS) { - return BT_SMP_ERR_AUTH_REQUIREMENTS; - } + if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || + conn->required_sec_level == BT_SECURITY_L4) && + smp->method == JUST_WORKS) { + return BT_SMP_ERR_AUTH_REQUIREMENTS; + } - if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || - conn->required_sec_level == BT_SECURITY_L4) && - get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) { - return BT_SMP_ERR_ENC_KEY_SIZE; - } + if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || + conn->required_sec_level == BT_SECURITY_L4) && + get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) { + return BT_SMP_ERR_ENC_KEY_SIZE; + } - if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && - !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && - bt_auth && bt_auth->pairing_confirm) { - - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->pairing_confirm(smp->chan.chan.conn); + if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && + !atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && + bt_auth && bt_auth->pairing_confirm) { - return 0; - } + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->pairing_confirm(smp->chan.chan.conn); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); - return send_pairing_rsp(smp); + return 0; + } + + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); + return send_pairing_rsp(smp); } #else static u8_t smp_pairing_req(struct bt_smp *smp, struct net_buf *buf) { - return BT_SMP_ERR_CMD_NOTSUPP; + return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_PERIPHERAL */ static u8_t sc_send_public_key(struct bt_smp *smp) { - struct bt_smp_public_key *req; - struct net_buf *req_buf; + struct bt_smp_public_key *req; + struct net_buf *req_buf; - req_buf = smp_create_pdu(smp, BT_SMP_CMD_PUBLIC_KEY, sizeof(*req)); - if (!req_buf) { - return BT_SMP_ERR_UNSPECIFIED; - } + req_buf = smp_create_pdu(smp, BT_SMP_CMD_PUBLIC_KEY, sizeof(*req)); + if (!req_buf) { + return BT_SMP_ERR_UNSPECIFIED; + } - req = net_buf_add(req_buf, sizeof(*req)); + req = net_buf_add(req_buf, sizeof(*req)); - memcpy(req->x, sc_public_key, sizeof(req->x)); - memcpy(req->y, &sc_public_key[32], sizeof(req->y)); + memcpy(req->x, sc_public_key, sizeof(req->x)); + memcpy(req->y, &sc_public_key[32], sizeof(req->y)); - smp_send(smp, req_buf, NULL, NULL); + smp_send(smp, req_buf, NULL, NULL); - if (IS_ENABLED(CONFIG_BT_USE_DEBUG_KEYS)) { - atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY); - } + if (IS_ENABLED(CONFIG_BT_USE_DEBUG_KEYS)) { + atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY); + } - return 0; + return 0; } #if defined(CONFIG_BT_CENTRAL) static int smp_send_pairing_req(struct bt_conn *conn) { - struct bt_smp *smp; - struct bt_smp_pairing *req; - struct net_buf *req_buf; + struct bt_smp *smp; + struct bt_smp_pairing *req; + struct net_buf *req_buf; - BT_DBG(""); + BT_DBG(""); - smp = smp_chan_get(conn); - if (!smp) { - return -ENOTCONN; - } + smp = smp_chan_get(conn); + if (!smp) { + return -ENOTCONN; + } - /* SMP Timeout */ - if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { - return -EIO; - } + /* SMP Timeout */ + if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { + return -EIO; + } - /* pairing is in progress */ - if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { - return -EBUSY; - } + /* pairing is in progress */ + if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { + return -EBUSY; + } - /* Encryption is in progress */ - if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { - return -EBUSY; - } + /* Encryption is in progress */ + if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { + return -EBUSY; + } - /* early verify if required sec level if reachable */ - if (!sec_level_reachable(conn)) { - return -EINVAL; - } + /* early verify if required sec level if reachable */ + if (!sec_level_reachable(conn)) { + return -EINVAL; + } - if (!conn->le.keys) { - conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); - if (!conn->le.keys) { - return -ENOMEM; - } - } + if (!conn->le.keys) { + conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); + if (!conn->le.keys) { + return -ENOMEM; + } + } - if (smp_init(smp)) { - return -ENOBUFS; - } + if (smp_init(smp)) { + return -ENOBUFS; + } - req_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req)); - if (!req_buf) { - return -ENOBUFS; - } + req_buf = smp_create_pdu(smp, BT_SMP_CMD_PAIRING_REQ, sizeof(*req)); + if (!req_buf) { + return -ENOBUFS; + } - req = net_buf_add(req_buf, sizeof(*req)); + req = net_buf_add(req_buf, sizeof(*req)); - req->auth_req = get_auth(conn, BT_SMP_AUTH_DEFAULT); + req->auth_req = get_auth(conn, BT_SMP_AUTH_DEFAULT); - #if defined(CONFIG_BT_STACK_PTS) - if(atomic_test_and_clear_bit(&smp_test_flag, SMP_AUTH_NO_BONDING_MITM) || - atomic_test_bit(&smp_test_flag, SMP_AUTH_NO_BONDING_MITM_IO_DISPLAY_ONLY)){ - req->auth_req &= ~(BT_SMP_AUTH_BONDING | BT_SMP_AUTH_MITM); - }else if(atomic_test_and_clear_bit(&smp_test_flag, SMP_AUTH_NO_MITM)){ - req->auth_req &= ~(BT_SMP_AUTH_MITM); - } - #endif - - req->io_capability = get_io_capa(); - req->oob_flag = oobd_present ? BT_SMP_OOB_PRESENT : - BT_SMP_OOB_NOT_PRESENT; - req->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE; - req->init_key_dist = SEND_KEYS; - req->resp_key_dist = RECV_KEYS; + #if defined(CONFIG_BT_STACK_PTS) + if(atomic_test_and_clear_bit(&smp_test_flag, SMP_AUTH_NO_BONDING_MITM) || + atomic_test_bit(&smp_test_flag, SMP_AUTH_NO_BONDING_MITM_IO_DISPLAY_ONLY)){ + req->auth_req &= ~(BT_SMP_AUTH_BONDING | BT_SMP_AUTH_MITM); + }else if(atomic_test_and_clear_bit(&smp_test_flag, SMP_AUTH_NO_MITM)){ + req->auth_req &= ~(BT_SMP_AUTH_MITM); + } + #endif - smp->local_dist = SEND_KEYS; - smp->remote_dist = RECV_KEYS; + req->io_capability = get_io_capa(); + req->oob_flag = oobd_present ? BT_SMP_OOB_PRESENT : + BT_SMP_OOB_NOT_PRESENT; + req->max_key_size = BT_SMP_MAX_ENC_KEY_SIZE; + req->init_key_dist = SEND_KEYS; + req->resp_key_dist = RECV_KEYS; - /* Store req for later use */ - smp->preq[0] = BT_SMP_CMD_PAIRING_REQ; - memcpy(smp->preq + 1, req, sizeof(*req)); + smp->local_dist = SEND_KEYS; + smp->remote_dist = RECV_KEYS; - smp_send(smp, req_buf, NULL, NULL); + /* Store req for later use */ + smp->preq[0] = BT_SMP_CMD_PAIRING_REQ; + memcpy(smp->preq + 1, req, sizeof(*req)); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); - atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); + smp_send(smp, req_buf, NULL, NULL); - return 0; + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RSP); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); + atomic_set_bit(smp->flags, SMP_FLAG_PAIRING); + + return 0; } static u8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_pairing *rsp = (void *)buf->data; - struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1]; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_pairing *rsp = (void *)buf->data; + struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1]; - BT_DBG(""); + BT_DBG(""); - if ((rsp->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) || - (rsp->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) { - return BT_SMP_ERR_ENC_KEY_SIZE; - } + if ((rsp->max_key_size > BT_SMP_MAX_ENC_KEY_SIZE) || + (rsp->max_key_size < BT_SMP_MIN_ENC_KEY_SIZE)) { + return BT_SMP_ERR_ENC_KEY_SIZE; + } - smp->local_dist &= rsp->init_key_dist; - smp->remote_dist &= rsp->resp_key_dist; + smp->local_dist &= rsp->init_key_dist; + smp->remote_dist &= rsp->resp_key_dist; - /* Store rsp for later use */ - smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP; - memcpy(smp->prsp + 1, rsp, sizeof(*rsp)); + /* Store rsp for later use */ + smp->prsp[0] = BT_SMP_CMD_PAIRING_RSP; + memcpy(smp->prsp + 1, rsp, sizeof(*rsp)); - if ((rsp->auth_req & BT_SMP_AUTH_SC) && - (req->auth_req & BT_SMP_AUTH_SC)) { - atomic_set_bit(smp->flags, SMP_FLAG_SC); - } + if ((rsp->auth_req & BT_SMP_AUTH_SC) && + (req->auth_req & BT_SMP_AUTH_SC)) { + atomic_set_bit(smp->flags, SMP_FLAG_SC); + } - if ((rsp->auth_req & BT_SMP_AUTH_CT2) && - (req->auth_req & BT_SMP_AUTH_CT2)) { - atomic_set_bit(smp->flags, SMP_FLAG_CT2); - } + if ((rsp->auth_req & BT_SMP_AUTH_CT2) && + (req->auth_req & BT_SMP_AUTH_CT2)) { + atomic_set_bit(smp->flags, SMP_FLAG_CT2); + } - if ((rsp->auth_req & BT_SMP_AUTH_BONDING) && - (req->auth_req & BT_SMP_AUTH_BONDING)) { - atomic_set_bit(smp->flags, SMP_FLAG_BOND); - } + if ((rsp->auth_req & BT_SMP_AUTH_BONDING) && + (req->auth_req & BT_SMP_AUTH_BONDING)) { + atomic_set_bit(smp->flags, SMP_FLAG_BOND); + } - smp->method = get_pair_method(smp, rsp->io_capability); + smp->method = get_pair_method(smp, rsp->io_capability); - if (!update_keys_check(smp)) { - return BT_SMP_ERR_AUTH_REQUIREMENTS; - } + if (!update_keys_check(smp)) { + return BT_SMP_ERR_AUTH_REQUIREMENTS; + } - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { #if defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - return BT_SMP_ERR_AUTH_REQUIREMENTS; + return BT_SMP_ERR_AUTH_REQUIREMENTS; #else - return legacy_pairing_rsp(smp); + return legacy_pairing_rsp(smp); #endif /* CONFIG_BT_SMP_SC_PAIR_ONLY */ - } + } - if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || - conn->required_sec_level == BT_SECURITY_L4) && - smp->method == JUST_WORKS) { - return BT_SMP_ERR_AUTH_REQUIREMENTS; - } + if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || + conn->required_sec_level == BT_SECURITY_L4) && + smp->method == JUST_WORKS) { + return BT_SMP_ERR_AUTH_REQUIREMENTS; + } - if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || - conn->required_sec_level == BT_SECURITY_L4) && - get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) { - return BT_SMP_ERR_ENC_KEY_SIZE; - } + if ((IS_ENABLED(CONFIG_BT_SMP_SC_ONLY) || + conn->required_sec_level == BT_SECURITY_L4) && + get_encryption_key_size(smp) != BT_SMP_MAX_ENC_KEY_SIZE) { + return BT_SMP_ERR_ENC_KEY_SIZE; + } - smp->local_dist &= SEND_KEYS_SC; - smp->remote_dist &= RECV_KEYS_SC; + smp->local_dist &= SEND_KEYS_SC; + smp->remote_dist &= RECV_KEYS_SC; - if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && - atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && - bt_auth && bt_auth->pairing_confirm) { - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->pairing_confirm(smp->chan.chan.conn); - return 0; - } + if ((DISPLAY_FIXED(smp) || smp->method == JUST_WORKS) && + atomic_test_bit(smp->flags, SMP_FLAG_SEC_REQ) && + bt_auth && bt_auth->pairing_confirm) { + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->pairing_confirm(smp->chan.chan.conn); + return 0; + } - if (!sc_public_key) { - atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); - return 0; - } + if (!sc_public_key) { + atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); + return 0; + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); - atomic_clear_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); + atomic_clear_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); - return sc_send_public_key(smp); + return sc_send_public_key(smp); } #else static u8_t smp_pairing_rsp(struct bt_smp *smp, struct net_buf *buf) { - return BT_SMP_ERR_CMD_NOTSUPP; + return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_CENTRAL */ static u8_t smp_pairing_confirm(struct bt_smp *smp, struct net_buf *buf) { - struct bt_smp_pairing_confirm *req = (void *)buf->data; + struct bt_smp_pairing_confirm *req = (void *)buf->data; - BT_DBG(""); + BT_DBG(""); - atomic_clear_bit(smp->flags, SMP_FLAG_DISPLAY); + atomic_clear_bit(smp->flags, SMP_FLAG_DISPLAY); - memcpy(smp->pcnf, req->val, sizeof(smp->pcnf)); + memcpy(smp->pcnf, req->val, sizeof(smp->pcnf)); - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - return smp_send_pairing_random(smp); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + return smp_send_pairing_random(smp); + } - if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - return 0; - } + if (!IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + return 0; + } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - return legacy_pairing_confirm(smp); - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + return legacy_pairing_confirm(smp); + } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ - switch (smp->method) { - case PASSKEY_DISPLAY: - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - return smp_send_pairing_confirm(smp); - case PASSKEY_INPUT: - if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { - atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); - return 0; - } + switch (smp->method) { + case PASSKEY_DISPLAY: + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + return smp_send_pairing_confirm(smp); + case PASSKEY_INPUT: + if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { + atomic_set_bit(smp->flags, SMP_FLAG_CFM_DELAYED); + return 0; + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - return smp_send_pairing_confirm(smp); - case JUST_WORKS: - case PASSKEY_CONFIRM: - default: - return BT_SMP_ERR_UNSPECIFIED; - } + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + return smp_send_pairing_confirm(smp); + case JUST_WORKS: + case PASSKEY_CONFIRM: + default: + return BT_SMP_ERR_UNSPECIFIED; + } } static u8_t sc_smp_send_dhkey_check(struct bt_smp *smp, const u8_t *e) { - struct bt_smp_dhkey_check *req; - struct net_buf *buf; + struct bt_smp_dhkey_check *req; + struct net_buf *buf; - BT_DBG(""); + BT_DBG(""); - buf = smp_create_pdu(smp, BT_SMP_DHKEY_CHECK, sizeof(*req)); - if (!buf) { - return BT_SMP_ERR_UNSPECIFIED; - } + buf = smp_create_pdu(smp, BT_SMP_DHKEY_CHECK, sizeof(*req)); + if (!buf) { + return BT_SMP_ERR_UNSPECIFIED; + } - req = net_buf_add(buf, sizeof(*req)); - memcpy(req->e, e, sizeof(req->e)); + req = net_buf_add(buf, sizeof(*req)); + memcpy(req->e, e, sizeof(req->e)); - smp_send(smp, buf, NULL, NULL); + smp_send(smp, buf, NULL, NULL); - return 0; + return 0; } #if defined(CONFIG_BT_CENTRAL) static u8_t compute_and_send_master_dhcheck(struct bt_smp *smp) { - u8_t e[16], r[16]; + u8_t e[16], r[16]; - (void)memset(r, 0, sizeof(r)); + (void)memset(r, 0, sizeof(r)); - switch (smp->method) { - case JUST_WORKS: - case PASSKEY_CONFIRM: - break; - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - memcpy(r, &smp->passkey, sizeof(smp->passkey)); - break; - case LE_SC_OOB: - if (smp->oobd_remote) { - memcpy(r, smp->oobd_remote->r, sizeof(r)); - } - break; - default: - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case JUST_WORKS: + case PASSKEY_CONFIRM: + break; + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + memcpy(r, &smp->passkey, sizeof(smp->passkey)); + break; + case LE_SC_OOB: + if (smp->oobd_remote) { + memcpy(r, smp->oobd_remote->r, sizeof(r)); + } + break; + default: + return BT_SMP_ERR_UNSPECIFIED; + } - /* calculate LTK and mackey */ - if (smp_f5(smp->dhkey, smp->prnd, smp->rrnd, - &smp->chan.chan.conn->le.init_addr, - &smp->chan.chan.conn->le.resp_addr, smp->mackey, - smp->tk)) { - return BT_SMP_ERR_UNSPECIFIED; - } - /* calculate local DHKey check */ - if (smp_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->preq[1], - &smp->chan.chan.conn->le.init_addr, - &smp->chan.chan.conn->le.resp_addr, e)) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* calculate LTK and mackey */ + if (smp_f5(smp->dhkey, smp->prnd, smp->rrnd, + &smp->chan.chan.conn->le.init_addr, + &smp->chan.chan.conn->le.resp_addr, smp->mackey, + smp->tk)) { + return BT_SMP_ERR_UNSPECIFIED; + } + /* calculate local DHKey check */ + if (smp_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->preq[1], + &smp->chan.chan.conn->le.init_addr, + &smp->chan.chan.conn->le.resp_addr, e)) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); - return sc_smp_send_dhkey_check(smp, e); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); + return sc_smp_send_dhkey_check(smp, e); } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) static u8_t compute_and_check_and_send_slave_dhcheck(struct bt_smp *smp) { - u8_t re[16], e[16], r[16]; - u8_t err; + u8_t re[16], e[16], r[16]; + u8_t err; - (void)memset(r, 0, sizeof(r)); + (void)memset(r, 0, sizeof(r)); - switch (smp->method) { - case JUST_WORKS: - case PASSKEY_CONFIRM: - break; - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - memcpy(r, &smp->passkey, sizeof(smp->passkey)); - break; - case LE_SC_OOB: - if (smp->oobd_remote) { - memcpy(r, smp->oobd_remote->r, sizeof(r)); - } - break; - default: - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case JUST_WORKS: + case PASSKEY_CONFIRM: + break; + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + memcpy(r, &smp->passkey, sizeof(smp->passkey)); + break; + case LE_SC_OOB: + if (smp->oobd_remote) { + memcpy(r, smp->oobd_remote->r, sizeof(r)); + } + break; + default: + return BT_SMP_ERR_UNSPECIFIED; + } - /* calculate LTK and mackey */ - if (smp_f5(smp->dhkey, smp->rrnd, smp->prnd, - &smp->chan.chan.conn->le.init_addr, - &smp->chan.chan.conn->le.resp_addr, smp->mackey, - smp->tk)) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* calculate LTK and mackey */ + if (smp_f5(smp->dhkey, smp->rrnd, smp->prnd, + &smp->chan.chan.conn->le.init_addr, + &smp->chan.chan.conn->le.resp_addr, smp->mackey, + smp->tk)) { + return BT_SMP_ERR_UNSPECIFIED; + } - /* calculate local DHKey check */ - if (smp_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->prsp[1], - &smp->chan.chan.conn->le.resp_addr, - &smp->chan.chan.conn->le.init_addr, e)) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* calculate local DHKey check */ + if (smp_f6(smp->mackey, smp->prnd, smp->rrnd, r, &smp->prsp[1], + &smp->chan.chan.conn->le.resp_addr, + &smp->chan.chan.conn->le.init_addr, e)) { + return BT_SMP_ERR_UNSPECIFIED; + } - if (smp->method == LE_SC_OOB) { - if (smp->oobd_local) { - memcpy(r, smp->oobd_local->r, sizeof(r)); - } else { - memset(r, 0, sizeof(r)); - } - } + if (smp->method == LE_SC_OOB) { + if (smp->oobd_local) { + memcpy(r, smp->oobd_local->r, sizeof(r)); + } else { + memset(r, 0, sizeof(r)); + } + } - /* calculate remote DHKey check */ - if (smp_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->preq[1], - &smp->chan.chan.conn->le.init_addr, - &smp->chan.chan.conn->le.resp_addr, re)) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* calculate remote DHKey check */ + if (smp_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->preq[1], + &smp->chan.chan.conn->le.init_addr, + &smp->chan.chan.conn->le.resp_addr, re)) { + return BT_SMP_ERR_UNSPECIFIED; + } - /* compare received E with calculated remote */ - if (memcmp(smp->e, re, 16)) { - return BT_SMP_ERR_DHKEY_CHECK_FAILED; - } + /* compare received E with calculated remote */ + if (memcmp(smp->e, re, 16)) { + return BT_SMP_ERR_DHKEY_CHECK_FAILED; + } - /* send local e */ - err = sc_smp_send_dhkey_check(smp, e); - if (err) { - return err; - } + /* send local e */ + err = sc_smp_send_dhkey_check(smp, e); + if (err) { + return err; + } - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return 0; + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + return 0; } #endif /* CONFIG_BT_PERIPHERAL */ static void bt_smp_dhkey_ready(const u8_t *dhkey) { - struct bt_smp *smp = NULL; - int i; + struct bt_smp *smp = NULL; + int i; - BT_DBG("%p", dhkey); + BT_DBG("%p", dhkey); - for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { - if (atomic_test_and_clear_bit(bt_smp_pool[i].flags, - SMP_FLAG_DHKEY_PENDING)) { - smp = &bt_smp_pool[i]; - break; - } - } + for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { + if (atomic_test_and_clear_bit(bt_smp_pool[i].flags, + SMP_FLAG_DHKEY_PENDING)) { + smp = &bt_smp_pool[i]; + break; + } + } - if (!smp) { - return; - } + if (!smp) { + return; + } - if (!dhkey) { - smp_error(smp, BT_SMP_ERR_DHKEY_CHECK_FAILED); - return; - } + if (!dhkey) { + smp_error(smp, BT_SMP_ERR_DHKEY_CHECK_FAILED); + return; + } - memcpy(smp->dhkey, dhkey, 32); + memcpy(smp->dhkey, dhkey, 32); - /* wait for user passkey confirmation */ - if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - return; - } + /* wait for user passkey confirmation */ + if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + return; + } - /* wait for remote DHKey Check */ - if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) { - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - return; - } + /* wait for remote DHKey Check */ + if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) { + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + return; + } - if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) { - u8_t err; + if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) { + u8_t err; #if defined(CONFIG_BT_CENTRAL) - if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - err = compute_and_send_master_dhcheck(smp); - if (err) { - smp_error(smp, err); - } + if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + err = compute_and_send_master_dhcheck(smp); + if (err) { + smp_error(smp, err); + } - return; - } + return; + } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) - err = compute_and_check_and_send_slave_dhcheck(smp); - if (err) { - smp_error(smp, err); - } + err = compute_and_check_and_send_slave_dhcheck(smp); + if (err) { + smp_error(smp, err); + } #endif /* CONFIG_BT_PERIPHERAL */ - } + } } static u8_t sc_smp_check_confirm(struct bt_smp *smp) { - u8_t cfm[16]; - u8_t r; + u8_t cfm[16]; + u8_t r; - switch (smp->method) { - case LE_SC_OOB: - return 0; - case PASSKEY_CONFIRM: - case JUST_WORKS: - r = 0U; - break; - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - /* - * In the Passkey Entry protocol, the most significant - * bit of Z is set equal to one and the least - * significant bit is made up from one bit of the - * passkey e.g. if the passkey bit is 1, then Z = 0x81 - * and if the passkey bit is 0, then Z = 0x80. - */ - r = (smp->passkey >> smp->passkey_round) & 0x01; - r |= 0x80; - break; - default: - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case LE_SC_OOB: + return 0; + case PASSKEY_CONFIRM: + case JUST_WORKS: + r = 0U; + break; + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + /* + * In the Passkey Entry protocol, the most significant + * bit of Z is set equal to one and the least + * significant bit is made up from one bit of the + * passkey e.g. if the passkey bit is 1, then Z = 0x81 + * and if the passkey bit is 0, then Z = 0x80. + */ + r = (smp->passkey >> smp->passkey_round) & 0x01; + r |= 0x80; + break; + default: + return BT_SMP_ERR_UNSPECIFIED; + } - if (smp_f4(smp->pkey, sc_public_key, smp->rrnd, r, cfm)) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (smp_f4(smp->pkey, sc_public_key, smp->rrnd, r, cfm)) { + return BT_SMP_ERR_UNSPECIFIED; + } - BT_DBG("pcnf %s", bt_hex(smp->pcnf, 16)); - BT_DBG("cfm %s", bt_hex(cfm, 16)); + BT_DBG("pcnf %s", bt_hex(smp->pcnf, 16)); + BT_DBG("cfm %s", bt_hex(cfm, 16)); - if (memcmp(smp->pcnf, cfm, 16)) { - return BT_SMP_ERR_CONFIRM_FAILED; - } + if (memcmp(smp->pcnf, cfm, 16)) { + return BT_SMP_ERR_CONFIRM_FAILED; + } - return 0; + return 0; } static bool le_sc_oob_data_req_check(struct bt_smp *smp) { - struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1]; + struct bt_smp_pairing *req = (struct bt_smp_pairing *)&smp->preq[1]; - return ((req->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT); + return ((req->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT); } static bool le_sc_oob_data_rsp_check(struct bt_smp *smp) { - struct bt_smp_pairing *rsp = (struct bt_smp_pairing *)&smp->prsp[1]; + struct bt_smp_pairing *rsp = (struct bt_smp_pairing *)&smp->prsp[1]; - return ((rsp->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT); + return ((rsp->oob_flag & BT_SMP_OOB_DATA_MASK) == BT_SMP_OOB_PRESENT); } static void le_sc_oob_config_set(struct bt_smp *smp, - struct bt_conn_oob_info *info) + struct bt_conn_oob_info *info) { - bool req_oob_present = le_sc_oob_data_req_check(smp); - bool rsp_oob_present = le_sc_oob_data_rsp_check(smp); - int oob_config = BT_CONN_OOB_NO_DATA; + bool req_oob_present = le_sc_oob_data_req_check(smp); + bool rsp_oob_present = le_sc_oob_data_rsp_check(smp); + int oob_config = BT_CONN_OOB_NO_DATA; - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - oob_config = req_oob_present ? BT_CONN_OOB_REMOTE_ONLY : - BT_CONN_OOB_NO_DATA; + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + oob_config = req_oob_present ? BT_CONN_OOB_REMOTE_ONLY : + BT_CONN_OOB_NO_DATA; - if (rsp_oob_present) { - oob_config = (oob_config == BT_CONN_OOB_REMOTE_ONLY) ? - BT_CONN_OOB_BOTH_PEERS : - BT_CONN_OOB_LOCAL_ONLY; - } - } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - oob_config = req_oob_present ? BT_CONN_OOB_LOCAL_ONLY : - BT_CONN_OOB_NO_DATA; + if (rsp_oob_present) { + oob_config = (oob_config == BT_CONN_OOB_REMOTE_ONLY) ? + BT_CONN_OOB_BOTH_PEERS : + BT_CONN_OOB_LOCAL_ONLY; + } + } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + oob_config = req_oob_present ? BT_CONN_OOB_LOCAL_ONLY : + BT_CONN_OOB_NO_DATA; - if (rsp_oob_present) { - oob_config = (oob_config == BT_CONN_OOB_LOCAL_ONLY) ? - BT_CONN_OOB_BOTH_PEERS : - BT_CONN_OOB_REMOTE_ONLY; - } - } + if (rsp_oob_present) { + oob_config = (oob_config == BT_CONN_OOB_LOCAL_ONLY) ? + BT_CONN_OOB_BOTH_PEERS : + BT_CONN_OOB_REMOTE_ONLY; + } + } - info->lesc.oob_config = oob_config; + info->lesc.oob_config = oob_config; } static u8_t smp_pairing_random(struct bt_smp *smp, struct net_buf *buf) { - struct bt_smp_pairing_random *req = (void *)buf->data; - u32_t passkey; - u8_t err; + struct bt_smp_pairing_random *req = (void *)buf->data; + u32_t passkey; + u8_t err; - BT_DBG(""); + BT_DBG(""); - memcpy(smp->rrnd, req->val, sizeof(smp->rrnd)); + memcpy(smp->rrnd, req->val, sizeof(smp->rrnd)); #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - return legacy_pairing_random(smp); - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + return legacy_pairing_random(smp); + } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ #if defined(CONFIG_BT_CENTRAL) - if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - err = sc_smp_check_confirm(smp); - if (err) { - return err; - } + if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + err = sc_smp_check_confirm(smp); + if (err) { + return err; + } - switch (smp->method) { - case PASSKEY_CONFIRM: - /* compare passkey before calculating LTK */ - if (smp_g2(sc_public_key, smp->pkey, smp->prnd, - smp->rrnd, &passkey)) { - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case PASSKEY_CONFIRM: + /* compare passkey before calculating LTK */ + if (smp_g2(sc_public_key, smp->pkey, smp->prnd, + smp->rrnd, &passkey)) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(smp->flags, SMP_FLAG_USER); - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - bt_auth->passkey_confirm(smp->chan.chan.conn, passkey); - return 0; - case JUST_WORKS: - break; - case LE_SC_OOB: - break; - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - smp->passkey_round++; - if (smp->passkey_round == 20U) { - break; - } + atomic_set_bit(smp->flags, SMP_FLAG_USER); + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + bt_auth->passkey_confirm(smp->chan.chan.conn, passkey); + return 0; + case JUST_WORKS: + break; + case LE_SC_OOB: + break; + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + smp->passkey_round++; + if (smp->passkey_round == 20U) { + break; + } - if (bt_rand(smp->prnd, 16)) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (bt_rand(smp->prnd, 16)) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PAIRING_CONFIRM); - return smp_send_pairing_confirm(smp); - default: - return BT_SMP_ERR_UNSPECIFIED; - } + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PAIRING_CONFIRM); + return smp_send_pairing_confirm(smp); + default: + return BT_SMP_ERR_UNSPECIFIED; + } - /* wait for DHKey being generated */ - if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - return 0; - } + /* wait for DHKey being generated */ + if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + return 0; + } - return compute_and_send_master_dhcheck(smp); - } + return compute_and_send_master_dhcheck(smp); + } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) - switch (smp->method) { - case PASSKEY_CONFIRM: - if (smp_g2(smp->pkey, sc_public_key, smp->rrnd, smp->prnd, - &passkey)) { - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case PASSKEY_CONFIRM: + if (smp_g2(smp->pkey, sc_public_key, smp->rrnd, smp->prnd, + &passkey)) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->passkey_confirm(smp->chan.chan.conn, passkey); - break; - case JUST_WORKS: - break; - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - err = sc_smp_check_confirm(smp); - if (err) { - return err; - } + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->passkey_confirm(smp->chan.chan.conn, passkey); + break; + case JUST_WORKS: + break; + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + err = sc_smp_check_confirm(smp); + if (err) { + return err; + } - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PAIRING_CONFIRM); - err = smp_send_pairing_random(smp); - if (err) { - return err; - } + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PAIRING_CONFIRM); + err = smp_send_pairing_random(smp); + if (err) { + return err; + } - smp->passkey_round++; - if (smp->passkey_round == 20U) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); - atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); - return 0; - } + smp->passkey_round++; + if (smp->passkey_round == 20U) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); + atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); + return 0; + } - if (bt_rand(smp->prnd, 16)) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (bt_rand(smp->prnd, 16)) { + return BT_SMP_ERR_UNSPECIFIED; + } - return 0; - case LE_SC_OOB: - /* Step 6: Select random N */ - if (bt_rand(smp->prnd, 16)) { - return BT_SMP_ERR_UNSPECIFIED; - } + return 0; + case LE_SC_OOB: + /* Step 6: Select random N */ + if (bt_rand(smp->prnd, 16)) { + return BT_SMP_ERR_UNSPECIFIED; + } - if (bt_auth && bt_auth->oob_data_request) { - struct bt_conn_oob_info info = { - .type = BT_CONN_OOB_LE_SC, - .lesc.oob_config = BT_CONN_OOB_NO_DATA, - }; + if (bt_auth && bt_auth->oob_data_request) { + struct bt_conn_oob_info info = { + .type = BT_CONN_OOB_LE_SC, + .lesc.oob_config = BT_CONN_OOB_NO_DATA, + }; - le_sc_oob_config_set(smp, &info); + le_sc_oob_config_set(smp, &info); - smp->oobd_local = NULL; - smp->oobd_remote = NULL; + smp->oobd_local = NULL; + smp->oobd_remote = NULL; - atomic_set_bit(smp->flags, SMP_FLAG_OOB_PENDING); - bt_auth->oob_data_request(smp->chan.chan.conn, &info); + atomic_set_bit(smp->flags, SMP_FLAG_OOB_PENDING); + bt_auth->oob_data_request(smp->chan.chan.conn, &info); - return 0; - } else { - return BT_SMP_ERR_OOB_NOT_AVAIL; - } - default: - return BT_SMP_ERR_UNSPECIFIED; - } + return 0; + } else { + return BT_SMP_ERR_OOB_NOT_AVAIL; + } + default: + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); - atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); - return smp_send_pairing_random(smp); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); + atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); + return smp_send_pairing_random(smp); #else - return BT_SMP_ERR_PAIRING_NOTSUPP; + return BT_SMP_ERR_PAIRING_NOTSUPP; #endif /* CONFIG_BT_PERIPHERAL */ } static u8_t smp_pairing_failed(struct bt_smp *smp, struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_pairing_fail *req = (void *)buf->data; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_pairing_fail *req = (void *)buf->data; - BT_ERR("reason 0x%x", req->reason); + BT_ERR("reason 0x%x", req->reason); - if (atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER) || - atomic_test_and_clear_bit(smp->flags, SMP_FLAG_DISPLAY)) { - if (bt_auth && bt_auth->cancel) { - bt_auth->cancel(conn); - } - } + if (atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER) || + atomic_test_and_clear_bit(smp->flags, SMP_FLAG_DISPLAY)) { + if (bt_auth && bt_auth->cancel) { + bt_auth->cancel(conn); + } + } - /* - * Pairing Failed command may be sent at any time during the pairing, - * so if there are any keys distributed, shall be cleared. - */ - if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR) && - smp->chan.chan.conn->le.keys) { - bt_keys_clear(smp->chan.chan.conn->le.keys); - } + /* + * Pairing Failed command may be sent at any time during the pairing, + * so if there are any keys distributed, shall be cleared. + */ + if (atomic_test_bit(smp->flags, SMP_FLAG_KEYS_DISTR) && + smp->chan.chan.conn->le.keys) { + bt_keys_clear(smp->chan.chan.conn->le.keys); + } - smp_pairing_complete(smp, req->reason); + smp_pairing_complete(smp, req->reason); - /* return no error to avoid sending Pairing Failed in response */ - return 0; + /* return no error to avoid sending Pairing Failed in response */ + return 0; } static u8_t smp_ident_info(struct bt_smp *smp, struct net_buf *buf) { - BT_DBG(""); + BT_DBG(""); - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - struct bt_smp_ident_info *req = (void *)buf->data; - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_keys *keys; + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + struct bt_smp_ident_info *req = (void *)buf->data; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_keys *keys; - keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst); - if (!keys) { - BT_ERR("Unable to get keys for %s", - bt_addr_le_str(&conn->le.dst)); - return BT_SMP_ERR_UNSPECIFIED; - } + keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst); + if (!keys) { + BT_ERR("Unable to get keys for %s", + bt_addr_le_str(&conn->le.dst)); + return BT_SMP_ERR_UNSPECIFIED; + } - memcpy(keys->irk.val, req->irk, 16); - } + memcpy(keys->irk.val, req->irk, 16); + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_ADDR_INFO); - return 0; + return 0; } static u8_t smp_ident_addr_info(struct bt_smp *smp, struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_ident_addr_info *req = (void *)buf->data; - u8_t err; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_ident_addr_info *req = (void *)buf->data; + u8_t err; - BT_DBG("identity %s", bt_addr_le_str(&req->addr)); + BT_DBG("identity %s", bt_addr_le_str(&req->addr)); - if (!bt_addr_le_is_identity(&req->addr)) { - BT_ERR("Invalid identity %s", bt_addr_le_str(&req->addr)); - BT_ERR(" for %s", bt_addr_le_str(&conn->le.dst)); - return BT_SMP_ERR_INVALID_PARAMS; - } + if (!bt_addr_le_is_identity(&req->addr)) { + BT_ERR("Invalid identity %s", bt_addr_le_str(&req->addr)); + BT_ERR(" for %s", bt_addr_le_str(&conn->le.dst)); + return BT_SMP_ERR_INVALID_PARAMS; + } - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - const bt_addr_le_t *dst; - struct bt_keys *keys; + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + const bt_addr_le_t *dst; + struct bt_keys *keys; - keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst); - if (!keys) { - BT_ERR("Unable to get keys for %s", - bt_addr_le_str(&conn->le.dst)); - return BT_SMP_ERR_UNSPECIFIED; - } + keys = bt_keys_get_type(BT_KEYS_IRK, conn->id, &conn->le.dst); + if (!keys) { + BT_ERR("Unable to get keys for %s", + bt_addr_le_str(&conn->le.dst)); + return BT_SMP_ERR_UNSPECIFIED; + } - /* - * We can't use conn->dst here as this might already contain - * identity address known from previous pairing. Since all keys - * are cleared on re-pairing we wouldn't store IRK distributed - * in new pairing. - */ - if (conn->role == BT_HCI_ROLE_MASTER) { - dst = &conn->le.resp_addr; - } else { - dst = &conn->le.init_addr; - } + /* + * We can't use conn->dst here as this might already contain + * identity address known from previous pairing. Since all keys + * are cleared on re-pairing we wouldn't store IRK distributed + * in new pairing. + */ + if (conn->role == BT_HCI_ROLE_MASTER) { + dst = &conn->le.resp_addr; + } else { + dst = &conn->le.init_addr; + } - if (bt_addr_le_is_rpa(dst)) { - /* always update last use RPA */ - bt_addr_copy(&keys->irk.rpa, &dst->a); + if (bt_addr_le_is_rpa(dst)) { + /* always update last use RPA */ + bt_addr_copy(&keys->irk.rpa, &dst->a); - /* - * Update connection address and notify about identity - * resolved only if connection wasn't already reported - * with identity address. This may happen if IRK was - * present before ie. due to re-pairing. - */ - if (!bt_addr_le_is_identity(&conn->le.dst)) { - bt_addr_le_copy(&keys->addr, &req->addr); - bt_addr_le_copy(&conn->le.dst, &req->addr); + /* + * Update connection address and notify about identity + * resolved only if connection wasn't already reported + * with identity address. This may happen if IRK was + * present before ie. due to re-pairing. + */ + if (!bt_addr_le_is_identity(&conn->le.dst)) { + bt_addr_le_copy(&keys->addr, &req->addr); + bt_addr_le_copy(&conn->le.dst, &req->addr); - bt_conn_identity_resolved(conn); - } - } + bt_conn_identity_resolved(conn); + } + } - bt_id_add(keys); - } + bt_id_add(keys); + } - smp->remote_dist &= ~BT_SMP_DIST_ID_KEY; + smp->remote_dist &= ~BT_SMP_DIST_ID_KEY; - if (smp->remote_dist & BT_SMP_DIST_SIGN) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); - } + if (smp->remote_dist & BT_SMP_DIST_SIGN) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { - err = bt_smp_distribute_keys(smp); - if (err) { - return err; - } - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { + err = bt_smp_distribute_keys(smp); + if (err) { + return err; + } + } - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_complete(smp, 0); + } - return 0; + return 0; } #if defined(CONFIG_BT_SIGNING) static u8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - u8_t err; + struct bt_conn *conn = smp->chan.chan.conn; + u8_t err; - BT_DBG(""); + BT_DBG(""); - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - struct bt_smp_signing_info *req = (void *)buf->data; - struct bt_keys *keys; + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + struct bt_smp_signing_info *req = (void *)buf->data; + struct bt_keys *keys; - keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id, - &conn->le.dst); - if (!keys) { - BT_ERR("Unable to get keys for %s", - bt_addr_le_str(&conn->le.dst)); - return BT_SMP_ERR_UNSPECIFIED; - } + keys = bt_keys_get_type(BT_KEYS_REMOTE_CSRK, conn->id, + &conn->le.dst); + if (!keys) { + BT_ERR("Unable to get keys for %s", + bt_addr_le_str(&conn->le.dst)); + return BT_SMP_ERR_UNSPECIFIED; + } - memcpy(keys->remote_csrk.val, req->csrk, - sizeof(keys->remote_csrk.val)); - } + memcpy(keys->remote_csrk.val, req->csrk, + sizeof(keys->remote_csrk.val)); + } - smp->remote_dist &= ~BT_SMP_DIST_SIGN; + smp->remote_dist &= ~BT_SMP_DIST_SIGN; - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { - err = bt_smp_distribute_keys(smp); - if (err) { - return err; - } - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_HCI_ROLE_MASTER && !smp->remote_dist) { + err = bt_smp_distribute_keys(smp); + if (err) { + return err; + } + } - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_complete(smp, 0); + } - return 0; + return 0; } #else static u8_t smp_signing_info(struct bt_smp *smp, struct net_buf *buf) { - return BT_SMP_ERR_CMD_NOTSUPP; + return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_SIGNING */ #if defined(CONFIG_BT_CENTRAL) static u8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf) { - struct bt_conn *conn = smp->chan.chan.conn; - struct bt_smp_security_request *req = (void *)buf->data; - u8_t auth; + struct bt_conn *conn = smp->chan.chan.conn; + struct bt_smp_security_request *req = (void *)buf->data; + u8_t auth; - BT_DBG(""); + BT_DBG(""); - if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { - /* We have already started pairing process */ - return 0; - } + if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { + /* We have already started pairing process */ + return 0; + } - if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { - /* We have already started encryption procedure */ - return 0; - } + if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { + /* We have already started encryption procedure */ + return 0; + } - if (sc_supported) { - auth = req->auth_req & BT_SMP_AUTH_MASK_SC; - } else { - auth = req->auth_req & BT_SMP_AUTH_MASK; - } + if (sc_supported) { + auth = req->auth_req & BT_SMP_AUTH_MASK_SC; + } else { + auth = req->auth_req & BT_SMP_AUTH_MASK; + } - if (conn->le.keys) { - /* Make sure we have an LTK to encrypt with */ - if (!(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { - goto pair; - } - } else { - conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id, - &conn->le.dst); - if (!conn->le.keys) { - conn->le.keys = bt_keys_find(BT_KEYS_LTK, conn->id, - &conn->le.dst); - } - } + if (conn->le.keys) { + /* Make sure we have an LTK to encrypt with */ + if (!(conn->le.keys->keys & (BT_KEYS_LTK_P256 | BT_KEYS_LTK))) { + goto pair; + } + } else { + conn->le.keys = bt_keys_find(BT_KEYS_LTK_P256, conn->id, + &conn->le.dst); + if (!conn->le.keys) { + conn->le.keys = bt_keys_find(BT_KEYS_LTK, conn->id, + &conn->le.dst); + } + } - if (!conn->le.keys) { - goto pair; - } + if (!conn->le.keys) { + goto pair; + } - /* if MITM required key must be authenticated */ - if ((auth & BT_SMP_AUTH_MITM) && - !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { - if (get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT) { - BT_INFO("New auth requirements: 0x%x, repairing", - auth); - goto pair; - } + /* if MITM required key must be authenticated */ + if ((auth & BT_SMP_AUTH_MITM) && + !(conn->le.keys->flags & BT_KEYS_AUTHENTICATED)) { + if (get_io_capa() != BT_SMP_IO_NO_INPUT_OUTPUT) { + BT_INFO("New auth requirements: 0x%x, repairing", + auth); + goto pair; + } - BT_WARN("Unsupported auth requirements: 0x%x, repairing", - auth); - goto pair; - } + BT_WARN("Unsupported auth requirements: 0x%x, repairing", + auth); + goto pair; + } - /* if LE SC required and no p256 key present repair */ - if ((auth & BT_SMP_AUTH_SC) && - !(conn->le.keys->keys & BT_KEYS_LTK_P256)) { - BT_INFO("New auth requirements: 0x%x, repairing", auth); - goto pair; - } + /* if LE SC required and no p256 key present repair */ + if ((auth & BT_SMP_AUTH_SC) && + !(conn->le.keys->keys & BT_KEYS_LTK_P256)) { + BT_INFO("New auth requirements: 0x%x, repairing", auth); + goto pair; + } - if (bt_conn_le_start_encryption(conn, conn->le.keys->ltk.rand, - conn->le.keys->ltk.ediv, - conn->le.keys->ltk.val, - conn->le.keys->enc_size) < 0) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (bt_conn_le_start_encryption(conn, conn->le.keys->ltk.rand, + conn->le.keys->ltk.ediv, + conn->le.keys->ltk.val, + conn->le.keys->enc_size) < 0) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return 0; + return 0; pair: - if (smp_send_pairing_req(conn) < 0) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (smp_send_pairing_req(conn) < 0) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ); + atomic_set_bit(smp->flags, SMP_FLAG_SEC_REQ); - return 0; + return 0; } #else static u8_t smp_security_request(struct bt_smp *smp, struct net_buf *buf) { - return BT_SMP_ERR_CMD_NOTSUPP; + return BT_SMP_ERR_CMD_NOTSUPP; } #endif /* CONFIG_BT_CENTRAL */ static u8_t generate_dhkey(struct bt_smp *smp) { - if (bt_dh_key_gen(smp->pkey, bt_smp_dhkey_ready)) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (bt_dh_key_gen(smp->pkey, bt_smp_dhkey_ready)) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_PENDING); - return 0; + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_PENDING); + return 0; } static u8_t display_passkey(struct bt_smp *smp) { - if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && - fixed_passkey != BT_PASSKEY_INVALID) { - smp->passkey = fixed_passkey; - } else { - if (bt_rand(&smp->passkey, sizeof(smp->passkey))) { - return BT_SMP_ERR_UNSPECIFIED; - } + if (IS_ENABLED(CONFIG_BT_FIXED_PASSKEY) && + fixed_passkey != BT_PASSKEY_INVALID) { + smp->passkey = fixed_passkey; + } else { + if (bt_rand(&smp->passkey, sizeof(smp->passkey))) { + return BT_SMP_ERR_UNSPECIFIED; + } - smp->passkey %= 1000000; - } + smp->passkey %= 1000000; + } - smp->passkey_round = 0U; + smp->passkey_round = 0U; - if (bt_auth && bt_auth->passkey_display) { - atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY); - bt_auth->passkey_display(smp->chan.chan.conn, smp->passkey); - } + if (bt_auth && bt_auth->passkey_display) { + atomic_set_bit(smp->flags, SMP_FLAG_DISPLAY); + bt_auth->passkey_display(smp->chan.chan.conn, smp->passkey); + } - smp->passkey = sys_cpu_to_le32(smp->passkey); + smp->passkey = sys_cpu_to_le32(smp->passkey); - return 0; + return 0; } #if defined(CONFIG_BT_PERIPHERAL) static u8_t smp_public_key_slave(struct bt_smp *smp) { - u8_t err; + u8_t err; - err = sc_send_public_key(smp); - if (err) { - return err; - } - #if defined(CONFIG_BT_STACK_PTS) - if(atomic_test_bit(&smp_test_flag, SMP_PARING_INVALID_PUBLIC_KEY)){ - return 1; - } - #endif - - switch (smp->method) { - case PASSKEY_CONFIRM: - case JUST_WORKS: - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + err = sc_send_public_key(smp); + if (err) { + return err; + } + #if defined(CONFIG_BT_STACK_PTS) + if(atomic_test_bit(&smp_test_flag, SMP_PARING_INVALID_PUBLIC_KEY)){ + return 1; + } + #endif - err = smp_send_pairing_confirm(smp); - if (err) { - return err; - } - break; - case PASSKEY_DISPLAY: - err = display_passkey(smp); - if (err) { - return err; - } + switch (smp->method) { + case PASSKEY_CONFIRM: + case JUST_WORKS: + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); - break; - case PASSKEY_INPUT: - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->passkey_entry(smp->chan.chan.conn); - break; - case LE_SC_OOB: - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - break; - default: - return BT_SMP_ERR_UNSPECIFIED; - } + err = smp_send_pairing_confirm(smp); + if (err) { + return err; + } + break; + case PASSKEY_DISPLAY: + err = display_passkey(smp); + if (err) { + return err; + } - return generate_dhkey(smp); + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + break; + case PASSKEY_INPUT: + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->passkey_entry(smp->chan.chan.conn); + break; + case LE_SC_OOB: + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + break; + default: + return BT_SMP_ERR_UNSPECIFIED; + } + + return generate_dhkey(smp); } #endif /* CONFIG_BT_PERIPHERAL */ static u8_t smp_public_key(struct bt_smp *smp, struct net_buf *buf) { - struct bt_smp_public_key *req = (void *)buf->data; - u8_t err; + struct bt_smp_public_key *req = (void *)buf->data; + u8_t err; - BT_DBG(""); + BT_DBG(""); - memcpy(smp->pkey, req->x, 32); - memcpy(&smp->pkey[32], req->y, 32); + memcpy(smp->pkey, req->x, 32); + memcpy(&smp->pkey[32], req->y, 32); - /* mark key as debug if remote is using it */ - if (memcmp(smp->pkey, sc_debug_public_key, 64) == 0) { - BT_INFO("Remote is using Debug Public key"); - atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY); + /* mark key as debug if remote is using it */ + if (memcmp(smp->pkey, sc_debug_public_key, 64) == 0) { + BT_INFO("Remote is using Debug Public key"); + atomic_set_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY); - /* Don't allow a bond established without debug key to be - * updated using LTK generated from debug key. - */ - if (!update_debug_keys_check(smp)) { - return BT_SMP_ERR_AUTH_REQUIREMENTS; - } - } + /* Don't allow a bond established without debug key to be + * updated using LTK generated from debug key. + */ + if (!update_debug_keys_check(smp)) { + return BT_SMP_ERR_AUTH_REQUIREMENTS; + } + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - #if defined(CONFIG_BT_STACK_PTS) - if(atomic_test_bit(&smp_test_flag, SMP_PARING_INVALID_PUBLIC_KEY)){ - return 1; - } - #endif - switch (smp->method) { - case PASSKEY_CONFIRM: - case JUST_WORKS: - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PAIRING_CONFIRM); - break; - case PASSKEY_DISPLAY: - err = display_passkey(smp); - if (err) { - return err; - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + #if defined(CONFIG_BT_STACK_PTS) + if(atomic_test_bit(&smp_test_flag, SMP_PARING_INVALID_PUBLIC_KEY)){ + return 1; + } + #endif + switch (smp->method) { + case PASSKEY_CONFIRM: + case JUST_WORKS: + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PAIRING_CONFIRM); + break; + case PASSKEY_DISPLAY: + err = display_passkey(smp); + if (err) { + return err; + } - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PAIRING_CONFIRM); + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PAIRING_CONFIRM); - err = smp_send_pairing_confirm(smp); - if (err) { - return err; - } - break; - case PASSKEY_INPUT: - atomic_set_bit(smp->flags, SMP_FLAG_USER); - bt_auth->passkey_entry(smp->chan.chan.conn); - break; - case LE_SC_OOB: - /* Step 6: Select random N */ - if (bt_rand(smp->prnd, 16)) { - return BT_SMP_ERR_UNSPECIFIED; - } + err = smp_send_pairing_confirm(smp); + if (err) { + return err; + } + break; + case PASSKEY_INPUT: + atomic_set_bit(smp->flags, SMP_FLAG_USER); + bt_auth->passkey_entry(smp->chan.chan.conn); + break; + case LE_SC_OOB: + /* Step 6: Select random N */ + if (bt_rand(smp->prnd, 16)) { + return BT_SMP_ERR_UNSPECIFIED; + } - if (bt_auth && bt_auth->oob_data_request) { - struct bt_conn_oob_info info = { - .type = BT_CONN_OOB_LE_SC, - .lesc.oob_config = BT_CONN_OOB_NO_DATA, - }; + if (bt_auth && bt_auth->oob_data_request) { + struct bt_conn_oob_info info = { + .type = BT_CONN_OOB_LE_SC, + .lesc.oob_config = BT_CONN_OOB_NO_DATA, + }; - le_sc_oob_config_set(smp, &info); + le_sc_oob_config_set(smp, &info); - smp->oobd_local = NULL; - smp->oobd_remote = NULL; + smp->oobd_local = NULL; + smp->oobd_remote = NULL; - atomic_set_bit(smp->flags, - SMP_FLAG_OOB_PENDING); - bt_auth->oob_data_request(smp->chan.chan.conn, - &info); - } else { - return BT_SMP_ERR_OOB_NOT_AVAIL; - } - break; - default: - return BT_SMP_ERR_UNSPECIFIED; - } + atomic_set_bit(smp->flags, + SMP_FLAG_OOB_PENDING); + bt_auth->oob_data_request(smp->chan.chan.conn, + &info); + } else { + return BT_SMP_ERR_OOB_NOT_AVAIL; + } + break; + default: + return BT_SMP_ERR_UNSPECIFIED; + } - return generate_dhkey(smp); - } + return generate_dhkey(smp); + } #if defined(CONFIG_BT_PERIPHERAL) - if (!sc_public_key) { - atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); - return 0; - } + if (!sc_public_key) { + atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); + return 0; + } - err = smp_public_key_slave(smp); - if (err) { - return err; - } + err = smp_public_key_slave(smp); + if (err) { + return err; + } #endif /* CONFIG_BT_PERIPHERAL */ - return 0; + return 0; } static u8_t smp_dhkey_check(struct bt_smp *smp, struct net_buf *buf) { - struct bt_smp_dhkey_check *req = (void *)buf->data; + struct bt_smp_dhkey_check *req = (void *)buf->data; - BT_DBG(""); + BT_DBG(""); - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - u8_t e[16], r[16], enc_size; - u8_t ediv[2], rand[8]; + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + u8_t e[16], r[16], enc_size; + u8_t ediv[2], rand[8]; - (void)memset(r, 0, sizeof(r)); + (void)memset(r, 0, sizeof(r)); - switch (smp->method) { - case JUST_WORKS: - case PASSKEY_CONFIRM: - break; - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - memcpy(r, &smp->passkey, sizeof(smp->passkey)); - break; - case LE_SC_OOB: - if (smp->oobd_local) { - memcpy(r, smp->oobd_local->r, sizeof(r)); - } - break; - default: - return BT_SMP_ERR_UNSPECIFIED; - } + switch (smp->method) { + case JUST_WORKS: + case PASSKEY_CONFIRM: + break; + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + memcpy(r, &smp->passkey, sizeof(smp->passkey)); + break; + case LE_SC_OOB: + if (smp->oobd_local) { + memcpy(r, smp->oobd_local->r, sizeof(r)); + } + break; + default: + return BT_SMP_ERR_UNSPECIFIED; + } - /* calculate remote DHKey check for comparison */ - if (smp_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->prsp[1], - &smp->chan.chan.conn->le.resp_addr, - &smp->chan.chan.conn->le.init_addr, e)) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* calculate remote DHKey check for comparison */ + if (smp_f6(smp->mackey, smp->rrnd, smp->prnd, r, &smp->prsp[1], + &smp->chan.chan.conn->le.resp_addr, + &smp->chan.chan.conn->le.init_addr, e)) { + return BT_SMP_ERR_UNSPECIFIED; + } - if (memcmp(e, req->e, 16)) { - return BT_SMP_ERR_DHKEY_CHECK_FAILED; - } + if (memcmp(e, req->e, 16)) { + return BT_SMP_ERR_DHKEY_CHECK_FAILED; + } - enc_size = get_encryption_key_size(smp); + enc_size = get_encryption_key_size(smp); - /* Rand and EDiv are 0 */ - (void)memset(ediv, 0, sizeof(ediv)); - (void)memset(rand, 0, sizeof(rand)); - if (bt_conn_le_start_encryption(smp->chan.chan.conn, rand, ediv, - smp->tk, enc_size) < 0) { - return BT_SMP_ERR_UNSPECIFIED; - } + /* Rand and EDiv are 0 */ + (void)memset(ediv, 0, sizeof(ediv)); + (void)memset(rand, 0, sizeof(rand)); + if (bt_conn_le_start_encryption(smp->chan.chan.conn, rand, ediv, + smp->tk, enc_size) < 0) { + return BT_SMP_ERR_UNSPECIFIED; + } - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return 0; - } + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + return 0; + } #if defined(CONFIG_BT_PERIPHERAL) - if (smp->chan.chan.conn->role == BT_HCI_ROLE_SLAVE) { - atomic_clear_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); - memcpy(smp->e, req->e, sizeof(smp->e)); + if (smp->chan.chan.conn->role == BT_HCI_ROLE_SLAVE) { + atomic_clear_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); + memcpy(smp->e, req->e, sizeof(smp->e)); - /* wait for DHKey being generated */ - if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - return 0; - } + /* wait for DHKey being generated */ + if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + return 0; + } - /* waiting for user to confirm passkey */ - if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - return 0; - } + /* waiting for user to confirm passkey */ + if (atomic_test_bit(smp->flags, SMP_FLAG_USER)) { + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + return 0; + } - return compute_and_check_and_send_slave_dhcheck(smp); - } + return compute_and_check_and_send_slave_dhcheck(smp); + } #endif /* CONFIG_BT_PERIPHERAL */ - return 0; + return 0; } static const struct { - u8_t (*func)(struct bt_smp *smp, struct net_buf *buf); - u8_t expect_len; + u8_t (*func)(struct bt_smp *smp, struct net_buf *buf); + u8_t expect_len; } handlers[] = { - { }, /* No op-code defined for 0x00 */ - { smp_pairing_req, sizeof(struct bt_smp_pairing) }, - { smp_pairing_rsp, sizeof(struct bt_smp_pairing) }, - { smp_pairing_confirm, sizeof(struct bt_smp_pairing_confirm) }, - { smp_pairing_random, sizeof(struct bt_smp_pairing_random) }, - { smp_pairing_failed, sizeof(struct bt_smp_pairing_fail) }, - { smp_encrypt_info, sizeof(struct bt_smp_encrypt_info) }, - { smp_master_ident, sizeof(struct bt_smp_master_ident) }, - { smp_ident_info, sizeof(struct bt_smp_ident_info) }, - { smp_ident_addr_info, sizeof(struct bt_smp_ident_addr_info) }, - { smp_signing_info, sizeof(struct bt_smp_signing_info) }, - { smp_security_request, sizeof(struct bt_smp_security_request) }, - { smp_public_key, sizeof(struct bt_smp_public_key) }, - { smp_dhkey_check, sizeof(struct bt_smp_dhkey_check) }, + { }, /* No op-code defined for 0x00 */ + { smp_pairing_req, sizeof(struct bt_smp_pairing) }, + { smp_pairing_rsp, sizeof(struct bt_smp_pairing) }, + { smp_pairing_confirm, sizeof(struct bt_smp_pairing_confirm) }, + { smp_pairing_random, sizeof(struct bt_smp_pairing_random) }, + { smp_pairing_failed, sizeof(struct bt_smp_pairing_fail) }, + { smp_encrypt_info, sizeof(struct bt_smp_encrypt_info) }, + { smp_master_ident, sizeof(struct bt_smp_master_ident) }, + { smp_ident_info, sizeof(struct bt_smp_ident_info) }, + { smp_ident_addr_info, sizeof(struct bt_smp_ident_addr_info) }, + { smp_signing_info, sizeof(struct bt_smp_signing_info) }, + { smp_security_request, sizeof(struct bt_smp_security_request) }, + { smp_public_key, sizeof(struct bt_smp_public_key) }, + { smp_dhkey_check, sizeof(struct bt_smp_dhkey_check) }, }; static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { - struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); - struct bt_smp_hdr *hdr; - u8_t err; + struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); + struct bt_smp_hdr *hdr; + u8_t err; - if (buf->len < sizeof(*hdr)) { - BT_ERR("Too small SMP PDU received"); - return 0; - } + if (buf->len < sizeof(*hdr)) { + BT_ERR("Too small SMP PDU received"); + return 0; + } - hdr = net_buf_pull_mem(buf, sizeof(*hdr)); - BT_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len); + hdr = net_buf_pull_mem(buf, sizeof(*hdr)); + BT_DBG("Received SMP code 0x%02x len %u", hdr->code, buf->len); - /* - * If SMP timeout occurred "no further SMP commands shall be sent over - * the L2CAP Security Manager Channel. A new SM procedure shall only be - * performed when a new physical link has been established." - */ - if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { - BT_WARN("SMP command (code 0x%02x) received after timeout", - hdr->code); - return 0; - } + /* + * If SMP timeout occurred "no further SMP commands shall be sent over + * the L2CAP Security Manager Channel. A new SM procedure shall only be + * performed when a new physical link has been established." + */ + if (atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) { + BT_WARN("SMP command (code 0x%02x) received after timeout", + hdr->code); + return 0; + } - if (hdr->code >= ARRAY_SIZE(handlers) || !handlers[hdr->code].func) { - BT_WARN("Unhandled SMP code 0x%02x", hdr->code); - smp_error(smp, BT_SMP_ERR_CMD_NOTSUPP); - return 0; - } + if (hdr->code >= ARRAY_SIZE(handlers) || !handlers[hdr->code].func) { + BT_WARN("Unhandled SMP code 0x%02x", hdr->code); + smp_error(smp, BT_SMP_ERR_CMD_NOTSUPP); + return 0; + } - if (!atomic_test_and_clear_bit(&smp->allowed_cmds, hdr->code)) { - BT_WARN("Unexpected SMP code 0x%02x", hdr->code); - /* Don't send error responses to error PDUs */ - if (hdr->code != BT_SMP_CMD_PAIRING_FAIL) { + if (!atomic_test_and_clear_bit(&smp->allowed_cmds, hdr->code)) { + BT_WARN("Unexpected SMP code 0x%02x", hdr->code); + /* Don't send error responses to error PDUs */ + if (hdr->code != BT_SMP_CMD_PAIRING_FAIL) { - /*Don't send error responses when smp is timeout*/ - #if defined(CONFIG_BT_STACK_PTS) - if(atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) - #endif - smp_error(smp, BT_SMP_ERR_UNSPECIFIED); - - } - return 0; - } + /*Don't send error responses when smp is timeout*/ + #if defined(CONFIG_BT_STACK_PTS) + if(atomic_test_bit(smp->flags, SMP_FLAG_TIMEOUT)) + #endif + smp_error(smp, BT_SMP_ERR_UNSPECIFIED); - if (buf->len != handlers[hdr->code].expect_len) { - BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); - smp_error(smp, BT_SMP_ERR_INVALID_PARAMS); - return 0; - } + } + return 0; + } - err = handlers[hdr->code].func(smp, buf); - if (err) { - smp_error(smp, err); - } + if (buf->len != handlers[hdr->code].expect_len) { + BT_ERR("Invalid len %u for code 0x%02x", buf->len, hdr->code); + smp_error(smp, BT_SMP_ERR_INVALID_PARAMS); + return 0; + } - return 0; + err = handlers[hdr->code].func(smp, buf); + if (err) { + smp_error(smp, err); + } + + return 0; } static void bt_smp_pkey_ready(const u8_t *pkey) { - int i; + int i; - BT_DBG(""); + BT_DBG(""); - sc_public_key = pkey; + sc_public_key = pkey; - if (!pkey) { - BT_WARN("Public key not available"); - return; - } + if (!pkey) { + BT_WARN("Public key not available"); + return; + } - k_sem_give(&sc_local_pkey_ready); + k_sem_give(&sc_local_pkey_ready); - for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { - struct bt_smp *smp = &bt_smp_pool[i]; - u8_t err; + for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { + struct bt_smp *smp = &bt_smp_pool[i]; + u8_t err; - if (!atomic_test_bit(smp->flags, SMP_FLAG_PKEY_SEND)) { - continue; - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_PKEY_SEND)) { + continue; + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - err = sc_send_public_key(smp); - if (err) { - smp_error(smp, err); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + err = sc_send_public_key(smp); + if (err) { + smp_error(smp, err); + } - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PUBLIC_KEY); - continue; - } + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PUBLIC_KEY); + continue; + } #if defined(CONFIG_BT_PERIPHERAL) - err = smp_public_key_slave(smp); - if (err) { - smp_error(smp, err); - } + err = smp_public_key_slave(smp); + if (err) { + smp_error(smp, err); + } #endif /* CONFIG_BT_PERIPHERAL */ - } + } } static void bt_smp_connected(struct bt_l2cap_chan *chan) { - struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); + struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); - BT_DBG("chan %p cid 0x%04x", chan, - CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid); + BT_DBG("chan %p cid 0x%04x", chan, + CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid); - k_delayed_work_init(&smp->work, smp_timeout); - smp_reset(smp); + k_delayed_work_init(&smp->work, smp_timeout); + smp_reset(smp); } static void bt_smp_disconnected(struct bt_l2cap_chan *chan) { - struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); - struct bt_keys *keys = chan->conn->le.keys; + struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); + struct bt_keys *keys = chan->conn->le.keys; - BT_DBG("chan %p cid 0x%04x", chan, - CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid); + BT_DBG("chan %p cid 0x%04x", chan, + CONTAINER_OF(chan, struct bt_l2cap_le_chan, chan)->tx.cid); - k_delayed_work_cancel(&smp->work); + k_delayed_work_cancel(&smp->work); #ifdef BFLB_BLE_PATCH_FREE_ALLOCATED_BUFFER_IN_OS if(smp->work.timer.timer.hdl) @@ -4234,91 +4234,91 @@ static void bt_smp_disconnected(struct bt_l2cap_chan *chan) if(chan->rtx_work.timer.timer.hdl) k_delayed_work_del_timer(&chan->rtx_work); #endif - - if (keys) { - /* - * If debug keys were used for pairing remove them. - * No keys indicate no bonding so free keys storage. - */ - if (!keys->keys || (!IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS) && - (keys->flags & BT_KEYS_DEBUG))) { - bt_keys_clear(keys); - } - } - (void)memset(smp, 0, sizeof(*smp)); + if (keys) { + /* + * If debug keys were used for pairing remove them. + * No keys indicate no bonding so free keys storage. + */ + if (!keys->keys || (!IS_ENABLED(CONFIG_BT_STORE_DEBUG_KEYS) && + (keys->flags & BT_KEYS_DEBUG))) { + bt_keys_clear(keys); + } + } + + (void)memset(smp, 0, sizeof(*smp)); } static void bt_smp_encrypt_change(struct bt_l2cap_chan *chan, - u8_t hci_status) + u8_t hci_status) { - struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); - struct bt_conn *conn = chan->conn; + struct bt_smp *smp = CONTAINER_OF(chan, struct bt_smp, chan); + struct bt_conn *conn = chan->conn; - BT_DBG("chan %p conn %p handle %u encrypt 0x%02x hci status 0x%02x", - chan, conn, conn->handle, conn->encrypt, hci_status); + BT_DBG("chan %p conn %p handle %u encrypt 0x%02x hci status 0x%02x", + chan, conn, conn->handle, conn->encrypt, hci_status); - atomic_clear_bit(smp->flags, SMP_FLAG_ENC_PENDING); + atomic_clear_bit(smp->flags, SMP_FLAG_ENC_PENDING); - if (hci_status) { - return; - } + if (hci_status) { + return; + } - if (!conn->encrypt) { - return; - } + if (!conn->encrypt) { + return; + } - /* We were waiting for encryption but with no pairing in progress. - * This can happen if paired slave sent Security Request and we - * enabled encryption. - */ - if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { - smp_reset(smp); - return; - } + /* We were waiting for encryption but with no pairing in progress. + * This can happen if paired slave sent Security Request and we + * enabled encryption. + */ + if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { + smp_reset(smp); + return; + } - /* derive BR/EDR LinkKey if supported by both sides */ - if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - if ((smp->local_dist & BT_SMP_DIST_LINK_KEY) && - (smp->remote_dist & BT_SMP_DIST_LINK_KEY)) { - /* - * Link Key will be derived after key distribution to - * make sure remote device identity is known - */ - atomic_set_bit(smp->flags, SMP_FLAG_DERIVE_LK); - } - /* - * Those are used as pairing finished indicator so generated - * but not distributed keys must be cleared here. - */ - smp->local_dist &= ~BT_SMP_DIST_LINK_KEY; - smp->remote_dist &= ~BT_SMP_DIST_LINK_KEY; - } + /* derive BR/EDR LinkKey if supported by both sides */ + if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + if ((smp->local_dist & BT_SMP_DIST_LINK_KEY) && + (smp->remote_dist & BT_SMP_DIST_LINK_KEY)) { + /* + * Link Key will be derived after key distribution to + * make sure remote device identity is known + */ + atomic_set_bit(smp->flags, SMP_FLAG_DERIVE_LK); + } + /* + * Those are used as pairing finished indicator so generated + * but not distributed keys must be cleared here. + */ + smp->local_dist &= ~BT_SMP_DIST_LINK_KEY; + smp->remote_dist &= ~BT_SMP_DIST_LINK_KEY; + } - if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_ENCRYPT_INFO); - } else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); - } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); - } + if (smp->remote_dist & BT_SMP_DIST_ENC_KEY) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_ENCRYPT_INFO); + } else if (smp->remote_dist & BT_SMP_DIST_ID_KEY) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_IDENT_INFO); + } else if (smp->remote_dist & BT_SMP_DIST_SIGN) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SIGNING_INFO); + } - atomic_set_bit(smp->flags, SMP_FLAG_KEYS_DISTR); + atomic_set_bit(smp->flags, SMP_FLAG_KEYS_DISTR); - /* Slave distributes it's keys first */ - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_HCI_ROLE_MASTER && smp->remote_dist) { - return; - } + /* Slave distributes it's keys first */ + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_HCI_ROLE_MASTER && smp->remote_dist) { + return; + } - if (bt_smp_distribute_keys(smp)) { - return; - } + if (bt_smp_distribute_keys(smp)) { + return; + } - /* if all keys were distributed, pairing is done */ - if (!smp->local_dist && !smp->remote_dist) { - smp_pairing_complete(smp, 0); - } + /* if all keys were distributed, pairing is done */ + if (!smp->local_dist && !smp->remote_dist) { + smp_pairing_complete(smp, 0); + } } #if defined(CONFIG_BT_SIGNING) || defined(CONFIG_BT_SMP_SELFTEST) @@ -4329,125 +4329,125 @@ static void bt_smp_encrypt_change(struct bt_l2cap_chan *chan, */ static int smp_sign_buf(const u8_t *key, u8_t *msg, u16_t len) { - u8_t *m = msg; - u32_t cnt = UNALIGNED_GET((u32_t *)&msg[len]); - u8_t *sig = msg + len; - u8_t key_s[16], tmp[16]; - int err; + u8_t *m = msg; + u32_t cnt = UNALIGNED_GET((u32_t *)&msg[len]); + u8_t *sig = msg + len; + u8_t key_s[16], tmp[16]; + int err; - BT_DBG("Signing msg %s len %u key %s", bt_hex(msg, len), len, - bt_hex(key, 16)); + BT_DBG("Signing msg %s len %u key %s", bt_hex(msg, len), len, + bt_hex(key, 16)); - sys_mem_swap(m, len + sizeof(cnt)); - sys_memcpy_swap(key_s, key, 16); + sys_mem_swap(m, len + sizeof(cnt)); + sys_memcpy_swap(key_s, key, 16); - err = bt_smp_aes_cmac(key_s, m, len + sizeof(cnt), tmp); - if (err) { - BT_ERR("Data signing failed"); - return err; - } + err = bt_smp_aes_cmac(key_s, m, len + sizeof(cnt), tmp); + if (err) { + BT_ERR("Data signing failed"); + return err; + } - sys_mem_swap(tmp, sizeof(tmp)); - memcpy(tmp + 4, &cnt, sizeof(cnt)); + sys_mem_swap(tmp, sizeof(tmp)); + memcpy(tmp + 4, &cnt, sizeof(cnt)); - /* Swap original message back */ - sys_mem_swap(m, len + sizeof(cnt)); + /* Swap original message back */ + sys_mem_swap(m, len + sizeof(cnt)); - memcpy(sig, tmp + 4, 12); + memcpy(sig, tmp + 4, 12); - BT_DBG("sig %s", bt_hex(sig, 12)); + BT_DBG("sig %s", bt_hex(sig, 12)); - return 0; + return 0; } #endif #if defined(CONFIG_BT_SIGNING) int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { - struct bt_keys *keys; - u8_t sig[12]; - u32_t cnt; - int err; + struct bt_keys *keys; + u8_t sig[12]; + u32_t cnt; + int err; - /* Store signature incl. count */ - memcpy(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig)); + /* Store signature incl. count */ + memcpy(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig)); - keys = bt_keys_find(BT_KEYS_REMOTE_CSRK, conn->id, &conn->le.dst); - if (!keys) { - BT_ERR("Unable to find Remote CSRK for %s", - bt_addr_le_str(&conn->le.dst)); - return -ENOENT; - } + keys = bt_keys_find(BT_KEYS_REMOTE_CSRK, conn->id, &conn->le.dst); + if (!keys) { + BT_ERR("Unable to find Remote CSRK for %s", + bt_addr_le_str(&conn->le.dst)); + return -ENOENT; + } - /* Copy signing count */ - cnt = sys_cpu_to_le32(keys->remote_csrk.cnt); - memcpy(net_buf_tail(buf) - sizeof(sig), &cnt, sizeof(cnt)); + /* Copy signing count */ + cnt = sys_cpu_to_le32(keys->remote_csrk.cnt); + memcpy(net_buf_tail(buf) - sizeof(sig), &cnt, sizeof(cnt)); - BT_DBG("Sign data len %zu key %s count %u", buf->len - sizeof(sig), - bt_hex(keys->remote_csrk.val, 16), keys->remote_csrk.cnt); + BT_DBG("Sign data len %zu key %s count %u", buf->len - sizeof(sig), + bt_hex(keys->remote_csrk.val, 16), keys->remote_csrk.cnt); - err = smp_sign_buf(keys->remote_csrk.val, buf->data, - buf->len - sizeof(sig)); - if (err) { - BT_ERR("Unable to create signature for %s", - bt_addr_le_str(&conn->le.dst)); - return -EIO; - }; + err = smp_sign_buf(keys->remote_csrk.val, buf->data, + buf->len - sizeof(sig)); + if (err) { + BT_ERR("Unable to create signature for %s", + bt_addr_le_str(&conn->le.dst)); + return -EIO; + }; - if (memcmp(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig))) { - BT_ERR("Unable to verify signature for %s", - bt_addr_le_str(&conn->le.dst)); - return -EBADMSG; - }; + if (memcmp(sig, net_buf_tail(buf) - sizeof(sig), sizeof(sig))) { + BT_ERR("Unable to verify signature for %s", + bt_addr_le_str(&conn->le.dst)); + return -EBADMSG; + }; - keys->remote_csrk.cnt++; + keys->remote_csrk.cnt++; - return 0; + return 0; } int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { - struct bt_keys *keys; - u32_t cnt; - int err; + struct bt_keys *keys; + u32_t cnt; + int err; - keys = bt_keys_find(BT_KEYS_LOCAL_CSRK, conn->id, &conn->le.dst); - if (!keys) { - BT_ERR("Unable to find local CSRK for %s", - bt_addr_le_str(&conn->le.dst)); - return -ENOENT; - } + keys = bt_keys_find(BT_KEYS_LOCAL_CSRK, conn->id, &conn->le.dst); + if (!keys) { + BT_ERR("Unable to find local CSRK for %s", + bt_addr_le_str(&conn->le.dst)); + return -ENOENT; + } - /* Reserve space for data signature */ - net_buf_add(buf, 12); + /* Reserve space for data signature */ + net_buf_add(buf, 12); - /* Copy signing count */ - cnt = sys_cpu_to_le32(keys->local_csrk.cnt); - memcpy(net_buf_tail(buf) - 12, &cnt, sizeof(cnt)); + /* Copy signing count */ + cnt = sys_cpu_to_le32(keys->local_csrk.cnt); + memcpy(net_buf_tail(buf) - 12, &cnt, sizeof(cnt)); - BT_DBG("Sign data len %u key %s count %u", buf->len, - bt_hex(keys->local_csrk.val, 16), keys->local_csrk.cnt); + BT_DBG("Sign data len %u key %s count %u", buf->len, + bt_hex(keys->local_csrk.val, 16), keys->local_csrk.cnt); - err = smp_sign_buf(keys->local_csrk.val, buf->data, buf->len - 12); - if (err) { - BT_ERR("Unable to create signature for %s", - bt_addr_le_str(&conn->le.dst)); - return -EIO; - } + err = smp_sign_buf(keys->local_csrk.val, buf->data, buf->len - 12); + if (err) { + BT_ERR("Unable to create signature for %s", + bt_addr_le_str(&conn->le.dst)); + return -EIO; + } - keys->local_csrk.cnt++; + keys->local_csrk.cnt++; - return 0; + return 0; } #else int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { - return -ENOTSUP; + return -ENOTSUP; } int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { - return -ENOTSUP; + return -ENOTSUP; } #endif /* CONFIG_BT_SIGNING */ @@ -4457,896 +4457,896 @@ int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) * Same mentioned in the Bluetooth Spec. */ static const u8_t key[] = { - 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, - 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c + 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, + 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }; static const u8_t M[] = { - 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, - 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, - 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, - 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, - 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, - 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, - 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, - 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 + 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, + 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, + 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, + 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, + 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, + 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, + 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, + 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }; static int aes_test(const char *prefix, const u8_t *key, const u8_t *m, - u16_t len, const u8_t *mac) + u16_t len, const u8_t *mac) { - u8_t out[16]; + u8_t out[16]; - BT_DBG("%s: AES CMAC of message with len %u", prefix, len); + BT_DBG("%s: AES CMAC of message with len %u", prefix, len); - bt_smp_aes_cmac(key, m, len, out); - if (!memcmp(out, mac, 16)) { - BT_DBG("%s: Success", prefix); - } else { - BT_ERR("%s: Failed", prefix); - return -1; - } + bt_smp_aes_cmac(key, m, len, out); + if (!memcmp(out, mac, 16)) { + BT_DBG("%s: Success", prefix); + } else { + BT_ERR("%s: Failed", prefix); + return -1; + } - return 0; + return 0; } static int smp_aes_cmac_test(void) { - u8_t mac1[] = { - 0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, - 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46 - }; - u8_t mac2[] = { - 0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, - 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c - }; - u8_t mac3[] = { - 0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, - 0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27 - }; - u8_t mac4[] = { - 0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, - 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe - }; - int err; + u8_t mac1[] = { + 0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, + 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46 + }; + u8_t mac2[] = { + 0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, + 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c + }; + u8_t mac3[] = { + 0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, + 0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27 + }; + u8_t mac4[] = { + 0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, + 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe + }; + int err; - err = aes_test("Test aes-cmac0", key, M, 0, mac1); - if (err) { - return err; - } + err = aes_test("Test aes-cmac0", key, M, 0, mac1); + if (err) { + return err; + } - err = aes_test("Test aes-cmac16", key, M, 16, mac2); - if (err) { - return err; - } + err = aes_test("Test aes-cmac16", key, M, 16, mac2); + if (err) { + return err; + } - err = aes_test("Test aes-cmac40", key, M, 40, mac3); - if (err) { - return err; - } + err = aes_test("Test aes-cmac40", key, M, 40, mac3); + if (err) { + return err; + } - err = aes_test("Test aes-cmac64", key, M, 64, mac4); - if (err) { - return err; - } + err = aes_test("Test aes-cmac64", key, M, 64, mac4); + if (err) { + return err; + } - return 0; + return 0; } static int sign_test(const char *prefix, const u8_t *key, const u8_t *m, - u16_t len, const u8_t *sig) + u16_t len, const u8_t *sig) { - u8_t msg[len + sizeof(u32_t) + 8]; - u8_t orig[len + sizeof(u32_t) + 8]; - u8_t *out = msg + len; - int err; + u8_t msg[len + sizeof(u32_t) + 8]; + u8_t orig[len + sizeof(u32_t) + 8]; + u8_t *out = msg + len; + int err; - BT_DBG("%s: Sign message with len %u", prefix, len); + BT_DBG("%s: Sign message with len %u", prefix, len); - (void)memset(msg, 0, sizeof(msg)); - memcpy(msg, m, len); - (void)memset(msg + len, 0, sizeof(u32_t)); + (void)memset(msg, 0, sizeof(msg)); + memcpy(msg, m, len); + (void)memset(msg + len, 0, sizeof(u32_t)); - memcpy(orig, msg, sizeof(msg)); + memcpy(orig, msg, sizeof(msg)); - err = smp_sign_buf(key, msg, len); - if (err) { - return err; - } + err = smp_sign_buf(key, msg, len); + if (err) { + return err; + } - /* Check original message */ - if (!memcmp(msg, orig, len + sizeof(u32_t))) { - BT_DBG("%s: Original message intact", prefix); - } else { - BT_ERR("%s: Original message modified", prefix); - BT_DBG("%s: orig %s", prefix, bt_hex(orig, sizeof(orig))); - BT_DBG("%s: msg %s", prefix, bt_hex(msg, sizeof(msg))); - return -1; - } + /* Check original message */ + if (!memcmp(msg, orig, len + sizeof(u32_t))) { + BT_DBG("%s: Original message intact", prefix); + } else { + BT_ERR("%s: Original message modified", prefix); + BT_DBG("%s: orig %s", prefix, bt_hex(orig, sizeof(orig))); + BT_DBG("%s: msg %s", prefix, bt_hex(msg, sizeof(msg))); + return -1; + } - if (!memcmp(out, sig, 12)) { - BT_DBG("%s: Success", prefix); - } else { - BT_ERR("%s: Failed", prefix); - return -1; - } + if (!memcmp(out, sig, 12)) { + BT_DBG("%s: Success", prefix); + } else { + BT_ERR("%s: Failed", prefix); + return -1; + } - return 0; + return 0; } static int smp_sign_test(void) { - const u8_t sig1[] = { - 0x00, 0x00, 0x00, 0x00, 0xb3, 0xa8, 0x59, 0x41, - 0x27, 0xeb, 0xc2, 0xc0 - }; - const u8_t sig2[] = { - 0x00, 0x00, 0x00, 0x00, 0x27, 0x39, 0x74, 0xf4, - 0x39, 0x2a, 0x23, 0x2a - }; - const u8_t sig3[] = { - 0x00, 0x00, 0x00, 0x00, 0xb7, 0xca, 0x94, 0xab, - 0x87, 0xc7, 0x82, 0x18 - }; - const u8_t sig4[] = { - 0x00, 0x00, 0x00, 0x00, 0x44, 0xe1, 0xe6, 0xce, - 0x1d, 0xf5, 0x13, 0x68 - }; - u8_t key_s[16]; - int err; + const u8_t sig1[] = { + 0x00, 0x00, 0x00, 0x00, 0xb3, 0xa8, 0x59, 0x41, + 0x27, 0xeb, 0xc2, 0xc0 + }; + const u8_t sig2[] = { + 0x00, 0x00, 0x00, 0x00, 0x27, 0x39, 0x74, 0xf4, + 0x39, 0x2a, 0x23, 0x2a + }; + const u8_t sig3[] = { + 0x00, 0x00, 0x00, 0x00, 0xb7, 0xca, 0x94, 0xab, + 0x87, 0xc7, 0x82, 0x18 + }; + const u8_t sig4[] = { + 0x00, 0x00, 0x00, 0x00, 0x44, 0xe1, 0xe6, 0xce, + 0x1d, 0xf5, 0x13, 0x68 + }; + u8_t key_s[16]; + int err; - /* Use the same key as aes-cmac but swap bytes */ - sys_memcpy_swap(key_s, key, 16); + /* Use the same key as aes-cmac but swap bytes */ + sys_memcpy_swap(key_s, key, 16); - err = sign_test("Test sign0", key_s, M, 0, sig1); - if (err) { - return err; - } + err = sign_test("Test sign0", key_s, M, 0, sig1); + if (err) { + return err; + } - err = sign_test("Test sign16", key_s, M, 16, sig2); - if (err) { - return err; - } + err = sign_test("Test sign16", key_s, M, 16, sig2); + if (err) { + return err; + } - err = sign_test("Test sign40", key_s, M, 40, sig3); - if (err) { - return err; - } + err = sign_test("Test sign40", key_s, M, 40, sig3); + if (err) { + return err; + } - err = sign_test("Test sign64", key_s, M, 64, sig4); - if (err) { - return err; - } + err = sign_test("Test sign64", key_s, M, 64, sig4); + if (err) { + return err; + } - return 0; + return 0; } static int smp_f4_test(void) { - u8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, - 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, - 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, - 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 }; - u8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b, - 0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59, - 0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90, - 0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 }; - u8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, - 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; - u8_t z = 0x00; - u8_t exp[16] = { 0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1, - 0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 }; - u8_t res[16]; - int err; + u8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, + 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, + 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, + 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 }; + u8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b, + 0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59, + 0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90, + 0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 }; + u8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, + 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; + u8_t z = 0x00; + u8_t exp[16] = { 0x2d, 0x87, 0x74, 0xa9, 0xbe, 0xa1, 0xed, 0xf1, + 0x1c, 0xbd, 0xa9, 0x07, 0xf1, 0x16, 0xc9, 0xf2 }; + u8_t res[16]; + int err; - err = smp_f4(u, v, x, z, res); - if (err) { - return err; - } + err = smp_f4(u, v, x, z, res); + if (err) { + return err; + } - if (memcmp(res, exp, 16)) { - return -EINVAL; - } + if (memcmp(res, exp, 16)) { + return -EINVAL; + } - return 0; + return 0; } static int smp_f5_test(void) { - u8_t w[32] = { 0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86, - 0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99, - 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, - 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; - u8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, - 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; - u8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, - 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; - bt_addr_le_t a1 = { .type = 0x00, - .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } }; - bt_addr_le_t a2 = { .type = 0x00, - .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } }; - u8_t exp_ltk[16] = { 0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05, - 0x98, 0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79, - 0x86, 0x69 }; - u8_t exp_mackey[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, - 0xfd, 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, - 0x65, 0x29 }; - u8_t mackey[16], ltk[16]; - int err; + u8_t w[32] = { 0x98, 0xa6, 0xbf, 0x73, 0xf3, 0x34, 0x8d, 0x86, + 0xf1, 0x66, 0xf8, 0xb4, 0x13, 0x6b, 0x79, 0x99, + 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, + 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; + u8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, + 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; + u8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, + 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; + bt_addr_le_t a1 = { .type = 0x00, + .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } }; + bt_addr_le_t a2 = { .type = 0x00, + .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } }; + u8_t exp_ltk[16] = { 0x38, 0x0a, 0x75, 0x94, 0xb5, 0x22, 0x05, + 0x98, 0x23, 0xcd, 0xd7, 0x69, 0x11, 0x79, + 0x86, 0x69 }; + u8_t exp_mackey[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, + 0xfd, 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, + 0x65, 0x29 }; + u8_t mackey[16], ltk[16]; + int err; - err = smp_f5(w, n1, n2, &a1, &a2, mackey, ltk); - if (err) { - return err; - } + err = smp_f5(w, n1, n2, &a1, &a2, mackey, ltk); + if (err) { + return err; + } - if (memcmp(mackey, exp_mackey, 16) || memcmp(ltk, exp_ltk, 16)) { - return -EINVAL; - } + if (memcmp(mackey, exp_mackey, 16) || memcmp(ltk, exp_ltk, 16)) { + return -EINVAL; + } - return 0; + return 0; } static int smp_f6_test(void) { - u8_t w[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd, - 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 }; - u8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, - 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; - u8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, - 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; - u8_t r[16] = { 0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08, - 0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 }; - u8_t io_cap[3] = { 0x02, 0x01, 0x01 }; - bt_addr_le_t a1 = { .type = 0x00, - .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } }; - bt_addr_le_t a2 = { .type = 0x00, - .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } }; - u8_t exp[16] = { 0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2, - 0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 }; - u8_t res[16]; - int err; + u8_t w[16] = { 0x20, 0x6e, 0x63, 0xce, 0x20, 0x6a, 0x3f, 0xfd, + 0x02, 0x4a, 0x08, 0xa1, 0x76, 0xf1, 0x65, 0x29 }; + u8_t n1[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, + 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; + u8_t n2[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, + 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; + u8_t r[16] = { 0xc8, 0x0f, 0x2d, 0x0c, 0xd2, 0x42, 0xda, 0x08, + 0x54, 0xbb, 0x53, 0xb4, 0x3b, 0x34, 0xa3, 0x12 }; + u8_t io_cap[3] = { 0x02, 0x01, 0x01 }; + bt_addr_le_t a1 = { .type = 0x00, + .a.val = { 0xce, 0xbf, 0x37, 0x37, 0x12, 0x56 } }; + bt_addr_le_t a2 = { .type = 0x00, + .a.val = {0xc1, 0xcf, 0x2d, 0x70, 0x13, 0xa7 } }; + u8_t exp[16] = { 0x61, 0x8f, 0x95, 0xda, 0x09, 0x0b, 0x6c, 0xd2, + 0xc5, 0xe8, 0xd0, 0x9c, 0x98, 0x73, 0xc4, 0xe3 }; + u8_t res[16]; + int err; - err = smp_f6(w, n1, n2, r, io_cap, &a1, &a2, res); - if (err) - return err; + err = smp_f6(w, n1, n2, r, io_cap, &a1, &a2, res); + if (err) + return err; - if (memcmp(res, exp, 16)) - return -EINVAL; + if (memcmp(res, exp, 16)) + return -EINVAL; - return 0; + return 0; } static int smp_g2_test(void) { - u8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, - 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, - 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, - 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 }; - u8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b, - 0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59, - 0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90, - 0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 }; - u8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, - 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; - u8_t y[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, - 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; - u32_t exp_val = 0x2f9ed5ba % 1000000; - u32_t val; - int err; + u8_t u[32] = { 0xe6, 0x9d, 0x35, 0x0e, 0x48, 0x01, 0x03, 0xcc, + 0xdb, 0xfd, 0xf4, 0xac, 0x11, 0x91, 0xf4, 0xef, + 0xb9, 0xa5, 0xf9, 0xe9, 0xa7, 0x83, 0x2c, 0x5e, + 0x2c, 0xbe, 0x97, 0xf2, 0xd2, 0x03, 0xb0, 0x20 }; + u8_t v[32] = { 0xfd, 0xc5, 0x7f, 0xf4, 0x49, 0xdd, 0x4f, 0x6b, + 0xfb, 0x7c, 0x9d, 0xf1, 0xc2, 0x9a, 0xcb, 0x59, + 0x2a, 0xe7, 0xd4, 0xee, 0xfb, 0xfc, 0x0a, 0x90, + 0x9a, 0xbb, 0xf6, 0x32, 0x3d, 0x8b, 0x18, 0x55 }; + u8_t x[16] = { 0xab, 0xae, 0x2b, 0x71, 0xec, 0xb2, 0xff, 0xff, + 0x3e, 0x73, 0x77, 0xd1, 0x54, 0x84, 0xcb, 0xd5 }; + u8_t y[16] = { 0xcf, 0xc4, 0x3d, 0xff, 0xf7, 0x83, 0x65, 0x21, + 0x6e, 0x5f, 0xa7, 0x25, 0xcc, 0xe7, 0xe8, 0xa6 }; + u32_t exp_val = 0x2f9ed5ba % 1000000; + u32_t val; + int err; - err = smp_g2(u, v, x, y, &val); - if (err) { - return err; - } + err = smp_g2(u, v, x, y, &val); + if (err) { + return err; + } - if (val != exp_val) { - return -EINVAL; - } + if (val != exp_val) { + return -EINVAL; + } - return 0; + return 0; } #if defined(CONFIG_BT_BREDR) static int smp_h6_test(void) { - u8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, - 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; - u8_t key_id[4] = { 0x72, 0x62, 0x65, 0x6c }; - u8_t exp_res[16] = { 0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8, - 0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d}; - u8_t res[16]; - int err; + u8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, + 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; + u8_t key_id[4] = { 0x72, 0x62, 0x65, 0x6c }; + u8_t exp_res[16] = { 0x99, 0x63, 0xb1, 0x80, 0xe2, 0xa9, 0xd3, 0xe8, + 0x1c, 0xc9, 0x6d, 0xe7, 0x02, 0xe1, 0x9a, 0x2d}; + u8_t res[16]; + int err; - err = smp_h6(w, key_id, res); - if (err) { - return err; - } + err = smp_h6(w, key_id, res); + if (err) { + return err; + } - if (memcmp(res, exp_res, 16)) { - return -EINVAL; - } + if (memcmp(res, exp_res, 16)) { + return -EINVAL; + } - return 0; + return 0; } static int smp_h7_test(void) { - u8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - u8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, - 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; - u8_t exp_res[16] = { 0x11, 0x70, 0xa5, 0x75, 0x2a, 0x8c, 0x99, 0xd2, - 0xec, 0xc0, 0xa3, 0xc6, 0x97, 0x35, 0x17, 0xfb}; - u8_t res[16]; - int err; + u8_t salt[16] = { 0x31, 0x70, 0x6d, 0x74, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + u8_t w[16] = { 0x9b, 0x7d, 0x39, 0x0a, 0xa6, 0x10, 0x10, 0x34, + 0x05, 0xad, 0xc8, 0x57, 0xa3, 0x34, 0x02, 0xec }; + u8_t exp_res[16] = { 0x11, 0x70, 0xa5, 0x75, 0x2a, 0x8c, 0x99, 0xd2, + 0xec, 0xc0, 0xa3, 0xc6, 0x97, 0x35, 0x17, 0xfb}; + u8_t res[16]; + int err; - err = smp_h7(salt, w, res); - if (err) { - return err; - } + err = smp_h7(salt, w, res); + if (err) { + return err; + } - if (memcmp(res, exp_res, 16)) { - return -EINVAL; - } + if (memcmp(res, exp_res, 16)) { + return -EINVAL; + } - return 0; + return 0; } #endif /* CONFIG_BT_BREDR */ static int smp_self_test(void) { - int err; + int err; - err = smp_aes_cmac_test(); - if (err) { - BT_ERR("SMP AES-CMAC self tests failed"); - return err; - } + err = smp_aes_cmac_test(); + if (err) { + BT_ERR("SMP AES-CMAC self tests failed"); + return err; + } - err = smp_sign_test(); - if (err) { - BT_ERR("SMP signing self tests failed"); - return err; - } + err = smp_sign_test(); + if (err) { + BT_ERR("SMP signing self tests failed"); + return err; + } - err = smp_f4_test(); - if (err) { - BT_ERR("SMP f4 self test failed"); - return err; - } + err = smp_f4_test(); + if (err) { + BT_ERR("SMP f4 self test failed"); + return err; + } - err = smp_f5_test(); - if (err) { - BT_ERR("SMP f5 self test failed"); - return err; - } + err = smp_f5_test(); + if (err) { + BT_ERR("SMP f5 self test failed"); + return err; + } - err = smp_f6_test(); - if (err) { - BT_ERR("SMP f6 self test failed"); - return err; - } + err = smp_f6_test(); + if (err) { + BT_ERR("SMP f6 self test failed"); + return err; + } - err = smp_g2_test(); - if (err) { - BT_ERR("SMP g2 self test failed"); - return err; - } + err = smp_g2_test(); + if (err) { + BT_ERR("SMP g2 self test failed"); + return err; + } #if defined(CONFIG_BT_BREDR) - err = smp_h6_test(); - if (err) { - BT_ERR("SMP h6 self test failed"); - return err; - } + err = smp_h6_test(); + if (err) { + BT_ERR("SMP h6 self test failed"); + return err; + } - err = smp_h7_test(); - if (err) { - BT_ERR("SMP h7 self test failed"); - return err; - } + err = smp_h7_test(); + if (err) { + BT_ERR("SMP h7 self test failed"); + return err; + } #endif /* CONFIG_BT_BREDR */ - return 0; + return 0; } #else static inline int smp_self_test(void) { - return 0; + return 0; } #endif int bt_smp_auth_passkey_entry(struct bt_conn *conn, unsigned int passkey) { - struct bt_smp *smp; - u8_t err; + struct bt_smp *smp; + u8_t err; - smp = smp_chan_get(conn); - if (!smp) { - return -EINVAL; - } + smp = smp_chan_get(conn); + if (!smp) { + return -EINVAL; + } - if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { - return -EINVAL; - } + if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { + return -EINVAL; + } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - legacy_passkey_entry(smp, passkey); - return 0; - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + legacy_passkey_entry(smp, passkey); + return 0; + } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ - smp->passkey = sys_cpu_to_le32(passkey); + smp->passkey = sys_cpu_to_le32(passkey); - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - err = smp_send_pairing_confirm(smp); - if (err) { - smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); - return 0; - } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); - return 0; - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + err = smp_send_pairing_confirm(smp); + if (err) { + smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); + return 0; + } + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_CONFIRM); + return 0; + } - if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && - atomic_test_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) { - err = smp_send_pairing_confirm(smp); - if (err) { - smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); - return 0; - } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - } + if (IS_ENABLED(CONFIG_BT_PERIPHERAL) && + atomic_test_bit(smp->flags, SMP_FLAG_CFM_DELAYED)) { + err = smp_send_pairing_confirm(smp); + if (err) { + smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); + return 0; + } + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + } - return 0; + return 0; } int bt_smp_auth_passkey_confirm(struct bt_conn *conn) { - struct bt_smp *smp; + struct bt_smp *smp; - smp = smp_chan_get(conn); - if (!smp) { - return -EINVAL; - } + smp = smp_chan_get(conn); + if (!smp) { + return -EINVAL; + } - if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { - return -EINVAL; - } + if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { + return -EINVAL; + } - /* wait for DHKey being generated */ - if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - return 0; - } + /* wait for DHKey being generated */ + if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_PENDING)) { + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + return 0; + } - /* wait for remote DHKey Check */ - if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) { - atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); - return 0; - } + /* wait for remote DHKey Check */ + if (atomic_test_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT)) { + atomic_set_bit(smp->flags, SMP_FLAG_DHKEY_SEND); + return 0; + } - if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) { - u8_t err; + if (atomic_test_bit(smp->flags, SMP_FLAG_DHKEY_SEND)) { + u8_t err; #if defined(CONFIG_BT_CENTRAL) - if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - err = compute_and_send_master_dhcheck(smp); - if (err) { - smp_error(smp, err); - } - return 0; - } + if (smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + err = compute_and_send_master_dhcheck(smp); + if (err) { + smp_error(smp, err); + } + return 0; + } #endif /* CONFIG_BT_CENTRAL */ #if defined(CONFIG_BT_PERIPHERAL) - err = compute_and_check_and_send_slave_dhcheck(smp); - if (err) { - smp_error(smp, err); - } + err = compute_and_check_and_send_slave_dhcheck(smp); + if (err) { + smp_error(smp, err); + } #endif /* CONFIG_BT_PERIPHERAL */ - } + } - return 0; + return 0; } int bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data *le_sc_oob) { - int err; + int err; - if (!sc_public_key) { - err = k_sem_take(&sc_local_pkey_ready, K_FOREVER); - if (err) { - return err; - } - } + if (!sc_public_key) { + err = k_sem_take(&sc_local_pkey_ready, K_FOREVER); + if (err) { + return err; + } + } - if (IS_ENABLED(CONFIG_BT_OOB_DATA_FIXED)) { - u8_t rand_num[] = { - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - }; + if (IS_ENABLED(CONFIG_BT_OOB_DATA_FIXED)) { + u8_t rand_num[] = { + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + }; - memcpy(le_sc_oob->r, rand_num, sizeof(le_sc_oob->r)); - } else { - err = bt_rand(le_sc_oob->r, 16); - if (err) { - return err; - } - } + memcpy(le_sc_oob->r, rand_num, sizeof(le_sc_oob->r)); + } else { + err = bt_rand(le_sc_oob->r, 16); + if (err) { + return err; + } + } - err = smp_f4(sc_public_key, sc_public_key, le_sc_oob->r, 0, - le_sc_oob->c); - if (err) { - return err; - } + err = smp_f4(sc_public_key, sc_public_key, le_sc_oob->r, 0, + le_sc_oob->c); + if (err) { + return err; + } - return 0; + return 0; } static bool le_sc_oob_data_check(struct bt_smp *smp, bool oobd_local_present, - bool oobd_remote_present) + bool oobd_remote_present) { - bool req_oob_present = le_sc_oob_data_req_check(smp); - bool rsp_oob_present = le_sc_oob_data_rsp_check(smp); + bool req_oob_present = le_sc_oob_data_req_check(smp); + bool rsp_oob_present = le_sc_oob_data_rsp_check(smp); - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - if ((req_oob_present != oobd_remote_present) && - (rsp_oob_present != oobd_local_present)) { - return false; - } - } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - if ((req_oob_present != oobd_local_present) && - (rsp_oob_present != oobd_remote_present)) { - return false; - } - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + if ((req_oob_present != oobd_remote_present) && + (rsp_oob_present != oobd_local_present)) { + return false; + } + } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + if ((req_oob_present != oobd_local_present) && + (rsp_oob_present != oobd_remote_present)) { + return false; + } + } - return true; + return true; } static int le_sc_oob_pairing_continue(struct bt_smp *smp) { - if (smp->oobd_remote) { - int err; - u8_t c[16]; + if (smp->oobd_remote) { + int err; + u8_t c[16]; - err = smp_f4(smp->pkey, smp->pkey, smp->oobd_remote->r, 0, c); - if (err) { - return err; - } + err = smp_f4(smp->pkey, smp->pkey, smp->oobd_remote->r, 0, c); + if (err) { + return err; + } - bool match = (memcmp(c, smp->oobd_remote->c, sizeof(c)) == 0); + bool match = (memcmp(c, smp->oobd_remote->c, sizeof(c)) == 0); - if (!match) { - smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED); - return 0; - } - } + if (!match) { + smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED); + return 0; + } + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); - } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { - atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); - atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + smp->chan.chan.conn->role == BT_HCI_ROLE_MASTER) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PAIRING_RANDOM); + } else if (IS_ENABLED(CONFIG_BT_PERIPHERAL)) { + atomic_set_bit(&smp->allowed_cmds, BT_SMP_DHKEY_CHECK); + atomic_set_bit(smp->flags, SMP_FLAG_DHCHECK_WAIT); + } - return smp_send_pairing_random(smp); + return smp_send_pairing_random(smp); } int bt_smp_le_oob_set_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data *oobd_local, - const struct bt_le_oob_sc_data *oobd_remote) + const struct bt_le_oob_sc_data *oobd_local, + const struct bt_le_oob_sc_data *oobd_remote) { - struct bt_smp *smp; + struct bt_smp *smp; - smp = smp_chan_get(conn); - if (!smp) { - return -EINVAL; - } + smp = smp_chan_get(conn); + if (!smp) { + return -EINVAL; + } - if (!le_sc_oob_data_check(smp, (oobd_local != NULL), - (oobd_remote != NULL))) { - return -EINVAL; - } + if (!le_sc_oob_data_check(smp, (oobd_local != NULL), + (oobd_remote != NULL))) { + return -EINVAL; + } - if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_OOB_PENDING)) { - return -EINVAL; - } + if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_OOB_PENDING)) { + return -EINVAL; + } - smp->oobd_local = oobd_local; - smp->oobd_remote = oobd_remote; + smp->oobd_local = oobd_local; + smp->oobd_remote = oobd_remote; - return le_sc_oob_pairing_continue(smp); + return le_sc_oob_pairing_continue(smp); } int bt_smp_le_oob_get_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data **oobd_local, - const struct bt_le_oob_sc_data **oobd_remote) + const struct bt_le_oob_sc_data **oobd_local, + const struct bt_le_oob_sc_data **oobd_remote) { - struct bt_smp *smp; + struct bt_smp *smp; - smp = smp_chan_get(conn); - if (!smp) { - return -EINVAL; - } + smp = smp_chan_get(conn); + if (!smp) { + return -EINVAL; + } - if (!smp->oobd_local && !smp->oobd_remote) { - return -ESRCH; - } + if (!smp->oobd_local && !smp->oobd_remote) { + return -ESRCH; + } - if (oobd_local) { - *oobd_local = smp->oobd_local; - } + if (oobd_local) { + *oobd_local = smp->oobd_local; + } - if (oobd_remote) { - *oobd_remote = smp->oobd_remote; - } + if (oobd_remote) { + *oobd_remote = smp->oobd_remote; + } - return 0; + return 0; } int bt_smp_auth_cancel(struct bt_conn *conn) { - struct bt_smp *smp; + struct bt_smp *smp; - smp = smp_chan_get(conn); - if (!smp) { - return -EINVAL; - } + smp = smp_chan_get(conn); + if (!smp) { + return -EINVAL; + } - if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { - return -EINVAL; - } + if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { + return -EINVAL; + } - switch (smp->method) { - case PASSKEY_INPUT: - case PASSKEY_DISPLAY: - return smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); - case PASSKEY_CONFIRM: - return smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED); - case LE_SC_OOB: - return smp_error(smp, BT_SMP_ERR_OOB_NOT_AVAIL); - case JUST_WORKS: - return smp_error(smp, BT_SMP_ERR_UNSPECIFIED); - default: - return 0; - } + switch (smp->method) { + case PASSKEY_INPUT: + case PASSKEY_DISPLAY: + return smp_error(smp, BT_SMP_ERR_PASSKEY_ENTRY_FAILED); + case PASSKEY_CONFIRM: + return smp_error(smp, BT_SMP_ERR_CONFIRM_FAILED); + case LE_SC_OOB: + return smp_error(smp, BT_SMP_ERR_OOB_NOT_AVAIL); + case JUST_WORKS: + return smp_error(smp, BT_SMP_ERR_UNSPECIFIED); + default: + return 0; + } } #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) int bt_smp_auth_pairing_confirm(struct bt_conn *conn) { - struct bt_smp *smp; + struct bt_smp *smp; - smp = smp_chan_get(conn); - if (!smp) { - return -EINVAL; - } + smp = smp_chan_get(conn); + if (!smp) { + return -EINVAL; + } - if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { - return -EINVAL; - } + if (!atomic_test_and_clear_bit(smp->flags, SMP_FLAG_USER)) { + return -EINVAL; + } - if (IS_ENABLED(CONFIG_BT_CENTRAL) && - conn->role == BT_CONN_ROLE_MASTER) { - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PAIRING_CONFIRM); - return legacy_send_pairing_confirm(smp); - } + if (IS_ENABLED(CONFIG_BT_CENTRAL) && + conn->role == BT_CONN_ROLE_MASTER) { + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PAIRING_CONFIRM); + return legacy_send_pairing_confirm(smp); + } - if (!sc_public_key) { - atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); - return 0; - } + if (!sc_public_key) { + atomic_set_bit(smp->flags, SMP_FLAG_PKEY_SEND); + return 0; + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); - return sc_send_public_key(smp); - } + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); + return sc_send_public_key(smp); + } #if defined(CONFIG_BT_PERIPHERAL) - if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - atomic_set_bit(&smp->allowed_cmds, - BT_SMP_CMD_PAIRING_CONFIRM); - return send_pairing_rsp(smp); - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + atomic_set_bit(&smp->allowed_cmds, + BT_SMP_CMD_PAIRING_CONFIRM); + return send_pairing_rsp(smp); + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); - if (send_pairing_rsp(smp)) { - return -EIO; - } + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_PUBLIC_KEY); + if (send_pairing_rsp(smp)) { + return -EIO; + } #endif /* CONFIG_BT_PERIPHERAL */ - return 0; + return 0; } #else int bt_smp_auth_pairing_confirm(struct bt_conn *conn) { - /* confirm_pairing will never be called in LE SC only mode */ - return -EINVAL; + /* confirm_pairing will never be called in LE SC only mode */ + return -EINVAL; } #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */ #if defined(CONFIG_BT_FIXED_PASSKEY) int bt_passkey_set(unsigned int passkey) { - if (passkey == BT_PASSKEY_INVALID) { - passkey = BT_PASSKEY_INVALID; - return 0; - } + if (passkey == BT_PASSKEY_INVALID) { + passkey = BT_PASSKEY_INVALID; + return 0; + } - if (passkey > 999999) { - return -EINVAL; - } + if (passkey > 999999) { + return -EINVAL; + } - fixed_passkey = passkey; - return 0; + fixed_passkey = passkey; + return 0; } #endif /* CONFIG_BT_FIXED_PASSKEY */ int bt_smp_start_security(struct bt_conn *conn) { - switch (conn->role) { + switch (conn->role) { #if defined(CONFIG_BT_CENTRAL) - case BT_HCI_ROLE_MASTER: - { - int err; - struct bt_smp *smp; + case BT_HCI_ROLE_MASTER: + { + int err; + struct bt_smp *smp; - smp = smp_chan_get(conn); - if (!smp) { - return -ENOTCONN; - } + smp = smp_chan_get(conn); + if (!smp) { + return -ENOTCONN; + } - if (!smp_keys_check(conn)) { - return smp_send_pairing_req(conn); - } + if (!smp_keys_check(conn)) { + return smp_send_pairing_req(conn); + } - /* pairing is in progress */ - if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { - return -EBUSY; - } + /* pairing is in progress */ + if (atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { + return -EBUSY; + } - /* Encryption is in progress */ - if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { - return -EBUSY; - } + /* Encryption is in progress */ + if (atomic_test_bit(smp->flags, SMP_FLAG_ENC_PENDING)) { + return -EBUSY; + } - /* LE SC LTK and legacy master LTK are stored in same place */ - err = bt_conn_le_start_encryption(conn, - conn->le.keys->ltk.rand, - conn->le.keys->ltk.ediv, - conn->le.keys->ltk.val, - conn->le.keys->enc_size); - if (err) { - return err; - } + /* LE SC LTK and legacy master LTK are stored in same place */ + err = bt_conn_le_start_encryption(conn, + conn->le.keys->ltk.rand, + conn->le.keys->ltk.ediv, + conn->le.keys->ltk.val, + conn->le.keys->enc_size); + if (err) { + return err; + } - atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); - atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); - return 0; - } + atomic_set_bit(&smp->allowed_cmds, BT_SMP_CMD_SECURITY_REQUEST); + atomic_set_bit(smp->flags, SMP_FLAG_ENC_PENDING); + return 0; + } #endif /* CONFIG_BT_CENTRAL && CONFIG_BT_SMP */ #if defined(CONFIG_BT_PERIPHERAL) - case BT_HCI_ROLE_SLAVE: - return smp_send_security_req(conn); + case BT_HCI_ROLE_SLAVE: + return smp_send_security_req(conn); #endif /* CONFIG_BT_PERIPHERAL && CONFIG_BT_SMP */ - default: - return -EINVAL; - } + default: + return -EINVAL; + } } void bt_smp_update_keys(struct bt_conn *conn) { - struct bt_smp *smp; + struct bt_smp *smp; - smp = smp_chan_get(conn); - if (!smp) { - return; - } + smp = smp_chan_get(conn); + if (!smp) { + return; + } - if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { - return; - } + if (!atomic_test_bit(smp->flags, SMP_FLAG_PAIRING)) { + return; + } - /* - * If link was successfully encrypted cleanup old keys as from now on - * only keys distributed in this pairing or LTK from LE SC will be used. - */ - if (conn->le.keys) { - bt_keys_clear(conn->le.keys); - } + /* + * If link was successfully encrypted cleanup old keys as from now on + * only keys distributed in this pairing or LTK from LE SC will be used. + */ + if (conn->le.keys) { + bt_keys_clear(conn->le.keys); + } - conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); - if (!conn->le.keys) { - BT_ERR("Unable to get keys for %s", - bt_addr_le_str(&conn->le.dst)); - smp_error(smp, BT_SMP_ERR_UNSPECIFIED); - return; - } + conn->le.keys = bt_keys_get_addr(conn->id, &conn->le.dst); + if (!conn->le.keys) { + BT_ERR("Unable to get keys for %s", + bt_addr_le_str(&conn->le.dst)); + smp_error(smp, BT_SMP_ERR_UNSPECIFIED); + return; + } - /* mark keys as debug */ - if (atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY)) { - conn->le.keys->flags |= BT_KEYS_DEBUG; - } + /* mark keys as debug */ + if (atomic_test_bit(smp->flags, SMP_FLAG_SC_DEBUG_KEY)) { + conn->le.keys->flags |= BT_KEYS_DEBUG; + } - /* - * store key type deducted from pairing method used - * it is important to store it since type is used to determine - * security level upon encryption - */ - switch (smp->method) { - case PASSKEY_DISPLAY: - case PASSKEY_INPUT: - case PASSKEY_CONFIRM: - case LE_SC_OOB: - conn->le.keys->flags |= BT_KEYS_AUTHENTICATED; - break; - case JUST_WORKS: - default: - /* unauthenticated key, clear it */ - conn->le.keys->flags &= ~BT_KEYS_AUTHENTICATED; - break; - } + /* + * store key type deducted from pairing method used + * it is important to store it since type is used to determine + * security level upon encryption + */ + switch (smp->method) { + case PASSKEY_DISPLAY: + case PASSKEY_INPUT: + case PASSKEY_CONFIRM: + case LE_SC_OOB: + conn->le.keys->flags |= BT_KEYS_AUTHENTICATED; + break; + case JUST_WORKS: + default: + /* unauthenticated key, clear it */ + conn->le.keys->flags &= ~BT_KEYS_AUTHENTICATED; + break; + } - conn->le.keys->enc_size = get_encryption_key_size(smp); + conn->le.keys->enc_size = get_encryption_key_size(smp); - /* - * Store LTK if LE SC is used, this is safe since LE SC is mutually - * exclusive with legacy pairing. Other keys are added on keys - * distribution. - */ - if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) { - conn->le.keys->flags |= BT_KEYS_SC; + /* + * Store LTK if LE SC is used, this is safe since LE SC is mutually + * exclusive with legacy pairing. Other keys are added on keys + * distribution. + */ + if (atomic_test_bit(smp->flags, SMP_FLAG_SC)) { + conn->le.keys->flags |= BT_KEYS_SC; - if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { - bt_keys_add_type(conn->le.keys, BT_KEYS_LTK_P256); - memcpy(conn->le.keys->ltk.val, smp->tk, - sizeof(conn->le.keys->ltk.val)); - (void)memset(conn->le.keys->ltk.rand, 0, - sizeof(conn->le.keys->ltk.rand)); - (void)memset(conn->le.keys->ltk.ediv, 0, - sizeof(conn->le.keys->ltk.ediv)); - } - } else { - conn->le.keys->flags &= ~BT_KEYS_SC; - } + if (atomic_test_bit(smp->flags, SMP_FLAG_BOND)) { + bt_keys_add_type(conn->le.keys, BT_KEYS_LTK_P256); + memcpy(conn->le.keys->ltk.val, smp->tk, + sizeof(conn->le.keys->ltk.val)); + (void)memset(conn->le.keys->ltk.rand, 0, + sizeof(conn->le.keys->ltk.rand)); + (void)memset(conn->le.keys->ltk.ediv, 0, + sizeof(conn->le.keys->ltk.ediv)); + } + } else { + conn->le.keys->flags &= ~BT_KEYS_SC; + } } static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { - int i; - static struct bt_l2cap_chan_ops ops = { - .connected = bt_smp_connected, - .disconnected = bt_smp_disconnected, - .encrypt_change = bt_smp_encrypt_change, - .recv = bt_smp_recv, - }; + int i; + static struct bt_l2cap_chan_ops ops = { + .connected = bt_smp_connected, + .disconnected = bt_smp_disconnected, + .encrypt_change = bt_smp_encrypt_change, + .recv = bt_smp_recv, + }; - BT_DBG("conn %p handle %u", conn, conn->handle); + BT_DBG("conn %p handle %u", conn, conn->handle); - for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { - struct bt_smp *smp = &bt_smp_pool[i]; + for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { + struct bt_smp *smp = &bt_smp_pool[i]; - if (smp->chan.chan.conn) { - continue; - } + if (smp->chan.chan.conn) { + continue; + } - smp->chan.chan.ops = &ops; + smp->chan.chan.ops = &ops; - *chan = &smp->chan.chan; + *chan = &smp->chan.chan; - return 0; - } + return 0; + } - BT_ERR("No available SMP context for conn %p", conn); + BT_ERR("No available SMP context for conn %p", conn); - return -ENOMEM; + return -ENOMEM; } static bool le_sc_supported(void) @@ -5354,49 +5354,49 @@ static bool le_sc_supported(void) #ifdef CONFIG_BT_REMOTE_CONTROL return false; #endif - /* - * If controller based ECC is to be used it must support - * "LE Read Local P-256 Public Key" and "LE Generate DH Key" commands. - * Otherwise LE SC are not supported. - */ - return BT_CMD_TEST(bt_dev.supported_commands, 34, 1) && - BT_CMD_TEST(bt_dev.supported_commands, 34, 2); + /* + * If controller based ECC is to be used it must support + * "LE Read Local P-256 Public Key" and "LE Generate DH Key" commands. + * Otherwise LE SC are not supported. + */ + return BT_CMD_TEST(bt_dev.supported_commands, 34, 1) && + BT_CMD_TEST(bt_dev.supported_commands, 34, 2); } BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept); #if defined(CONFIG_BT_BREDR) BT_L2CAP_CHANNEL_DEFINE(smp_br_fixed_chan, BT_L2CAP_CID_BR_SMP, - bt_smp_br_accept); + bt_smp_br_accept); #endif /* CONFIG_BT_BREDR */ int bt_smp_init(void) { #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) - static struct bt_l2cap_fixed_chan chan = { - .cid = BT_L2CAP_CID_SMP, - .accept = bt_smp_accept, - }; + static struct bt_l2cap_fixed_chan chan = { + .cid = BT_L2CAP_CID_SMP, + .accept = bt_smp_accept, + }; #endif - static struct bt_pub_key_cb pub_key_cb = { - .func = bt_smp_pkey_ready, - }; + static struct bt_pub_key_cb pub_key_cb = { + .func = bt_smp_pkey_ready, + }; #if defined(BFLB_BLE) k_sem_init(&sc_local_pkey_ready, 0, 1); #endif - - sc_supported = le_sc_supported(); - if (IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) && !sc_supported) { - BT_ERR("SC Pair Only Mode selected but LE SC not supported"); - return -ENOENT; - } + + sc_supported = le_sc_supported(); + if (IS_ENABLED(CONFIG_BT_SMP_SC_PAIR_ONLY) && !sc_supported) { + BT_ERR("SC Pair Only Mode selected but LE SC not supported"); + return -ENOENT; + } #if defined(BFLB_BLE_DISABLE_STATIC_CHANNEL) - bt_l2cap_le_fixed_chan_register(&chan); + bt_l2cap_le_fixed_chan_register(&chan); #endif - BT_DBG("LE SC %s", sc_supported ? "enabled" : "disabled"); + BT_DBG("LE SC %s", sc_supported ? "enabled" : "disabled"); - bt_pub_key_gen(&pub_key_cb); + bt_pub_key_gen(&pub_key_cb); - return smp_self_test(); + return smp_self_test(); } diff --git a/components/network/ble/blestack/src/host/smp.h b/components/network/ble/blestack/src/host/smp.h index ca8bb5e8..ae91b19e 100644 --- a/components/network/ble/blestack/src/host/smp.h +++ b/components/network/ble/blestack/src/host/smp.h @@ -10,122 +10,122 @@ */ struct bt_smp_hdr { - u8_t code; + u8_t code; } __packed; -#define BT_SMP_ERR_PASSKEY_ENTRY_FAILED 0x01 -#define BT_SMP_ERR_OOB_NOT_AVAIL 0x02 -#define BT_SMP_ERR_AUTH_REQUIREMENTS 0x03 -#define BT_SMP_ERR_CONFIRM_FAILED 0x04 -#define BT_SMP_ERR_PAIRING_NOTSUPP 0x05 -#define BT_SMP_ERR_ENC_KEY_SIZE 0x06 -#define BT_SMP_ERR_CMD_NOTSUPP 0x07 -#define BT_SMP_ERR_UNSPECIFIED 0x08 -#define BT_SMP_ERR_REPEATED_ATTEMPTS 0x09 -#define BT_SMP_ERR_INVALID_PARAMS 0x0a -#define BT_SMP_ERR_DHKEY_CHECK_FAILED 0x0b -#define BT_SMP_ERR_NUMERIC_COMP_FAILED 0x0c -#define BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS 0x0d -#define BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED 0x0e +#define BT_SMP_ERR_PASSKEY_ENTRY_FAILED 0x01 +#define BT_SMP_ERR_OOB_NOT_AVAIL 0x02 +#define BT_SMP_ERR_AUTH_REQUIREMENTS 0x03 +#define BT_SMP_ERR_CONFIRM_FAILED 0x04 +#define BT_SMP_ERR_PAIRING_NOTSUPP 0x05 +#define BT_SMP_ERR_ENC_KEY_SIZE 0x06 +#define BT_SMP_ERR_CMD_NOTSUPP 0x07 +#define BT_SMP_ERR_UNSPECIFIED 0x08 +#define BT_SMP_ERR_REPEATED_ATTEMPTS 0x09 +#define BT_SMP_ERR_INVALID_PARAMS 0x0a +#define BT_SMP_ERR_DHKEY_CHECK_FAILED 0x0b +#define BT_SMP_ERR_NUMERIC_COMP_FAILED 0x0c +#define BT_SMP_ERR_BREDR_PAIRING_IN_PROGRESS 0x0d +#define BT_SMP_ERR_CROSS_TRANSP_NOT_ALLOWED 0x0e -#define BT_SMP_IO_DISPLAY_ONLY 0x00 -#define BT_SMP_IO_DISPLAY_YESNO 0x01 -#define BT_SMP_IO_KEYBOARD_ONLY 0x02 -#define BT_SMP_IO_NO_INPUT_OUTPUT 0x03 -#define BT_SMP_IO_KEYBOARD_DISPLAY 0x04 +#define BT_SMP_IO_DISPLAY_ONLY 0x00 +#define BT_SMP_IO_DISPLAY_YESNO 0x01 +#define BT_SMP_IO_KEYBOARD_ONLY 0x02 +#define BT_SMP_IO_NO_INPUT_OUTPUT 0x03 +#define BT_SMP_IO_KEYBOARD_DISPLAY 0x04 -#define BT_SMP_OOB_DATA_MASK 0x01 -#define BT_SMP_OOB_NOT_PRESENT 0x00 -#define BT_SMP_OOB_PRESENT 0x01 +#define BT_SMP_OOB_DATA_MASK 0x01 +#define BT_SMP_OOB_NOT_PRESENT 0x00 +#define BT_SMP_OOB_PRESENT 0x01 -#define BT_SMP_MIN_ENC_KEY_SIZE 7 -#define BT_SMP_MAX_ENC_KEY_SIZE 16 +#define BT_SMP_MIN_ENC_KEY_SIZE 7 +#define BT_SMP_MAX_ENC_KEY_SIZE 16 -#define BT_SMP_DIST_ENC_KEY 0x01 -#define BT_SMP_DIST_ID_KEY 0x02 -#define BT_SMP_DIST_SIGN 0x04 -#define BT_SMP_DIST_LINK_KEY 0x08 +#define BT_SMP_DIST_ENC_KEY 0x01 +#define BT_SMP_DIST_ID_KEY 0x02 +#define BT_SMP_DIST_SIGN 0x04 +#define BT_SMP_DIST_LINK_KEY 0x08 -#define BT_SMP_DIST_MASK 0x0f +#define BT_SMP_DIST_MASK 0x0f -#define BT_SMP_AUTH_NONE 0x00 -#define BT_SMP_AUTH_BONDING 0x01 -#define BT_SMP_AUTH_MITM 0x04 -#define BT_SMP_AUTH_SC 0x08 -#define BT_SMP_AUTH_KEYPRESS 0x10 -#define BT_SMP_AUTH_CT2 0x20 +#define BT_SMP_AUTH_NONE 0x00 +#define BT_SMP_AUTH_BONDING 0x01 +#define BT_SMP_AUTH_MITM 0x04 +#define BT_SMP_AUTH_SC 0x08 +#define BT_SMP_AUTH_KEYPRESS 0x10 +#define BT_SMP_AUTH_CT2 0x20 -#define BT_SMP_CMD_PAIRING_REQ 0x01 -#define BT_SMP_CMD_PAIRING_RSP 0x02 +#define BT_SMP_CMD_PAIRING_REQ 0x01 +#define BT_SMP_CMD_PAIRING_RSP 0x02 struct bt_smp_pairing { - u8_t io_capability; - u8_t oob_flag; - u8_t auth_req; - u8_t max_key_size; - u8_t init_key_dist; - u8_t resp_key_dist; + u8_t io_capability; + u8_t oob_flag; + u8_t auth_req; + u8_t max_key_size; + u8_t init_key_dist; + u8_t resp_key_dist; } __packed; -#define BT_SMP_CMD_PAIRING_CONFIRM 0x03 +#define BT_SMP_CMD_PAIRING_CONFIRM 0x03 struct bt_smp_pairing_confirm { - u8_t val[16]; + u8_t val[16]; } __packed; -#define BT_SMP_CMD_PAIRING_RANDOM 0x04 +#define BT_SMP_CMD_PAIRING_RANDOM 0x04 struct bt_smp_pairing_random { - u8_t val[16]; + u8_t val[16]; } __packed; -#define BT_SMP_CMD_PAIRING_FAIL 0x05 +#define BT_SMP_CMD_PAIRING_FAIL 0x05 struct bt_smp_pairing_fail { - u8_t reason; + u8_t reason; } __packed; -#define BT_SMP_CMD_ENCRYPT_INFO 0x06 +#define BT_SMP_CMD_ENCRYPT_INFO 0x06 struct bt_smp_encrypt_info { - u8_t ltk[16]; + u8_t ltk[16]; } __packed; -#define BT_SMP_CMD_MASTER_IDENT 0x07 +#define BT_SMP_CMD_MASTER_IDENT 0x07 struct bt_smp_master_ident { - u8_t ediv[2]; - u8_t rand[8]; + u8_t ediv[2]; + u8_t rand[8]; } __packed; -#define BT_SMP_CMD_IDENT_INFO 0x08 +#define BT_SMP_CMD_IDENT_INFO 0x08 struct bt_smp_ident_info { - u8_t irk[16]; + u8_t irk[16]; } __packed; -#define BT_SMP_CMD_IDENT_ADDR_INFO 0x09 +#define BT_SMP_CMD_IDENT_ADDR_INFO 0x09 struct bt_smp_ident_addr_info { - bt_addr_le_t addr; + bt_addr_le_t addr; } __packed; -#define BT_SMP_CMD_SIGNING_INFO 0x0a +#define BT_SMP_CMD_SIGNING_INFO 0x0a struct bt_smp_signing_info { - u8_t csrk[16]; + u8_t csrk[16]; } __packed; -#define BT_SMP_CMD_SECURITY_REQUEST 0x0b +#define BT_SMP_CMD_SECURITY_REQUEST 0x0b struct bt_smp_security_request { - u8_t auth_req; + u8_t auth_req; } __packed; -#define BT_SMP_CMD_PUBLIC_KEY 0x0c +#define BT_SMP_CMD_PUBLIC_KEY 0x0c struct bt_smp_public_key { - u8_t x[32]; - u8_t y[32]; + u8_t x[32]; + u8_t y[32]; } __packed; -#define BT_SMP_DHKEY_CHECK 0x0d +#define BT_SMP_DHKEY_CHECK 0x0d struct bt_smp_dhkey_check { - u8_t e[16]; + u8_t e[16]; } __packed; int bt_smp_start_security(struct bt_conn *conn); bool bt_smp_request_ltk(struct bt_conn *conn, u64_t rand, u16_t ediv, - u8_t *ltk); + u8_t *ltk); void bt_smp_update_keys(struct bt_conn *conn); @@ -140,11 +140,11 @@ int bt_smp_auth_cancel(struct bt_conn *conn); int bt_smp_le_oob_generate_sc_data(struct bt_le_oob_sc_data *le_sc_oob); int bt_smp_le_oob_set_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data *oobd_local, - const struct bt_le_oob_sc_data *oobd_remote); + const struct bt_le_oob_sc_data *oobd_local, + const struct bt_le_oob_sc_data *oobd_remote); int bt_smp_le_oob_get_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data **oobd_local, - const struct bt_le_oob_sc_data **oobd_remote); + const struct bt_le_oob_sc_data **oobd_local, + const struct bt_le_oob_sc_data **oobd_remote); /** brief Verify signed message * diff --git a/components/network/ble/blestack/src/host/smp_null.c b/components/network/ble/blestack/src/host/smp_null.c index 2dbd473e..e9c23923 100644 --- a/components/network/ble/blestack/src/host/smp_null.c +++ b/components/network/ble/blestack/src/host/smp_null.c @@ -31,71 +31,71 @@ static struct bt_l2cap_le_chan bt_smp_pool[CONFIG_BT_MAX_CONN]; int bt_smp_sign_verify(struct bt_conn *conn, struct net_buf *buf) { - return -ENOTSUP; + return -ENOTSUP; } int bt_smp_sign(struct bt_conn *conn, struct net_buf *buf) { - return -ENOTSUP; + return -ENOTSUP; } static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf) { - struct bt_conn *conn = chan->conn; - struct bt_smp_pairing_fail *rsp; - struct bt_smp_hdr *hdr; + struct bt_conn *conn = chan->conn; + struct bt_smp_pairing_fail *rsp; + struct bt_smp_hdr *hdr; - /* If a device does not support pairing then it shall respond with - * a Pairing Failed command with the reason set to "Pairing Not - * Supported" when any command is received. - * Core Specification Vol. 3, Part H, 3.3 - */ + /* If a device does not support pairing then it shall respond with + * a Pairing Failed command with the reason set to "Pairing Not + * Supported" when any command is received. + * Core Specification Vol. 3, Part H, 3.3 + */ - buf = bt_l2cap_create_pdu(NULL, 0); - /* NULL is not a possible return due to K_FOREVER */ + buf = bt_l2cap_create_pdu(NULL, 0); + /* NULL is not a possible return due to K_FOREVER */ - hdr = net_buf_add(buf, sizeof(*hdr)); - hdr->code = BT_SMP_CMD_PAIRING_FAIL; + hdr = net_buf_add(buf, sizeof(*hdr)); + hdr->code = BT_SMP_CMD_PAIRING_FAIL; - rsp = net_buf_add(buf, sizeof(*rsp)); - rsp->reason = BT_SMP_ERR_PAIRING_NOTSUPP; + rsp = net_buf_add(buf, sizeof(*rsp)); + rsp->reason = BT_SMP_ERR_PAIRING_NOTSUPP; - bt_l2cap_send(conn, BT_L2CAP_CID_SMP, buf); + bt_l2cap_send(conn, BT_L2CAP_CID_SMP, buf); - return 0; + return 0; } static int bt_smp_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan) { - int i; - static struct bt_l2cap_chan_ops ops = { - .recv = bt_smp_recv, - }; + int i; + static struct bt_l2cap_chan_ops ops = { + .recv = bt_smp_recv, + }; - BT_DBG("conn %p handle %u", conn, conn->handle); + BT_DBG("conn %p handle %u", conn, conn->handle); - for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { - struct bt_l2cap_le_chan *smp = &bt_smp_pool[i]; + for (i = 0; i < ARRAY_SIZE(bt_smp_pool); i++) { + struct bt_l2cap_le_chan *smp = &bt_smp_pool[i]; - if (smp->chan.conn) { - continue; - } + if (smp->chan.conn) { + continue; + } - smp->chan.ops = &ops; + smp->chan.ops = &ops; - *chan = &smp->chan; + *chan = &smp->chan; - return 0; - } + return 0; + } - BT_ERR("No available SMP context for conn %p", conn); + BT_ERR("No available SMP context for conn %p", conn); - return -ENOMEM; + return -ENOMEM; } BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept); int bt_smp_init(void) { - return 0; + return 0; } diff --git a/components/network/ble/blestack/src/host/uuid.c b/components/network/ble/blestack/src/host/uuid.c index 2d5fb5b4..6fad72ff 100644 --- a/components/network/ble/blestack/src/host/uuid.c +++ b/components/network/ble/blestack/src/host/uuid.c @@ -23,117 +23,117 @@ * big endian 0x2800 : [28 00] -> swapping required */ static const struct bt_uuid_128 uuid128_base = { - .uuid = { BT_UUID_TYPE_128 }, - .val = { BT_UUID_128_ENCODE( - 0x00000000, 0x0000, 0x1000, 0x8000, 0x00805F9B34FB) } + .uuid = { BT_UUID_TYPE_128 }, + .val = { BT_UUID_128_ENCODE( + 0x00000000, 0x0000, 0x1000, 0x8000, 0x00805F9B34FB) } }; static void uuid_to_uuid128(const struct bt_uuid *src, struct bt_uuid_128 *dst) { - switch (src->type) { - case BT_UUID_TYPE_16: - *dst = uuid128_base; - sys_put_le16(BT_UUID_16(src)->val, - &dst->val[UUID_16_BASE_OFFSET]); - return; - case BT_UUID_TYPE_32: - *dst = uuid128_base; - sys_put_le32(BT_UUID_32(src)->val, - &dst->val[UUID_16_BASE_OFFSET]); - return; - case BT_UUID_TYPE_128: - memcpy(dst, src, sizeof(*dst)); - return; - } + switch (src->type) { + case BT_UUID_TYPE_16: + *dst = uuid128_base; + sys_put_le16(BT_UUID_16(src)->val, + &dst->val[UUID_16_BASE_OFFSET]); + return; + case BT_UUID_TYPE_32: + *dst = uuid128_base; + sys_put_le32(BT_UUID_32(src)->val, + &dst->val[UUID_16_BASE_OFFSET]); + return; + case BT_UUID_TYPE_128: + memcpy(dst, src, sizeof(*dst)); + return; + } } static int uuid128_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) { - struct bt_uuid_128 uuid1, uuid2; + struct bt_uuid_128 uuid1, uuid2; - uuid_to_uuid128(u1, &uuid1); - uuid_to_uuid128(u2, &uuid2); + uuid_to_uuid128(u1, &uuid1); + uuid_to_uuid128(u2, &uuid2); - return memcmp(uuid1.val, uuid2.val, 16); + return memcmp(uuid1.val, uuid2.val, 16); } int bt_uuid_cmp(const struct bt_uuid *u1, const struct bt_uuid *u2) { - /* Convert to 128 bit if types don't match */ - if (u1->type != u2->type) { - return uuid128_cmp(u1, u2); - } + /* Convert to 128 bit if types don't match */ + if (u1->type != u2->type) { + return uuid128_cmp(u1, u2); + } - switch (u1->type) { - case BT_UUID_TYPE_16: - return (int)BT_UUID_16(u1)->val - (int)BT_UUID_16(u2)->val; - case BT_UUID_TYPE_32: - return (int)BT_UUID_32(u1)->val - (int)BT_UUID_32(u2)->val; - case BT_UUID_TYPE_128: - return memcmp(BT_UUID_128(u1)->val, BT_UUID_128(u2)->val, 16); - } + switch (u1->type) { + case BT_UUID_TYPE_16: + return (int)BT_UUID_16(u1)->val - (int)BT_UUID_16(u2)->val; + case BT_UUID_TYPE_32: + return (int)BT_UUID_32(u1)->val - (int)BT_UUID_32(u2)->val; + case BT_UUID_TYPE_128: + return memcmp(BT_UUID_128(u1)->val, BT_UUID_128(u2)->val, 16); + } - return -EINVAL; + return -EINVAL; } bool bt_uuid_create(struct bt_uuid *uuid, const u8_t *data, u8_t data_len) { - /* Copy UUID from packet data/internal variable to internal bt_uuid */ - switch (data_len) { - case 2: - uuid->type = BT_UUID_TYPE_16; - BT_UUID_16(uuid)->val = sys_get_le16(data); - break; - case 4: - uuid->type = BT_UUID_TYPE_32; - BT_UUID_32(uuid)->val = sys_get_le32(data); - break; - case 16: - uuid->type = BT_UUID_TYPE_128; - memcpy(&BT_UUID_128(uuid)->val, data, 16); - break; - default: - return false; - } - return true; + /* Copy UUID from packet data/internal variable to internal bt_uuid */ + switch (data_len) { + case 2: + uuid->type = BT_UUID_TYPE_16; + BT_UUID_16(uuid)->val = sys_get_le16(data); + break; + case 4: + uuid->type = BT_UUID_TYPE_32; + BT_UUID_32(uuid)->val = sys_get_le32(data); + break; + case 16: + uuid->type = BT_UUID_TYPE_128; + memcpy(&BT_UUID_128(uuid)->val, data, 16); + break; + default: + return false; + } + return true; } #if defined(CONFIG_BT_DEBUG) void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, size_t len) { - u32_t tmp1, tmp5; - u16_t tmp0, tmp2, tmp3, tmp4; + u32_t tmp1, tmp5; + u16_t tmp0, tmp2, tmp3, tmp4; - switch (uuid->type) { - case BT_UUID_TYPE_16: - snprintk(str, len, "%04x", BT_UUID_16(uuid)->val); - break; - case BT_UUID_TYPE_32: - snprintk(str, len, "%04x", BT_UUID_32(uuid)->val); - break; - case BT_UUID_TYPE_128: - memcpy(&tmp0, &BT_UUID_128(uuid)->val[0], sizeof(tmp0)); - memcpy(&tmp1, &BT_UUID_128(uuid)->val[2], sizeof(tmp1)); - memcpy(&tmp2, &BT_UUID_128(uuid)->val[6], sizeof(tmp2)); - memcpy(&tmp3, &BT_UUID_128(uuid)->val[8], sizeof(tmp3)); - memcpy(&tmp4, &BT_UUID_128(uuid)->val[10], sizeof(tmp4)); - memcpy(&tmp5, &BT_UUID_128(uuid)->val[12], sizeof(tmp5)); + switch (uuid->type) { + case BT_UUID_TYPE_16: + snprintk(str, len, "%04x", BT_UUID_16(uuid)->val); + break; + case BT_UUID_TYPE_32: + snprintk(str, len, "%04x", BT_UUID_32(uuid)->val); + break; + case BT_UUID_TYPE_128: + memcpy(&tmp0, &BT_UUID_128(uuid)->val[0], sizeof(tmp0)); + memcpy(&tmp1, &BT_UUID_128(uuid)->val[2], sizeof(tmp1)); + memcpy(&tmp2, &BT_UUID_128(uuid)->val[6], sizeof(tmp2)); + memcpy(&tmp3, &BT_UUID_128(uuid)->val[8], sizeof(tmp3)); + memcpy(&tmp4, &BT_UUID_128(uuid)->val[10], sizeof(tmp4)); + memcpy(&tmp5, &BT_UUID_128(uuid)->val[12], sizeof(tmp5)); - snprintk(str, len, "%08x-%04x-%04x-%04x-%08x%04x", - tmp5, tmp4, tmp3, tmp2, tmp1, tmp0); - break; - default: - (void)memset(str, 0, len); - return; - } + snprintk(str, len, "%08x-%04x-%04x-%04x-%08x%04x", + tmp5, tmp4, tmp3, tmp2, tmp1, tmp0); + break; + default: + (void)memset(str, 0, len); + return; + } } const char *bt_uuid_str_real(const struct bt_uuid *uuid) { - static char str[37]; + static char str[37]; - bt_uuid_to_str(uuid, str, sizeof(str)); + bt_uuid_to_str(uuid, str, sizeof(str)); - return str; + return str; } #endif /* CONFIG_BT_DEBUG */ diff --git a/components/network/ble/blestack/src/host_cmdproc/oadc_cmdproc.c b/components/network/ble/blestack/src/host_cmdproc/oadc_cmdproc.c index 640e9689..3b282256 100644 --- a/components/network/ble/blestack/src/host_cmdproc/oadc_cmdproc.c +++ b/components/network/ble/blestack/src/host_cmdproc/oadc_cmdproc.c @@ -33,11 +33,11 @@ void oad_cmdproc_start(void) } void oad_cmdproc_image_identity(struct oad_file_info* file_info) -{ +{ struct oad_cmdproc_req_t req; req.cmd_id = OAD_CMDPROC_IMAGE_IDENTITY; memcpy(&req.q.file_info, file_info, sizeof(*file_info)); - cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); + cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); } void oad_cmdproc_block_req(struct oad_file_info* file_info, uint32_t file_offset, uint8_t data_len) @@ -48,7 +48,7 @@ void oad_cmdproc_block_req(struct oad_file_info* file_info, uint32_t file_offset memcpy(&req.q.block_req.file_info, file_info, sizeof(*file_info)); req.q.block_req.file_offset = file_offset; req.q.block_req.data_len = data_len; - cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); + cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); } void oad_cmdproc_upgrd_end(uint8_t status, struct oad_file_info* file_info) @@ -59,7 +59,7 @@ void oad_cmdproc_upgrd_end(uint8_t status, struct oad_file_info* file_info) req.q.upgrd_end.status = status; memcpy(&req.q.upgrd_end.file_info, file_info, sizeof(*file_info)); - cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); + cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); } void oad_cmdproc_enable(cmdproc_recv_cb cb) { diff --git a/components/network/ble/blestack/src/include/bluetooth/addr.h b/components/network/ble/blestack/src/include/bluetooth/addr.h index 1e1abd30..15c6da12 100644 --- a/components/network/ble/blestack/src/include/bluetooth/addr.h +++ b/components/network/ble/blestack/src/include/bluetooth/addr.h @@ -29,40 +29,40 @@ extern "C" { /** Bluetooth Device Address */ typedef struct { - u8_t val[6]; + u8_t val[6]; } bt_addr_t; /** Bluetooth LE Device Address */ typedef struct { - u8_t type; - bt_addr_t a; + u8_t type; + bt_addr_t a; } bt_addr_le_t; #define BT_ADDR_ANY (&(bt_addr_t) { { 0, 0, 0, 0, 0, 0 } }) #define BT_ADDR_NONE (&(bt_addr_t) { \ - { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } }) + { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } }) #define BT_ADDR_LE_ANY (&(bt_addr_le_t) { 0, { { 0, 0, 0, 0, 0, 0 } } }) #define BT_ADDR_LE_NONE (&(bt_addr_le_t) { 0, \ - { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } }) + { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } }) static inline int bt_addr_cmp(const bt_addr_t *a, const bt_addr_t *b) { - return memcmp(a, b, sizeof(*a)); + return memcmp(a, b, sizeof(*a)); } static inline int bt_addr_le_cmp(const bt_addr_le_t *a, const bt_addr_le_t *b) { - return memcmp(a, b, sizeof(*a)); + return memcmp(a, b, sizeof(*a)); } static inline void bt_addr_copy(bt_addr_t *dst, const bt_addr_t *src) { - memcpy(dst, src, sizeof(*dst)); + memcpy(dst, src, sizeof(*dst)); } static inline void bt_addr_le_copy(bt_addr_le_t *dst, const bt_addr_le_t *src) { - memcpy(dst, src, sizeof(*dst)); + memcpy(dst, src, sizeof(*dst)); } #define BT_ADDR_IS_RPA(a) (((a)->val[5] & 0xc0) == 0x40) @@ -78,20 +78,20 @@ int bt_addr_le_create_static(bt_addr_le_t *addr); static inline bool bt_addr_le_is_rpa(const bt_addr_le_t *addr) { - if (addr->type != BT_ADDR_LE_RANDOM) { - return false; - } + if (addr->type != BT_ADDR_LE_RANDOM) { + return false; + } - return BT_ADDR_IS_RPA(&addr->a); + return BT_ADDR_IS_RPA(&addr->a); } static inline bool bt_addr_le_is_identity(const bt_addr_le_t *addr) { - if (addr->type == BT_ADDR_LE_PUBLIC) { - return true; - } + if (addr->type == BT_ADDR_LE_PUBLIC) { + return true; + } - return BT_ADDR_IS_STATIC(&addr->a); + return BT_ADDR_IS_STATIC(&addr->a); } #ifdef __cplusplus diff --git a/components/network/ble/blestack/src/include/bluetooth/att.h b/components/network/ble/blestack/src/include/bluetooth/att.h index f2ee968b..3a638649 100644 --- a/components/network/ble/blestack/src/include/bluetooth/att.h +++ b/components/network/ble/blestack/src/include/bluetooth/att.h @@ -18,46 +18,46 @@ extern "C" { #include /* Error codes for Error response PDU */ -#define BT_ATT_ERR_INVALID_HANDLE 0x01 -#define BT_ATT_ERR_READ_NOT_PERMITTED 0x02 -#define BT_ATT_ERR_WRITE_NOT_PERMITTED 0x03 -#define BT_ATT_ERR_INVALID_PDU 0x04 -#define BT_ATT_ERR_AUTHENTICATION 0x05 -#define BT_ATT_ERR_NOT_SUPPORTED 0x06 -#define BT_ATT_ERR_INVALID_OFFSET 0x07 -#define BT_ATT_ERR_AUTHORIZATION 0x08 -#define BT_ATT_ERR_PREPARE_QUEUE_FULL 0x09 -#define BT_ATT_ERR_ATTRIBUTE_NOT_FOUND 0x0a -#define BT_ATT_ERR_ATTRIBUTE_NOT_LONG 0x0b -#define BT_ATT_ERR_ENCRYPTION_KEY_SIZE 0x0c -#define BT_ATT_ERR_INVALID_ATTRIBUTE_LEN 0x0d -#define BT_ATT_ERR_UNLIKELY 0x0e -#define BT_ATT_ERR_INSUFFICIENT_ENCRYPTION 0x0f -#define BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE 0x10 -#define BT_ATT_ERR_INSUFFICIENT_RESOURCES 0x11 -#define BT_ATT_ERR_DB_OUT_OF_SYNC 0x12 -#define BT_ATT_ERR_VALUE_NOT_ALLOWED 0x13 +#define BT_ATT_ERR_INVALID_HANDLE 0x01 +#define BT_ATT_ERR_READ_NOT_PERMITTED 0x02 +#define BT_ATT_ERR_WRITE_NOT_PERMITTED 0x03 +#define BT_ATT_ERR_INVALID_PDU 0x04 +#define BT_ATT_ERR_AUTHENTICATION 0x05 +#define BT_ATT_ERR_NOT_SUPPORTED 0x06 +#define BT_ATT_ERR_INVALID_OFFSET 0x07 +#define BT_ATT_ERR_AUTHORIZATION 0x08 +#define BT_ATT_ERR_PREPARE_QUEUE_FULL 0x09 +#define BT_ATT_ERR_ATTRIBUTE_NOT_FOUND 0x0a +#define BT_ATT_ERR_ATTRIBUTE_NOT_LONG 0x0b +#define BT_ATT_ERR_ENCRYPTION_KEY_SIZE 0x0c +#define BT_ATT_ERR_INVALID_ATTRIBUTE_LEN 0x0d +#define BT_ATT_ERR_UNLIKELY 0x0e +#define BT_ATT_ERR_INSUFFICIENT_ENCRYPTION 0x0f +#define BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE 0x10 +#define BT_ATT_ERR_INSUFFICIENT_RESOURCES 0x11 +#define BT_ATT_ERR_DB_OUT_OF_SYNC 0x12 +#define BT_ATT_ERR_VALUE_NOT_ALLOWED 0x13 /* Common Profile Error Codes (from CSS) */ -#define BT_ATT_ERR_WRITE_REQ_REJECTED 0xfc -#define BT_ATT_ERR_CCC_IMPROPER_CONF 0xfd -#define BT_ATT_ERR_PROCEDURE_IN_PROGRESS 0xfe -#define BT_ATT_ERR_OUT_OF_RANGE 0xff +#define BT_ATT_ERR_WRITE_REQ_REJECTED 0xfc +#define BT_ATT_ERR_CCC_IMPROPER_CONF 0xfd +#define BT_ATT_ERR_PROCEDURE_IN_PROGRESS 0xfe +#define BT_ATT_ERR_OUT_OF_RANGE 0xff typedef void (*bt_att_func_t)(struct bt_conn *conn, u8_t err, - const void *pdu, u16_t length, - void *user_data); + const void *pdu, u16_t length, + void *user_data); typedef void (*bt_att_destroy_t)(void *user_data); /* ATT request context */ struct bt_att_req { - sys_snode_t node; - bt_att_func_t func; - bt_att_destroy_t destroy; - struct net_buf_simple_state state; - struct net_buf *buf; + sys_snode_t node; + bt_att_func_t func; + bt_att_destroy_t destroy; + struct net_buf_simple_state state; + struct net_buf *buf; #if defined(CONFIG_BT_SMP) - bool retrying; + bool retrying; #endif /* CONFIG_BT_SMP */ }; diff --git a/components/network/ble/blestack/src/include/bluetooth/bluetooth.h b/components/network/ble/blestack/src/include/bluetooth/bluetooth.h index fd3ee5e5..0f2062ae 100644 --- a/components/network/ble/blestack/src/include/bluetooth/bluetooth.h +++ b/components/network/ble/blestack/src/include/bluetooth/bluetooth.h @@ -212,9 +212,9 @@ int bt_id_delete(u8_t id); * bt_le_adv_start() function. */ struct bt_data { - u8_t type; - u8_t data_len; - const u8_t *data; + u8_t type; + u8_t data_len; + const u8_t *data; }; /** @brief Helper to declare elements of bt_data arrays @@ -227,11 +227,11 @@ struct bt_data { * @param _data_len Number of bytes behind the _data pointer */ #define BT_DATA(_type, _data, _data_len) \ - { \ - .type = (_type), \ - .data_len = (_data_len), \ - .data = (const u8_t *)(_data), \ - } + { \ + .type = (_type), \ + .data_len = (_data_len), \ + .data = (const u8_t *)(_data), \ + } /** @brief Helper to declare elements of bt_data arrays * @@ -242,77 +242,77 @@ struct bt_data { * @param _bytes Variable number of single-byte parameters */ #define BT_DATA_BYTES(_type, _bytes...) \ - BT_DATA(_type, ((u8_t []) { _bytes }), \ - sizeof((u8_t []) { _bytes })) + BT_DATA(_type, ((u8_t []) { _bytes }), \ + sizeof((u8_t []) { _bytes })) /** Advertising options */ enum { - /** Convenience value when no options are specified. */ - BT_LE_ADV_OPT_NONE = 0, + /** Convenience value when no options are specified. */ + BT_LE_ADV_OPT_NONE = 0, - /** Advertise as connectable. Type of advertising is determined by - * providing SCAN_RSP data and/or enabling local privacy support. - */ - BT_LE_ADV_OPT_CONNECTABLE = BIT(0), + /** Advertise as connectable. Type of advertising is determined by + * providing SCAN_RSP data and/or enabling local privacy support. + */ + BT_LE_ADV_OPT_CONNECTABLE = BIT(0), - /** Don't try to resume connectable advertising after a connection. - * This option is only meaningful when used together with - * BT_LE_ADV_OPT_CONNECTABLE. If set the advertising will be stopped - * when bt_le_adv_stop() is called or when an incoming (slave) - * connection happens. If this option is not set the stack will - * take care of keeping advertising enabled even as connections - * occur. - */ - BT_LE_ADV_OPT_ONE_TIME = BIT(1), + /** Don't try to resume connectable advertising after a connection. + * This option is only meaningful when used together with + * BT_LE_ADV_OPT_CONNECTABLE. If set the advertising will be stopped + * when bt_le_adv_stop() is called or when an incoming (slave) + * connection happens. If this option is not set the stack will + * take care of keeping advertising enabled even as connections + * occur. + */ + BT_LE_ADV_OPT_ONE_TIME = BIT(1), - /** Advertise using the identity address as the own address. - * @warning This will compromise the privacy of the device, so care - * must be taken when using this option. - */ - BT_LE_ADV_OPT_USE_IDENTITY = BIT(2), + /** Advertise using the identity address as the own address. + * @warning This will compromise the privacy of the device, so care + * must be taken when using this option. + */ + BT_LE_ADV_OPT_USE_IDENTITY = BIT(2), - /** Advertise using GAP device name */ - BT_LE_ADV_OPT_USE_NAME = BIT(3), + /** Advertise using GAP device name */ + BT_LE_ADV_OPT_USE_NAME = BIT(3), - /** Use low duty directed advertising mode, otherwise high duty mode - * will be used. This option is only effective when used with - * bt_conn_create_slave_le(). - */ - BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY = BIT(4), + /** Use low duty directed advertising mode, otherwise high duty mode + * will be used. This option is only effective when used with + * bt_conn_create_slave_le(). + */ + BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY = BIT(4), - /** Enable use of Resolvable Private Address (RPA) as the target address - * in directed advertisements when CONFIG_BT_PRIVACY is not enabled. - * This is required if the remote device is privacy-enabled and - * supports address resolution of the target address in directed - * advertisement. - * It is the responsibility of the application to check that the remote - * device supports address resolution of directed advertisements by - * reading its Central Address Resolution characteristic. - */ - BT_LE_ADV_OPT_DIR_ADDR_RPA = BIT(5), + /** Enable use of Resolvable Private Address (RPA) as the target address + * in directed advertisements when CONFIG_BT_PRIVACY is not enabled. + * This is required if the remote device is privacy-enabled and + * supports address resolution of the target address in directed + * advertisement. + * It is the responsibility of the application to check that the remote + * device supports address resolution of directed advertisements by + * reading its Central Address Resolution characteristic. + */ + BT_LE_ADV_OPT_DIR_ADDR_RPA = BIT(5), - /** Use whitelist to filter devices that can request scan response - * data. - */ - BT_LE_ADV_OPT_FILTER_SCAN_REQ = BIT(6), + /** Use whitelist to filter devices that can request scan response + * data. + */ + BT_LE_ADV_OPT_FILTER_SCAN_REQ = BIT(6), - /** Use whitelist to filter devices that can connect. */ - BT_LE_ADV_OPT_FILTER_CONN = BIT(7), + /** Use whitelist to filter devices that can connect. */ + BT_LE_ADV_OPT_FILTER_CONN = BIT(7), }; /** LE Advertising Parameters. */ struct bt_le_adv_param { - /** Local identity */ - u8_t id; + /** Local identity */ + u8_t id; - /** Bit-field of advertising options */ - u8_t options; + /** Bit-field of advertising options */ + u8_t options; - /** Minimum Advertising Interval (N * 0.625) */ - u16_t interval_min; + /** Minimum Advertising Interval (N * 0.625) */ + u16_t interval_min; - /** Maximum Advertising Interval (N * 0.625) */ - u16_t interval_max; + /** Maximum Advertising Interval (N * 0.625) */ + u16_t interval_max; #if defined(CONFIG_BT_STACK_PTS) u8_t addr_type; @@ -326,35 +326,35 @@ struct bt_le_adv_param { * @param _int_max Maximum advertising interval */ #define BT_LE_ADV_PARAM(_options, _int_min, _int_max) \ - (&(struct bt_le_adv_param) { \ - .options = (_options), \ - .interval_min = (_int_min), \ - .interval_max = (_int_max), \ - }) + (&(struct bt_le_adv_param) { \ + .options = (_options), \ + .interval_min = (_int_min), \ + .interval_max = (_int_max), \ + }) #define BT_LE_ADV_CONN BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE, \ - BT_GAP_ADV_FAST_INT_MIN_2, \ - BT_GAP_ADV_FAST_INT_MAX_2) + BT_GAP_ADV_FAST_INT_MIN_2, \ + BT_GAP_ADV_FAST_INT_MAX_2) #define BT_LE_ADV_CONN_NAME BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE | \ - BT_LE_ADV_OPT_USE_NAME, \ - BT_GAP_ADV_FAST_INT_MIN_2, \ - BT_GAP_ADV_FAST_INT_MAX_2) + BT_LE_ADV_OPT_USE_NAME, \ + BT_GAP_ADV_FAST_INT_MIN_2, \ + BT_GAP_ADV_FAST_INT_MAX_2) #define BT_LE_ADV_CONN_DIR_LOW_DUTY \ - BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME | \ - BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY, \ - BT_GAP_ADV_FAST_INT_MIN_2, BT_GAP_ADV_FAST_INT_MAX_2) + BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME | \ + BT_LE_ADV_OPT_DIR_MODE_LOW_DUTY, \ + BT_GAP_ADV_FAST_INT_MIN_2, BT_GAP_ADV_FAST_INT_MAX_2) #define BT_LE_ADV_CONN_DIR BT_LE_ADV_PARAM(BT_LE_ADV_OPT_CONNECTABLE | \ - BT_LE_ADV_OPT_ONE_TIME, 0, 0) + BT_LE_ADV_OPT_ONE_TIME, 0, 0) #define BT_LE_ADV_NCONN BT_LE_ADV_PARAM(0, BT_GAP_ADV_FAST_INT_MIN_2, \ - BT_GAP_ADV_FAST_INT_MAX_2) + BT_GAP_ADV_FAST_INT_MAX_2) #define BT_LE_ADV_NCONN_NAME BT_LE_ADV_PARAM(BT_LE_ADV_OPT_USE_NAME, \ - BT_GAP_ADV_FAST_INT_MIN_2, \ - BT_GAP_ADV_FAST_INT_MAX_2) + BT_GAP_ADV_FAST_INT_MIN_2, \ + BT_GAP_ADV_FAST_INT_MAX_2) /** @brief Start advertising * @@ -369,14 +369,14 @@ struct bt_le_adv_param { * * @return Zero on success or (negative) error code otherwise. * @return -ECONNREFUSED When connectable advertising is requested and there - * is already maximum number of connections established. - * This error code is only guaranteed when using Zephyr - * controller, for other controllers code returned in - * this case may be -EIO. + * is already maximum number of connections established. + * This error code is only guaranteed when using Zephyr + * controller, for other controllers code returned in + * this case may be -EIO. */ int bt_le_adv_start(const struct bt_le_adv_param *param, - const struct bt_data *ad, size_t ad_len, - const struct bt_data *sd, size_t sd_len); + const struct bt_data *ad, size_t ad_len, + const struct bt_data *sd, size_t sd_len); /** @brief Update advertising * @@ -390,7 +390,7 @@ int bt_le_adv_start(const struct bt_le_adv_param *param, * @return Zero on success or (negative) error code otherwise. */ int bt_le_adv_update_data(const struct bt_data *ad, size_t ad_len, - const struct bt_data *sd, size_t sd_len); + const struct bt_data *sd, size_t sd_len); /** @brief Stop advertising * @@ -412,40 +412,40 @@ int bt_le_adv_stop(void); * @param buf Buffer containing advertiser data. */ typedef void bt_le_scan_cb_t(const bt_addr_le_t *addr, s8_t rssi, - u8_t adv_type, struct net_buf_simple *buf); + u8_t adv_type, struct net_buf_simple *buf); enum { - /* Filter duplicates. */ - BT_LE_SCAN_FILTER_DUPLICATE = BIT(0), + /* Filter duplicates. */ + BT_LE_SCAN_FILTER_DUPLICATE = BIT(0), - /* Filter using whitelist. */ - BT_LE_SCAN_FILTER_WHITELIST = BIT(1), + /* Filter using whitelist. */ + BT_LE_SCAN_FILTER_WHITELIST = BIT(1), - /* Filter using extended filter policies. */ - BT_LE_SCAN_FILTER_EXTENDED = BIT(2), + /* Filter using extended filter policies. */ + BT_LE_SCAN_FILTER_EXTENDED = BIT(2), }; enum { - /* Scan without requesting additional information from advertisers. */ - BT_LE_SCAN_TYPE_PASSIVE = 0x00, + /* Scan without requesting additional information from advertisers. */ + BT_LE_SCAN_TYPE_PASSIVE = 0x00, - /* Scan and request additional information from advertisers. */ - BT_LE_SCAN_TYPE_ACTIVE = 0x01, + /* Scan and request additional information from advertisers. */ + BT_LE_SCAN_TYPE_ACTIVE = 0x01, }; /** LE scan parameters */ struct bt_le_scan_param { - /** Scan type (BT_LE_SCAN_TYPE_ACTIVE or BT_LE_SCAN_TYPE_PASSIVE) */ - u8_t type; + /** Scan type (BT_LE_SCAN_TYPE_ACTIVE or BT_LE_SCAN_TYPE_PASSIVE) */ + u8_t type; - /** Bit-field of scanning filter options. */ - u8_t filter_dup; + /** Bit-field of scanning filter options. */ + u8_t filter_dup; - /** Scan interval (N * 0.625 ms) */ - u16_t interval; + /** Scan interval (N * 0.625 ms) */ + u16_t interval; - /** Scan window (N * 0.625 ms) */ - u16_t window; + /** Scan window (N * 0.625 ms) */ + u16_t window; }; /** Helper to declare scan parameters inline @@ -457,18 +457,18 @@ struct bt_le_scan_param { * @param _window Scan Window (N * 0.625 ms) */ #define BT_LE_SCAN_PARAM(_type, _filter, _interval, _window) \ - (&(struct bt_le_scan_param) { \ - .type = (_type), \ - .filter_dup = (_filter), \ - .interval = (_interval), \ - .window = (_window), \ - }) + (&(struct bt_le_scan_param) { \ + .type = (_type), \ + .filter_dup = (_filter), \ + .interval = (_interval), \ + .window = (_window), \ + }) /** Helper macro to enable active scanning to discover new devices. */ #define BT_LE_SCAN_ACTIVE BT_LE_SCAN_PARAM(BT_LE_SCAN_TYPE_ACTIVE, \ - BT_LE_SCAN_FILTER_DUPLICATE, \ - BT_GAP_SCAN_FAST_INTERVAL, \ - BT_GAP_SCAN_FAST_WINDOW) + BT_LE_SCAN_FILTER_DUPLICATE, \ + BT_GAP_SCAN_FAST_INTERVAL, \ + BT_GAP_SCAN_FAST_WINDOW) /** Helper macro to enable passive scanning to discover new devices. * @@ -476,9 +476,9 @@ struct bt_le_scan_param { * (e.g., UUID) are known to be placed in Advertising Data. */ #define BT_LE_SCAN_PASSIVE BT_LE_SCAN_PARAM(BT_LE_SCAN_TYPE_PASSIVE, \ - BT_LE_SCAN_FILTER_DUPLICATE, \ - BT_GAP_SCAN_FAST_INTERVAL, \ - BT_GAP_SCAN_FAST_WINDOW) + BT_LE_SCAN_FILTER_DUPLICATE, \ + BT_GAP_SCAN_FAST_INTERVAL, \ + BT_GAP_SCAN_FAST_WINDOW) /** @brief Start (LE) scanning * @@ -572,27 +572,27 @@ int bt_le_set_chan_map(u8_t chan_map[5]); * @param user_data User data to be passed to the callback. */ void bt_data_parse(struct net_buf_simple *ad, - bool (*func)(struct bt_data *data, void *user_data), - void *user_data); + bool (*func)(struct bt_data *data, void *user_data), + void *user_data); /** OOB data that is specific for LE SC pairing method. */ struct bt_le_oob_sc_data { - /** Random Number. */ - u8_t r[16]; + /** Random Number. */ + u8_t r[16]; - /** Confirm Value. */ - u8_t c[16]; + /** Confirm Value. */ + u8_t c[16]; }; /** General OOB data. */ struct bt_le_oob { - /** LE address. If local privacy is enabled this is Resolvable Private - * Address. - */ - bt_addr_le_t addr; + /** LE address. If local privacy is enabled this is Resolvable Private + * Address. + */ + bt_addr_le_t addr; - /** OOB data that are relevant for LESC pairing. */ - struct bt_le_oob_sc_data le_sc_data; + /** OOB data that are relevant for LESC pairing. */ + struct bt_le_oob_sc_data le_sc_data; }; /** @@ -615,20 +615,20 @@ int bt_le_oob_get_local(u8_t id, struct bt_le_oob *oob); /** @brief BR/EDR discovery result structure */ struct bt_br_discovery_result { - /** private */ - u8_t _priv[4]; + /** private */ + u8_t _priv[4]; - /** Remote device address */ - bt_addr_t addr; + /** Remote device address */ + bt_addr_t addr; - /** RSSI from inquiry */ - s8_t rssi; + /** RSSI from inquiry */ + s8_t rssi; - /** Class of Device */ - u8_t cod[3]; + /** Class of Device */ + u8_t cod[3]; - /** Extended Inquiry Response */ - u8_t eir[240]; + /** Extended Inquiry Response */ + u8_t eir[240]; }; /** @typedef bt_br_discovery_cb_t @@ -643,17 +643,17 @@ struct bt_br_discovery_result { * @param count Number of valid discovery results. */ typedef void bt_br_discovery_cb_t(struct bt_br_discovery_result *results, - size_t count); + size_t count); /** BR/EDR discovery parameters */ struct bt_br_discovery_param { - /** Maximum length of the discovery in units of 1.28 seconds. - * Valid range is 0x01 - 0x30. - */ - u8_t length; + /** Maximum length of the discovery in units of 1.28 seconds. + * Valid range is 0x01 - 0x30. + */ + u8_t length; - /** True if limited discovery procedure is to be used. */ - bool limited; + /** True if limited discovery procedure is to be used. */ + bool limited; }; /** @brief Start BR/EDR discovery @@ -673,8 +673,8 @@ struct bt_br_discovery_param { * of protocol error or negative (POSIX) in case of stack internal error */ int bt_br_discovery_start(const struct bt_br_discovery_param *param, - struct bt_br_discovery_result *results, size_t count, - bt_br_discovery_cb_t cb); + struct bt_br_discovery_result *results, size_t count, + bt_br_discovery_cb_t cb); /** @brief Stop BR/EDR discovery. * @@ -690,8 +690,8 @@ int bt_disable(void); struct bt_br_oob { - /** BR/EDR address. */ - bt_addr_t addr; + /** BR/EDR address. */ + bt_addr_t addr; }; /** @@ -736,9 +736,9 @@ int bt_br_oob_get_local(struct bt_br_oob *oob); */ static inline int bt_addr_to_str(const bt_addr_t *addr, char *str, size_t len) { - return snprintk(str, len, "%02X:%02X:%02X:%02X:%02X:%02X", - addr->val[5], addr->val[4], addr->val[3], - addr->val[2], addr->val[1], addr->val[0]); + return snprintk(str, len, "%02X:%02X:%02X:%02X:%02X:%02X", + addr->val[5], addr->val[4], addr->val[3], + addr->val[2], addr->val[1], addr->val[0]); } /** @brief Converts binary LE Bluetooth address to string. @@ -752,31 +752,31 @@ static inline int bt_addr_to_str(const bt_addr_t *addr, char *str, size_t len) * @return Number of successfully formatted bytes from binary address. */ static inline int bt_addr_le_to_str(const bt_addr_le_t *addr, char *str, - size_t len) + size_t len) { - char type[10]; + char type[10]; - switch (addr->type) { - case BT_ADDR_LE_PUBLIC: - strcpy(type, "public"); - break; - case BT_ADDR_LE_RANDOM: - strcpy(type, "random"); - break; - case BT_ADDR_LE_PUBLIC_ID: - strcpy(type, "public-id"); - break; - case BT_ADDR_LE_RANDOM_ID: - strcpy(type, "random-id"); - break; - default: - snprintk(type, sizeof(type), "0x%02x", addr->type); - break; - } + switch (addr->type) { + case BT_ADDR_LE_PUBLIC: + strcpy(type, "public"); + break; + case BT_ADDR_LE_RANDOM: + strcpy(type, "random"); + break; + case BT_ADDR_LE_PUBLIC_ID: + strcpy(type, "public-id"); + break; + case BT_ADDR_LE_RANDOM_ID: + strcpy(type, "random-id"); + break; + default: + snprintk(type, sizeof(type), "0x%02x", addr->type); + break; + } - return snprintk(str, len, "%02X:%02X:%02X:%02X:%02X:%02X (%s)", - addr->a.val[5], addr->a.val[4], addr->a.val[3], - addr->a.val[2], addr->a.val[1], addr->a.val[0], type); + return snprintk(str, len, "%02X:%02X:%02X:%02X:%02X:%02X (%s)", + addr->a.val[5], addr->a.val[4], addr->a.val[3], + addr->a.val[2], addr->a.val[1], addr->a.val[0], type); } /** @@ -838,8 +838,8 @@ int bt_unpair(u8_t id, const bt_addr_le_t *addr); /** Information about a bond with a remote device. */ struct bt_bond_info { - /** Address of the remote device. */ - bt_addr_le_t addr; + /** Address of the remote device. */ + bt_addr_le_t addr; }; /** Iterate through all existing bonds. @@ -849,8 +849,8 @@ struct bt_bond_info { * @param user_data Data to pass to the callback function. */ void bt_foreach_bond(u8_t id, void (*func)(const struct bt_bond_info *info, - void *user_data), - void *user_data); + void *user_data), + void *user_data); /** * @} diff --git a/components/network/ble/blestack/src/include/bluetooth/buf.h b/components/network/ble/blestack/src/include/bluetooth/buf.h index 18badaba..bbb4a1a7 100644 --- a/components/network/ble/blestack/src/include/bluetooth/buf.h +++ b/components/network/ble/blestack/src/include/bluetooth/buf.h @@ -24,14 +24,14 @@ /** Possible types of buffers passed around the Bluetooth stack */ enum bt_buf_type { - /** HCI command */ - BT_BUF_CMD, - /** HCI event */ - BT_BUF_EVT, - /** Outgoing ACL data */ - BT_BUF_ACL_OUT, - /** Incoming ACL data */ - BT_BUF_ACL_IN, + /** HCI command */ + BT_BUF_CMD, + /** HCI event */ + BT_BUF_EVT, + /** Outgoing ACL data */ + BT_BUF_ACL_OUT, + /** Incoming ACL data */ + BT_BUF_ACL_IN, }; /** Minimum amount of user data size for buffers passed to the stack. */ @@ -92,7 +92,7 @@ struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, s32_t timeout); */ static inline void bt_buf_set_type(struct net_buf *buf, enum bt_buf_type type) { - *(u8_t *)net_buf_user_data(buf) = type; + *(u8_t *)net_buf_user_data(buf) = type; } /** Get the buffer type @@ -103,13 +103,13 @@ static inline void bt_buf_set_type(struct net_buf *buf, enum bt_buf_type type) */ static inline enum bt_buf_type bt_buf_get_type(struct net_buf *buf) { - /* De-referencing the pointer from net_buf_user_data(buf) as a - * pointer to an enum causes issues on qemu_x86 because the true - * size is 8-bit, but the enum is 32-bit on qemu_x86. So we put in - * a temporary cast to 8-bit to ensure only 8 bits are read from - * the pointer. - */ - return (enum bt_buf_type)(*(u8_t *)net_buf_user_data(buf)); + /* De-referencing the pointer from net_buf_user_data(buf) as a + * pointer to an enum causes issues on qemu_x86 because the true + * size is 8-bit, but the enum is 32-bit on qemu_x86. So we put in + * a temporary cast to 8-bit to ensure only 8 bits are read from + * the pointer. + */ + return (enum bt_buf_type)(*(u8_t *)net_buf_user_data(buf)); } /** diff --git a/components/network/ble/blestack/src/include/bluetooth/conn.h b/components/network/ble/blestack/src/include/bluetooth/conn.h index 9be6e074..d8280791 100644 --- a/components/network/ble/blestack/src/include/bluetooth/conn.h +++ b/components/network/ble/blestack/src/include/bluetooth/conn.h @@ -31,14 +31,14 @@ struct bt_conn; /** Connection parameters for LE connections */ struct bt_le_conn_param { - u16_t interval_min; - u16_t interval_max; - u16_t latency; - u16_t timeout; + u16_t interval_min; + u16_t interval_max; + u16_t latency; + u16_t timeout; #if defined(CONFIG_BT_STACK_PTS) - u8_t own_address_type; - #endif + u8_t own_address_type; + #endif }; /** Helper to declare connection parameters inline @@ -49,12 +49,12 @@ struct bt_le_conn_param { * @param to Supervision Timeout (N * 10 ms) */ #define BT_LE_CONN_PARAM(int_min, int_max, lat, to) \ - (&(struct bt_le_conn_param) { \ - .interval_min = (int_min), \ - .interval_max = (int_max), \ - .latency = (lat), \ - .timeout = (to), \ - }) + (&(struct bt_le_conn_param) { \ + .interval_min = (int_min), \ + .interval_max = (int_max), \ + .latency = (lat), \ + .timeout = (to), \ + }) /** Default LE connection parameters: * Connection Interval: 30-50 ms @@ -62,8 +62,8 @@ struct bt_le_conn_param { * Timeout: 4 s */ #define BT_LE_CONN_PARAM_DEFAULT BT_LE_CONN_PARAM(BT_GAP_INIT_CONN_INT_MIN, \ - BT_GAP_INIT_CONN_INT_MAX, \ - 0, 400) + BT_GAP_INIT_CONN_INT_MAX, \ + 0, 400) /** @brief Increment a connection's reference count. * * Increment the reference count of a connection object. @@ -89,7 +89,7 @@ void bt_conn_unref(struct bt_conn *conn); * @param data Data to pass to the callback function. */ void bt_conn_foreach(int type, void (*func)(struct bt_conn *conn, void *data), - void *data); + void *data); /** @brief Look up an existing connection by address. * @@ -130,42 +130,42 @@ u8_t bt_conn_index(struct bt_conn *conn); /** Connection Type */ enum { - /** LE Connection Type */ - BT_CONN_TYPE_LE = BIT(0), - /** BR/EDR Connection Type */ - BT_CONN_TYPE_BR = BIT(1), - /** SCO Connection Type */ - BT_CONN_TYPE_SCO = BIT(2), - /** All Connection Type */ - BT_CONN_TYPE_ALL = BT_CONN_TYPE_LE | BT_CONN_TYPE_BR | BT_CONN_TYPE_SCO, + /** LE Connection Type */ + BT_CONN_TYPE_LE = BIT(0), + /** BR/EDR Connection Type */ + BT_CONN_TYPE_BR = BIT(1), + /** SCO Connection Type */ + BT_CONN_TYPE_SCO = BIT(2), + /** All Connection Type */ + BT_CONN_TYPE_ALL = BT_CONN_TYPE_LE | BT_CONN_TYPE_BR | BT_CONN_TYPE_SCO, }; /** LE Connection Info Structure */ struct bt_conn_le_info { - /** Source (Local) Identity Address */ - const bt_addr_le_t *src; - /** Destination (Remote) Identity Address or remote Resolvable Private - * Address (RPA) before identity has been resolved. - */ - const bt_addr_le_t *dst; - /** Local device address used during connection setup. */ - const bt_addr_le_t *local; - /** Remote device address used during connection setup. */ - const bt_addr_le_t *remote; - u16_t interval; /** Connection interval */ - u16_t latency; /** Connection slave latency */ - u16_t timeout; /** Connection supervision timeout */ + /** Source (Local) Identity Address */ + const bt_addr_le_t *src; + /** Destination (Remote) Identity Address or remote Resolvable Private + * Address (RPA) before identity has been resolved. + */ + const bt_addr_le_t *dst; + /** Local device address used during connection setup. */ + const bt_addr_le_t *local; + /** Remote device address used during connection setup. */ + const bt_addr_le_t *remote; + u16_t interval; /** Connection interval */ + u16_t latency; /** Connection slave latency */ + u16_t timeout; /** Connection supervision timeout */ }; /** BR/EDR Connection Info Structure */ struct bt_conn_br_info { - const bt_addr_t *dst; /** Destination (Remote) BR/EDR address */ + const bt_addr_t *dst; /** Destination (Remote) BR/EDR address */ }; /** Connection role (master or slave) */ enum { - BT_CONN_ROLE_MASTER, - BT_CONN_ROLE_SLAVE, + BT_CONN_ROLE_MASTER, + BT_CONN_ROLE_SLAVE, }; /** @brief Connection Info Structure @@ -178,17 +178,17 @@ enum { * @param br BR/EDR Connection specific Info */ struct bt_conn_info { - u8_t type; + u8_t type; - u8_t role; + u8_t role; - u8_t id; + u8_t id; - union { - struct bt_conn_le_info le; + union { + struct bt_conn_le_info le; - struct bt_conn_br_info br; - }; + struct bt_conn_br_info br; + }; }; /** @brief Get connection info @@ -217,10 +217,10 @@ int bt_conn_get_info(const struct bt_conn *conn, struct bt_conn_info *info); */ #if defined(CONFIG_BT_STACK_PTS) int pts_bt_conn_le_param_update(struct bt_conn *conn, - const struct bt_le_conn_param *param); + const struct bt_le_conn_param *param); #endif int bt_conn_le_param_update(struct bt_conn *conn, - const struct bt_le_conn_param *param); + const struct bt_le_conn_param *param); /** @brief Disconnect from a remote device or cancel pending connection. * * Disconnect an active connection with the specified reason code or cancel @@ -246,7 +246,7 @@ int bt_conn_disconnect(struct bt_conn *conn, u8_t reason); * @return Valid connection object on success or NULL otherwise. */ struct bt_conn *bt_conn_create_le(const bt_addr_le_t *peer, - const struct bt_le_conn_param *param); + const struct bt_le_conn_param *param); /** @brief Automatically connect to remote devices in whitelist. * @@ -279,7 +279,7 @@ int bt_conn_create_auto_stop(void); * @return Zero on success or error code otherwise. */ int bt_le_set_auto_conn(const bt_addr_le_t *addr, - const struct bt_le_conn_param *param); + const struct bt_le_conn_param *param); /** @brief Initiate directed advertising to a remote device * @@ -303,31 +303,31 @@ int bt_le_set_auto_conn(const bt_addr_le_t *addr, * @return Valid connection object on success or NULL otherwise. */ struct bt_conn *bt_conn_create_slave_le(const bt_addr_le_t *peer, - const struct bt_le_adv_param *param); + const struct bt_le_adv_param *param); /** Security level. */ typedef enum __packed { - /** Level 0: Only for BR/EDR special cases, like SDP */ - BT_SECURITY_L0, - /** Level 1: No encryption and no authentication. */ - BT_SECURITY_L1, - /** Level 2: Encryption and no authentication (no MITM). */ - BT_SECURITY_L2, - /** Level 3: Encryption and authentication (MITM). */ - BT_SECURITY_L3, - /** Level 4: Authenticated Secure Connections and 128-bit key. */ - BT_SECURITY_L4, + /** Level 0: Only for BR/EDR special cases, like SDP */ + BT_SECURITY_L0, + /** Level 1: No encryption and no authentication. */ + BT_SECURITY_L1, + /** Level 2: Encryption and no authentication (no MITM). */ + BT_SECURITY_L2, + /** Level 3: Encryption and authentication (MITM). */ + BT_SECURITY_L3, + /** Level 4: Authenticated Secure Connections and 128-bit key. */ + BT_SECURITY_L4, - BT_SECURITY_NONE __deprecated = BT_SECURITY_L0, - BT_SECURITY_LOW __deprecated = BT_SECURITY_L1, - BT_SECURITY_MEDIUM __deprecated = BT_SECURITY_L2, - BT_SECURITY_HIGH __deprecated = BT_SECURITY_L3, - BT_SECURITY_FIPS __deprecated = BT_SECURITY_L4, + BT_SECURITY_NONE __deprecated = BT_SECURITY_L0, + BT_SECURITY_LOW __deprecated = BT_SECURITY_L1, + BT_SECURITY_MEDIUM __deprecated = BT_SECURITY_L2, + BT_SECURITY_HIGH __deprecated = BT_SECURITY_L3, + BT_SECURITY_FIPS __deprecated = BT_SECURITY_L4, - /** Bit to force new pairing procedure, bit-wise OR with requested - * security level. - */ - BT_SECURITY_FORCE_PAIR = BIT(7), + /** Bit to force new pairing procedure, bit-wise OR with requested + * security level. + */ + BT_SECURITY_FORCE_PAIR = BIT(7), } bt_security_t; /** @brief Set security level for a connection. @@ -362,9 +362,9 @@ int bt_conn_set_security(struct bt_conn *conn, bt_security_t sec); bt_security_t bt_conn_get_security(struct bt_conn *conn); static inline int __deprecated bt_conn_security(struct bt_conn *conn, - bt_security_t sec) + bt_security_t sec) { - return bt_conn_set_security(conn, sec); + return bt_conn_set_security(conn, sec); } /** @brief Get encryption key size. @@ -379,32 +379,32 @@ static inline int __deprecated bt_conn_security(struct bt_conn *conn, u8_t bt_conn_enc_key_size(struct bt_conn *conn); enum bt_security_err { - /** Security procedure successful. */ - BT_SECURITY_ERR_SUCCESS, + /** Security procedure successful. */ + BT_SECURITY_ERR_SUCCESS, - /** Authentication failed. */ - BT_SECURITY_ERR_AUTH_FAIL, + /** Authentication failed. */ + BT_SECURITY_ERR_AUTH_FAIL, - /** PIN or encryption key is missing. */ - BT_SECURITY_ERR_PIN_OR_KEY_MISSING, + /** PIN or encryption key is missing. */ + BT_SECURITY_ERR_PIN_OR_KEY_MISSING, - /** OOB data is not available. */ - BT_SECURITY_ERR_OOB_NOT_AVAILABLE, + /** OOB data is not available. */ + BT_SECURITY_ERR_OOB_NOT_AVAILABLE, - /** The requested security level could not be reached. */ - BT_SECURITY_ERR_AUTH_REQUIREMENT, + /** The requested security level could not be reached. */ + BT_SECURITY_ERR_AUTH_REQUIREMENT, - /** Pairing is not supported */ - BT_SECURITY_ERR_PAIR_NOT_SUPPORTED, + /** Pairing is not supported */ + BT_SECURITY_ERR_PAIR_NOT_SUPPORTED, - /** Pairing is not allowed. */ - BT_SECURITY_ERR_PAIR_NOT_ALLOWED, + /** Pairing is not allowed. */ + BT_SECURITY_ERR_PAIR_NOT_ALLOWED, - /** Invalid parameters. */ - BT_SECURITY_ERR_INVALID_PARAM, + /** Invalid parameters. */ + BT_SECURITY_ERR_INVALID_PARAM, - /** Pairing failed but the exact reason could not be specified. */ - BT_SECURITY_ERR_UNSPECIFIED, + /** Pairing failed but the exact reason could not be specified. */ + BT_SECURITY_ERR_UNSPECIFIED, }; /** @brief Connection callback structure. @@ -418,112 +418,112 @@ enum bt_security_err { * used for that instance. */ struct bt_conn_cb { - /** @brief A new connection has been established. - * - * This callback notifies the application of a new connection. - * In case the err parameter is non-zero it means that the - * connection establishment failed. - * - * @param conn New connection object. - * @param err HCI error. Zero for success, non-zero otherwise. - * - * @p err can mean either of the following: - * - @ref BT_HCI_ERR_UNKNOWN_CONN_ID Creating the connection started by - * @ref bt_conn_create_le was canceled either by the user through - * @ref bt_conn_disconnect or by the timeout in the host through - * :option:`CONFIG_BT_CREATE_CONN_TIMEOUT`. - * - @p BT_HCI_ERR_ADV_TIMEOUT Directed advertiser started by @ref - * bt_conn_create_slave_le with high duty cycle timed out after 1.28 - * seconds. - */ - void (*connected)(struct bt_conn *conn, u8_t err); + /** @brief A new connection has been established. + * + * This callback notifies the application of a new connection. + * In case the err parameter is non-zero it means that the + * connection establishment failed. + * + * @param conn New connection object. + * @param err HCI error. Zero for success, non-zero otherwise. + * + * @p err can mean either of the following: + * - @ref BT_HCI_ERR_UNKNOWN_CONN_ID Creating the connection started by + * @ref bt_conn_create_le was canceled either by the user through + * @ref bt_conn_disconnect or by the timeout in the host through + * :option:`CONFIG_BT_CREATE_CONN_TIMEOUT`. + * - @p BT_HCI_ERR_ADV_TIMEOUT Directed advertiser started by @ref + * bt_conn_create_slave_le with high duty cycle timed out after 1.28 + * seconds. + */ + void (*connected)(struct bt_conn *conn, u8_t err); - /** @brief A connection has been disconnected. - * - * This callback notifies the application that a connection - * has been disconnected. - * - * @param conn Connection object. - * @param reason HCI reason for the disconnection. - */ - void (*disconnected)(struct bt_conn *conn, u8_t reason); + /** @brief A connection has been disconnected. + * + * This callback notifies the application that a connection + * has been disconnected. + * + * @param conn Connection object. + * @param reason HCI reason for the disconnection. + */ + void (*disconnected)(struct bt_conn *conn, u8_t reason); - /** @brief LE connection parameter update request. - * - * This callback notifies the application that a remote device - * is requesting to update the connection parameters. The - * application accepts the parameters by returning true, or - * rejects them by returning false. Before accepting, the - * application may also adjust the parameters to better suit - * its needs. - * - * It is recommended for an application to have just one of these - * callbacks for simplicity. However, if an application registers - * multiple it needs to manage the potentially different - * requirements for each callback. Each callback gets the - * parameters as returned by previous callbacks, i.e. they are not - * necessarily the same ones as the remote originally sent. - * - * @param conn Connection object. - * @param param Proposed connection parameters. - * - * @return true to accept the parameters, or false to reject them. - */ - bool (*le_param_req)(struct bt_conn *conn, - struct bt_le_conn_param *param); + /** @brief LE connection parameter update request. + * + * This callback notifies the application that a remote device + * is requesting to update the connection parameters. The + * application accepts the parameters by returning true, or + * rejects them by returning false. Before accepting, the + * application may also adjust the parameters to better suit + * its needs. + * + * It is recommended for an application to have just one of these + * callbacks for simplicity. However, if an application registers + * multiple it needs to manage the potentially different + * requirements for each callback. Each callback gets the + * parameters as returned by previous callbacks, i.e. they are not + * necessarily the same ones as the remote originally sent. + * + * @param conn Connection object. + * @param param Proposed connection parameters. + * + * @return true to accept the parameters, or false to reject them. + */ + bool (*le_param_req)(struct bt_conn *conn, + struct bt_le_conn_param *param); - /** @brief The parameters for an LE connection have been updated. - * - * This callback notifies the application that the connection - * parameters for an LE connection have been updated. - * - * @param conn Connection object. - * @param interval Connection interval. - * @param latency Connection latency. - * @param timeout Connection supervision timeout. - */ - void (*le_param_updated)(struct bt_conn *conn, u16_t interval, - u16_t latency, u16_t timeout); + /** @brief The parameters for an LE connection have been updated. + * + * This callback notifies the application that the connection + * parameters for an LE connection have been updated. + * + * @param conn Connection object. + * @param interval Connection interval. + * @param latency Connection latency. + * @param timeout Connection supervision timeout. + */ + void (*le_param_updated)(struct bt_conn *conn, u16_t interval, + u16_t latency, u16_t timeout); #if defined(CONFIG_BT_SMP) - /** @brief Remote Identity Address has been resolved. - * - * This callback notifies the application that a remote - * Identity Address has been resolved - * - * @param conn Connection object. - * @param rpa Resolvable Private Address. - * @param identity Identity Address. - */ - void (*identity_resolved)(struct bt_conn *conn, - const bt_addr_le_t *rpa, - const bt_addr_le_t *identity); + /** @brief Remote Identity Address has been resolved. + * + * This callback notifies the application that a remote + * Identity Address has been resolved + * + * @param conn Connection object. + * @param rpa Resolvable Private Address. + * @param identity Identity Address. + */ + void (*identity_resolved)(struct bt_conn *conn, + const bt_addr_le_t *rpa, + const bt_addr_le_t *identity); #endif /* CONFIG_BT_SMP */ #if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) - /** @brief The security level of a connection has changed. - * - * This callback notifies the application that the security level - * of a connection has changed. - * - * @param conn Connection object. - * @param level New security level of the connection. - * @param err Security error. Zero for success, non-zero otherwise. - */ - void (*security_changed)(struct bt_conn *conn, bt_security_t level, - enum bt_security_err err); + /** @brief The security level of a connection has changed. + * + * This callback notifies the application that the security level + * of a connection has changed. + * + * @param conn Connection object. + * @param level New security level of the connection. + * @param err Security error. Zero for success, non-zero otherwise. + */ + void (*security_changed)(struct bt_conn *conn, bt_security_t level, + enum bt_security_err err); #endif /* defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) */ - struct bt_conn_cb *_next; + struct bt_conn_cb *_next; }; #if defined(CONFIG_BT_STACK_PTS) typedef enum{ - SMP_AUTH_NO_BONDING_MITM = 1, - SMP_IO_CAP_DISPLAY_ONLY = 2, - SMP_AUTH_NO_MITM = 3, - SMP_AUTH_NO_BONDING_MITM_IO_DISPLAY_ONLY = 4, - SMP_IO_KEYBOARD_ONLY = 5, - SMP_IO_NO_INPUT_OUTPUT = 6, - SMP_PARING_INVALID_PUBLIC_KEY = 7, + SMP_AUTH_NO_BONDING_MITM = 1, + SMP_IO_CAP_DISPLAY_ONLY = 2, + SMP_AUTH_NO_MITM = 3, + SMP_AUTH_NO_BONDING_MITM_IO_DISPLAY_ONLY = 4, + SMP_IO_KEYBOARD_ONLY = 5, + SMP_IO_NO_INPUT_OUTPUT = 6, + SMP_PARING_INVALID_PUBLIC_KEY = 7, }smp_test_id; void bt_set_mitm(bool enable); @@ -581,8 +581,8 @@ void bt_set_oob_data_flag(bool enable); * of protocol error or negative (POSIX) in case of stack internal error */ int bt_le_oob_set_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data *oobd_local, - const struct bt_le_oob_sc_data *oobd_remote); + const struct bt_le_oob_sc_data *oobd_local, + const struct bt_le_oob_sc_data *oobd_remote); /** * @brief Get OOB data used for LE SC pairing procedure @@ -601,8 +601,8 @@ int bt_le_oob_set_sc_data(struct bt_conn *conn, * of protocol error or negative (POSIX) in case of stack internal error */ int bt_le_oob_get_sc_data(struct bt_conn *conn, - const struct bt_le_oob_sc_data **oobd_local, - const struct bt_le_oob_sc_data **oobd_remote); + const struct bt_le_oob_sc_data **oobd_local, + const struct bt_le_oob_sc_data **oobd_remote); /** @def BT_PASSKEY_INVALID * @@ -628,192 +628,192 @@ int bt_passkey_set(unsigned int passkey); /** Info Structure for OOB pairing */ struct bt_conn_oob_info { - /** Type of OOB pairing method */ - enum { - /** LE legacy pairing */ - BT_CONN_OOB_LE_LEGACY, + /** Type of OOB pairing method */ + enum { + /** LE legacy pairing */ + BT_CONN_OOB_LE_LEGACY, - /** LE SC pairing */ - BT_CONN_OOB_LE_SC, - } type; + /** LE SC pairing */ + BT_CONN_OOB_LE_SC, + } type; - union { - /** LESC OOB pairing parameters */ - struct { - /** OOB data configuration */ - enum { - /** Local OOB data requested */ - BT_CONN_OOB_LOCAL_ONLY, + union { + /** LESC OOB pairing parameters */ + struct { + /** OOB data configuration */ + enum { + /** Local OOB data requested */ + BT_CONN_OOB_LOCAL_ONLY, - /** Remote OOB data requested */ - BT_CONN_OOB_REMOTE_ONLY, + /** Remote OOB data requested */ + BT_CONN_OOB_REMOTE_ONLY, - /** Both local and remote OOB data requested */ - BT_CONN_OOB_BOTH_PEERS, + /** Both local and remote OOB data requested */ + BT_CONN_OOB_BOTH_PEERS, - /** No OOB data requested */ - BT_CONN_OOB_NO_DATA, - } oob_config; - } lesc; - }; + /** No OOB data requested */ + BT_CONN_OOB_NO_DATA, + } oob_config; + } lesc; + }; }; /** Authenticated pairing callback structure */ struct bt_conn_auth_cb { - /** @brief Display a passkey to the user. - * - * When called the application is expected to display the given - * passkey to the user, with the expectation that the passkey will - * then be entered on the peer device. The passkey will be in the - * range of 0 - 999999, and is expected to be padded with zeroes so - * that six digits are always shown. E.g. the value 37 should be - * shown as 000037. - * - * This callback may be set to NULL, which means that the local - * device lacks the ability do display a passkey. If set - * to non-NULL the cancel callback must also be provided, since - * this is the only way the application can find out that it should - * stop displaying the passkey. - * - * @param conn Connection where pairing is currently active. - * @param passkey Passkey to show to the user. - */ - void (*passkey_display)(struct bt_conn *conn, unsigned int passkey); + /** @brief Display a passkey to the user. + * + * When called the application is expected to display the given + * passkey to the user, with the expectation that the passkey will + * then be entered on the peer device. The passkey will be in the + * range of 0 - 999999, and is expected to be padded with zeroes so + * that six digits are always shown. E.g. the value 37 should be + * shown as 000037. + * + * This callback may be set to NULL, which means that the local + * device lacks the ability do display a passkey. If set + * to non-NULL the cancel callback must also be provided, since + * this is the only way the application can find out that it should + * stop displaying the passkey. + * + * @param conn Connection where pairing is currently active. + * @param passkey Passkey to show to the user. + */ + void (*passkey_display)(struct bt_conn *conn, unsigned int passkey); - /** @brief Request the user to enter a passkey. - * - * When called the user is expected to enter a passkey. The passkey - * must be in the range of 0 - 999999, and should be expected to - * be zero-padded, as that's how the peer device will typically be - * showing it (e.g. 37 would be shown as 000037). - * - * Once the user has entered the passkey its value should be given - * to the stack using the bt_conn_auth_passkey_entry() API. - * - * This callback may be set to NULL, which means that the local - * device lacks the ability to enter a passkey. If set to non-NULL - * the cancel callback must also be provided, since this is the - * only way the application can find out that it should stop - * requesting the user to enter a passkey. - * - * @param conn Connection where pairing is currently active. - */ - void (*passkey_entry)(struct bt_conn *conn); + /** @brief Request the user to enter a passkey. + * + * When called the user is expected to enter a passkey. The passkey + * must be in the range of 0 - 999999, and should be expected to + * be zero-padded, as that's how the peer device will typically be + * showing it (e.g. 37 would be shown as 000037). + * + * Once the user has entered the passkey its value should be given + * to the stack using the bt_conn_auth_passkey_entry() API. + * + * This callback may be set to NULL, which means that the local + * device lacks the ability to enter a passkey. If set to non-NULL + * the cancel callback must also be provided, since this is the + * only way the application can find out that it should stop + * requesting the user to enter a passkey. + * + * @param conn Connection where pairing is currently active. + */ + void (*passkey_entry)(struct bt_conn *conn); - /** @brief Request the user to confirm a passkey. - * - * When called the user is expected to confirm that the given - * passkey is also shown on the peer device.. The passkey will - * be in the range of 0 - 999999, and should be zero-padded to - * always be six digits (e.g. 37 would be shown as 000037). - * - * Once the user has confirmed the passkey to match, the - * bt_conn_auth_passkey_confirm() API should be called. If the - * user concluded that the passkey doesn't match the - * bt_conn_auth_cancel() API should be called. - * - * This callback may be set to NULL, which means that the local - * device lacks the ability to confirm a passkey. If set to non-NULL - * the cancel callback must also be provided, since this is the - * only way the application can find out that it should stop - * requesting the user to confirm a passkey. - * - * @param conn Connection where pairing is currently active. - * @param passkey Passkey to be confirmed. - */ - void (*passkey_confirm)(struct bt_conn *conn, unsigned int passkey); + /** @brief Request the user to confirm a passkey. + * + * When called the user is expected to confirm that the given + * passkey is also shown on the peer device.. The passkey will + * be in the range of 0 - 999999, and should be zero-padded to + * always be six digits (e.g. 37 would be shown as 000037). + * + * Once the user has confirmed the passkey to match, the + * bt_conn_auth_passkey_confirm() API should be called. If the + * user concluded that the passkey doesn't match the + * bt_conn_auth_cancel() API should be called. + * + * This callback may be set to NULL, which means that the local + * device lacks the ability to confirm a passkey. If set to non-NULL + * the cancel callback must also be provided, since this is the + * only way the application can find out that it should stop + * requesting the user to confirm a passkey. + * + * @param conn Connection where pairing is currently active. + * @param passkey Passkey to be confirmed. + */ + void (*passkey_confirm)(struct bt_conn *conn, unsigned int passkey); - /** @brief Request the user to provide OOB data. - * - * When called the user is expected to provide OOB data. The required - * data are indicated by the information structure. - * - * For LESC OOB pairing method, the user should provide local OOB data, - * remote OOB data or both depending on their availability. Their value - * should be given to the stack using the bt_le_oob_set_sc_data() API. - * - * This callback must be set to non-NULL in order to support OOB - * pairing. - * - * @param conn Connection where pairing is currently active. - * @param info OOB pairing information. - */ - void (*oob_data_request)(struct bt_conn *conn, - struct bt_conn_oob_info *info); + /** @brief Request the user to provide OOB data. + * + * When called the user is expected to provide OOB data. The required + * data are indicated by the information structure. + * + * For LESC OOB pairing method, the user should provide local OOB data, + * remote OOB data or both depending on their availability. Their value + * should be given to the stack using the bt_le_oob_set_sc_data() API. + * + * This callback must be set to non-NULL in order to support OOB + * pairing. + * + * @param conn Connection where pairing is currently active. + * @param info OOB pairing information. + */ + void (*oob_data_request)(struct bt_conn *conn, + struct bt_conn_oob_info *info); - /** @brief Cancel the ongoing user request. - * - * This callback will be called to notify the application that it - * should cancel any previous user request (passkey display, entry - * or confirmation). - * - * This may be set to NULL, but must always be provided whenever the - * passkey_display, passkey_entry passkey_confirm or pairing_confirm - * callback has been provided. - * - * @param conn Connection where pairing is currently active. - */ - void (*cancel)(struct bt_conn *conn); + /** @brief Cancel the ongoing user request. + * + * This callback will be called to notify the application that it + * should cancel any previous user request (passkey display, entry + * or confirmation). + * + * This may be set to NULL, but must always be provided whenever the + * passkey_display, passkey_entry passkey_confirm or pairing_confirm + * callback has been provided. + * + * @param conn Connection where pairing is currently active. + */ + void (*cancel)(struct bt_conn *conn); - /** @brief Request confirmation for an incoming pairing. - * - * This callback will be called to confirm an incoming pairing - * request where none of the other user callbacks is applicable. - * - * If the user decides to accept the pairing the - * bt_conn_auth_pairing_confirm() API should be called. If the - * user decides to reject the pairing the bt_conn_auth_cancel() API - * should be called. - * - * This callback may be set to NULL, which means that the local - * device lacks the ability to confirm a pairing request. If set - * to non-NULL the cancel callback must also be provided, since - * this is the only way the application can find out that it should - * stop requesting the user to confirm a pairing request. - * - * @param conn Connection where pairing is currently active. - */ - void (*pairing_confirm)(struct bt_conn *conn); + /** @brief Request confirmation for an incoming pairing. + * + * This callback will be called to confirm an incoming pairing + * request where none of the other user callbacks is applicable. + * + * If the user decides to accept the pairing the + * bt_conn_auth_pairing_confirm() API should be called. If the + * user decides to reject the pairing the bt_conn_auth_cancel() API + * should be called. + * + * This callback may be set to NULL, which means that the local + * device lacks the ability to confirm a pairing request. If set + * to non-NULL the cancel callback must also be provided, since + * this is the only way the application can find out that it should + * stop requesting the user to confirm a pairing request. + * + * @param conn Connection where pairing is currently active. + */ + void (*pairing_confirm)(struct bt_conn *conn); #if defined(CONFIG_BT_BREDR) - /** @brief Request the user to enter a passkey. - * - * This callback will be called for a BR/EDR (Bluetooth Classic) - * connection where pairing is being performed. Once called the - * user is expected to enter a PIN code with a length between - * 1 and 16 digits. If the @a highsec parameter is set to true - * the PIN code must be 16 digits long. - * - * Once entered, the PIN code should be given to the stack using - * the bt_conn_auth_pincode_entry() API. - * - * This callback may be set to NULL, however in that case pairing - * over BR/EDR will not be possible. If provided, the cancel - * callback must be provided as well. - * - * @param conn Connection where pairing is currently active. - * @param highsec true if 16 digit PIN is required. - */ - void (*pincode_entry)(struct bt_conn *conn, bool highsec); + /** @brief Request the user to enter a passkey. + * + * This callback will be called for a BR/EDR (Bluetooth Classic) + * connection where pairing is being performed. Once called the + * user is expected to enter a PIN code with a length between + * 1 and 16 digits. If the @a highsec parameter is set to true + * the PIN code must be 16 digits long. + * + * Once entered, the PIN code should be given to the stack using + * the bt_conn_auth_pincode_entry() API. + * + * This callback may be set to NULL, however in that case pairing + * over BR/EDR will not be possible. If provided, the cancel + * callback must be provided as well. + * + * @param conn Connection where pairing is currently active. + * @param highsec true if 16 digit PIN is required. + */ + void (*pincode_entry)(struct bt_conn *conn, bool highsec); #endif - /** @brief notify that pairing process was complete. - * - * This callback notifies the application that the pairing process - * has been completed. - * - * @param conn Connection object. - * @param bonded pairing is bonded or not. - */ - void (*pairing_complete)(struct bt_conn *conn, bool bonded); + /** @brief notify that pairing process was complete. + * + * This callback notifies the application that the pairing process + * has been completed. + * + * @param conn Connection object. + * @param bonded pairing is bonded or not. + */ + void (*pairing_complete)(struct bt_conn *conn, bool bonded); - /** @brief notify that pairing process has failed. - * - * @param conn Connection object. - * @param reason Pairing failed reason - */ - void (*pairing_failed)(struct bt_conn *conn, - enum bt_security_err reason); + /** @brief notify that pairing process has failed. + * + * @param conn Connection object. + * @param reason Pairing failed reason + */ + void (*pairing_failed)(struct bt_conn *conn, + enum bt_security_err reason); }; /** @brief Register authentication callbacks. @@ -885,7 +885,7 @@ int bt_conn_auth_pincode_entry(struct bt_conn *conn, const char *pin); /** Connection parameters for BR/EDR connections */ struct bt_br_conn_param { - bool allow_role_switch; + bool allow_role_switch; }; /** Helper to declare BR/EDR connection parameters inline @@ -893,9 +893,9 @@ struct bt_br_conn_param { * @param role_switch True if role switch is allowed */ #define BT_BR_CONN_PARAM(role_switch) \ - (&(struct bt_br_conn_param) { \ - .allow_role_switch = (role_switch), \ - }) + (&(struct bt_br_conn_param) { \ + .allow_role_switch = (role_switch), \ + }) /** Default BR/EDR connection parameters: * Role switch allowed @@ -914,7 +914,7 @@ struct bt_br_conn_param { * @return Valid connection object on success or NULL otherwise. */ struct bt_conn *bt_conn_create_br(const bt_addr_t *peer, - const struct bt_br_conn_param *param); + const struct bt_br_conn_param *param); /** @brief Initiate an SCO connection to a remote device. * diff --git a/components/network/ble/blestack/src/include/bluetooth/crypto.h b/components/network/ble/blestack/src/include/bluetooth/crypto.h index 4f2034c4..65edfd64 100644 --- a/components/network/ble/blestack/src/include/bluetooth/crypto.h +++ b/components/network/ble/blestack/src/include/bluetooth/crypto.h @@ -50,7 +50,7 @@ int bt_rand(void *buf, size_t len); * @return Zero on success or error code otherwise. */ int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16], - u8_t enc_data[16]); + u8_t enc_data[16]); /** @brief AES encrypt big-endian data. * @@ -65,7 +65,7 @@ int bt_encrypt_le(const u8_t key[16], const u8_t plaintext[16], * @return Zero on success or error code otherwise. */ int bt_encrypt_be(const u8_t key[16], const u8_t plaintext[16], - u8_t enc_data[16]); + u8_t enc_data[16]); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/include/bluetooth/gatt.h b/components/network/ble/blestack/src/include/bluetooth/gatt.h index 48ba34cb..ce2eb808 100644 --- a/components/network/ble/blestack/src/include/bluetooth/gatt.h +++ b/components/network/ble/blestack/src/include/bluetooth/gatt.h @@ -29,47 +29,47 @@ extern "C" { /* GATT attribute permission bit field values */ enum { - /** No operations supported, e.g. for notify-only */ - BT_GATT_PERM_NONE = 0, + /** No operations supported, e.g. for notify-only */ + BT_GATT_PERM_NONE = 0, - /** Attribute read permission. */ - BT_GATT_PERM_READ = BIT(0), + /** Attribute read permission. */ + BT_GATT_PERM_READ = BIT(0), - /** Attribute write permission. */ - BT_GATT_PERM_WRITE = BIT(1), + /** Attribute write permission. */ + BT_GATT_PERM_WRITE = BIT(1), - /** Attribute read permission with encryption. - * - * If set, requires encryption for read access. - */ - BT_GATT_PERM_READ_ENCRYPT = BIT(2), + /** Attribute read permission with encryption. + * + * If set, requires encryption for read access. + */ + BT_GATT_PERM_READ_ENCRYPT = BIT(2), - /** Attribute write permission with encryption. - * - * If set, requires encryption for write access. - */ - BT_GATT_PERM_WRITE_ENCRYPT = BIT(3), + /** Attribute write permission with encryption. + * + * If set, requires encryption for write access. + */ + BT_GATT_PERM_WRITE_ENCRYPT = BIT(3), - /** Attribute read permission with authentication. - * - * If set, requires encryption using authenticated link-key for read - * access. - */ - BT_GATT_PERM_READ_AUTHEN = BIT(4), + /** Attribute read permission with authentication. + * + * If set, requires encryption using authenticated link-key for read + * access. + */ + BT_GATT_PERM_READ_AUTHEN = BIT(4), - /** Attribute write permission with authentication. - * - * If set, requires encryption using authenticated link-key for write - * access. - */ - BT_GATT_PERM_WRITE_AUTHEN = BIT(5), + /** Attribute write permission with authentication. + * + * If set, requires encryption using authenticated link-key for write + * access. + */ + BT_GATT_PERM_WRITE_AUTHEN = BIT(5), - /** Attribute prepare write permission. - * - * If set, allows prepare writes with use of BT_GATT_WRITE_FLAG_PREPARE - * passed to write callback. - */ - BT_GATT_PERM_PREPARE_WRITE = BIT(6), + /** Attribute prepare write permission. + * + * If set, allows prepare writes with use of BT_GATT_WRITE_FLAG_PREPARE + * passed to write callback. + */ + BT_GATT_PERM_PREPARE_WRITE = BIT(6), }; /** @def BT_GATT_ERR @@ -84,106 +84,106 @@ enum { /* GATT attribute write flags */ enum { - /** Attribute prepare write flag - * - * If set, write callback should only check if the device is - * authorized but no data shall be written. - */ - BT_GATT_WRITE_FLAG_PREPARE = BIT(0), + /** Attribute prepare write flag + * + * If set, write callback should only check if the device is + * authorized but no data shall be written. + */ + BT_GATT_WRITE_FLAG_PREPARE = BIT(0), - /** Attribute write command flag - * - * If set, indicates that write operation is a command (Write without - * response) which doesn't generate any response. - */ - BT_GATT_WRITE_FLAG_CMD = BIT(1), + /** Attribute write command flag + * + * If set, indicates that write operation is a command (Write without + * response) which doesn't generate any response. + */ + BT_GATT_WRITE_FLAG_CMD = BIT(1), }; /** @brief GATT Attribute structure. */ struct bt_gatt_attr { - /** Attribute UUID */ - const struct bt_uuid *uuid; + /** Attribute UUID */ + const struct bt_uuid *uuid; - /** Attribute read callback - * - * The callback can also be used locally to read the contents of the - * attribute in which case no connection will be set. - * - * @param conn The connection that is requesting to read - * @param attr The attribute that's being read - * @param buf Buffer to place the read result in - * @param len Length of data to read - * @param offset Offset to start reading from - * - * @return Number fo bytes read, or in case of an error - * BT_GATT_ERR() with a specific ATT error code. - */ - ssize_t (*read)(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, - u16_t offset); + /** Attribute read callback + * + * The callback can also be used locally to read the contents of the + * attribute in which case no connection will be set. + * + * @param conn The connection that is requesting to read + * @param attr The attribute that's being read + * @param buf Buffer to place the read result in + * @param len Length of data to read + * @param offset Offset to start reading from + * + * @return Number fo bytes read, or in case of an error + * BT_GATT_ERR() with a specific ATT error code. + */ + ssize_t (*read)(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + void *buf, u16_t len, + u16_t offset); - /** Attribute write callback - * - * The callback can also be used locally to read the contents of the - * attribute in which case no connection will be set. - * - * @param conn The connection that is requesting to write - * @param attr The attribute that's being written - * @param buf Buffer with the data to write - * @param len Number of bytes in the buffer - * @param offset Offset to start writing from - * @param flags Flags (BT_GATT_WRITE_*) - * - * @return Number of bytes written, or in case of an error - * BT_GATT_ERR() with a specific ATT error code. - */ - ssize_t (*write)(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - const void *buf, u16_t len, - u16_t offset, u8_t flags); + /** Attribute write callback + * + * The callback can also be used locally to read the contents of the + * attribute in which case no connection will be set. + * + * @param conn The connection that is requesting to write + * @param attr The attribute that's being written + * @param buf Buffer with the data to write + * @param len Number of bytes in the buffer + * @param offset Offset to start writing from + * @param flags Flags (BT_GATT_WRITE_*) + * + * @return Number of bytes written, or in case of an error + * BT_GATT_ERR() with a specific ATT error code. + */ + ssize_t (*write)(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + const void *buf, u16_t len, + u16_t offset, u8_t flags); - /** Attribute user data */ - void *user_data; - /** Attribute handle */ - u16_t handle; - /** Attribute permissions */ - u8_t perm; + /** Attribute user data */ + void *user_data; + /** Attribute handle */ + u16_t handle; + /** Attribute permissions */ + u8_t perm; }; /** @brief GATT Service structure */ struct bt_gatt_service_static { - /** Service Attributes */ - const struct bt_gatt_attr *attrs; - /** Service Attribute count */ - size_t attr_count; + /** Service Attributes */ + const struct bt_gatt_attr *attrs; + /** Service Attribute count */ + size_t attr_count; }; /** @brief GATT Service structure */ struct bt_gatt_service { - /** Service Attributes */ - struct bt_gatt_attr *attrs; - /** Service Attribute count */ - size_t attr_count; - sys_snode_t node; + /** Service Attributes */ + struct bt_gatt_attr *attrs; + /** Service Attribute count */ + size_t attr_count; + sys_snode_t node; }; /** @brief Service Attribute Value. */ struct bt_gatt_service_val { - /** Service UUID. */ - const struct bt_uuid *uuid; - /** Service end handle. */ - u16_t end_handle; + /** Service UUID. */ + const struct bt_uuid *uuid; + /** Service end handle. */ + u16_t end_handle; }; /** @brief Include Attribute Value. */ struct bt_gatt_include { - /** Service UUID. */ - const struct bt_uuid *uuid; - /** Service start handle. */ - u16_t start_handle; - /** Service end handle. */ - u16_t end_handle; + /** Service UUID. */ + const struct bt_uuid *uuid; + /** Service start handle. */ + u16_t start_handle; + /** Service end handle. */ + u16_t end_handle; }; /* Characteristic Properties Bit field values */ @@ -194,70 +194,70 @@ struct bt_gatt_include { * If set, permits broadcasts of the Characteristic Value using Server * Characteristic Configuration Descriptor. */ -#define BT_GATT_CHRC_BROADCAST 0x01 +#define BT_GATT_CHRC_BROADCAST 0x01 /** @def BT_GATT_CHRC_READ * @brief Characteristic read property. * * If set, permits reads of the Characteristic Value. */ -#define BT_GATT_CHRC_READ 0x02 +#define BT_GATT_CHRC_READ 0x02 /** @def BT_GATT_CHRC_WRITE_WITHOUT_RESP * @brief Characteristic write without response property. * * If set, permits write of the Characteristic Value without response. */ -#define BT_GATT_CHRC_WRITE_WITHOUT_RESP 0x04 +#define BT_GATT_CHRC_WRITE_WITHOUT_RESP 0x04 /** @def BT_GATT_CHRC_WRITE * @brief Characteristic write with response property. * * If set, permits write of the Characteristic Value with response. */ -#define BT_GATT_CHRC_WRITE 0x08 +#define BT_GATT_CHRC_WRITE 0x08 /** @def BT_GATT_CHRC_NOTIFY * @brief Characteristic notify property. * * If set, permits notifications of a Characteristic Value without * acknowledgment. */ -#define BT_GATT_CHRC_NOTIFY 0x10 +#define BT_GATT_CHRC_NOTIFY 0x10 /** @def BT_GATT_CHRC_INDICATE * @brief Characteristic indicate property. * * If set, permits indications of a Characteristic Value with acknowledgment. */ -#define BT_GATT_CHRC_INDICATE 0x20 +#define BT_GATT_CHRC_INDICATE 0x20 /** @def BT_GATT_CHRC_AUTH * @brief Characteristic Authenticated Signed Writes property. * * If set, permits signed writes to the Characteristic Value. */ -#define BT_GATT_CHRC_AUTH 0x40 +#define BT_GATT_CHRC_AUTH 0x40 /** @def BT_GATT_CHRC_EXT_PROP * @brief Characteristic Extended Properties property. * * If set, additional characteristic properties are defined in the * Characteristic Extended Properties Descriptor. */ -#define BT_GATT_CHRC_EXT_PROP 0x80 +#define BT_GATT_CHRC_EXT_PROP 0x80 /** @brief Characteristic Attribute Value. */ struct bt_gatt_chrc { - /** Characteristic UUID. */ - const struct bt_uuid *uuid; - /** Characteristic Value handle. */ - u16_t value_handle; - /** Characteristic properties. */ - u8_t properties; + /** Characteristic UUID. */ + const struct bt_uuid *uuid; + /** Characteristic Value handle. */ + u16_t value_handle; + /** Characteristic properties. */ + u8_t properties; }; /* Characteristic Extended Properties Bit field values */ -#define BT_GATT_CEP_RELIABLE_WRITE 0x0001 -#define BT_GATT_CEP_WRITABLE_AUX 0x0002 +#define BT_GATT_CEP_RELIABLE_WRITE 0x0001 +#define BT_GATT_CEP_WRITABLE_AUX 0x0002 /** @brief Characteristic Extended Properties Attribute Value. */ struct bt_gatt_cep { - /** Characteristic Extended properties */ - u16_t properties; + /** Characteristic Extended properties */ + u16_t properties; }; /* Client Characteristic Configuration Values */ @@ -267,34 +267,34 @@ struct bt_gatt_cep { * * If set, changes to Characteristic Value shall be notified. */ -#define BT_GATT_CCC_NOTIFY 0x0001 +#define BT_GATT_CCC_NOTIFY 0x0001 /** @def BT_GATT_CCC_INDICATE * @brief Client Characteristic Configuration Indication. * * If set, changes to Characteristic Value shall be indicated. */ -#define BT_GATT_CCC_INDICATE 0x0002 +#define BT_GATT_CCC_INDICATE 0x0002 /* Client Characteristic Configuration Attribute Value */ struct bt_gatt_ccc { - /** Client Characteristic Configuration flags */ - u16_t flags; + /** Client Characteristic Configuration flags */ + u16_t flags; }; /** @brief GATT Characteristic Presentation Format Attribute Value. */ struct bt_gatt_cpf { - /** Format of the value of the characteristic */ - u8_t format; - /** Exponent field to determine how the value of this characteristic is - * further formatted - */ - s8_t exponent; - /** Unit of the characteristic */ - u16_t unit; - /** Name space of the description */ - u8_t name_space; - /** Description of the characteristic as defined in a higher layer profile */ - u16_t description; + /** Format of the value of the characteristic */ + u8_t format; + /** Exponent field to determine how the value of this characteristic is + * further formatted + */ + s8_t exponent; + /** Unit of the characteristic */ + u16_t unit; + /** Name space of the description */ + u8_t name_space; + /** Description of the characteristic as defined in a higher layer profile */ + u16_t description; } __packed; /** @@ -324,8 +324,8 @@ int bt_gatt_service_register(struct bt_gatt_service *svc); int bt_gatt_service_unregister(struct bt_gatt_service *svc); enum { - BT_GATT_ITER_STOP = 0, - BT_GATT_ITER_CONTINUE, + BT_GATT_ITER_STOP = 0, + BT_GATT_ITER_CONTINUE, }; /** @typedef bt_gatt_attr_func_t @@ -338,7 +338,7 @@ enum { * or BT_GATT_ITER_STOP to stop. */ typedef u8_t (*bt_gatt_attr_func_t)(const struct bt_gatt_attr *attr, - void *user_data); + void *user_data); /** @brief Attribute iterator by type. * @@ -353,10 +353,10 @@ typedef u8_t (*bt_gatt_attr_func_t)(const struct bt_gatt_attr *attr, * @param user_data Data to pass to the callback. */ void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle, - const struct bt_uuid *uuid, - const void *attr_data, uint16_t num_matches, - bt_gatt_attr_func_t func, - void *user_data); + const struct bt_uuid *uuid, + const void *attr_data, uint16_t num_matches, + bt_gatt_attr_func_t func, + void *user_data); /** @brief Attribute iterator. * @@ -368,11 +368,11 @@ void bt_gatt_foreach_attr_type(u16_t start_handle, u16_t end_handle, * @param user_data Data to pass to the callback. */ static inline void bt_gatt_foreach_attr(u16_t start_handle, u16_t end_handle, - bt_gatt_attr_func_t func, - void *user_data) + bt_gatt_attr_func_t func, + void *user_data) { - bt_gatt_foreach_attr_type(start_handle, end_handle, NULL, NULL, 0, func, - user_data); + bt_gatt_foreach_attr_type(start_handle, end_handle, NULL, NULL, 0, func, + user_data); } /** @brief Iterate to the next attribute @@ -411,8 +411,8 @@ uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr); * case of error. */ ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, - void *buf, u16_t buf_len, u16_t offset, - const void *value, u16_t value_len); + void *buf, u16_t buf_len, u16_t offset, + const void *value, u16_t value_len); /** @brief Read Service Attribute helper. * @@ -430,8 +430,8 @@ ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, * case of error. */ ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset); + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset); /** @def BT_GATT_SERVICE_DEFINE * @brief Statically define and register a service. @@ -440,10 +440,10 @@ ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, * * @param _name Service name. */ -#define BT_GATT_SERVICE_DEFINE(_name, ...) \ - const struct bt_gatt_attr attr_##_name[] = { __VA_ARGS__ }; \ - const Z_STRUCT_SECTION_ITERABLE(bt_gatt_service_static, _name) =\ - BT_GATT_SERVICE(attr_##_name) +#define BT_GATT_SERVICE_DEFINE(_name, ...) \ + const struct bt_gatt_attr attr_##_name[] = { __VA_ARGS__ }; \ + const Z_STRUCT_SECTION_ITERABLE(bt_gatt_service_static, _name) =\ + BT_GATT_SERVICE(attr_##_name) /** @def BT_GATT_SERVICE * @brief Service Structure Declaration Macro. @@ -452,10 +452,10 @@ ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, * * @param _attrs Service attributes. */ -#define BT_GATT_SERVICE(_attrs) \ -{ \ - .attrs = _attrs, \ - .attr_count = ARRAY_SIZE(_attrs), \ +#define BT_GATT_SERVICE(_attrs) \ +{ \ + .attrs = _attrs, \ + .attr_count = ARRAY_SIZE(_attrs), \ } /** @def BT_GATT_PRIMARY_SERVICE @@ -465,9 +465,9 @@ ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, * * @param _service Service attribute value. */ -#define BT_GATT_PRIMARY_SERVICE(_service) \ - BT_GATT_ATTRIBUTE(BT_UUID_GATT_PRIMARY, BT_GATT_PERM_READ, \ - bt_gatt_attr_read_service, NULL, _service) +#define BT_GATT_PRIMARY_SERVICE(_service) \ + BT_GATT_ATTRIBUTE(BT_UUID_GATT_PRIMARY, BT_GATT_PERM_READ, \ + bt_gatt_attr_read_service, NULL, _service) /** @def BT_GATT_SECONDARY_SERVICE * @brief Secondary Service Declaration Macro. @@ -476,9 +476,9 @@ ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, * * @param _service Service attribute value. */ -#define BT_GATT_SECONDARY_SERVICE(_service) \ - BT_GATT_ATTRIBUTE(BT_UUID_GATT_SECONDARY, BT_GATT_PERM_READ, \ - bt_gatt_attr_read_service, NULL, _service) +#define BT_GATT_SECONDARY_SERVICE(_service) \ + BT_GATT_ATTRIBUTE(BT_UUID_GATT_SECONDARY, BT_GATT_PERM_READ, \ + bt_gatt_attr_read_service, NULL, _service) /** @brief Read Include Attribute helper. * @@ -496,8 +496,8 @@ ssize_t bt_gatt_attr_read_service(struct bt_conn *conn, * case of error. */ ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset); + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset); /** @def BT_GATT_INCLUDE_SERVICE * @brief Include Service Declaration Macro. @@ -506,9 +506,9 @@ ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, * * @param _service_incl the first service attribute of service to include */ -#define BT_GATT_INCLUDE_SERVICE(_service_incl) \ - BT_GATT_ATTRIBUTE(BT_UUID_GATT_INCLUDE, BT_GATT_PERM_READ, \ - bt_gatt_attr_read_included, NULL, _service_incl) +#define BT_GATT_INCLUDE_SERVICE(_service_incl) \ + BT_GATT_ATTRIBUTE(BT_UUID_GATT_INCLUDE, BT_GATT_PERM_READ, \ + bt_gatt_attr_read_included, NULL, _service_incl) /** @brief Read Characteristic Attribute helper. * @@ -526,8 +526,8 @@ ssize_t bt_gatt_attr_read_included(struct bt_conn *conn, * case of error. */ ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset); + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset); /** @def BT_GATT_CHARACTERISTIC * @brief Characteristic and Value Declaration Macro. @@ -543,17 +543,17 @@ ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, * @param _value Characteristic Attribute value. */ #define BT_GATT_CHARACTERISTIC(_uuid, _props, _perm, _read, _write, _value) \ - BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \ - bt_gatt_attr_read_chrc, NULL, \ - (&(struct bt_gatt_chrc) { .uuid = _uuid, \ - .value_handle = 0U, \ - .properties = _props, })), \ - BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) + BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \ + bt_gatt_attr_read_chrc, NULL, \ + (&(struct bt_gatt_chrc) { .uuid = _uuid, \ + .value_handle = 0U, \ + .properties = _props, })), \ + BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) #if IS_ENABLED(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING) - #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_CONN) + #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_CONN) #else - #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) + #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN) #endif /** @brief GATT CCC configuration entry. @@ -563,22 +563,22 @@ ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn, * @param data Configuration pointer data. */ struct bt_gatt_ccc_cfg { - u8_t id; - bt_addr_le_t peer; - u16_t value; + u8_t id; + bt_addr_le_t peer; + u16_t value; }; /* Internal representation of CCC value */ struct _bt_gatt_ccc { - struct bt_gatt_ccc_cfg cfg[BT_GATT_CCC_MAX]; - u16_t value; - void (*cfg_changed)(const struct bt_gatt_attr *attr, - u16_t value); - bool (*cfg_write)(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - u16_t value); - bool (*cfg_match)(struct bt_conn *conn, - const struct bt_gatt_attr *attr); + struct bt_gatt_ccc_cfg cfg[BT_GATT_CCC_MAX]; + u16_t value; + void (*cfg_changed)(const struct bt_gatt_attr *attr, + u16_t value); + bool (*cfg_write)(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + u16_t value); + bool (*cfg_match)(struct bt_conn *conn, + const struct bt_gatt_attr *attr); }; /** @brief Read Client Characteristic Configuration Attribute helper. @@ -597,8 +597,8 @@ struct _bt_gatt_ccc { * case of error. */ ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset); + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset); /** @brief Write Client Characteristic Configuration Attribute helper. * @@ -616,8 +616,8 @@ ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn, * case of error. */ ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, - const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags); + const struct bt_gatt_attr *attr, const void *buf, + u16_t len, u16_t offset, u8_t flags); /** @def BT_GATT_CCC_INITIALIZER @@ -630,12 +630,12 @@ ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, * @param _match Configuration match callback. */ #define BT_GATT_CCC_INITIALIZER(_changed, _write, _match) \ - { \ - .cfg = {}, \ - .cfg_changed = _changed, \ - .cfg_write = _write, \ - .cfg_match = _match, \ - } + { \ + .cfg = {}, \ + .cfg_changed = _changed, \ + .cfg_write = _write, \ + .cfg_match = _match, \ + } /** @def BT_GATT_CCC_MANAGED * @brief Managed Client Characteristic Configuration Declaration Macro. @@ -645,10 +645,10 @@ ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, * @param _ccc CCC attribute user data, shall point to a _bt_gatt_ccc. * @param _perm CCC access permissions. */ -#define BT_GATT_CCC_MANAGED(_ccc, _perm) \ - BT_GATT_ATTRIBUTE(BT_UUID_GATT_CCC, _perm, \ - bt_gatt_attr_read_ccc, bt_gatt_attr_write_ccc, \ - _ccc) +#define BT_GATT_CCC_MANAGED(_ccc, _perm) \ + BT_GATT_ATTRIBUTE(BT_UUID_GATT_CCC, _perm, \ + bt_gatt_attr_read_ccc, bt_gatt_attr_write_ccc, \ + _ccc) /** @def BT_GATT_CCC * @brief Client Characteristic Configuration Declaration Macro. @@ -658,9 +658,9 @@ ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, * @param _changed Configuration changed callback. * @param _perm CCC access permissions. */ -#define BT_GATT_CCC(_changed, _perm) \ - BT_GATT_CCC_MANAGED((&(struct _bt_gatt_ccc) \ - BT_GATT_CCC_INITIALIZER(_changed, NULL, NULL)), _perm) +#define BT_GATT_CCC(_changed, _perm) \ + BT_GATT_CCC_MANAGED((&(struct _bt_gatt_ccc) \ + BT_GATT_CCC_INITIALIZER(_changed, NULL, NULL)), _perm) /** @brief Read Characteristic Extended Properties Attribute helper * @@ -678,8 +678,8 @@ ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn, * case of error. */ ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset); + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset); /** @def BT_GATT_CEP * @brief Characteristic Extended Properties Declaration Macro. @@ -688,9 +688,9 @@ ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, * * @param _value Descriptor attribute value. */ -#define BT_GATT_CEP(_value) \ - BT_GATT_DESCRIPTOR(BT_UUID_GATT_CEP, BT_GATT_PERM_READ, \ - bt_gatt_attr_read_cep, NULL, (void *)_value) +#define BT_GATT_CEP(_value) \ + BT_GATT_DESCRIPTOR(BT_UUID_GATT_CEP, BT_GATT_PERM_READ, \ + bt_gatt_attr_read_cep, NULL, (void *)_value) /** @brief Read Characteristic User Description Descriptor Attribute helper * @@ -709,8 +709,8 @@ ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn, * case of error. */ ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset); + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset); /** @def BT_GATT_CUD * @brief Characteristic User Format Descriptor Declaration Macro. @@ -720,9 +720,9 @@ ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, * @param _value User description NULL-terminated C string. * @param _perm Descriptor attribute access permissions. */ -#define BT_GATT_CUD(_value, _perm) \ - BT_GATT_DESCRIPTOR(BT_UUID_GATT_CUD, _perm, bt_gatt_attr_read_cud, \ - NULL, (void *)_value) +#define BT_GATT_CUD(_value, _perm) \ + BT_GATT_DESCRIPTOR(BT_UUID_GATT_CUD, _perm, bt_gatt_attr_read_cud, \ + NULL, (void *)_value) /** @brief Read Characteristic Presentation format Descriptor Attribute helper * @@ -740,8 +740,8 @@ ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn, * case of error. */ ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset); + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset); /** @def BT_GATT_CPF * @brief Characteristic Presentation Format Descriptor Declaration Macro. @@ -750,9 +750,9 @@ ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, * * @param _value Descriptor attribute value. */ -#define BT_GATT_CPF(_value) \ - BT_GATT_DESCRIPTOR(BT_UUID_GATT_CPF, BT_GATT_PERM_READ, \ - bt_gatt_attr_read_cpf, NULL, (void *)_value) +#define BT_GATT_CPF(_value) \ + BT_GATT_DESCRIPTOR(BT_UUID_GATT_CPF, BT_GATT_PERM_READ, \ + bt_gatt_attr_read_cpf, NULL, (void *)_value) /** @def BT_GATT_DESCRIPTOR * @brief Descriptor Declaration Macro. @@ -765,8 +765,8 @@ ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, * @param _write Descriptor attribute write callback. * @param _value Descriptor attribute value. */ -#define BT_GATT_DESCRIPTOR(_uuid, _perm, _read, _write, _value) \ - BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) +#define BT_GATT_DESCRIPTOR(_uuid, _perm, _read, _write, _value) \ + BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) /** @def BT_GATT_ATTRIBUTE * @brief Attribute Declaration Macro. @@ -779,13 +779,13 @@ ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, * @param _write Attribute write callback. * @param _value Attribute value. */ -#define BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) \ -{ \ - .uuid = _uuid, \ - .perm = _perm, \ - .read = _read, \ - .write = _write, \ - .user_data = _value, \ +#define BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _value) \ +{ \ + .uuid = _uuid, \ + .perm = _perm, \ + .read = _read, \ + .write = _write, \ + .user_data = _value, \ } /** @brief Notification complete result callback. @@ -795,18 +795,18 @@ ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn, typedef void (*bt_gatt_complete_func_t) (struct bt_conn *conn, void *user_data); struct bt_gatt_notify_params { - /** Notification Attribute UUID type */ - const struct bt_uuid *uuid; - /** Notification Attribute object*/ - const struct bt_gatt_attr *attr; - /** Notification Value data */ - const void *data; - /** Notification Value length */ - u16_t len; - /** Notification Value callback */ - bt_gatt_complete_func_t func; - /** Notification Value callback user data */ - void *user_data; + /** Notification Attribute UUID type */ + const struct bt_uuid *uuid; + /** Notification Attribute object*/ + const struct bt_gatt_attr *attr; + /** Notification Value data */ + const void *data; + /** Notification Value length */ + u16_t len; + /** Notification Value callback */ + bt_gatt_complete_func_t func; + /** Notification Value callback user data */ + void *user_data; }; /** @brief Notify attribute value change. @@ -827,7 +827,7 @@ struct bt_gatt_notify_params { * @return 0 in case of success or negative value in case of error. */ int bt_gatt_notify_cb(struct bt_conn *conn, - struct bt_gatt_notify_params *params); + struct bt_gatt_notify_params *params); /** @brief Notify attribute value change. * @@ -849,18 +849,18 @@ int bt_gatt_notify_cb(struct bt_conn *conn, * @return 0 in case of success or negative value in case of error. */ static inline int bt_gatt_notify(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - const void *data, u16_t len) + const struct bt_gatt_attr *attr, + const void *data, u16_t len) { - struct bt_gatt_notify_params params; + struct bt_gatt_notify_params params; - memset(¶ms, 0, sizeof(params)); + memset(¶ms, 0, sizeof(params)); - params.attr = attr; - params.data = data; - params.len = len; + params.attr = attr; + params.data = data; + params.len = len; - return bt_gatt_notify_cb(conn, ¶ms); + return bt_gatt_notify_cb(conn, ¶ms); } /** @typedef bt_gatt_indicate_func_t @@ -873,22 +873,22 @@ static inline int bt_gatt_notify(struct bt_conn *conn, * @return 0 in case of success or negative value in case of error. */ typedef void (*bt_gatt_indicate_func_t)(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - u8_t err); + const struct bt_gatt_attr *attr, + u8_t err); /** @brief GATT Indicate Value parameters */ struct bt_gatt_indicate_params { - struct bt_att_req _req; - /** Notification Attribute UUID type */ - const struct bt_uuid *uuid; - /** Indicate Attribute object*/ - const struct bt_gatt_attr *attr; - /** Indicate Value callback */ - bt_gatt_indicate_func_t func; - /** Indicate Value data*/ - const void *data; - /** Indicate Value length*/ - u16_t len; + struct bt_att_req _req; + /** Notification Attribute UUID type */ + const struct bt_uuid *uuid; + /** Indicate Attribute object*/ + const struct bt_gatt_attr *attr; + /** Indicate Value callback */ + bt_gatt_indicate_func_t func; + /** Indicate Value data*/ + const void *data; + /** Indicate Value length*/ + u16_t len; }; /** @brief Indicate attribute value change. @@ -918,7 +918,7 @@ struct bt_gatt_indicate_params { * @return 0 in case of success or negative value in case of error. */ int bt_gatt_indicate(struct bt_conn *conn, - struct bt_gatt_indicate_params *params); + struct bt_gatt_indicate_params *params); #if defined(CONFIG_BT_STACK_PTS) int service_change_test(struct bt_gatt_indicate_params *params,const struct bt_conn *con); @@ -942,7 +942,7 @@ int service_change_test(struct bt_gatt_indicate_params *params,const struct bt_c * @return true if the attribute object has been subscribed. */ bool bt_gatt_is_subscribed(struct bt_conn *conn, - const struct bt_gatt_attr *attr, u16_t ccc_value); + const struct bt_gatt_attr *attr, u16_t ccc_value); /** @brief Get ATT MTU for a connection * @@ -965,10 +965,10 @@ u16_t bt_gatt_get_mtu(struct bt_conn *conn); /** @brief GATT Exchange MTU parameters */ struct bt_gatt_exchange_params { - struct bt_att_req _req; - /** Response callback */ - void (*func)(struct bt_conn *conn, u8_t err, - struct bt_gatt_exchange_params *params); + struct bt_att_req _req; + /** Response callback */ + void (*func)(struct bt_conn *conn, u8_t err, + struct bt_gatt_exchange_params *params); }; /** @brief Exchange MTU @@ -984,7 +984,7 @@ struct bt_gatt_exchange_params { * @return 0 in case of success or negative value in case of error. */ int bt_gatt_exchange_mtu(struct bt_conn *conn, - struct bt_gatt_exchange_params *params); + struct bt_gatt_exchange_params *params); struct bt_gatt_discover_params; @@ -1004,65 +1004,65 @@ struct bt_gatt_discover_params; * or BT_GATT_ITER_STOP to stop discovery procedure. */ typedef u8_t (*bt_gatt_discover_func_t)(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - struct bt_gatt_discover_params *params); + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params); /* GATT Discover types */ enum { - /** Discover Primary Services. */ - BT_GATT_DISCOVER_PRIMARY, - /** Discover Secondary Services. */ - BT_GATT_DISCOVER_SECONDARY, - /** Discover Included Services. */ - BT_GATT_DISCOVER_INCLUDE, - /** Discover Characteristic Values. - * - * Discover Characteristic Value and its properties. - */ - BT_GATT_DISCOVER_CHARACTERISTIC, - /** Discover Descriptors. - * - * Discover Attributes which are not services or characteristics. - * - * Note: The use of this type of discover is not recommended for - * discovering in ranges across multiple services/characteristics - * as it may incur in extra round trips. - */ - BT_GATT_DISCOVER_DESCRIPTOR, - /** Discover Attributes. - * - * Discover Attributes of any type. - * - * Note: The use of this type of discover is not recommended for - * discovering in ranges across multiple services/characteristics as - * it may incur in more round trips. - */ - BT_GATT_DISCOVER_ATTRIBUTE, + /** Discover Primary Services. */ + BT_GATT_DISCOVER_PRIMARY, + /** Discover Secondary Services. */ + BT_GATT_DISCOVER_SECONDARY, + /** Discover Included Services. */ + BT_GATT_DISCOVER_INCLUDE, + /** Discover Characteristic Values. + * + * Discover Characteristic Value and its properties. + */ + BT_GATT_DISCOVER_CHARACTERISTIC, + /** Discover Descriptors. + * + * Discover Attributes which are not services or characteristics. + * + * Note: The use of this type of discover is not recommended for + * discovering in ranges across multiple services/characteristics + * as it may incur in extra round trips. + */ + BT_GATT_DISCOVER_DESCRIPTOR, + /** Discover Attributes. + * + * Discover Attributes of any type. + * + * Note: The use of this type of discover is not recommended for + * discovering in ranges across multiple services/characteristics as + * it may incur in more round trips. + */ + BT_GATT_DISCOVER_ATTRIBUTE, }; /** @brief GATT Discover Attributes parameters */ struct bt_gatt_discover_params { - struct bt_att_req _req; - /** Discover UUID type */ - struct bt_uuid *uuid; - /** Discover attribute callback */ - bt_gatt_discover_func_t func; - union { - struct { - /** Include service attribute declaration handle */ - u16_t attr_handle; - /** Included service start handle */ - u16_t start_handle; - /** Included service end handle */ - u16_t end_handle; - } _included; - /** Discover start handle */ - u16_t start_handle; - }; - /** Discover end handle */ - u16_t end_handle; - /** Discover type */ - u8_t type; + struct bt_att_req _req; + /** Discover UUID type */ + struct bt_uuid *uuid; + /** Discover attribute callback */ + bt_gatt_discover_func_t func; + union { + struct { + /** Include service attribute declaration handle */ + u16_t attr_handle; + /** Included service start handle */ + u16_t start_handle; + /** Included service end handle */ + u16_t end_handle; + } _included; + /** Discover start handle */ + u16_t start_handle; + }; + /** Discover end handle */ + u16_t end_handle; + /** Discover type */ + u8_t type; }; /** @brief GATT Discover function @@ -1091,7 +1091,7 @@ struct bt_gatt_discover_params { * @return 0 in case of success or negative value in case of error. */ int bt_gatt_discover(struct bt_conn *conn, - struct bt_gatt_discover_params *params); + struct bt_gatt_discover_params *params); struct bt_gatt_read_params; @@ -1105,8 +1105,8 @@ struct bt_gatt_read_params; * @param length Attribute value length. */ typedef u8_t (*bt_gatt_read_func_t)(struct bt_conn *conn, u8_t err, - struct bt_gatt_read_params *params, - const void *data, u16_t length); + struct bt_gatt_read_params *params, + const void *data, u16_t length); /** @brief GATT Read parameters * @param func Read attribute callback @@ -1123,21 +1123,21 @@ typedef u8_t (*bt_gatt_read_func_t)(struct bt_conn *conn, u8_t err, * @param uuid 2 or 16 octet UUID */ struct bt_gatt_read_params { - struct bt_att_req _req; - bt_gatt_read_func_t func; - size_t handle_count; - union { - struct { - u16_t handle; - u16_t offset; - } single; - u16_t *handles; - struct { - u16_t start_handle; - u16_t end_handle; - struct bt_uuid *uuid; - } by_uuid; - }; + struct bt_att_req _req; + bt_gatt_read_func_t func; + size_t handle_count; + union { + struct { + u16_t handle; + u16_t offset; + } single; + u16_t *handles; + struct { + u16_t start_handle; + u16_t end_handle; + struct bt_uuid *uuid; + } by_uuid; + }; }; /** @brief Read Attribute Value by handle @@ -1172,21 +1172,21 @@ struct bt_gatt_write_params; * @param params Write parameters used. */ typedef void (*bt_gatt_write_func_t)(struct bt_conn *conn, u8_t err, - struct bt_gatt_write_params *params); + struct bt_gatt_write_params *params); /** @brief GATT Write parameters */ struct bt_gatt_write_params { - struct bt_att_req _req; - /** Response callback */ - bt_gatt_write_func_t func; - /** Attribute handle */ - u16_t handle; - /** Attribute data offset */ - u16_t offset; - /** Data to be written */ - const void *data; - /** Length of the data */ - u16_t length; + struct bt_att_req _req; + /** Response callback */ + bt_gatt_write_func_t func; + /** Attribute handle */ + u16_t handle; + /** Attribute data offset */ + u16_t offset; + /** Data to be written */ + const void *data; + /** Length of the data */ + u16_t length; }; /** @brief Write Attribute Value by handle @@ -1207,7 +1207,7 @@ int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params); #if defined(CONFIG_BT_STACK_PTS) int bt_gatt_prepare_write(struct bt_conn *conn, - struct bt_gatt_write_params *params); + struct bt_gatt_write_params *params); #endif @@ -1235,9 +1235,9 @@ int bt_gatt_prepare_write(struct bt_conn *conn, * @return 0 in case of success or negative value in case of error. */ int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle, - const void *data, u16_t length, - bool sign, bt_gatt_complete_func_t func, - void *user_data); + const void *data, u16_t length, + bool sign, bt_gatt_complete_func_t func, + void *user_data); /** @brief Write Attribute Value by handle without response * @@ -1253,11 +1253,11 @@ int bt_gatt_write_without_response_cb(struct bt_conn *conn, u16_t handle, * @return 0 in case of success or negative value in case of error. */ static inline int bt_gatt_write_without_response(struct bt_conn *conn, - u16_t handle, const void *data, - u16_t length, bool sign) + u16_t handle, const void *data, + u16_t length, bool sign) { - return bt_gatt_write_without_response_cb(conn, handle, data, length, - sign, NULL, NULL); + return bt_gatt_write_without_response_cb(conn, handle, data, length, + sign, NULL, NULL); } struct bt_gatt_subscribe_params; @@ -1272,48 +1272,48 @@ struct bt_gatt_subscribe_params; * @param length Attribute value length. */ typedef u8_t (*bt_gatt_notify_func_t)(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params, - const void *data, u16_t length); + struct bt_gatt_subscribe_params *params, + const void *data, u16_t length); /* Subscription flags */ enum { - /** Persistence flag - * - * If set, indicates that the subscription is not saved - * on the GATT server side. Therefore, upon disconnection, - * the subscription will be automatically removed - * from the client's subscriptions list and - * when the client reconnects, it will have to - * issue a new subscription. - */ - BT_GATT_SUBSCRIBE_FLAG_VOLATILE, + /** Persistence flag + * + * If set, indicates that the subscription is not saved + * on the GATT server side. Therefore, upon disconnection, + * the subscription will be automatically removed + * from the client's subscriptions list and + * when the client reconnects, it will have to + * issue a new subscription. + */ + BT_GATT_SUBSCRIBE_FLAG_VOLATILE, - /** Write pending flag - * - * If set, indicates write operation is pending waiting remote end to - * respond. - */ - BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING, + /** Write pending flag + * + * If set, indicates write operation is pending waiting remote end to + * respond. + */ + BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING, - BT_GATT_SUBSCRIBE_NUM_FLAGS + BT_GATT_SUBSCRIBE_NUM_FLAGS }; /** @brief GATT Subscribe parameters */ struct bt_gatt_subscribe_params { - struct bt_att_req _req; - bt_addr_le_t _peer; - /** Notification value callback */ - bt_gatt_notify_func_t notify; - /** Subscribe value handle */ - u16_t value_handle; - /** Subscribe CCC handle */ - u16_t ccc_handle; - /** Subscribe value */ - u16_t value; - /** Subscription flags */ - ATOMIC_DEFINE(flags, BT_GATT_SUBSCRIBE_NUM_FLAGS); + struct bt_att_req _req; + bt_addr_le_t _peer; + /** Notification value callback */ + bt_gatt_notify_func_t notify; + /** Subscribe value handle */ + u16_t value_handle; + /** Subscribe CCC handle */ + u16_t ccc_handle; + /** Subscribe value */ + u16_t value; + /** Subscription flags */ + ATOMIC_DEFINE(flags, BT_GATT_SUBSCRIBE_NUM_FLAGS); - sys_snode_t node; + sys_snode_t node; }; /** @brief Subscribe Attribute Value Notification @@ -1334,7 +1334,7 @@ struct bt_gatt_subscribe_params { * @return 0 in case of success or negative value in case of error. */ int bt_gatt_subscribe(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params); + struct bt_gatt_subscribe_params *params); /** @brief Unsubscribe Attribute Value Notification * @@ -1349,7 +1349,7 @@ int bt_gatt_subscribe(struct bt_conn *conn, * @return 0 in case of success or negative value in case of error. */ int bt_gatt_unsubscribe(struct bt_conn *conn, - struct bt_gatt_subscribe_params *params); + struct bt_gatt_subscribe_params *params); /** @brief Cancel GATT pending request * diff --git a/components/network/ble/blestack/src/include/bluetooth/hci_host.h b/components/network/ble/blestack/src/include/bluetooth/hci_host.h index 052375a4..70b8c79e 100644 --- a/components/network/ble/blestack/src/include/bluetooth/hci_host.h +++ b/components/network/ble/blestack/src/include/bluetooth/hci_host.h @@ -34,8 +34,8 @@ extern "C" { #define BT_ENC_KEY_SIZE_MAX 0x10 struct bt_hci_evt_hdr { - u8_t evt; - u8_t len; + u8_t evt; + u8_t len; } __packed; #define BT_HCI_EVT_HDR_SIZE 2 @@ -48,14 +48,14 @@ struct bt_hci_evt_hdr { #define bt_acl_handle_pack(h, f) ((h) | ((f) << 12)) struct bt_hci_acl_hdr { - u16_t handle; - u16_t len; + u16_t handle; + u16_t len; } __packed; #define BT_HCI_ACL_HDR_SIZE 4 struct bt_hci_cmd_hdr { - u16_t opcode; - u8_t param_len; + u16_t opcode; + u8_t param_len; } __packed; #define BT_HCI_CMD_HDR_SIZE 3 @@ -100,22 +100,22 @@ struct bt_hci_cmd_hdr { #define BT_LE_FEAT_BIT_MIN_USED_CHAN_PROC 16 #define BT_LE_FEAT_TEST(feat, n) (feat[(n) >> 3] & \ - BIT((n) & 7)) + BIT((n) & 7)) #define BT_FEAT_LE_ENCR(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_ENC) + BT_LE_FEAT_BIT_ENC) #define BT_FEAT_LE_CONN_PARAM_REQ_PROC(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_CONN_PARAM_REQ) + BT_LE_FEAT_BIT_CONN_PARAM_REQ) #define BT_FEAT_LE_SLAVE_FEATURE_XCHG(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_SLAVE_FEAT_REQ) + BT_LE_FEAT_BIT_SLAVE_FEAT_REQ) #define BT_FEAT_LE_DLE(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_DLE) + BT_LE_FEAT_BIT_DLE) #define BT_FEAT_LE_PHY_2M(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_PHY_2M) + BT_LE_FEAT_BIT_PHY_2M) #define BT_FEAT_LE_PHY_CODED(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_PHY_CODED) + BT_LE_FEAT_BIT_PHY_CODED) #define BT_FEAT_LE_PRIVACY(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_PRIVACY) + BT_LE_FEAT_BIT_PRIVACY) /* LE States */ #define BT_LE_STATES_SLAVE_CONN_ADV(states) (states & 0x0000004000000000) @@ -159,15 +159,15 @@ struct bt_hci_cmd_hdr { #define ESCO_PKT_MASK (HCI_PKT_TYPE_ESCO_HV1 | \ - HCI_PKT_TYPE_ESCO_HV2 | \ - HCI_PKT_TYPE_ESCO_HV3) + HCI_PKT_TYPE_ESCO_HV2 | \ + HCI_PKT_TYPE_ESCO_HV3) #define SCO_PKT_MASK (HCI_PKT_TYPE_HV1 | \ - HCI_PKT_TYPE_HV2 | \ - HCI_PKT_TYPE_HV3) + HCI_PKT_TYPE_HV2 | \ + HCI_PKT_TYPE_HV3) #define EDR_ESCO_PKT_MASK (HCI_PKT_TYPE_ESCO_2EV3 | \ - HCI_PKT_TYPE_ESCO_3EV3 | \ - HCI_PKT_TYPE_ESCO_2EV5 | \ - HCI_PKT_TYPE_ESCO_3EV5) + HCI_PKT_TYPE_ESCO_3EV3 | \ + HCI_PKT_TYPE_ESCO_2EV5 | \ + HCI_PKT_TYPE_ESCO_3EV5) /* HCI BR/EDR link types */ #define BT_HCI_SCO 0x00 @@ -186,7 +186,7 @@ struct bt_hci_cmd_hdr { #define BT_OP(ogf, ocf) ((ocf) | ((ogf) << 10)) /* Invalid opcode */ -#define BT_OP_NOP 0x0000 +#define BT_OP_NOP 0x0000 /* Obtain OGF from OpCode */ #define BT_OGF(opcode) (((opcode) >> 10) & BIT_MASK(6)) @@ -195,192 +195,192 @@ struct bt_hci_cmd_hdr { #define BT_HCI_OP_INQUIRY BT_OP(BT_OGF_LINK_CTRL, 0x0001) struct bt_hci_op_inquiry { - u8_t lap[3]; - u8_t length; - u8_t num_rsp; + u8_t lap[3]; + u8_t length; + u8_t num_rsp; } __packed; #define BT_HCI_OP_INQUIRY_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x0002) #define BT_HCI_OP_CONNECT BT_OP(BT_OGF_LINK_CTRL, 0x0005) struct bt_hci_cp_connect { - bt_addr_t bdaddr; - u16_t packet_type; - u8_t pscan_rep_mode; - u8_t reserved; - u16_t clock_offset; - u8_t allow_role_switch; + bt_addr_t bdaddr; + u16_t packet_type; + u8_t pscan_rep_mode; + u8_t reserved; + u16_t clock_offset; + u8_t allow_role_switch; } __packed; #define BT_HCI_OP_DISCONNECT BT_OP(BT_OGF_LINK_CTRL, 0x0006) struct bt_hci_cp_disconnect { - u16_t handle; - u8_t reason; + u16_t handle; + u8_t reason; } __packed; #define BT_HCI_OP_CONNECT_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x0008) struct bt_hci_cp_connect_cancel { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_connect_cancel { - u8_t status; - bt_addr_t bdaddr; + u8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_ACCEPT_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x0009) struct bt_hci_cp_accept_conn_req { - bt_addr_t bdaddr; - u8_t role; + bt_addr_t bdaddr; + u8_t role; } __packed; #define BT_HCI_OP_SETUP_SYNC_CONN BT_OP(BT_OGF_LINK_CTRL, 0x0028) struct bt_hci_cp_setup_sync_conn { - u16_t handle; - u32_t tx_bandwidth; - u32_t rx_bandwidth; - u16_t max_latency; - u16_t content_format; - u8_t retrans_effort; - u16_t pkt_type; + u16_t handle; + u32_t tx_bandwidth; + u32_t rx_bandwidth; + u16_t max_latency; + u16_t content_format; + u8_t retrans_effort; + u16_t pkt_type; } __packed; #define BT_HCI_OP_ACCEPT_SYNC_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x0029) struct bt_hci_cp_accept_sync_conn_req { - bt_addr_t bdaddr; - u32_t tx_bandwidth; - u32_t rx_bandwidth; - u16_t max_latency; - u16_t content_format; - u8_t retrans_effort; - u16_t pkt_type; + bt_addr_t bdaddr; + u32_t tx_bandwidth; + u32_t rx_bandwidth; + u16_t max_latency; + u16_t content_format; + u8_t retrans_effort; + u16_t pkt_type; } __packed; #define BT_HCI_OP_REJECT_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x000a) struct bt_hci_cp_reject_conn_req { - bt_addr_t bdaddr; - u8_t reason; + bt_addr_t bdaddr; + u8_t reason; } __packed; #define BT_HCI_OP_LINK_KEY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000b) struct bt_hci_cp_link_key_reply { - bt_addr_t bdaddr; - u8_t link_key[16]; + bt_addr_t bdaddr; + u8_t link_key[16]; } __packed; #define BT_HCI_OP_LINK_KEY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000c) struct bt_hci_cp_link_key_neg_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_PIN_CODE_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000d) struct bt_hci_cp_pin_code_reply { - bt_addr_t bdaddr; - u8_t pin_len; - u8_t pin_code[16]; + bt_addr_t bdaddr; + u8_t pin_len; + u8_t pin_code[16]; } __packed; struct bt_hci_rp_pin_code_reply { - u8_t status; - bt_addr_t bdaddr; + u8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_PIN_CODE_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000e) struct bt_hci_cp_pin_code_neg_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_pin_code_neg_reply { - u8_t status; - bt_addr_t bdaddr; + u8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_AUTH_REQUESTED BT_OP(BT_OGF_LINK_CTRL, 0x0011) struct bt_hci_cp_auth_requested { - u16_t handle; + u16_t handle; } __packed; #define BT_HCI_OP_SET_CONN_ENCRYPT BT_OP(BT_OGF_LINK_CTRL, 0x0013) struct bt_hci_cp_set_conn_encrypt { - u16_t handle; - u8_t encrypt; + u16_t handle; + u8_t encrypt; } __packed; #define BT_HCI_OP_REMOTE_NAME_REQUEST BT_OP(BT_OGF_LINK_CTRL, 0x0019) struct bt_hci_cp_remote_name_request { - bt_addr_t bdaddr; - u8_t pscan_rep_mode; - u8_t reserved; - u16_t clock_offset; + bt_addr_t bdaddr; + u8_t pscan_rep_mode; + u8_t reserved; + u16_t clock_offset; } __packed; #define BT_HCI_OP_REMOTE_NAME_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x001a) struct bt_hci_cp_remote_name_cancel { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_remote_name_cancel { - u8_t status; - bt_addr_t bdaddr; + u8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_READ_REMOTE_FEATURES BT_OP(BT_OGF_LINK_CTRL, 0x001b) struct bt_hci_cp_read_remote_features { - u16_t handle; + u16_t handle; } __packed; #define BT_HCI_OP_READ_REMOTE_EXT_FEATURES BT_OP(BT_OGF_LINK_CTRL, 0x001c) struct bt_hci_cp_read_remote_ext_features { - u16_t handle; - u8_t page; + u16_t handle; + u8_t page; } __packed; #define BT_HCI_OP_READ_REMOTE_VERSION_INFO BT_OP(BT_OGF_LINK_CTRL, 0x001d) struct bt_hci_cp_read_remote_version_info { - u16_t handle; + u16_t handle; } __packed; #define BT_HCI_OP_IO_CAPABILITY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002b) struct bt_hci_cp_io_capability_reply { - bt_addr_t bdaddr; - u8_t capability; - u8_t oob_data; - u8_t authentication; + bt_addr_t bdaddr; + u8_t capability; + u8_t oob_data; + u8_t authentication; } __packed; #define BT_HCI_OP_USER_CONFIRM_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002c) #define BT_HCI_OP_USER_CONFIRM_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002d) struct bt_hci_cp_user_confirm_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_user_confirm_reply { - u8_t status; - bt_addr_t bdaddr; + u8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_USER_PASSKEY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002e) struct bt_hci_cp_user_passkey_reply { - bt_addr_t bdaddr; - u32_t passkey; + bt_addr_t bdaddr; + u32_t passkey; } __packed; #define BT_HCI_OP_USER_PASSKEY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002f) struct bt_hci_cp_user_passkey_neg_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_IO_CAPABILITY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x0034) struct bt_hci_cp_io_capability_neg_reply { - bt_addr_t bdaddr; - u8_t reason; + bt_addr_t bdaddr; + u8_t reason; } __packed; #define BT_HCI_OP_SET_EVENT_MASK BT_OP(BT_OGF_BASEBAND, 0x0001) struct bt_hci_cp_set_event_mask { - u8_t events[8]; + u8_t events[8]; } __packed; #define BT_HCI_OP_RESET BT_OP(BT_OGF_BASEBAND, 0x0003) #define BT_HCI_OP_WRITE_LOCAL_NAME BT_OP(BT_OGF_BASEBAND, 0x0013) struct bt_hci_write_local_name { - u8_t local_name[248]; + u8_t local_name[248]; } __packed; #define BT_HCI_OP_WRITE_PAGE_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x0018) @@ -394,88 +394,88 @@ struct bt_hci_write_local_name { #define BT_TX_POWER_LEVEL_MAX 0x01 #define BT_HCI_OP_READ_TX_POWER_LEVEL BT_OP(BT_OGF_BASEBAND, 0x002d) struct bt_hci_cp_read_tx_power_level { - u16_t handle; - u8_t type; + u16_t handle; + u8_t type; } __packed; struct bt_hci_rp_read_tx_power_level { - u8_t status; - u16_t handle; - s8_t tx_power_level; + u8_t status; + u16_t handle; + s8_t tx_power_level; } __packed; #define BT_HCI_CTL_TO_HOST_FLOW_DISABLE 0x00 #define BT_HCI_CTL_TO_HOST_FLOW_ENABLE 0x01 #define BT_HCI_OP_SET_CTL_TO_HOST_FLOW BT_OP(BT_OGF_BASEBAND, 0x0031) struct bt_hci_cp_set_ctl_to_host_flow { - u8_t flow_enable; + u8_t flow_enable; } __packed; #define BT_HCI_OP_HOST_BUFFER_SIZE BT_OP(BT_OGF_BASEBAND, 0x0033) struct bt_hci_cp_host_buffer_size { - u16_t acl_mtu; - u8_t sco_mtu; - u16_t acl_pkts; - u16_t sco_pkts; + u16_t acl_mtu; + u8_t sco_mtu; + u16_t acl_pkts; + u16_t sco_pkts; } __packed; struct bt_hci_handle_count { - u16_t handle; - u16_t count; + u16_t handle; + u16_t count; } __packed; #define BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS BT_OP(BT_OGF_BASEBAND, 0x0035) struct bt_hci_cp_host_num_completed_packets { - u8_t num_handles; - struct bt_hci_handle_count h[0]; + u8_t num_handles; + struct bt_hci_handle_count h[0]; } __packed; #define BT_HCI_OP_WRITE_INQUIRY_MODE BT_OP(BT_OGF_BASEBAND, 0x0045) struct bt_hci_cp_write_inquiry_mode { - u8_t mode; + u8_t mode; } __packed; #define BT_HCI_OP_WRITE_SSP_MODE BT_OP(BT_OGF_BASEBAND, 0x0056) struct bt_hci_cp_write_ssp_mode { - u8_t mode; + u8_t mode; } __packed; #define BT_HCI_OP_SET_EVENT_MASK_PAGE_2 BT_OP(BT_OGF_BASEBAND, 0x0063) struct bt_hci_cp_set_event_mask_page_2 { - u8_t events_page_2[8]; + u8_t events_page_2[8]; } __packed; #define BT_HCI_OP_LE_WRITE_LE_HOST_SUPP BT_OP(BT_OGF_BASEBAND, 0x006d) struct bt_hci_cp_write_le_host_supp { - u8_t le; - u8_t simul; + u8_t le; + u8_t simul; } __packed; #define BT_HCI_OP_WRITE_SC_HOST_SUPP BT_OP(BT_OGF_BASEBAND, 0x007a) struct bt_hci_cp_write_sc_host_supp { - u8_t sc_support; + u8_t sc_support; } __packed; #define BT_HCI_OP_READ_AUTH_PAYLOAD_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x007b) struct bt_hci_cp_read_auth_payload_timeout { - u16_t handle; + u16_t handle; } __packed; struct bt_hci_rp_read_auth_payload_timeout { - u8_t status; - u16_t handle; - u16_t auth_payload_timeout; + u8_t status; + u16_t handle; + u16_t auth_payload_timeout; } __packed; #define BT_HCI_OP_WRITE_AUTH_PAYLOAD_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x007c) struct bt_hci_cp_write_auth_payload_timeout { - u16_t handle; - u16_t auth_payload_timeout; + u16_t handle; + u16_t auth_payload_timeout; } __packed; struct bt_hci_rp_write_auth_payload_timeout { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; /* HCI version from Assigned Numbers */ @@ -493,60 +493,60 @@ struct bt_hci_rp_write_auth_payload_timeout { #define BT_HCI_OP_READ_LOCAL_VERSION_INFO BT_OP(BT_OGF_INFO, 0x0001) struct bt_hci_rp_read_local_version_info { - u8_t status; - u8_t hci_version; - u16_t hci_revision; - u8_t lmp_version; - u16_t manufacturer; - u16_t lmp_subversion; + u8_t status; + u8_t hci_version; + u16_t hci_revision; + u8_t lmp_version; + u16_t manufacturer; + u16_t lmp_subversion; } __packed; #define BT_HCI_OP_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_INFO, 0x0002) struct bt_hci_rp_read_supported_commands { - u8_t status; - u8_t commands[64]; + u8_t status; + u8_t commands[64]; } __packed; #define BT_HCI_OP_READ_LOCAL_EXT_FEATURES BT_OP(BT_OGF_INFO, 0x0004) struct bt_hci_cp_read_local_ext_features { - u8_t page; + u8_t page; }; struct bt_hci_rp_read_local_ext_features { - u8_t status; - u8_t page; - u8_t max_page; - u8_t ext_features[8]; + u8_t status; + u8_t page; + u8_t max_page; + u8_t ext_features[8]; } __packed; #define BT_HCI_OP_READ_LOCAL_FEATURES BT_OP(BT_OGF_INFO, 0x0003) struct bt_hci_rp_read_local_features { - u8_t status; - u8_t features[8]; + u8_t status; + u8_t features[8]; } __packed; #define BT_HCI_OP_READ_BUFFER_SIZE BT_OP(BT_OGF_INFO, 0x0005) struct bt_hci_rp_read_buffer_size { - u8_t status; - u16_t acl_max_len; - u8_t sco_max_len; - u16_t acl_max_num; - u16_t sco_max_num; + u8_t status; + u16_t acl_max_len; + u8_t sco_max_len; + u16_t acl_max_num; + u16_t sco_max_num; } __packed; #define BT_HCI_OP_READ_BD_ADDR BT_OP(BT_OGF_INFO, 0x0009) struct bt_hci_rp_read_bd_addr { - u8_t status; - bt_addr_t bdaddr; + u8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_READ_RSSI BT_OP(BT_OGF_STATUS, 0x0005) struct bt_hci_cp_read_rssi { - u16_t handle; + u16_t handle; } __packed; struct bt_hci_rp_read_rssi { - u8_t status; - u16_t handle; - s8_t rssi; + u8_t status; + u16_t handle; + s8_t rssi; } __packed; #define BT_HCI_ENCRYPTION_KEY_SIZE_MIN 7 @@ -554,37 +554,37 @@ struct bt_hci_rp_read_rssi { #define BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE BT_OP(BT_OGF_STATUS, 0x0008) struct bt_hci_cp_read_encryption_key_size { - u16_t handle; + u16_t handle; } __packed; struct bt_hci_rp_read_encryption_key_size { - u8_t status; - u16_t handle; - u8_t key_size; + u8_t status; + u16_t handle; + u8_t key_size; } __packed; /* BLE */ #define BT_HCI_OP_LE_SET_EVENT_MASK BT_OP(BT_OGF_LE, 0x0001) struct bt_hci_cp_le_set_event_mask { - u8_t events[8]; + u8_t events[8]; } __packed; #define BT_HCI_OP_LE_READ_BUFFER_SIZE BT_OP(BT_OGF_LE, 0x0002) struct bt_hci_rp_le_read_buffer_size { - u8_t status; - u16_t le_max_len; - u8_t le_max_num; + u8_t status; + u16_t le_max_len; + u8_t le_max_num; } __packed; #define BT_HCI_OP_LE_READ_LOCAL_FEATURES BT_OP(BT_OGF_LE, 0x0003) struct bt_hci_rp_le_read_local_features { - u8_t status; - u8_t features[8]; + u8_t status; + u8_t features[8]; } __packed; #define BT_HCI_OP_LE_SET_RANDOM_ADDRESS BT_OP(BT_OGF_LE, 0x0005) struct bt_hci_cp_le_set_random_address { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; /* Advertising types */ @@ -603,31 +603,31 @@ struct bt_hci_cp_le_set_random_address { #define BT_HCI_OP_LE_SET_ADV_PARAM BT_OP(BT_OGF_LE, 0x0006) struct bt_hci_cp_le_set_adv_param { - u16_t min_interval; - u16_t max_interval; - u8_t type; - u8_t own_addr_type; - bt_addr_le_t direct_addr; - u8_t channel_map; - u8_t filter_policy; + u16_t min_interval; + u16_t max_interval; + u8_t type; + u8_t own_addr_type; + bt_addr_le_t direct_addr; + u8_t channel_map; + u8_t filter_policy; } __packed; #define BT_HCI_OP_LE_READ_ADV_CHAN_TX_POWER BT_OP(BT_OGF_LE, 0x0007) struct bt_hci_rp_le_read_chan_tx_power { - u8_t status; - s8_t tx_power_level; + u8_t status; + s8_t tx_power_level; } __packed; #define BT_HCI_OP_LE_SET_ADV_DATA BT_OP(BT_OGF_LE, 0x0008) struct bt_hci_cp_le_set_adv_data { - u8_t len; - u8_t data[31]; + u8_t len; + u8_t data[31]; } __packed; #define BT_HCI_OP_LE_SET_SCAN_RSP_DATA BT_OP(BT_OGF_LE, 0x0009) struct bt_hci_cp_le_set_scan_rsp_data { - u8_t len; - u8_t data[31]; + u8_t len; + u8_t data[31]; } __packed; #define BT_HCI_LE_ADV_DISABLE 0x00 @@ -635,7 +635,7 @@ struct bt_hci_cp_le_set_scan_rsp_data { #define BT_HCI_OP_LE_SET_ADV_ENABLE BT_OP(BT_OGF_LE, 0x000a) struct bt_hci_cp_le_set_adv_enable { - u8_t enable; + u8_t enable; } __packed; /* Scan types */ @@ -647,11 +647,11 @@ struct bt_hci_cp_le_set_adv_enable { #define BT_HCI_LE_SCAN_FP_USE_WHITELIST 0x01 struct bt_hci_cp_le_set_scan_param { - u8_t scan_type; - u16_t interval; - u16_t window; - u8_t addr_type; - u8_t filter_policy; + u8_t scan_type; + u16_t interval; + u16_t window; + u8_t addr_type; + u8_t filter_policy; } __packed; #define BT_HCI_OP_LE_SET_SCAN_ENABLE BT_OP(BT_OGF_LE, 0x000c) @@ -663,8 +663,8 @@ struct bt_hci_cp_le_set_scan_param { #define BT_HCI_LE_SCAN_FILTER_DUP_ENABLE 0x01 struct bt_hci_cp_le_set_scan_enable { - u8_t enable; - u8_t filter_dup; + u8_t enable; + u8_t filter_dup; } __packed; #define BT_HCI_OP_LE_CREATE_CONN BT_OP(BT_OGF_LE, 0x000d) @@ -673,229 +673,229 @@ struct bt_hci_cp_le_set_scan_enable { #define BT_HCI_LE_CREATE_CONN_FP_WHITELIST 0x01 struct bt_hci_cp_le_create_conn { - u16_t scan_interval; - u16_t scan_window; - u8_t filter_policy; - bt_addr_le_t peer_addr; - u8_t own_addr_type; - u16_t conn_interval_min; - u16_t conn_interval_max; - u16_t conn_latency; - u16_t supervision_timeout; - u16_t min_ce_len; - u16_t max_ce_len; + u16_t scan_interval; + u16_t scan_window; + u8_t filter_policy; + bt_addr_le_t peer_addr; + u8_t own_addr_type; + u16_t conn_interval_min; + u16_t conn_interval_max; + u16_t conn_latency; + u16_t supervision_timeout; + u16_t min_ce_len; + u16_t max_ce_len; } __packed; #define BT_HCI_OP_LE_CREATE_CONN_CANCEL BT_OP(BT_OGF_LE, 0x000e) #define BT_HCI_OP_LE_READ_WL_SIZE BT_OP(BT_OGF_LE, 0x000f) struct bt_hci_rp_le_read_wl_size { - u8_t status; - u8_t wl_size; + u8_t status; + u8_t wl_size; } __packed; #define BT_HCI_OP_LE_CLEAR_WL BT_OP(BT_OGF_LE, 0x0010) #define BT_HCI_OP_LE_ADD_DEV_TO_WL BT_OP(BT_OGF_LE, 0x0011) struct bt_hci_cp_le_add_dev_to_wl { - bt_addr_le_t addr; + bt_addr_le_t addr; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_WL BT_OP(BT_OGF_LE, 0x0012) struct bt_hci_cp_le_rem_dev_from_wl { - bt_addr_le_t addr; + bt_addr_le_t addr; } __packed; #define BT_HCI_OP_LE_CONN_UPDATE BT_OP(BT_OGF_LE, 0x0013) struct hci_cp_le_conn_update { - u16_t handle; - u16_t conn_interval_min; - u16_t conn_interval_max; - u16_t conn_latency; - u16_t supervision_timeout; - u16_t min_ce_len; - u16_t max_ce_len; + u16_t handle; + u16_t conn_interval_min; + u16_t conn_interval_max; + u16_t conn_latency; + u16_t supervision_timeout; + u16_t min_ce_len; + u16_t max_ce_len; } __packed; #define BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF BT_OP(BT_OGF_LE, 0x0014) struct bt_hci_cp_le_set_host_chan_classif { - u8_t ch_map[5]; + u8_t ch_map[5]; } __packed; #define BT_HCI_OP_LE_READ_CHAN_MAP BT_OP(BT_OGF_LE, 0x0015) struct bt_hci_cp_le_read_chan_map { - u16_t handle; + u16_t handle; } __packed; struct bt_hci_rp_le_read_chan_map { - u8_t status; - u16_t handle; - u8_t ch_map[5]; + u8_t status; + u16_t handle; + u8_t ch_map[5]; } __packed; #define BT_HCI_OP_LE_READ_REMOTE_FEATURES BT_OP(BT_OGF_LE, 0x0016) struct bt_hci_cp_le_read_remote_features { - u16_t handle; + u16_t handle; } __packed; #define BT_HCI_OP_LE_ENCRYPT BT_OP(BT_OGF_LE, 0x0017) struct bt_hci_cp_le_encrypt { - u8_t key[16]; - u8_t plaintext[16]; + u8_t key[16]; + u8_t plaintext[16]; } __packed; struct bt_hci_rp_le_encrypt { - u8_t status; - u8_t enc_data[16]; + u8_t status; + u8_t enc_data[16]; } __packed; #define BT_HCI_OP_LE_RAND BT_OP(BT_OGF_LE, 0x0018) struct bt_hci_rp_le_rand { - u8_t status; - u8_t rand[8]; + u8_t status; + u8_t rand[8]; } __packed; #define BT_HCI_OP_LE_START_ENCRYPTION BT_OP(BT_OGF_LE, 0x0019) struct bt_hci_cp_le_start_encryption { - u16_t handle; - u64_t rand; - u16_t ediv; - u8_t ltk[16]; + u16_t handle; + u64_t rand; + u16_t ediv; + u8_t ltk[16]; } __packed; #define BT_HCI_OP_LE_LTK_REQ_REPLY BT_OP(BT_OGF_LE, 0x001a) struct bt_hci_cp_le_ltk_req_reply { - u16_t handle; - u8_t ltk[16]; + u16_t handle; + u8_t ltk[16]; } __packed; struct bt_hci_rp_le_ltk_req_reply { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; #define BT_HCI_OP_LE_LTK_REQ_NEG_REPLY BT_OP(BT_OGF_LE, 0x001b) struct bt_hci_cp_le_ltk_req_neg_reply { - u16_t handle; + u16_t handle; } __packed; struct bt_hci_rp_le_ltk_req_neg_reply { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; #define BT_HCI_OP_LE_READ_SUPP_STATES BT_OP(BT_OGF_LE, 0x001c) struct bt_hci_rp_le_read_supp_states { - u8_t status; - u8_t le_states[8]; + u8_t status; + u8_t le_states[8]; } __packed; #define BT_HCI_OP_LE_RX_TEST BT_OP(BT_OGF_LE, 0x001d) struct bt_hci_cp_le_rx_test { - u8_t rx_ch; + u8_t rx_ch; } __packed; #define BT_HCI_OP_LE_TX_TEST BT_OP(BT_OGF_LE, 0x001e) struct bt_hci_cp_le_tx_test { - u8_t tx_ch; - u8_t test_data_len; - u8_t pkt_payload; + u8_t tx_ch; + u8_t test_data_len; + u8_t pkt_payload; } __packed; #define BT_HCI_OP_LE_TEST_END BT_OP(BT_OGF_LE, 0x001f) struct bt_hci_rp_le_test_end { - u8_t status; - u16_t rx_pkt_count; + u8_t status; + u16_t rx_pkt_count; } __packed; #define BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY BT_OP(BT_OGF_LE, 0x0020) struct bt_hci_cp_le_conn_param_req_reply { - u16_t handle; - u16_t interval_min; - u16_t interval_max; - u16_t latency; - u16_t timeout; - u16_t min_ce_len; - u16_t max_ce_len; + u16_t handle; + u16_t interval_min; + u16_t interval_max; + u16_t latency; + u16_t timeout; + u16_t min_ce_len; + u16_t max_ce_len; } __packed; struct bt_hci_rp_le_conn_param_req_reply { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; #define BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY BT_OP(BT_OGF_LE, 0x0021) struct bt_hci_cp_le_conn_param_req_neg_reply { - u16_t handle; - u8_t reason; + u16_t handle; + u8_t reason; } __packed; struct bt_hci_rp_le_conn_param_req_neg_reply { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; #define BT_HCI_OP_LE_SET_DATA_LEN BT_OP(BT_OGF_LE, 0x0022) struct bt_hci_cp_le_set_data_len { - u16_t handle; - u16_t tx_octets; - u16_t tx_time; + u16_t handle; + u16_t tx_octets; + u16_t tx_time; } __packed; struct bt_hci_rp_le_set_data_len { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; #define BT_HCI_OP_LE_READ_DEFAULT_DATA_LEN BT_OP(BT_OGF_LE, 0x0023) struct bt_hci_rp_le_read_default_data_len { - u8_t status; - u16_t max_tx_octets; - u16_t max_tx_time; + u8_t status; + u16_t max_tx_octets; + u16_t max_tx_time; } __packed; #define BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN BT_OP(BT_OGF_LE, 0x0024) struct bt_hci_cp_le_write_default_data_len { - u16_t max_tx_octets; - u16_t max_tx_time; + u16_t max_tx_octets; + u16_t max_tx_time; } __packed; #define BT_HCI_OP_LE_P256_PUBLIC_KEY BT_OP(BT_OGF_LE, 0x0025) #define BT_HCI_OP_LE_GENERATE_DHKEY BT_OP(BT_OGF_LE, 0x0026) struct bt_hci_cp_le_generate_dhkey { - u8_t key[64]; + u8_t key[64]; } __packed; #define BT_HCI_OP_LE_ADD_DEV_TO_RL BT_OP(BT_OGF_LE, 0x0027) struct bt_hci_cp_le_add_dev_to_rl { - bt_addr_le_t peer_id_addr; - u8_t peer_irk[16]; - u8_t local_irk[16]; + bt_addr_le_t peer_id_addr; + u8_t peer_irk[16]; + u8_t local_irk[16]; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_RL BT_OP(BT_OGF_LE, 0x0028) struct bt_hci_cp_le_rem_dev_from_rl { - bt_addr_le_t peer_id_addr; + bt_addr_le_t peer_id_addr; } __packed; #define BT_HCI_OP_LE_CLEAR_RL BT_OP(BT_OGF_LE, 0x0029) #define BT_HCI_OP_LE_READ_RL_SIZE BT_OP(BT_OGF_LE, 0x002a) struct bt_hci_rp_le_read_rl_size { - u8_t status; - u8_t rl_size; + u8_t status; + u8_t rl_size; } __packed; #define BT_HCI_OP_LE_READ_PEER_RPA BT_OP(BT_OGF_LE, 0x002b) struct bt_hci_cp_le_read_peer_rpa { - bt_addr_le_t peer_id_addr; + bt_addr_le_t peer_id_addr; } __packed; struct bt_hci_rp_le_read_peer_rpa { - u8_t status; - bt_addr_t peer_rpa; + u8_t status; + bt_addr_t peer_rpa; } __packed; #define BT_HCI_OP_LE_READ_LOCAL_RPA BT_OP(BT_OGF_LE, 0x002c) struct bt_hci_cp_le_read_local_rpa { - bt_addr_le_t peer_id_addr; + bt_addr_le_t peer_id_addr; } __packed; struct bt_hci_rp_le_read_local_rpa { - u8_t status; - bt_addr_t local_rpa; + u8_t status; + bt_addr_t local_rpa; } __packed; #define BT_HCI_ADDR_RES_DISABLE 0x00 @@ -903,21 +903,21 @@ struct bt_hci_rp_le_read_local_rpa { #define BT_HCI_OP_LE_SET_ADDR_RES_ENABLE BT_OP(BT_OGF_LE, 0x002d) struct bt_hci_cp_le_set_addr_res_enable { - u8_t enable; + u8_t enable; } __packed; #define BT_HCI_OP_LE_SET_RPA_TIMEOUT BT_OP(BT_OGF_LE, 0x002e) struct bt_hci_cp_le_set_rpa_timeout { - u16_t rpa_timeout; + u16_t rpa_timeout; } __packed; #define BT_HCI_OP_LE_READ_MAX_DATA_LEN BT_OP(BT_OGF_LE, 0x002f) struct bt_hci_rp_le_read_max_data_len { - u8_t status; - u16_t max_tx_octets; - u16_t max_tx_time; - u16_t max_rx_octets; - u16_t max_rx_time; + u8_t status; + u16_t max_tx_octets; + u16_t max_tx_time; + u16_t max_rx_octets; + u16_t max_rx_time; } __packed; #define BT_HCI_LE_PHY_1M 0x01 @@ -926,13 +926,13 @@ struct bt_hci_rp_le_read_max_data_len { #define BT_HCI_OP_LE_READ_PHY BT_OP(BT_OGF_LE, 0x0030) struct bt_hci_cp_le_read_phy { - u16_t handle; + u16_t handle; } __packed; struct bt_hci_rp_le_read_phy { - u8_t status; - u16_t handle; - u8_t tx_phy; - u8_t rx_phy; + u8_t status; + u16_t handle; + u8_t tx_phy; + u8_t rx_phy; } __packed; #define BT_HCI_LE_PHY_TX_ANY BIT(0) @@ -944,9 +944,9 @@ struct bt_hci_rp_le_read_phy { #define BT_HCI_OP_LE_SET_DEFAULT_PHY BT_OP(BT_OGF_LE, 0x0031) struct bt_hci_cp_le_set_default_phy { - u8_t all_phys; - u8_t tx_phys; - u8_t rx_phys; + u8_t all_phys; + u8_t tx_phys; + u8_t rx_phys; } __packed; #define BT_HCI_LE_PHY_CODED_ANY 0x00 @@ -955,11 +955,11 @@ struct bt_hci_cp_le_set_default_phy { #define BT_HCI_OP_LE_SET_PHY BT_OP(BT_OGF_LE, 0x0032) struct bt_hci_cp_le_set_phy { - u16_t handle; - u8_t all_phys; - u8_t tx_phys; - u8_t rx_phys; - u16_t phy_opts; + u16_t handle; + u8_t all_phys; + u8_t tx_phys; + u8_t rx_phys; + u16_t phy_opts; } __packed; #define BT_HCI_LE_MOD_INDEX_STANDARD 0x00 @@ -967,9 +967,9 @@ struct bt_hci_cp_le_set_phy { #define BT_HCI_OP_LE_ENH_RX_TEST BT_OP(BT_OGF_LE, 0x0033) struct bt_hci_cp_le_enh_rx_test { - u8_t rx_ch; - u8_t phy; - u8_t mod_index; + u8_t rx_ch; + u8_t phy; + u8_t mod_index; } __packed; /* Extends BT_HCI_LE_PHY */ @@ -978,16 +978,16 @@ struct bt_hci_cp_le_enh_rx_test { #define BT_HCI_OP_LE_ENH_TX_TEST BT_OP(BT_OGF_LE, 0x0034) struct bt_hci_cp_le_enh_tx_test { - u8_t tx_ch; - u8_t test_data_len; - u8_t pkt_payload; - u8_t phy; + u8_t tx_ch; + u8_t test_data_len; + u8_t pkt_payload; + u8_t phy; } __packed; #define BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR BT_OP(BT_OGF_LE, 0x0035) struct bt_hci_cp_le_set_adv_set_random_addr { - u8_t handle; - bt_addr_t bdaddr; + u8_t handle; + bt_addr_t bdaddr; } __packed; #define BT_HCI_LE_ADV_PROP_CONN BIT(0) @@ -1000,24 +1000,24 @@ struct bt_hci_cp_le_set_adv_set_random_addr { #define BT_HCI_OP_LE_SET_EXT_ADV_PARAM BT_OP(BT_OGF_LE, 0x0036) struct bt_hci_cp_le_set_ext_adv_param { - u8_t handle; - u16_t props; - u8_t prim_min_interval[3]; - u8_t prim_max_interval[3]; - u8_t prim_channel_map; - u8_t own_addr_type; - bt_addr_le_t peer_addr; - u8_t filter_policy; - s8_t tx_power; - u8_t prim_adv_phy; - u8_t sec_adv_max_skip; - u8_t sec_adv_phy; - u8_t sid; - u8_t scan_req_notify_enable; + u8_t handle; + u16_t props; + u8_t prim_min_interval[3]; + u8_t prim_max_interval[3]; + u8_t prim_channel_map; + u8_t own_addr_type; + bt_addr_le_t peer_addr; + u8_t filter_policy; + s8_t tx_power; + u8_t prim_adv_phy; + u8_t sec_adv_max_skip; + u8_t sec_adv_phy; + u8_t sid; + u8_t scan_req_notify_enable; } __packed; struct bt_hci_rp_le_set_ext_adv_param { - u8_t status; - s8_t tx_power; + u8_t status; + s8_t tx_power; } __packed; #define BT_HCI_LE_EXT_ADV_OP_INTERM_FRAG 0x00 @@ -1031,81 +1031,81 @@ struct bt_hci_rp_le_set_ext_adv_param { #define BT_HCI_OP_LE_SET_EXT_ADV_DATA BT_OP(BT_OGF_LE, 0x0037) struct bt_hci_cp_le_set_ext_adv_data { - u8_t handle; - u8_t op; - u8_t frag_pref; - u8_t len; - u8_t data[251]; + u8_t handle; + u8_t op; + u8_t frag_pref; + u8_t len; + u8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA BT_OP(BT_OGF_LE, 0x0038) struct bt_hci_cp_le_set_ext_scan_rsp_data { - u8_t handle; - u8_t op; - u8_t frag_pref; - u8_t len; - u8_t data[251]; + u8_t handle; + u8_t op; + u8_t frag_pref; + u8_t len; + u8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_EXT_ADV_ENABLE BT_OP(BT_OGF_LE, 0x0039) struct bt_hci_ext_adv_set { - u8_t handle; - u16_t duration; - u8_t max_ext_adv_evts; + u8_t handle; + u16_t duration; + u8_t max_ext_adv_evts; } __packed; struct bt_hci_cp_le_set_ext_adv_enable { - u8_t enable; - u8_t set_num; - struct bt_hci_ext_adv_set s[0]; + u8_t enable; + u8_t set_num; + struct bt_hci_ext_adv_set s[0]; } __packed; #define BT_HCI_OP_LE_READ_MAX_ADV_DATA_LEN BT_OP(BT_OGF_LE, 0x003a) struct bt_hci_rp_le_read_max_adv_data_len { - u8_t status; - u16_t max_adv_data_len; + u8_t status; + u16_t max_adv_data_len; } __packed; #define BT_HCI_OP_LE_READ_NUM_ADV_SETS BT_OP(BT_OGF_LE, 0x003b) struct bt_hci_rp_le_read_num_adv_sets { - u8_t status; - u8_t num_sets; + u8_t status; + u8_t num_sets; } __packed; #define BT_HCI_OP_LE_REMOVE_ADV_SET BT_OP(BT_OGF_LE, 0x003c) struct bt_hci_cp_le_remove_adv_set { - u8_t handle; + u8_t handle; } __packed; #define BT_HCI_OP_CLEAR_ADV_SETS BT_OP(BT_OGF_LE, 0x003d) #define BT_HCI_OP_LE_SET_PER_ADV_PARAM BT_OP(BT_OGF_LE, 0x003e) struct bt_hci_cp_le_set_per_adv_param { - u8_t handle; - u16_t min_interval; - u16_t max_interval; - u16_t props; + u8_t handle; + u16_t min_interval; + u16_t max_interval; + u16_t props; } __packed; #define BT_HCI_OP_LE_SET_PER_ADV_DATA BT_OP(BT_OGF_LE, 0x003f) struct bt_hci_cp_le_set_per_adv_data { - u8_t handle; - u8_t op; - u8_t len; - u8_t data[251]; + u8_t handle; + u8_t op; + u8_t len; + u8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_PER_ADV_ENABLE BT_OP(BT_OGF_LE, 0x0040) struct bt_hci_cp_le_set_per_adv_enable { - u8_t enable; - u8_t handle; + u8_t enable; + u8_t handle; } __packed; #define BT_HCI_OP_LE_SET_EXT_SCAN_PARAM BT_OP(BT_OGF_LE, 0x0041) struct bt_hci_ext_scan_phy { - u8_t type; - u16_t interval; - u16_t window; + u8_t type; + u16_t interval; + u16_t window; } __packed; #define BT_HCI_LE_EXT_SCAN_PHY_1M BIT(0) @@ -1113,10 +1113,10 @@ struct bt_hci_ext_scan_phy { #define BT_HCI_LE_EXT_SCAN_PHY_CODED BIT(2) struct bt_hci_cp_le_set_ext_scan_param { - u8_t own_addr_type; - u8_t filter_policy; - u8_t phys; - struct bt_hci_ext_scan_phy p[0]; + u8_t own_addr_type; + u8_t filter_policy; + u8_t phys; + struct bt_hci_ext_scan_phy p[0]; } __packed; /* Extends BT_HCI_LE_SCAN_FILTER_DUP */ @@ -1124,87 +1124,87 @@ struct bt_hci_cp_le_set_ext_scan_param { #define BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE BT_OP(BT_OGF_LE, 0x0042) struct bt_hci_cp_le_set_ext_scan_enable { - u8_t enable; - u8_t filter_dup; - u16_t duration; - u16_t period; + u8_t enable; + u8_t filter_dup; + u16_t duration; + u16_t period; } __packed; #define BT_HCI_OP_LE_EXT_CREATE_CONN BT_OP(BT_OGF_LE, 0x0043) struct bt_hci_ext_conn_phy { - u16_t interval; - u16_t window; - u16_t conn_interval_min; - u16_t conn_interval_max; - u16_t conn_latency; - u16_t supervision_timeout; - u16_t min_ce_len; - u16_t max_ce_len; + u16_t interval; + u16_t window; + u16_t conn_interval_min; + u16_t conn_interval_max; + u16_t conn_latency; + u16_t supervision_timeout; + u16_t min_ce_len; + u16_t max_ce_len; } __packed; struct bt_hci_cp_le_ext_create_conn { - u8_t filter_policy; - u8_t own_addr_type; - bt_addr_le_t peer_addr; - u8_t phys; - struct bt_hci_ext_conn_phy p[0]; + u8_t filter_policy; + u8_t own_addr_type; + bt_addr_le_t peer_addr; + u8_t phys; + struct bt_hci_ext_conn_phy p[0]; } __packed; #define BT_HCI_OP_LE_PER_ADV_CREATE_SYNC BT_OP(BT_OGF_LE, 0x0044) struct bt_hci_cp_le_per_adv_create_sync { - u8_t filter_policy; - u8_t sid; - bt_addr_le_t addr; - u16_t skip; - u16_t sync_timeout; - u8_t unused; + u8_t filter_policy; + u8_t sid; + bt_addr_le_t addr; + u16_t skip; + u16_t sync_timeout; + u8_t unused; } __packed; #define BT_HCI_OP_LE_PER_ADV_CREATE_SYNC_CANCEL BT_OP(BT_OGF_LE, 0x0045) #define BT_HCI_OP_LE_PER_ADV_TERMINATE_SYNC BT_OP(BT_OGF_LE, 0x0046) struct bt_hci_cp_le_per_adv_terminate_sync { - u16_t handle; + u16_t handle; } __packed; #define BT_HCI_OP_LE_ADD_DEV_TO_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0047) struct bt_hci_cp_le_add_dev_to_per_adv_list { - bt_addr_le_t addr; - u8_t sid; + bt_addr_le_t addr; + u8_t sid; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0048) struct bt_hci_cp_le_rem_dev_from_per_adv_list { - bt_addr_le_t addr; - u8_t sid; + bt_addr_le_t addr; + u8_t sid; } __packed; #define BT_HCI_OP_LE_CLEAR_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0049) #define BT_HCI_OP_LE_READ_PER_ADV_LIST_SIZE BT_OP(BT_OGF_LE, 0x004a) struct bt_hci_rp_le_read_per_adv_list_size { - u8_t status; - u8_t list_size; + u8_t status; + u8_t list_size; } __packed; #define BT_HCI_OP_LE_READ_TX_POWER BT_OP(BT_OGF_LE, 0x004b) struct bt_hci_rp_le_read_tx_power { - u8_t status; - s8_t min_tx_power; - s8_t max_tx_power; + u8_t status; + s8_t min_tx_power; + s8_t max_tx_power; } __packed; #define BT_HCI_OP_LE_READ_RF_PATH_COMP BT_OP(BT_OGF_LE, 0x004c) struct bt_hci_rp_le_read_rf_path_comp { - u8_t status; - s16_t tx_path_comp; - s16_t rx_path_comp; + u8_t status; + s16_t tx_path_comp; + s16_t rx_path_comp; } __packed; #define BT_HCI_OP_LE_WRITE_RF_PATH_COMP BT_OP(BT_OGF_LE, 0x004d) struct bt_hci_cp_le_write_rf_path_comp { - s16_t tx_path_comp; - s16_t rx_path_comp; + s16_t tx_path_comp; + s16_t rx_path_comp; } __packed; #define BT_HCI_LE_PRIVACY_MODE_NETWORK 0x00 @@ -1212,8 +1212,8 @@ struct bt_hci_cp_le_write_rf_path_comp { #define BT_HCI_OP_LE_SET_PRIVACY_MODE BT_OP(BT_OGF_LE, 0x004e) struct bt_hci_cp_le_set_privacy_mode { - bt_addr_le_t id_addr; - u8_t mode; + bt_addr_le_t id_addr; + u8_t mode; } __packed; /* Event definitions */ @@ -1230,106 +1230,106 @@ struct bt_hci_cp_le_set_privacy_mode { #define BT_HCI_EVT_INQUIRY_COMPLETE 0x01 struct bt_hci_evt_inquiry_complete { - u8_t status; + u8_t status; } __packed; #define BT_HCI_EVT_CONN_COMPLETE 0x03 struct bt_hci_evt_conn_complete { - u8_t status; - u16_t handle; - bt_addr_t bdaddr; - u8_t link_type; - u8_t encr_enabled; + u8_t status; + u16_t handle; + bt_addr_t bdaddr; + u8_t link_type; + u8_t encr_enabled; } __packed; #define BT_HCI_EVT_CONN_REQUEST 0x04 struct bt_hci_evt_conn_request { - bt_addr_t bdaddr; - u8_t dev_class[3]; - u8_t link_type; + bt_addr_t bdaddr; + u8_t dev_class[3]; + u8_t link_type; } __packed; #define BT_HCI_EVT_DISCONN_COMPLETE 0x05 struct bt_hci_evt_disconn_complete { - u8_t status; - u16_t handle; - u8_t reason; + u8_t status; + u16_t handle; + u8_t reason; } __packed; #define BT_HCI_EVT_AUTH_COMPLETE 0x06 struct bt_hci_evt_auth_complete { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; #define BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE 0x07 struct bt_hci_evt_remote_name_req_complete { - u8_t status; - bt_addr_t bdaddr; - u8_t name[248]; + u8_t status; + bt_addr_t bdaddr; + u8_t name[248]; } __packed; #define BT_HCI_EVT_ENCRYPT_CHANGE 0x08 struct bt_hci_evt_encrypt_change { - u8_t status; - u16_t handle; - u8_t encrypt; + u8_t status; + u16_t handle; + u8_t encrypt; } __packed; #define BT_HCI_EVT_REMOTE_FEATURES 0x0b struct bt_hci_evt_remote_features { - u8_t status; - u16_t handle; - u8_t features[8]; + u8_t status; + u16_t handle; + u8_t features[8]; } __packed; #define BT_HCI_EVT_REMOTE_VERSION_INFO 0x0c struct bt_hci_evt_remote_version_info { - u8_t status; - u16_t handle; - u8_t version; - u16_t manufacturer; - u16_t subversion; + u8_t status; + u16_t handle; + u8_t version; + u16_t manufacturer; + u16_t subversion; } __packed; #define BT_HCI_EVT_CMD_COMPLETE 0x0e struct bt_hci_evt_cmd_complete { - u8_t ncmd; - u16_t opcode; + u8_t ncmd; + u16_t opcode; } __packed; struct bt_hci_evt_cc_status { - u8_t status; + u8_t status; } __packed; #define BT_HCI_EVT_CMD_STATUS 0x0f struct bt_hci_evt_cmd_status { - u8_t status; - u8_t ncmd; - u16_t opcode; + u8_t status; + u8_t ncmd; + u16_t opcode; } __packed; #define BT_HCI_EVT_ROLE_CHANGE 0x12 struct bt_hci_evt_role_change { - u8_t status; - bt_addr_t bdaddr; - u8_t role; + u8_t status; + bt_addr_t bdaddr; + u8_t role; } __packed; #define BT_HCI_EVT_NUM_COMPLETED_PACKETS 0x13 struct bt_hci_evt_num_completed_packets { - u8_t num_handles; - struct bt_hci_handle_count h[0]; + u8_t num_handles; + struct bt_hci_handle_count h[0]; } __packed; #define BT_HCI_EVT_PIN_CODE_REQ 0x16 struct bt_hci_evt_pin_code_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_LINK_KEY_REQ 0x17 struct bt_hci_evt_link_key_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; /* Link Key types */ @@ -1345,9 +1345,9 @@ struct bt_hci_evt_link_key_req { #define BT_HCI_EVT_LINK_KEY_NOTIFY 0x18 struct bt_hci_evt_link_key_notify { - bt_addr_t bdaddr; - u8_t link_key[16]; - u8_t key_type; + bt_addr_t bdaddr; + u8_t link_key[16]; + u8_t key_type; } __packed; /* Overflow link types */ @@ -1356,103 +1356,103 @@ struct bt_hci_evt_link_key_notify { #define BT_HCI_EVT_DATA_BUF_OVERFLOW 0x1a struct bt_hci_evt_data_buf_overflow { - u8_t link_type; + u8_t link_type; } __packed; #define BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI 0x22 struct bt_hci_evt_inquiry_result_with_rssi { - bt_addr_t addr; - u8_t pscan_rep_mode; - u8_t reserved; - u8_t cod[3]; - u16_t clock_offset; - s8_t rssi; + bt_addr_t addr; + u8_t pscan_rep_mode; + u8_t reserved; + u8_t cod[3]; + u16_t clock_offset; + s8_t rssi; } __packed; #define BT_HCI_EVT_REMOTE_EXT_FEATURES 0x23 struct bt_hci_evt_remote_ext_features { - u8_t status; - u16_t handle; - u8_t page; - u8_t max_page; - u8_t features[8]; + u8_t status; + u16_t handle; + u8_t page; + u8_t max_page; + u8_t features[8]; } __packed; #define BT_HCI_EVT_SYNC_CONN_COMPLETE 0x2c struct bt_hci_evt_sync_conn_complete { - u8_t status; - u16_t handle; - bt_addr_t bdaddr; - u8_t link_type; - u8_t tx_interval; - u8_t retansmission_window; - u16_t rx_pkt_length; - u16_t tx_pkt_length; - u8_t air_mode; + u8_t status; + u16_t handle; + bt_addr_t bdaddr; + u8_t link_type; + u8_t tx_interval; + u8_t retansmission_window; + u16_t rx_pkt_length; + u16_t tx_pkt_length; + u8_t air_mode; } __packed; #define BT_HCI_EVT_EXTENDED_INQUIRY_RESULT 0x2f struct bt_hci_evt_extended_inquiry_result { - u8_t num_reports; - bt_addr_t addr; - u8_t pscan_rep_mode; - u8_t reserved; - u8_t cod[3]; - u16_t clock_offset; - s8_t rssi; - u8_t eir[240]; + u8_t num_reports; + bt_addr_t addr; + u8_t pscan_rep_mode; + u8_t reserved; + u8_t cod[3]; + u16_t clock_offset; + s8_t rssi; + u8_t eir[240]; } __packed; #define BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE 0x30 struct bt_hci_evt_encrypt_key_refresh_complete { - u8_t status; - u16_t handle; + u8_t status; + u16_t handle; } __packed; #define BT_HCI_EVT_IO_CAPA_REQ 0x31 struct bt_hci_evt_io_capa_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_IO_CAPA_RESP 0x32 struct bt_hci_evt_io_capa_resp { - bt_addr_t bdaddr; - u8_t capability; - u8_t oob_data; - u8_t authentication; + bt_addr_t bdaddr; + u8_t capability; + u8_t oob_data; + u8_t authentication; } __packed; #define BT_HCI_EVT_USER_CONFIRM_REQ 0x33 struct bt_hci_evt_user_confirm_req { - bt_addr_t bdaddr; - u32_t passkey; + bt_addr_t bdaddr; + u32_t passkey; } __packed; #define BT_HCI_EVT_USER_PASSKEY_REQ 0x34 struct bt_hci_evt_user_passkey_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_SSP_COMPLETE 0x36 struct bt_hci_evt_ssp_complete { - u8_t status; - bt_addr_t bdaddr; + u8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_USER_PASSKEY_NOTIFY 0x3b struct bt_hci_evt_user_passkey_notify { - bt_addr_t bdaddr; - u32_t passkey; + bt_addr_t bdaddr; + u32_t passkey; } __packed; #define BT_HCI_EVT_LE_META_EVENT 0x3e struct bt_hci_evt_le_meta_event { - u8_t subevent; + u8_t subevent; } __packed; #define BT_HCI_EVT_AUTH_PAYLOAD_TIMEOUT_EXP 0x57 struct bt_hci_evt_auth_payload_timeout_exp { - u16_t handle; + u16_t handle; } __packed; #define BT_HCI_ROLE_MASTER 0x00 @@ -1460,175 +1460,175 @@ struct bt_hci_evt_auth_payload_timeout_exp { #define BT_HCI_EVT_LE_CONN_COMPLETE 0x01 struct bt_hci_evt_le_conn_complete { - u8_t status; - u16_t handle; - u8_t role; - bt_addr_le_t peer_addr; - u16_t interval; - u16_t latency; - u16_t supv_timeout; - u8_t clock_accuracy; + u8_t status; + u16_t handle; + u8_t role; + bt_addr_le_t peer_addr; + u16_t interval; + u16_t latency; + u16_t supv_timeout; + u8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_ADVERTISING_REPORT 0x02 struct bt_hci_evt_le_advertising_info { - u8_t evt_type; - bt_addr_le_t addr; - u8_t length; - u8_t data[0]; + u8_t evt_type; + bt_addr_le_t addr; + u8_t length; + u8_t data[0]; } __packed; struct bt_hci_evt_le_advertising_report { - u8_t num_reports; - struct bt_hci_evt_le_advertising_info adv_info[0]; + u8_t num_reports; + struct bt_hci_evt_le_advertising_info adv_info[0]; } __packed; #define BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE 0x03 struct bt_hci_evt_le_conn_update_complete { - u8_t status; - u16_t handle; - u16_t interval; - u16_t latency; - u16_t supv_timeout; + u8_t status; + u16_t handle; + u16_t interval; + u16_t latency; + u16_t supv_timeout; } __packed; #define BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE 0x04 struct bt_hci_evt_le_remote_feat_complete { - u8_t status; - u16_t handle; - u8_t features[8]; + u8_t status; + u16_t handle; + u8_t features[8]; } __packed; #define BT_HCI_EVT_LE_LTK_REQUEST 0x05 struct bt_hci_evt_le_ltk_request { - u16_t handle; - u64_t rand; - u16_t ediv; + u16_t handle; + u64_t rand; + u16_t ediv; } __packed; #define BT_HCI_EVT_LE_CONN_PARAM_REQ 0x06 struct bt_hci_evt_le_conn_param_req { - u16_t handle; - u16_t interval_min; - u16_t interval_max; - u16_t latency; - u16_t timeout; + u16_t handle; + u16_t interval_min; + u16_t interval_max; + u16_t latency; + u16_t timeout; } __packed; #define BT_HCI_EVT_LE_DATA_LEN_CHANGE 0x07 struct bt_hci_evt_le_data_len_change { - u16_t handle; - u16_t max_tx_octets; - u16_t max_tx_time; - u16_t max_rx_octets; - u16_t max_rx_time; + u16_t handle; + u16_t max_tx_octets; + u16_t max_tx_time; + u16_t max_rx_octets; + u16_t max_rx_time; } __packed; #define BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE 0x08 struct bt_hci_evt_le_p256_public_key_complete { - u8_t status; - u8_t key[64]; + u8_t status; + u8_t key[64]; } __packed; #define BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE 0x09 struct bt_hci_evt_le_generate_dhkey_complete { - u8_t status; - u8_t dhkey[32]; + u8_t status; + u8_t dhkey[32]; } __packed; #define BT_HCI_EVT_LE_ENH_CONN_COMPLETE 0x0a struct bt_hci_evt_le_enh_conn_complete { - u8_t status; - u16_t handle; - u8_t role; - bt_addr_le_t peer_addr; - bt_addr_t local_rpa; - bt_addr_t peer_rpa; - u16_t interval; - u16_t latency; - u16_t supv_timeout; - u8_t clock_accuracy; + u8_t status; + u16_t handle; + u8_t role; + bt_addr_le_t peer_addr; + bt_addr_t local_rpa; + bt_addr_t peer_rpa; + u16_t interval; + u16_t latency; + u16_t supv_timeout; + u8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_DIRECT_ADV_REPORT 0x0b struct bt_hci_evt_le_direct_adv_info { - u8_t evt_type; - bt_addr_le_t addr; - bt_addr_le_t dir_addr; - s8_t rssi; + u8_t evt_type; + bt_addr_le_t addr; + bt_addr_le_t dir_addr; + s8_t rssi; } __packed; struct bt_hci_evt_le_direct_adv_report { - u8_t num_reports; - struct bt_hci_evt_le_direct_adv_info direct_adv_info[0]; + u8_t num_reports; + struct bt_hci_evt_le_direct_adv_info direct_adv_info[0]; } __packed; #define BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE 0x0c struct bt_hci_evt_le_phy_update_complete { - u8_t status; - u16_t handle; - u8_t tx_phy; - u8_t rx_phy; + u8_t status; + u16_t handle; + u8_t tx_phy; + u8_t rx_phy; } __packed; #define BT_HCI_EVT_LE_EXT_ADVERTISING_REPORT 0x0d struct bt_hci_evt_le_ext_advertising_info { - u8_t evt_type; - bt_addr_le_t addr; - u8_t prim_phy; - u8_t sec_phy; - u8_t sid; - s8_t tx_power; - s8_t rssi; - u16_t interval; - bt_addr_le_t direct_addr; - u8_t length; - u8_t data[0]; + u8_t evt_type; + bt_addr_le_t addr; + u8_t prim_phy; + u8_t sec_phy; + u8_t sid; + s8_t tx_power; + s8_t rssi; + u16_t interval; + bt_addr_le_t direct_addr; + u8_t length; + u8_t data[0]; } __packed; struct bt_hci_evt_le_ext_advertising_report { - u8_t num_reports; - struct bt_hci_evt_le_ext_advertising_info adv_info[0]; + u8_t num_reports; + struct bt_hci_evt_le_ext_advertising_info adv_info[0]; } __packed; #define BT_HCI_EVT_LE_PER_ADV_SYNC_ESTABLISHED 0x0e struct bt_hci_evt_le_per_adv_sync_established { - u8_t status; - u16_t handle; - u8_t sid; - bt_addr_le_t adv_addr; - u8_t phy; - u16_t interval; - u8_t clock_accuracy; + u8_t status; + u16_t handle; + u8_t sid; + bt_addr_le_t adv_addr; + u8_t phy; + u16_t interval; + u8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_PER_ADVERTISING_REPORT 0x0f struct bt_hci_evt_le_per_advertising_report { - u16_t handle; - s8_t tx_power; - s8_t rssi; - u8_t unused; - u8_t data_status; - u8_t length; - u8_t data[0]; + u16_t handle; + s8_t tx_power; + s8_t rssi; + u8_t unused; + u8_t data_status; + u8_t length; + u8_t data[0]; } __packed; #define BT_HCI_EVT_LE_PER_ADV_SYNC_LOST 0x10 struct bt_hci_evt_le_per_adv_sync_lost { - u16_t handle; + u16_t handle; } __packed; #define BT_HCI_EVT_LE_SCAN_TIMEOUT 0x11 #define BT_HCI_EVT_LE_ADV_SET_TERMINATED 0x12 struct bt_hci_evt_le_per_adv_set_terminated { - u8_t status; - u8_t adv_handle; - u16_t conn_handle; - u8_t num_completed_ext_adv_evts; + u8_t status; + u8_t adv_handle; + u16_t conn_handle; + u8_t num_completed_ext_adv_evts; } __packed; #define BT_HCI_EVT_LE_SCAN_REQ_RECEIVED 0x13 struct bt_hci_evt_le_scan_req_received { - u8_t handle; - bt_addr_le_t addr; + u8_t handle; + bt_addr_le_t addr; } __packed; #define BT_HCI_LE_CHAN_SEL_ALGO_1 0x00 @@ -1636,8 +1636,8 @@ struct bt_hci_evt_le_scan_req_received { #define BT_HCI_EVT_LE_CHAN_SEL_ALGO 0x14 struct bt_hci_evt_le_chan_sel_algo { - u16_t handle; - u8_t chan_sel_algo; + u16_t handle; + u8_t chan_sel_algo; } __packed; /* Event mask bits */ @@ -1777,7 +1777,7 @@ int bt_hci_cmd_send(u16_t opcode, struct net_buf *buf); * @return 0 on success or negative error value on failure. */ int bt_hci_cmd_send_sync(u16_t opcode, struct net_buf *buf, - struct net_buf **rsp); + struct net_buf **rsp); //declare bt_hci_get_conn_handle in conn_internal.h to pass compile #if !defined(BFLB_BLE) diff --git a/components/network/ble/blestack/src/include/bluetooth/hci_vs.h b/components/network/ble/blestack/src/include/bluetooth/hci_vs.h index fd717f50..52ce0170 100644 --- a/components/network/ble/blestack/src/include/bluetooth/hci_vs.h +++ b/components/network/ble/blestack/src/include/bluetooth/hci_vs.h @@ -29,44 +29,44 @@ extern "C" { #define BT_HCI_VS_FW_VAR_RESCUE_IMG 0x0004 #if !defined(BFLB_BLE) -#define BT_HCI_OP_VS_READ_VERSION_INFO BT_OP(BT_OGF_VS, 0x0001) +#define BT_HCI_OP_VS_READ_VERSION_INFO BT_OP(BT_OGF_VS, 0x0001) struct bt_hci_rp_vs_read_version_info { - u8_t status; - u16_t hw_platform; - u16_t hw_variant; - u8_t fw_variant; - u8_t fw_version; - u16_t fw_revision; - u32_t fw_build; + u8_t status; + u16_t hw_platform; + u16_t hw_variant; + u8_t fw_variant; + u8_t fw_version; + u16_t fw_revision; + u32_t fw_build; } __packed; -#define BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_VS, 0x0002) +#define BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_VS, 0x0002) struct bt_hci_rp_vs_read_supported_commands { - u8_t status; - u8_t commands[64]; + u8_t status; + u8_t commands[64]; } __packed; -#define BT_HCI_OP_VS_READ_SUPPORTED_FEATURES BT_OP(BT_OGF_VS, 0x0003) +#define BT_HCI_OP_VS_READ_SUPPORTED_FEATURES BT_OP(BT_OGF_VS, 0x0003) struct bt_hci_rp_vs_read_supported_features { - u8_t status; - u8_t features[8]; + u8_t status; + u8_t features[8]; } __packed; #define BT_HCI_OP_VS_SET_EVENT_MASK BT_OP(BT_OGF_VS, 0x0004) struct bt_hci_cp_vs_set_event_mask { - u8_t event_mask[8]; + u8_t event_mask[8]; } __packed; #define BT_HCI_VS_RESET_SOFT 0x00 #define BT_HCI_VS_RESET_HARD 0x01 #define BT_HCI_OP_VS_RESET BT_OP(BT_OGF_VS, 0x0005) struct bt_hci_cp_vs_reset { - u8_t type; + u8_t type; } __packed; #define BT_HCI_OP_VS_WRITE_BD_ADDR BT_OP(BT_OGF_VS, 0x0006) struct bt_hci_cp_vs_write_bd_addr { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_VS_TRACE_DISABLED 0x00 @@ -76,60 +76,60 @@ struct bt_hci_cp_vs_write_bd_addr { #define BT_HCI_VS_TRACE_VDC 0x01 #define BT_HCI_OP_VS_SET_TRACE_ENABLE BT_OP(BT_OGF_VS, 0x0007) struct bt_hci_cp_vs_set_trace_enable { - u8_t enable; - u8_t type; + u8_t enable; + u8_t type; } __packed; #define BT_HCI_OP_VS_READ_BUILD_INFO BT_OP(BT_OGF_VS, 0x0008) struct bt_hci_rp_vs_read_build_info { - u8_t status; - u8_t info[0]; + u8_t status; + u8_t info[0]; } __packed; struct bt_hci_vs_static_addr { - bt_addr_t bdaddr; - u8_t ir[16]; + bt_addr_t bdaddr; + u8_t ir[16]; } __packed; #define BT_HCI_OP_VS_READ_STATIC_ADDRS BT_OP(BT_OGF_VS, 0x0009) struct bt_hci_rp_vs_read_static_addrs { - u8_t status; - u8_t num_addrs; - struct bt_hci_vs_static_addr a[0]; + u8_t status; + u8_t num_addrs; + struct bt_hci_vs_static_addr a[0]; } __packed; #define BT_HCI_OP_VS_READ_KEY_HIERARCHY_ROOTS BT_OP(BT_OGF_VS, 0x000a) struct bt_hci_rp_vs_read_key_hierarchy_roots { - u8_t status; - u8_t ir[16]; - u8_t er[16]; + u8_t status; + u8_t ir[16]; + u8_t er[16]; } __packed; #define BT_HCI_OP_VS_READ_CHIP_TEMP BT_OP(BT_OGF_VS, 0x000b) struct bt_hci_rp_vs_read_chip_temp { - u8_t status; - s8_t temps; + u8_t status; + s8_t temps; } __packed; struct bt_hci_vs_cmd { - u16_t vendor_id; - u16_t opcode_base; + u16_t vendor_id; + u16_t opcode_base; } __packed; #define BT_HCI_VS_VID_ANDROID 0x0001 #define BT_HCI_VS_VID_MICROSOFT 0x0002 #define BT_HCI_OP_VS_READ_HOST_STACK_CMDS BT_OP(BT_OGF_VS, 0x000c) struct bt_hci_rp_vs_read_host_stack_cmds { - u8_t status; - u8_t num_cmds; - struct bt_hci_vs_cmd c[0]; + u8_t status; + u8_t num_cmds; + struct bt_hci_vs_cmd c[0]; } __packed; #define BT_HCI_VS_SCAN_REQ_REPORTS_DISABLED 0x00 #define BT_HCI_VS_SCAN_REQ_REPORTS_ENABLED 0x01 #define BT_HCI_OP_VS_SET_SCAN_REQ_REPORTS BT_OP(BT_OGF_VS, 0x000d) struct bt_hci_cp_vs_set_scan_req_reports { - u8_t enable; + u8_t enable; } __packed; #endif //BFLB_BLE @@ -143,13 +143,13 @@ struct bt_hci_cp_vs_set_tx_pwr { /* Events */ struct bt_hci_evt_vs { - u8_t subevent; + u8_t subevent; } __packed; #define BT_HCI_EVT_VS_FATAL_ERROR 0x02 struct bt_hci_evt_vs_fatal_error { - u64_t pc; - u8_t err_info[0]; + u64_t pc; + u8_t err_info[0]; } __packed; #define BT_HCI_VS_TRACE_LMP_TX 0x01 @@ -159,14 +159,14 @@ struct bt_hci_evt_vs_fatal_error { #define BT_HCI_VS_TRACE_LE_CONN_IND 0x05 #define BT_HCI_EVT_VS_TRACE_INFO 0x03 struct bt_hci_evt_vs_trace_info { - u8_t type; - u8_t data[0]; + u8_t type; + u8_t data[0]; } __packed; #define BT_HCI_EVT_VS_SCAN_REQ_RX 0x04 struct bt_hci_evt_vs_scan_req_rx { - bt_addr_le_t addr; - s8_t rssi; + bt_addr_le_t addr; + s8_t rssi; } __packed; /* Event mask bits */ @@ -182,133 +182,133 @@ struct bt_hci_evt_vs_scan_req_rx { #define BT_HCI_MESH_EVT_PREFIX 0xF0 struct bt_hci_cp_mesh { - u8_t opcode; + u8_t opcode; } __packed; #define BT_HCI_OC_MESH_GET_OPTS 0x00 struct bt_hci_rp_mesh_get_opts { - u8_t status; - u8_t opcode; - u8_t revision; - u8_t ch_map; - s8_t min_tx_power; - s8_t max_tx_power; - u8_t max_scan_filter; - u8_t max_filter_pattern; - u8_t max_adv_slot; - u8_t max_tx_window; - u8_t evt_prefix_len; - u8_t evt_prefix; + u8_t status; + u8_t opcode; + u8_t revision; + u8_t ch_map; + s8_t min_tx_power; + s8_t max_tx_power; + u8_t max_scan_filter; + u8_t max_filter_pattern; + u8_t max_adv_slot; + u8_t max_tx_window; + u8_t evt_prefix_len; + u8_t evt_prefix; } __packed; #define BT_HCI_MESH_PATTERN_LEN_MAX 0x0f #define BT_HCI_OC_MESH_SET_SCAN_FILTER 0x01 struct bt_hci_mesh_pattern { - u8_t pattern_len; - u8_t pattern[0]; + u8_t pattern_len; + u8_t pattern[0]; } __packed; struct bt_hci_cp_mesh_set_scan_filter { - u8_t scan_filter; - u8_t filter_dup; - u8_t num_patterns; - struct bt_hci_mesh_pattern patterns[0]; + u8_t scan_filter; + u8_t filter_dup; + u8_t num_patterns; + struct bt_hci_mesh_pattern patterns[0]; } __packed; struct bt_hci_rp_mesh_set_scan_filter { - u8_t status; - u8_t opcode; - u8_t scan_filter; + u8_t status; + u8_t opcode; + u8_t scan_filter; } __packed; #define BT_HCI_OC_MESH_ADVERTISE 0x02 struct bt_hci_cp_mesh_advertise { - u8_t adv_slot; - u8_t own_addr_type; - bt_addr_t random_addr; - u8_t ch_map; - s8_t tx_power; - u8_t min_tx_delay; - u8_t max_tx_delay; - u8_t retx_count; - u8_t retx_interval; - u8_t scan_delay; - u16_t scan_duration; - u8_t scan_filter; - u8_t data_len; - u8_t data[31]; + u8_t adv_slot; + u8_t own_addr_type; + bt_addr_t random_addr; + u8_t ch_map; + s8_t tx_power; + u8_t min_tx_delay; + u8_t max_tx_delay; + u8_t retx_count; + u8_t retx_interval; + u8_t scan_delay; + u16_t scan_duration; + u8_t scan_filter; + u8_t data_len; + u8_t data[31]; } __packed; struct bt_hci_rp_mesh_advertise { - u8_t status; - u8_t opcode; - u8_t adv_slot; + u8_t status; + u8_t opcode; + u8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_ADVERTISE_TIMED 0x03 struct bt_hci_cp_mesh_advertise_timed { - u8_t adv_slot; - u8_t own_addr_type; - bt_addr_t random_addr; - u8_t ch_map; - s8_t tx_power; - u8_t retx_count; - u8_t retx_interval; - u32_t instant; - u16_t tx_delay; - u16_t tx_window; - u8_t data_len; - u8_t data[31]; + u8_t adv_slot; + u8_t own_addr_type; + bt_addr_t random_addr; + u8_t ch_map; + s8_t tx_power; + u8_t retx_count; + u8_t retx_interval; + u32_t instant; + u16_t tx_delay; + u16_t tx_window; + u8_t data_len; + u8_t data[31]; } __packed; struct bt_hci_rp_mesh_advertise_timed { - u8_t status; - u8_t opcode; - u8_t adv_slot; + u8_t status; + u8_t opcode; + u8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_ADVERTISE_CANCEL 0x04 struct bt_hci_cp_mesh_advertise_cancel { - u8_t adv_slot; + u8_t adv_slot; } __packed; struct bt_hci_rp_mesh_advertise_cancel { - u8_t status; - u8_t opcode; - u8_t adv_slot; + u8_t status; + u8_t opcode; + u8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_SET_SCANNING 0x05 struct bt_hci_cp_mesh_set_scanning { - u8_t enable; - u8_t ch_map; - u8_t scan_filter; + u8_t enable; + u8_t ch_map; + u8_t scan_filter; } __packed; struct bt_hci_rp_mesh_set_scanning { - u8_t status; - u8_t opcode; + u8_t status; + u8_t opcode; } __packed; /* Events */ struct bt_hci_evt_mesh { - u8_t prefix; - u8_t subevent; + u8_t prefix; + u8_t subevent; } __packed; #define BT_HCI_EVT_MESH_ADV_COMPLETE 0x00 struct bt_hci_evt_mesh_adv_complete { - u8_t adv_slot; + u8_t adv_slot; } __packed; #define BT_HCI_EVT_MESH_SCANNING_REPORT 0x01 struct bt_hci_evt_mesh_scan_report { - bt_addr_le_t addr; - u8_t chan; - s8_t rssi; - u32_t instant; - u8_t data_len; - u8_t data[0]; + bt_addr_le_t addr; + u8_t chan; + s8_t rssi; + u32_t instant; + u8_t data_len; + u8_t data[0]; } __packed; struct bt_hci_evt_mesh_scanning_report { - u8_t num_reports; - struct bt_hci_evt_mesh_scan_report reports[0]; + u8_t num_reports; + struct bt_hci_evt_mesh_scan_report reports[0]; } __packed; #ifdef __cplusplus diff --git a/components/network/ble/blestack/src/include/bluetooth/l2cap.h b/components/network/ble/blestack/src/include/bluetooth/l2cap.h index de1fc9aa..f3f512c3 100644 --- a/components/network/ble/blestack/src/include/bluetooth/l2cap.h +++ b/components/network/ble/blestack/src/include/bluetooth/l2cap.h @@ -38,8 +38,8 @@ extern "C" { * @return Needed buffer size to match the requested L2CAP MTU. */ #define BT_L2CAP_BUF_SIZE(mtu) (BT_BUF_RESERVE + \ - BT_HCI_ACL_HDR_SIZE + BT_L2CAP_HDR_SIZE + \ - (mtu)) + BT_HCI_ACL_HDR_SIZE + BT_L2CAP_HDR_SIZE + \ + (mtu)) struct bt_l2cap_chan; @@ -55,82 +55,82 @@ typedef void (*bt_l2cap_chan_destroy_t)(struct bt_l2cap_chan *chan); * context. */ typedef enum bt_l2cap_chan_state { - /** Channel disconnected */ - BT_L2CAP_DISCONNECTED, - /** Channel in connecting state */ - BT_L2CAP_CONNECT, - /** Channel in config state, BR/EDR specific */ - BT_L2CAP_CONFIG, - /** Channel ready for upper layer traffic on it */ - BT_L2CAP_CONNECTED, - /** Channel in disconnecting state */ - BT_L2CAP_DISCONNECT, + /** Channel disconnected */ + BT_L2CAP_DISCONNECTED, + /** Channel in connecting state */ + BT_L2CAP_CONNECT, + /** Channel in config state, BR/EDR specific */ + BT_L2CAP_CONFIG, + /** Channel ready for upper layer traffic on it */ + BT_L2CAP_CONNECTED, + /** Channel in disconnecting state */ + BT_L2CAP_DISCONNECT, } __packed bt_l2cap_chan_state_t; /** @brief Status of L2CAP channel. */ typedef enum bt_l2cap_chan_status { - /** Channel output status */ - BT_L2CAP_STATUS_OUT, + /** Channel output status */ + BT_L2CAP_STATUS_OUT, - /* Total number of status - must be at the end of the enum */ - BT_L2CAP_NUM_STATUS, + /* Total number of status - must be at the end of the enum */ + BT_L2CAP_NUM_STATUS, } __packed bt_l2cap_chan_status_t; /** @brief L2CAP Channel structure. */ struct bt_l2cap_chan { - /** Channel connection reference */ - struct bt_conn *conn; - /** Channel operations reference */ - struct bt_l2cap_chan_ops *ops; - sys_snode_t node; - bt_l2cap_chan_destroy_t destroy; - /* Response Timeout eXpired (RTX) timer */ - struct k_delayed_work rtx_work; - ATOMIC_DEFINE(status, BT_L2CAP_NUM_STATUS); + /** Channel connection reference */ + struct bt_conn *conn; + /** Channel operations reference */ + struct bt_l2cap_chan_ops *ops; + sys_snode_t node; + bt_l2cap_chan_destroy_t destroy; + /* Response Timeout eXpired (RTX) timer */ + struct k_delayed_work rtx_work; + ATOMIC_DEFINE(status, BT_L2CAP_NUM_STATUS); #if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL) - bt_l2cap_chan_state_t state; - /** Remote PSM to be connected */ - u16_t psm; - /** Helps match request context during CoC */ - u8_t ident; - bt_security_t required_sec_level; + bt_l2cap_chan_state_t state; + /** Remote PSM to be connected */ + u16_t psm; + /** Helps match request context during CoC */ + u8_t ident; + bt_security_t required_sec_level; #endif /* CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */ }; /** @brief LE L2CAP Endpoint structure. */ struct bt_l2cap_le_endpoint { - /** Endpoint CID */ - u16_t cid; - /** Endpoint Maximum Transmission Unit */ - u16_t mtu; - /** Endpoint Maximum PDU payload Size */ - u16_t mps; - /** Endpoint initial credits */ - u16_t init_credits; - /** Endpoint credits */ - struct k_sem credits; + /** Endpoint CID */ + u16_t cid; + /** Endpoint Maximum Transmission Unit */ + u16_t mtu; + /** Endpoint Maximum PDU payload Size */ + u16_t mps; + /** Endpoint initial credits */ + u16_t init_credits; + /** Endpoint credits */ + struct k_sem credits; }; /** @brief LE L2CAP Channel structure. */ struct bt_l2cap_le_chan { - /** Common L2CAP channel reference object */ - struct bt_l2cap_chan chan; - /** Channel Receiving Endpoint */ - struct bt_l2cap_le_endpoint rx; - /** Channel Transmission Endpoint */ - struct bt_l2cap_le_endpoint tx; - /** Channel Transmission queue */ - struct k_fifo tx_queue; - /** Channel Pending Transmission buffer */ - struct net_buf *tx_buf; - /** Segment SDU packet from upper layer */ - struct net_buf *_sdu; - u16_t _sdu_len; + /** Common L2CAP channel reference object */ + struct bt_l2cap_chan chan; + /** Channel Receiving Endpoint */ + struct bt_l2cap_le_endpoint rx; + /** Channel Transmission Endpoint */ + struct bt_l2cap_le_endpoint tx; + /** Channel Transmission queue */ + struct k_fifo tx_queue; + /** Channel Pending Transmission buffer */ + struct net_buf *tx_buf; + /** Segment SDU packet from upper layer */ + struct net_buf *_sdu; + u16_t _sdu_len; - struct k_work rx_work; - struct k_fifo rx_queue; + struct k_work rx_work; + struct k_fifo rx_queue; }; /** @def BT_L2CAP_LE_CHAN(_ch) @@ -146,104 +146,104 @@ struct bt_l2cap_le_chan { /** @brief BREDR L2CAP Endpoint structure. */ struct bt_l2cap_br_endpoint { - /** Endpoint CID */ - u16_t cid; - /** Endpoint Maximum Transmission Unit */ - u16_t mtu; + /** Endpoint CID */ + u16_t cid; + /** Endpoint Maximum Transmission Unit */ + u16_t mtu; }; /** @brief BREDR L2CAP Channel structure. */ struct bt_l2cap_br_chan { - /** Common L2CAP channel reference object */ - struct bt_l2cap_chan chan; - /** Channel Receiving Endpoint */ - struct bt_l2cap_br_endpoint rx; - /** Channel Transmission Endpoint */ - struct bt_l2cap_br_endpoint tx; - /* For internal use only */ - atomic_t flags[1]; + /** Common L2CAP channel reference object */ + struct bt_l2cap_chan chan; + /** Channel Receiving Endpoint */ + struct bt_l2cap_br_endpoint rx; + /** Channel Transmission Endpoint */ + struct bt_l2cap_br_endpoint tx; + /* For internal use only */ + atomic_t flags[1]; }; /** @brief L2CAP Channel operations structure. */ struct bt_l2cap_chan_ops { - /** Channel connected callback - * - * If this callback is provided it will be called whenever the - * connection completes. - * - * @param chan The channel that has been connected - */ - void (*connected)(struct bt_l2cap_chan *chan); + /** Channel connected callback + * + * If this callback is provided it will be called whenever the + * connection completes. + * + * @param chan The channel that has been connected + */ + void (*connected)(struct bt_l2cap_chan *chan); - /** Channel disconnected callback - * - * If this callback is provided it will be called whenever the - * channel is disconnected, including when a connection gets - * rejected. - * - * @param chan The channel that has been Disconnected - */ - void (*disconnected)(struct bt_l2cap_chan *chan); + /** Channel disconnected callback + * + * If this callback is provided it will be called whenever the + * channel is disconnected, including when a connection gets + * rejected. + * + * @param chan The channel that has been Disconnected + */ + void (*disconnected)(struct bt_l2cap_chan *chan); - /** Channel encrypt_change callback - * - * If this callback is provided it will be called whenever the - * security level changed (indirectly link encryption done) or - * authentication procedure fails. In both cases security initiator - * and responder got the final status (HCI status) passed by - * related to encryption and authentication events from local host's - * controller. - * - * @param chan The channel which has made encryption status changed. - * @param status HCI status of performed security procedure caused - * by channel security requirements. The value is populated - * by HCI layer and set to 0 when success and to non-zero (reference to - * HCI Error Codes) when security/authentication failed. - */ - void (*encrypt_change)(struct bt_l2cap_chan *chan, u8_t hci_status); + /** Channel encrypt_change callback + * + * If this callback is provided it will be called whenever the + * security level changed (indirectly link encryption done) or + * authentication procedure fails. In both cases security initiator + * and responder got the final status (HCI status) passed by + * related to encryption and authentication events from local host's + * controller. + * + * @param chan The channel which has made encryption status changed. + * @param status HCI status of performed security procedure caused + * by channel security requirements. The value is populated + * by HCI layer and set to 0 when success and to non-zero (reference to + * HCI Error Codes) when security/authentication failed. + */ + void (*encrypt_change)(struct bt_l2cap_chan *chan, u8_t hci_status); - /** Channel alloc_buf callback - * - * If this callback is provided the channel will use it to allocate - * buffers to store incoming data. - * - * @param chan The channel requesting a buffer. - * - * @return Allocated buffer. - */ - struct net_buf *(*alloc_buf)(struct bt_l2cap_chan *chan); + /** Channel alloc_buf callback + * + * If this callback is provided the channel will use it to allocate + * buffers to store incoming data. + * + * @param chan The channel requesting a buffer. + * + * @return Allocated buffer. + */ + struct net_buf *(*alloc_buf)(struct bt_l2cap_chan *chan); - /** Channel recv callback - * - * @param chan The channel receiving data. - * @param buf Buffer containing incoming data. - * - * @return 0 in case of success or negative value in case of error. - * If -EINPROGRESS is returned user has to confirm once the data has - * been processed by calling bt_l2cap_chan_recv_complete passing back - * the buffer received with its original user_data which contains the - * number of segments/credits used by the packet. - */ - int (*recv)(struct bt_l2cap_chan *chan, struct net_buf *buf); + /** Channel recv callback + * + * @param chan The channel receiving data. + * @param buf Buffer containing incoming data. + * + * @return 0 in case of success or negative value in case of error. + * If -EINPROGRESS is returned user has to confirm once the data has + * been processed by calling bt_l2cap_chan_recv_complete passing back + * the buffer received with its original user_data which contains the + * number of segments/credits used by the packet. + */ + int (*recv)(struct bt_l2cap_chan *chan, struct net_buf *buf); - /* Channel sent callback - * - * If this callback is provided it will be called whenever a SDU has - * been completely sent. - * - * @param chan The channel which has sent data. - */ - void (*sent)(struct bt_l2cap_chan *chan); + /* Channel sent callback + * + * If this callback is provided it will be called whenever a SDU has + * been completely sent. + * + * @param chan The channel which has sent data. + */ + void (*sent)(struct bt_l2cap_chan *chan); - /* Channel status callback - * - * If this callback is provided it will be called whenever the - * channel status changes. - * - * @param chan The channel which status changed - * @param status The channel status - */ - void (*status)(struct bt_l2cap_chan *chan, atomic_t *status); + /* Channel status callback + * + * If this callback is provided it will be called whenever the + * channel status changes. + * + * @param chan The channel which status changed + * @param status The channel status + */ + void (*status)(struct bt_l2cap_chan *chan, atomic_t *status); }; /** @def BT_L2CAP_CHAN_SEND_RESERVE @@ -253,40 +253,40 @@ struct bt_l2cap_chan_ops { /** @brief L2CAP Server structure. */ struct bt_l2cap_server { - /** Server PSM. Possible values: - * - * 0 A dynamic value will be auto-allocated when - * bt_l2cap_server_register() is called. - * - * 0x0001-0x007f Standard, Bluetooth SIG-assigned fixed values. - * - * 0x0080-0x00ff Dynamically allocated. May be pre-set by the - * application before server registration (not - * recommended however), or auto-allocated by the - * stack if the app gave 0 as the value. - */ - u16_t psm; + /** Server PSM. Possible values: + * + * 0 A dynamic value will be auto-allocated when + * bt_l2cap_server_register() is called. + * + * 0x0001-0x007f Standard, Bluetooth SIG-assigned fixed values. + * + * 0x0080-0x00ff Dynamically allocated. May be pre-set by the + * application before server registration (not + * recommended however), or auto-allocated by the + * stack if the app gave 0 as the value. + */ + u16_t psm; - /** Required minimim security level */ - bt_security_t sec_level; + /** Required minimim security level */ + bt_security_t sec_level; - /** Server accept callback - * - * This callback is called whenever a new incoming connection requires - * authorization. - * - * @param conn The connection that is requesting authorization - * @param chan Pointer to received the allocated channel - * - * @return 0 in case of success or negative value in case of error. - * Possible return values: - * -ENOMEM if no available space for new channel. - * -EACCES if application did not authorize the connection. - * -EPERM if encryption key size is too short. - */ - int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); + /** Server accept callback + * + * This callback is called whenever a new incoming connection requires + * authorization. + * + * @param conn The connection that is requesting authorization + * @param chan Pointer to received the allocated channel + * + * @return 0 in case of success or negative value in case of error. + * Possible return values: + * -ENOMEM if no available space for new channel. + * -EACCES if application did not authorize the connection. + * -EPERM if encryption key size is too short. + */ + int (*accept)(struct bt_conn *conn, struct bt_l2cap_chan **chan); - sys_snode_t node; + sys_snode_t node; }; /** @brief Register L2CAP server. @@ -341,7 +341,7 @@ int bt_l2cap_br_server_register(struct bt_l2cap_server *server); * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_chan_connect(struct bt_conn *conn, struct bt_l2cap_chan *chan, - u16_t psm); + u16_t psm); /** @brief Disconnect L2CAP channel * @@ -380,7 +380,7 @@ int bt_l2cap_chan_send(struct bt_l2cap_chan *chan, struct net_buf *buf); * @return 0 in case of success or negative value in case of error. */ int bt_l2cap_chan_recv_complete(struct bt_l2cap_chan *chan, - struct net_buf *buf); + struct net_buf *buf); #ifdef __cplusplus } diff --git a/components/network/ble/blestack/src/include/bluetooth/uuid.h b/components/network/ble/blestack/src/include/bluetooth/uuid.h index b782cadd..df780e90 100644 --- a/components/network/ble/blestack/src/include/bluetooth/uuid.h +++ b/components/network/ble/blestack/src/include/bluetooth/uuid.h @@ -25,55 +25,55 @@ extern "C" { /** @brief Bluetooth UUID types */ enum { - BT_UUID_TYPE_16, - BT_UUID_TYPE_32, - BT_UUID_TYPE_128, + BT_UUID_TYPE_16, + BT_UUID_TYPE_32, + BT_UUID_TYPE_128, }; /** @brief This is a 'tentative' type and should be used as a pointer only */ struct bt_uuid { - u8_t type; + u8_t type; }; struct bt_uuid_16 { - struct bt_uuid uuid; - u16_t val; + struct bt_uuid uuid; + u16_t val; }; struct bt_uuid_32 { - struct bt_uuid uuid; - u32_t val; + struct bt_uuid uuid; + u32_t val; }; struct bt_uuid_128 { - struct bt_uuid uuid; - u8_t val[16]; + struct bt_uuid uuid; + u8_t val[16]; }; -#define BT_UUID_INIT_16(value) \ -{ \ - .uuid = { BT_UUID_TYPE_16 }, \ - .val = (value), \ +#define BT_UUID_INIT_16(value) \ +{ \ + .uuid = { BT_UUID_TYPE_16 }, \ + .val = (value), \ } -#define BT_UUID_INIT_32(value) \ -{ \ - .uuid = { BT_UUID_TYPE_32 }, \ - .val = (value), \ +#define BT_UUID_INIT_32(value) \ +{ \ + .uuid = { BT_UUID_TYPE_32 }, \ + .val = (value), \ } -#define BT_UUID_INIT_128(value...) \ -{ \ - .uuid = { BT_UUID_TYPE_128 }, \ - .val = { value }, \ +#define BT_UUID_INIT_128(value...) \ +{ \ + .uuid = { BT_UUID_TYPE_128 }, \ + .val = { value }, \ } #define BT_UUID_DECLARE_16(value) \ - ((struct bt_uuid *) (&(struct bt_uuid_16) BT_UUID_INIT_16(value))) + ((struct bt_uuid *) (&(struct bt_uuid_16) BT_UUID_INIT_16(value))) #define BT_UUID_DECLARE_32(value) \ - ((struct bt_uuid *) (&(struct bt_uuid_32) BT_UUID_INIT_32(value))) + ((struct bt_uuid *) (&(struct bt_uuid_32) BT_UUID_INIT_32(value))) #define BT_UUID_DECLARE_128(value...) \ - ((struct bt_uuid *) (&(struct bt_uuid_128) BT_UUID_INIT_128(value))) + ((struct bt_uuid *) (&(struct bt_uuid_128) BT_UUID_INIT_128(value))) #define BT_UUID_16(__u) CONTAINER_OF(__u, struct bt_uuid_16, uuid) #define BT_UUID_32(__u) CONTAINER_OF(__u, struct bt_uuid_32, uuid) @@ -107,22 +107,22 @@ struct bt_uuid_128 { * @ref BT_UUID_INIT_128 or @ref BT_UUID_DECLARE_128 */ #define BT_UUID_128_ENCODE(w32, w1, w2, w3, w48) \ - (((w48) >> 0) & 0xFF), \ - (((w48) >> 8) & 0xFF), \ - (((w48) >> 16) & 0xFF), \ - (((w48) >> 24) & 0xFF), \ - (((w48) >> 32) & 0xFF), \ - (((w48) >> 40) & 0xFF), \ - (((w3) >> 0) & 0xFF), \ - (((w3) >> 8) & 0xFF), \ - (((w2) >> 0) & 0xFF), \ - (((w2) >> 8) & 0xFF), \ - (((w1) >> 0) & 0xFF), \ - (((w1) >> 8) & 0xFF), \ - (((w32) >> 0) & 0xFF), \ - (((w32) >> 8) & 0xFF), \ - (((w32) >> 16) & 0xFF), \ - (((w32) >> 24) & 0xFF) + (((w48) >> 0) & 0xFF), \ + (((w48) >> 8) & 0xFF), \ + (((w48) >> 16) & 0xFF), \ + (((w48) >> 24) & 0xFF), \ + (((w48) >> 32) & 0xFF), \ + (((w48) >> 40) & 0xFF), \ + (((w3) >> 0) & 0xFF), \ + (((w3) >> 8) & 0xFF), \ + (((w2) >> 0) & 0xFF), \ + (((w2) >> 8) & 0xFF), \ + (((w1) >> 0) & 0xFF), \ + (((w1) >> 8) & 0xFF), \ + (((w32) >> 0) & 0xFF), \ + (((w32) >> 8) & 0xFF), \ + (((w32) >> 16) & 0xFF), \ + (((w32) >> 24) & 0xFF) @@ -478,40 +478,40 @@ struct bt_uuid_128 { #define BT_UUID_GATT_DB_HASH BT_UUID_DECLARE_16(0x2b2a) #if defined(CONFIG_BT_STACK_PTS) && defined(PTS_GAP_SLAVER_CONFIG_READ_CHARC) -#define BT_UUID_PTS BT_UUID_DECLARE_16(0x2b2b) -#define BT_UUID_PTS_CHAR_READ_AUTHEN BT_UUID_DECLARE_16(0x2b2c) -#define BT_UUID_PTS_CHAR_READ_NOPERM BT_UUID_DECLARE_16(0x2b2d) -#define BT_UUID_PTS_CHAR_READ_LONGVAL BT_UUID_DECLARE_16(0x2b2e) -#define BT_UUID_PTS_CHAR_READ_L_NOPERM BT_UUID_DECLARE_16(0x2b2f) -#define BT_UUID_PTS_CHAR_READ_LVAL_REF BT_UUID_DECLARE_16(0x2b30) +#define BT_UUID_PTS BT_UUID_DECLARE_16(0x2b2b) +#define BT_UUID_PTS_CHAR_READ_AUTHEN BT_UUID_DECLARE_16(0x2b2c) +#define BT_UUID_PTS_CHAR_READ_NOPERM BT_UUID_DECLARE_16(0x2b2d) +#define BT_UUID_PTS_CHAR_READ_LONGVAL BT_UUID_DECLARE_16(0x2b2e) +#define BT_UUID_PTS_CHAR_READ_L_NOPERM BT_UUID_DECLARE_16(0x2b2f) +#define BT_UUID_PTS_CHAR_READ_LVAL_REF BT_UUID_DECLARE_16(0x2b30) #endif #if defined(CONFIG_BT_STACK_PTS)&& defined(PTS_GAP_SLAVER_CONFIG_WRITE_CHARC) -#define BT_UUID_PTS_CHAR_WRITE_VALUE BT_UUID_DECLARE_16(0x2b31) -#define BT_UUID_PTS_CHAR_WRITE_AUTHEN BT_UUID_DECLARE_16(0x2b32) -#define BT_UUID_PTS_CHAR_WRITE_LONGVAL BT_UUID_DECLARE_16(0x2b33) -#define BT_UUID_PTS_CHAR_WRITE_NORSP BT_UUID_DECLARE_16(0x2b34) -#define BT_UUID_PTS_CHAR_WRITE_2LONGVAL BT_UUID_DECLARE_16(0x2b35) -#define BT_UUID_PTS_CHAR_WRITE_L_DES BT_UUID_DECLARE_16(0x2b36) +#define BT_UUID_PTS_CHAR_WRITE_VALUE BT_UUID_DECLARE_16(0x2b31) +#define BT_UUID_PTS_CHAR_WRITE_AUTHEN BT_UUID_DECLARE_16(0x2b32) +#define BT_UUID_PTS_CHAR_WRITE_LONGVAL BT_UUID_DECLARE_16(0x2b33) +#define BT_UUID_PTS_CHAR_WRITE_NORSP BT_UUID_DECLARE_16(0x2b34) +#define BT_UUID_PTS_CHAR_WRITE_2LONGVAL BT_UUID_DECLARE_16(0x2b35) +#define BT_UUID_PTS_CHAR_WRITE_L_DES BT_UUID_DECLARE_16(0x2b36) #endif #if defined(CONFIG_BT_STACK_PTS)&& defined(PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC) -#define BT_UUID_PTS_CHAR_NOTIFY_CHAR BT_UUID_DECLARE_16(0x2b37) +#define BT_UUID_PTS_CHAR_NOTIFY_CHAR BT_UUID_DECLARE_16(0x2b37) #endif #if defined(CONFIG_BT_STACK_PTS)&& defined(PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC) -#define BT_UUID_PTS_CHAR_INDICATE_CHAR BT_UUID_DECLARE_16(0x2b38) +#define BT_UUID_PTS_CHAR_INDICATE_CHAR BT_UUID_DECLARE_16(0x2b38) #endif #if defined(CONFIG_BT_STACK_PTS) && defined(PTS_TEST_CASE_INSUFFICIENT_KEY) -#define BT_UUID_PTS_ENC_KEY BT_UUID_DECLARE_16(0x2b3a) +#define BT_UUID_PTS_ENC_KEY BT_UUID_DECLARE_16(0x2b3a) #endif #if defined(CONFIG_BT_STACK_PTS) && defined(PTS_CHARC_LEN_EQUAL_MTU_SIZE) -#define BT_UUID_PTS_READ_MTU_SIZE_CHAR BT_UUID_DECLARE_16(0x2b3b) +#define BT_UUID_PTS_READ_MTU_SIZE_CHAR BT_UUID_DECLARE_16(0x2b3b) #endif #if defined(CONFIG_BT_STACK_PTS) -#define BT_UUID_PTS_AUTH_CHAR BT_UUID_DECLARE_16(0x2b39) +#define BT_UUID_PTS_AUTH_CHAR BT_UUID_DECLARE_16(0x2b39) #endif /* @@ -600,16 +600,16 @@ const char *bt_uuid_str_real(const struct bt_uuid *uuid); #define bt_uuid_str(_uuid) log_strdup(bt_uuid_str_real(_uuid)) #else static inline void bt_uuid_to_str(const struct bt_uuid *uuid, char *str, - size_t len) + size_t len) { - if (len > 0) { - str[0] = '\0'; - } + if (len > 0) { + str[0] = '\0'; + } } static inline const char *bt_uuid_str(const struct bt_uuid *uuid) { - return ""; + return ""; } #endif /* CONFIG_BT_DEBUG */ diff --git a/components/network/ble/blestack/src/include/drivers/bluetooth/hci_driver.h b/components/network/ble/blestack/src/include/drivers/bluetooth/hci_driver.h index 04839996..c083e63c 100644 --- a/components/network/ble/blestack/src/include/drivers/bluetooth/hci_driver.h +++ b/components/network/ble/blestack/src/include/drivers/bluetooth/hci_driver.h @@ -26,8 +26,8 @@ extern "C" { #endif enum { - /* The host should never send HCI_Reset */ - BT_QUIRK_NO_RESET = BIT(0), + /* The host should never send HCI_Reset */ + BT_QUIRK_NO_RESET = BIT(0), }; /** @@ -46,18 +46,18 @@ enum { */ static inline bool bt_hci_evt_is_prio(u8_t evt) { - switch (evt) { - case BT_HCI_EVT_CMD_COMPLETE: - case BT_HCI_EVT_CMD_STATUS: - /* fallthrough */ + switch (evt) { + case BT_HCI_EVT_CMD_COMPLETE: + case BT_HCI_EVT_CMD_STATUS: + /* fallthrough */ #if defined(CONFIG_BT_CONN) - case BT_HCI_EVT_NUM_COMPLETED_PACKETS: - case BT_HCI_EVT_DATA_BUF_OVERFLOW: + case BT_HCI_EVT_NUM_COMPLETED_PACKETS: + case BT_HCI_EVT_DATA_BUF_OVERFLOW: #endif - return true; - default: - return false; - } + return true; + default: + return false; + } } /** @@ -96,16 +96,16 @@ int bt_recv_prio(struct net_buf *buf); /** Possible values for the 'bus' member of the bt_hci_driver struct */ enum bt_hci_driver_bus { - BT_HCI_DRIVER_BUS_VIRTUAL = 0, - BT_HCI_DRIVER_BUS_USB = 1, - BT_HCI_DRIVER_BUS_PCCARD = 2, - BT_HCI_DRIVER_BUS_UART = 3, - BT_HCI_DRIVER_BUS_RS232 = 4, - BT_HCI_DRIVER_BUS_PCI = 5, - BT_HCI_DRIVER_BUS_SDIO = 6, - BT_HCI_DRIVER_BUS_SPI = 7, - BT_HCI_DRIVER_BUS_I2C = 8, - BT_HCI_DRIVER_BUS_IPM = 9, + BT_HCI_DRIVER_BUS_VIRTUAL = 0, + BT_HCI_DRIVER_BUS_USB = 1, + BT_HCI_DRIVER_BUS_PCCARD = 2, + BT_HCI_DRIVER_BUS_UART = 3, + BT_HCI_DRIVER_BUS_RS232 = 4, + BT_HCI_DRIVER_BUS_PCI = 5, + BT_HCI_DRIVER_BUS_SDIO = 6, + BT_HCI_DRIVER_BUS_SPI = 7, + BT_HCI_DRIVER_BUS_I2C = 8, + BT_HCI_DRIVER_BUS_IPM = 9, }; /** @@ -115,47 +115,47 @@ enum bt_hci_driver_bus { * controller. */ struct bt_hci_driver { - /** Name of the driver */ - const char *name; + /** Name of the driver */ + const char *name; - /** Bus of the transport (BT_HCI_DRIVER_BUS_*) */ - enum bt_hci_driver_bus bus; + /** Bus of the transport (BT_HCI_DRIVER_BUS_*) */ + enum bt_hci_driver_bus bus; - /** Specific controller quirks. These are set by the HCI driver - * and acted upon by the host. They can either be statically - * set at buildtime, or set at runtime before the HCI driver's - * open() callback returns. - */ - u32_t quirks; + /** Specific controller quirks. These are set by the HCI driver + * and acted upon by the host. They can either be statically + * set at buildtime, or set at runtime before the HCI driver's + * open() callback returns. + */ + u32_t quirks; - /** - * @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. - * - * If the driver uses its own RX thread, i.e. - * CONFIG_BT_RECV_IS_RX_THREAD is set, then this - * function is expected to start that thread. - * - * @return 0 on success or negative error number on failure. - */ - int (*open)(void); + /** + * @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. + * + * If the driver uses its own RX thread, i.e. + * CONFIG_BT_RECV_IS_RX_THREAD is set, then this + * function is expected to start that thread. + * + * @return 0 on success or negative error number on failure. + */ + int (*open)(void); - /** - * @brief Send HCI buffer to controller. - * - * Send an HCI command or ACL data to the controller. The exact - * type of the data can be checked with the help of bt_buf_get_type(). - * - * @note This function must only be called from a cooperative thread. - * - * @param buf Buffer containing data to be sent to the controller. - * - * @return 0 on success or negative error number on failure. - */ - int (*send)(struct net_buf *buf); + /** + * @brief Send HCI buffer to controller. + * + * Send an HCI command or ACL data to the controller. The exact + * type of the data can be checked with the help of bt_buf_get_type(). + * + * @note This function must only be called from a cooperative thread. + * + * @param buf Buffer containing data to be sent to the controller. + * + * @return 0 on success or negative error number on failure. + */ + int (*send)(struct net_buf *buf); }; /** @@ -183,7 +183,7 @@ int bt_hci_driver_register(const struct bt_hci_driver *drv); * @return 0 on success, negative error value on failure */ int bt_hci_transport_setup(struct device *dev); -#endif +#endif #if defined(BFLB_BLE) /** diff --git a/components/network/ble/blestack/src/port/bl_port.c b/components/network/ble/blestack/src/port/bl_port.c index 1e89a458..2952f2b1 100644 --- a/components/network/ble/blestack/src/port/bl_port.c +++ b/components/network/ble/blestack/src/port/bl_port.c @@ -36,7 +36,7 @@ void k_queue_insert(struct k_queue *queue, void *prev, void *data) { BaseType_t ret; (void) ret; - + ret = xQueueSend(queue->hdl, &data, portMAX_DELAY); BT_ASSERT(ret == pdPASS); } @@ -49,7 +49,7 @@ void k_queue_append(struct k_queue *queue, void *data) void k_queue_insert_from_isr(struct k_queue *queue, void *prev, void *data) { BaseType_t xHigherPriorityTaskWoken; - + xQueueSendFromISR(queue->hdl, &data, &xHigherPriorityTaskWoken); if(xHigherPriorityTaskWoken == pdTRUE) { @@ -69,7 +69,7 @@ void k_queue_free(struct k_queue *queue) BT_ERR("Queue is NULL\n"); return; } - + vQueueDelete(queue->hdl); queue->hdl = NULL; return; @@ -157,7 +157,7 @@ int k_sem_give(struct k_sem *sem) { BaseType_t ret; (void) ret; - + if (NULL == sem) { BT_ERR("sem is NULL\n"); return -EINVAL; @@ -213,7 +213,7 @@ int k_thread_create(struct k_thread *new_thread, const char *name, { stack_size /= sizeof(StackType_t); xTaskCreate(entry, name, stack_size, NULL, prio, (void *)(&new_thread->task)); - + return new_thread->task? 0 : -1; } @@ -224,7 +224,7 @@ void k_thread_delete(struct k_thread *new_thread) BT_ERR("task is NULL\n"); return; } - + vTaskDelete((void *)(new_thread->task)); new_thread->task = 0; return; @@ -245,13 +245,13 @@ void k_sleep(s32_t dur_ms) unsigned int irq_lock(void) { - taskENTER_CRITICAL(); + taskENTER_CRITICAL(); return 1; } void irq_unlock(unsigned int key) { - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); } int k_is_in_isr(void) @@ -272,7 +272,7 @@ void k_timer_init(k_timer_t *timer, k_timer_handler_t handle, void *args) timer->handler = handle; timer->args = args; - timer->timer.hdl = xTimerCreate("Timer", pdMS_TO_TICKS(1000), 0, 0, (TimerCallbackFunction_t)(timer->handler)); + timer->timer.hdl = xTimerCreate("Timer", pdMS_TO_TICKS(1000), 0, 0, (TimerCallbackFunction_t)(timer->handler)); BT_ASSERT(timer->timer.hdl != NULL); } @@ -280,7 +280,7 @@ void k_timer_start(k_timer_t *timer, uint32_t timeout) { BaseType_t ret; (void) ret; - + BT_ASSERT(timer != NULL); timer->timeout = timeout; timer->start_ms = k_now_ms(); @@ -299,7 +299,7 @@ void k_timer_stop(k_timer_t *timer) (void) ret; BT_ASSERT(timer != NULL); - + ret = xTimerStop(timer->timer.hdl, 0); BT_ASSERT(ret == pdPASS); } @@ -308,16 +308,16 @@ void k_timer_delete(k_timer_t *timer) { BaseType_t ret; (void) ret; - + BT_ASSERT(timer != NULL); - + ret = xTimerDelete(timer->timer.hdl, 0); BT_ASSERT(ret == pdPASS); } long long k_now_ms(void) { - return (long long)(xTaskGetTickCount() * 1000)/configTICK_RATE_HZ; + return (long long)(xTaskGetTickCount() * 1000)/configTICK_RATE_HZ; } void k_get_random_byte_array(uint8_t *buf, size_t len) diff --git a/components/network/ble/blestack/src/port/include/bl_port.h b/components/network/ble/blestack/src/port/include/bl_port.h index 14e744be..83ef8559 100644 --- a/components/network/ble/blestack/src/port/include/bl_port.h +++ b/components/network/ble/blestack/src/port/include/bl_port.h @@ -40,9 +40,9 @@ typedef uint32_t _task_t; _K_SEM_INITIALIZER(name, initial_count, count_limit) #define K_MUTEX_DEFINE(name) \ - struct k_mutex name \ - __in_section(_k_mutex, static, name) = \ - _K_MUTEX_INITIALIZER(name) + struct k_mutex name \ + __in_section(_k_mutex, static, name) = \ + _K_MUTEX_INITIALIZER(name) typedef sys_dlist_t _wait_q_t; @@ -226,7 +226,7 @@ typedef void (*k_thread_entry_t)(void *args); int k_thread_create(struct k_thread *new_thread, const char *name, size_t stack_size, k_thread_entry_t entry, int prio); - + void k_thread_delete(struct k_thread *new_thread); /** diff --git a/components/network/ble/blestack/src/port/include/config.h b/components/network/ble/blestack/src/port/include/config.h index 60518197..5c142b02 100644 --- a/components/network/ble/blestack/src/port/include/config.h +++ b/components/network/ble/blestack/src/port/include/config.h @@ -20,28 +20,28 @@ #if defined(CONFIG_BT_STACK_PTS) #ifndef PTS_CHARC_LEN_EQUAL_MTU_SIZE -#define PTS_CHARC_LEN_EQUAL_MTU_SIZE +#define PTS_CHARC_LEN_EQUAL_MTU_SIZE #endif //#ifndef CONFIG_BT_STACK_PTS_SM_SLA_KDU_BI_01 -//#define CONFIG_BT_STACK_PTS_SM_SLA_KDU_BI_01 +//#define CONFIG_BT_STACK_PTS_SM_SLA_KDU_BI_01 //#endif //#ifndef PTS_GAP_SLAVER_CONFIG_READ_CHARC -//#define PTS_GAP_SLAVER_CONFIG_READ_CHARC +//#define PTS_GAP_SLAVER_CONFIG_READ_CHARC //#endif //#ifndef PTS_GAP_SLAVER_CONFIG_WRITE_CHARC -//#define PTS_GAP_SLAVER_CONFIG_WRITE_CHARC +//#define PTS_GAP_SLAVER_CONFIG_WRITE_CHARC //#endif //#ifndef PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC -//#define PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC +//#define PTS_GAP_SLAVER_CONFIG_NOTIFY_CHARC //#endif //#ifndef PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC -//#define PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC +//#define PTS_GAP_SLAVER_CONFIG_INDICATE_CHARC //#endif #endif @@ -167,10 +167,10 @@ #define CONFIG_BT_CONN 1 #endif -#ifdef CONFIG_BT_CONN +#ifdef CONFIG_BT_CONN #ifndef CONFIG_BT_CREATE_CONN_TIMEOUT -#define CONFIG_BT_CREATE_CONN_TIMEOUT 3 +#define CONFIG_BT_CREATE_CONN_TIMEOUT 3 #endif #if defined(BFLB_BLE) diff --git a/components/network/ble/blestack/src/profiles/oad/oad_api.c b/components/network/ble/blestack/src/profiles/oad/oad_api.c index 1e3388f3..6da0050b 100644 --- a/components/network/ble/blestack/src/profiles/oad/oad_api.c +++ b/components/network/ble/blestack/src/profiles/oad/oad_api.c @@ -14,7 +14,7 @@ static app_check_oad_cb app_check_cb = NULL; struct oad_env_tag oad_env; -#define UPGRD_TIMEOUT K_SECONDS(2) +#define UPGRD_TIMEOUT K_SECONDS(2) static bool check_data_valid(struct oad_file_info *file_info) @@ -34,7 +34,7 @@ static void oad_notify_block_req(struct bt_conn *conn) *(buf->data) = OAD_CMD_IMAG_BLOCK_REQ; block_req = (struct oad_block_req_t *)(buf->data+1); buf->len = sizeof(struct oad_block_req_t) + OAD_OPCODE_SIZE; - + block_req->file_info.file_ver = oad_env.upgrd_file_ver; block_req->file_info.manu_code = oad_env.file_info.manu_code; block_req->file_offset = oad_env.upgrd_offset; @@ -54,7 +54,7 @@ static void oad_notify_upgrd_end(struct bt_conn *conn, u8_t status) k_delayed_work_submit(&oad_env.upgrd_work, UPGRD_TIMEOUT); } #endif - + net_buf_simple_init(buf, 0); *(buf->data) = OAD_CMD_IMAG_UPGRD_END; upgrd_end = (struct oad_upgrd_end_t *)(buf->data+1); @@ -114,7 +114,7 @@ static void oad_upgrade(struct k_work *work) ptEntry.activeIndex = 1 - ptEntry.activeIndex; bl_print(PRINT_UART0, PRINT_MODULE_APP,"update ptable,active index is %d\r\n", ptEntry.activeIndex); hal_boot2_update_ptable(&ptEntry); - XIP_SFlash_Exit_Cont_Read(); + XIP_SFlash_Exit_Cont_Read(); oad_systemReset(); } else @@ -127,9 +127,9 @@ static u8_t oad_get_new_image_addr(void) { PtTable_Entry_Config ptEntry; u8_t active_idx; - + if (0 == hal_boot2_get_active_entries(PT_ENTRY_FW_CPU0, &ptEntry)) - { + { active_idx = 1 - ptEntry.activeIndex; oad_env.new_img_addr = ptEntry.Address[active_idx]; bl_print(PRINT_UART0, PRINT_MODULE_APP,"oad_get_new_image_addr,addr is %d\r\n", oad_env.new_img_addr); @@ -137,14 +137,14 @@ static u8_t oad_get_new_image_addr(void) } return -1; -} +} #endif //CFG_BOOT2_ENABLED static u8_t oad_write_flash(u8_t *data, u16_t len) { #if defined(CFG_BOOT2_ENABLED) if(!oad_env.new_img_addr) - { + { if(oad_get_new_image_addr()){ bl_print(PRINT_UART0, PRINT_MODULE_APP,"New img address is null\r\n"); return -1; @@ -158,7 +158,7 @@ static u8_t oad_write_flash(u8_t *data, u16_t len) XIP_SFlash_Write_With_Lock(CPU_TYPE_NP, oad_env.new_img_addr + oad_env.upgrd_offset, data, len); bl_print(PRINT_UART0, PRINT_MODULE_APP,"Write complete addr = 0x%x \r\n", oad_env.new_img_addr + oad_env.upgrd_offset); #endif - return 0; + return 0; } static u8_t oad_image_data_handler(u8_t *data, u16_t len) @@ -172,7 +172,7 @@ static u8_t oad_image_data_handler(u8_t *data, u16_t len) return OAD_UPGRD_CMPLT; }else{ return OAD_REQ_MORE_DATA; - } + } } static u8_t oad_image_block_resp_handler(struct bt_conn *conn, const u8_t *data, u16_t len) @@ -197,11 +197,11 @@ static u8_t oad_image_block_resp_handler(struct bt_conn *conn, const u8_t *data, rsp_data = data + OAD_BLK_RSP_DATA_OFFSET; status = oad_image_data_handler(rsp_data, block_rsp->data_size); if(status == OAD_UPGRD_CMPLT){ - oad_notify_upgrd_end(conn, OAD_SUCC); + oad_notify_upgrd_end(conn, OAD_SUCC); }else if(status == OAD_REQ_MORE_DATA){ oad_notify_block_req(conn); }else{ - oad_notify_upgrd_end(conn, status); + oad_notify_upgrd_end(conn, status); } } break; @@ -210,7 +210,7 @@ static u8_t oad_image_block_resp_handler(struct bt_conn *conn, const u8_t *data, XIP_SFlash_Erase_With_Lock(CPU_TYPE_NP, oad_env.new_img_addr, oad_env.upgrd_file_size); } break; - + default: status = OAD_MALORMED_CMD; @@ -221,29 +221,29 @@ static u8_t oad_image_block_resp_handler(struct bt_conn *conn, const u8_t *data, static void oad_image_identity_handler(struct bt_conn *conn, const u8_t *data, u16_t len) { struct oad_image_identity_t *identity; - + identity = (struct oad_image_identity_t *)data; - + if(identity->file_info.manu_code == oad_env.file_info.manu_code && - (app_check_cb)(oad_env.file_info.file_ver, identity->file_info.file_ver)){ + (app_check_cb)(oad_env.file_info.file_ver, identity->file_info.file_ver)){ oad_env.upgrd_file_ver = identity->file_info.file_ver; oad_env.upgrd_file_size = identity->file_size; oad_env.upgrd_offset = 0x00; oad_env.upgrd_crc32 = identity->crc32; - + oad_notify_block_req(conn); }else{ oad_notity_image_identity(conn); } } - + static void oad_recv_callback(struct bt_conn *conn, const u8_t *data, u16_t len) -{ +{ if(*data == OAD_CMD_IMAG_IDENTITY){ oad_image_identity_handler(conn, data+1, len-1); }else{ if(*data == OAD_CMD_IMAG_BLOCK_RESP) - oad_image_block_resp_handler(conn, data+1, len-1); + oad_image_block_resp_handler(conn, data+1, len-1); } } diff --git a/components/network/ble/blestack/src/profiles/oad/oad_service.c b/components/network/ble/blestack/src/profiles/oad/oad_service.c index 02f8bf5c..63a8ba37 100644 --- a/components/network/ble/blestack/src/profiles/oad/oad_service.c +++ b/components/network/ble/blestack/src/profiles/oad/oad_service.c @@ -1,24 +1,24 @@ #include "byteorder.h" #include "oad_service.h" #include "oad.h" - + oad_upper_recv_cb upper_recv_cb; static int oad_recv(struct bt_conn *conn, - const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, const void *buf, + u16_t len, u16_t offset, u8_t flags) { (upper_recv_cb)(conn, buf, len); return 0; } static ssize_t oad_ccc_write(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - const void *buf, u16_t len, - u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, + const void *buf, u16_t len, + u16_t offset, u8_t flags) { uint16_t *value = attr->user_data; - + if(len != sizeof(*value)){ return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); } @@ -29,8 +29,8 @@ static ssize_t oad_ccc_write(struct bt_conn *conn, } static ssize_t oad_ccc_read(struct bt_conn *conn, - const struct bt_gatt_attr *attr, - void *buf, u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, + void *buf, u16_t len, u16_t offset) { u16_t *value = attr->user_data; @@ -52,7 +52,7 @@ static struct bt_gatt_attr oad_attrs[] = { static struct bt_gatt_service oad_svc = BT_GATT_SERVICE(oad_attrs); -void bt_oad_notify(struct bt_conn *conn, const void *data, u16_t len) +void bt_oad_notify(struct bt_conn *conn, const void *data, u16_t len) { bt_gatt_notify(conn, &oad_attrs[2], data, len); } diff --git a/components/network/ble/blestack/src/services/bas.c b/components/network/ble/blestack/src/services/bas.c index e434db8a..d29bdca4 100644 --- a/components/network/ble/blestack/src/services/bas.c +++ b/components/network/ble/blestack/src/services/bas.c @@ -30,34 +30,34 @@ static struct bt_gatt_ccc_cfg blvl_ccc_cfg[BT_GATT_CCC_MAX] = {}; static u8_t battery_level = 100U; static void blvl_ccc_cfg_changed(const struct bt_gatt_attr *attr, - u16_t value) + u16_t value) { - ARG_UNUSED(attr); + ARG_UNUSED(attr); - bool notif_enabled = (value == BT_GATT_CCC_NOTIFY); + bool notif_enabled = (value == BT_GATT_CCC_NOTIFY); #if !defined(BFLB_BLE) - LOG_INF("BAS Notifications %s", notif_enabled ? "enabled" : "disabled"); + LOG_INF("BAS Notifications %s", notif_enabled ? "enabled" : "disabled"); #endif } static ssize_t read_blvl(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - u8_t lvl8 = battery_level; + u8_t lvl8 = battery_level; - return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8, - sizeof(lvl8)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8, + sizeof(lvl8)); } static struct bt_gatt_attr attrs[]= { - BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS), - BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL, - BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, - BT_GATT_PERM_READ, read_blvl, NULL, - &battery_level), - BT_GATT_CCC(blvl_ccc_cfg, blvl_ccc_cfg_changed), + BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS), + BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL, + BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, + BT_GATT_PERM_READ, read_blvl, NULL, + &battery_level), + BT_GATT_CCC(blvl_ccc_cfg, blvl_ccc_cfg_changed), BT_GATT_DESCRIPTOR(BT_UUID_HIDS_REPORT_REF, BT_GATT_PERM_READ, NULL, NULL, NULL), }; @@ -65,28 +65,28 @@ static struct bt_gatt_attr attrs[]= { struct bt_gatt_service bas = BT_GATT_SERVICE(attrs); void bas_init(void) -{ +{ bt_gatt_service_register(&bas); } u8_t bt_gatt_bas_get_battery_level(void) { - return battery_level; + return battery_level; } int bt_gatt_bas_set_battery_level(u8_t level) { - int rc; + int rc; - if (level > 100U) { - return -EINVAL; - } + if (level > 100U) { + return -EINVAL; + } - battery_level = level; + battery_level = level; - rc = bt_gatt_notify(NULL, &bas.attrs[1], &level, sizeof(level)); + rc = bt_gatt_notify(NULL, &bas.attrs[1], &level, sizeof(level)); - return rc == -ENOTCONN ? 0 : rc; + return rc == -ENOTCONN ? 0 : rc; } #if !defined(BFLB_BLE) diff --git a/components/network/ble/blestack/src/services/ble_tp_svc.c b/components/network/ble/blestack/src/services/ble_tp_svc.c index 7d66300b..507e9a49 100644 --- a/components/network/ble/blestack/src/services/ble_tp_svc.c +++ b/components/network/ble/blestack/src/services/ble_tp_svc.c @@ -29,8 +29,8 @@ TaskHandle_t ble_tp_task_h; int tx_mtu_size = 20; static struct bt_conn_cb ble_tp_conn_callbacks = { - .connected = ble_tp_connected, - .disconnected = ble_tp_disconnected, + .connected = ble_tp_connected, + .disconnected = ble_tp_disconnected, }; /************************************************************************* @@ -38,7 +38,7 @@ NAME ble_tp_tx_mtu_size */ static void ble_tp_tx_mtu_size(struct bt_conn *conn, u8_t err, - struct bt_gatt_exchange_params *params) + struct bt_gatt_exchange_params *params) { if(!err) { @@ -57,49 +57,49 @@ NAME */ static void ble_tp_connected(struct bt_conn *conn, u8_t err) { - int tx_octets = 0x00fb; - int tx_time = 0x0848; - int ret = -1; + int tx_octets = 0x00fb; + int tx_time = 0x0848; + int ret = -1; - printf("%s\n",__func__); - ble_tp_conn = conn; + printf("%s\n",__func__); + ble_tp_conn = conn; - //set data length after connected. - ret = bt_le_set_data_len(ble_tp_conn, tx_octets, tx_time); - if(!ret) - { - printf("ble tp set data length success.\n"); - } - else - { - printf("ble tp set data length failure, err: %d\n", ret); - } + //set data length after connected. + ret = bt_le_set_data_len(ble_tp_conn, tx_octets, tx_time); + if(!ret) + { + printf("ble tp set data length success.\n"); + } + else + { + printf("ble tp set data length failure, err: %d\n", ret); + } - //exchange mtu size after connected. - exchg_mtu.func = ble_tp_tx_mtu_size; - ret = bt_gatt_exchange_mtu(ble_tp_conn, &exchg_mtu); - if (!ret) { - printf("ble tp exchange mtu size pending.\n"); - } else { - printf("ble tp exchange mtu size failure, err: %d\n", ret); - } + //exchange mtu size after connected. + exchg_mtu.func = ble_tp_tx_mtu_size; + ret = bt_gatt_exchange_mtu(ble_tp_conn, &exchg_mtu); + if (!ret) { + printf("ble tp exchange mtu size pending.\n"); + } else { + printf("ble tp exchange mtu size failure, err: %d\n", ret); + } } /************************************************************************* -NAME +NAME ble_tp_disconnected */ static void ble_tp_disconnected(struct bt_conn *conn, u8_t reason) -{ - printf("%s\n",__func__); - - ble_tp_conn = NULL; +{ + printf("%s\n",__func__); + + ble_tp_conn = NULL; } /************************************************************************* -NAME +NAME ble_tp_notify -*/ +*/ static void ble_tp_notify_task(void *pvParameters) { @@ -114,9 +114,9 @@ static void ble_tp_notify_task(void *pvParameters) } /************************************************************************* -NAME +NAME ble_tp_ccc_cfg_changed -*/ +*/ static void ble_tp_ccc_cfg_changed(const struct bt_gatt_attr *attr, u16_t value) { if(value == BT_GATT_CCC_NOTIFY) { @@ -136,47 +136,47 @@ static void ble_tp_ccc_cfg_changed(const struct bt_gatt_attr *attr, u16_t value) } /************************************************************************* -NAME +NAME ble_tp_recv -*/ +*/ static int ble_tp_recv(struct bt_conn *conn, - const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, const void *buf, + u16_t len, u16_t offset, u8_t flags) { - blog_debug("bletp rx\n"); - return 0; + blog_debug("bletp rx\n"); + return 0; } /************************************************************************* -* DEFINE : attrs +* DEFINE : attrs */ static struct bt_gatt_attr attrs[]= { - BT_GATT_PRIMARY_SERVICE(BT_UUID_SVC_BLE_TP), + BT_GATT_PRIMARY_SERVICE(BT_UUID_SVC_BLE_TP), - BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_TP_TX, - BT_GATT_CHRC_NOTIFY, - BT_GATT_PERM_READ, - NULL, - NULL, - NULL), + BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_TP_TX, + BT_GATT_CHRC_NOTIFY, + BT_GATT_PERM_READ, + NULL, + NULL, + NULL), - BT_GATT_CCC(ble_tp_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), + BT_GATT_CCC(ble_tp_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE), - BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_TP_RX, - BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, - NULL, - ble_tp_recv, - NULL) + BT_GATT_CHARACTERISTIC(BT_UUID_CHAR_BLE_TP_RX, + BT_GATT_CHRC_WRITE_WITHOUT_RESP, + BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, + NULL, + ble_tp_recv, + NULL) }; /************************************************************************* -NAME +NAME get_attr */ struct bt_gatt_attr *get_attr(u8_t index) { - return &attrs[index]; + return &attrs[index]; } @@ -184,13 +184,13 @@ struct bt_gatt_service ble_tp_server = BT_GATT_SERVICE(attrs); /************************************************************************* -NAME +NAME ble_tp_init */ void ble_tp_init() { - bt_conn_cb_register(&ble_tp_conn_callbacks); - bt_gatt_service_register(&ble_tp_server); + bt_conn_cb_register(&ble_tp_conn_callbacks); + bt_gatt_service_register(&ble_tp_server); } diff --git a/components/network/ble/blestack/src/services/ble_tp_svc.h b/components/network/ble/blestack/src/services/ble_tp_svc.h index 3cd3a98b..bc895d22 100644 --- a/components/network/ble/blestack/src/services/ble_tp_svc.h +++ b/components/network/ble/blestack/src/services/ble_tp_svc.h @@ -20,12 +20,12 @@ NOTES #define BT_UUID_CHAR_BLE_TP_RX BT_UUID_DECLARE_128(BT_UUID_128_ENCODE(0x07af27a8, 0x9c22, 0x11ea, 0x9afe, 0x02fcdc4e7412)) //TX value handle offset 2 -#define BT_CHAR_BLE_TP_TX_ATTR_VAL_INDEX (2) +#define BT_CHAR_BLE_TP_TX_ATTR_VAL_INDEX (2) //RX value handle offset 5 -#define BT_CHAR_BLE_TP_RX_ATTR_VAL_INDEX (5) +#define BT_CHAR_BLE_TP_RX_ATTR_VAL_INDEX (5) void ble_tp_init(); struct bt_gatt_attr *get_attr(u8_t index); -#endif +#endif diff --git a/components/network/ble/blestack/src/services/dis.c b/components/network/ble/blestack/src/services/dis.c index aadb4100..a99cf8bd 100644 --- a/components/network/ble/blestack/src/services/dis.c +++ b/components/network/ble/blestack/src/services/dis.c @@ -33,10 +33,10 @@ #if CONFIG_BT_GATT_DIS_PNP struct dis_pnp { - u8_t pnp_vid_src; - u16_t pnp_vid; - u16_t pnp_pid; - u16_t pnp_ver; + u8_t pnp_vid_src; + u16_t pnp_vid; + u16_t pnp_pid; + u16_t pnp_ver; } __packed; #if defined(BFLB_BLE) @@ -53,10 +53,10 @@ struct dis_pnp { #endif static struct dis_pnp dis_pnp_id = { - .pnp_vid_src = DIS_PNP_VID_SRC, - .pnp_vid = CONFIG_BT_GATT_DIS_PNP_VID, - .pnp_pid = CONFIG_BT_GATT_DIS_PNP_PID, - .pnp_ver = CONFIG_BT_GATT_DIS_PNP_VER, + .pnp_vid_src = DIS_PNP_VID_SRC, + .pnp_vid = CONFIG_BT_GATT_DIS_PNP_VID, + .pnp_pid = CONFIG_BT_GATT_DIS_PNP_PID, + .pnp_ver = CONFIG_BT_GATT_DIS_PNP_VER, }; #endif @@ -65,94 +65,94 @@ static u8_t dis_model[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_MODEL; static u8_t dis_manuf[CONFIG_BT_GATT_DIS_STR_MAX] = CONFIG_BT_GATT_DIS_MANUF; #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER) static u8_t dis_serial_number[CONFIG_BT_GATT_DIS_STR_MAX] = - CONFIG_BT_GATT_DIS_SERIAL_NUMBER_STR; + CONFIG_BT_GATT_DIS_SERIAL_NUMBER_STR; #endif #if defined(CONFIG_BT_GATT_DIS_FW_REV) static u8_t dis_fw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = - CONFIG_BT_GATT_DIS_FW_REV_STR; + CONFIG_BT_GATT_DIS_FW_REV_STR; #endif #if defined(CONFIG_BT_GATT_DIS_HW_REV) static u8_t dis_hw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = - CONFIG_BT_GATT_DIS_HW_REV_STR; + CONFIG_BT_GATT_DIS_HW_REV_STR; #endif #if defined(CONFIG_BT_GATT_DIS_SW_REV) static u8_t dis_sw_rev[CONFIG_BT_GATT_DIS_STR_MAX] = - CONFIG_BT_GATT_DIS_SW_REV_STR; + CONFIG_BT_GATT_DIS_SW_REV_STR; #endif -#define BT_GATT_DIS_MODEL_REF dis_model -#define BT_GATT_DIS_MANUF_REF dis_manuf -#define BT_GATT_DIS_SERIAL_NUMBER_STR_REF dis_serial_number -#define BT_GATT_DIS_FW_REV_STR_REF dis_fw_rev -#define BT_GATT_DIS_HW_REV_STR_REF dis_hw_rev -#define BT_GATT_DIS_SW_REV_STR_REF dis_sw_rev +#define BT_GATT_DIS_MODEL_REF dis_model +#define BT_GATT_DIS_MANUF_REF dis_manuf +#define BT_GATT_DIS_SERIAL_NUMBER_STR_REF dis_serial_number +#define BT_GATT_DIS_FW_REV_STR_REF dis_fw_rev +#define BT_GATT_DIS_HW_REV_STR_REF dis_hw_rev +#define BT_GATT_DIS_SW_REV_STR_REF dis_sw_rev #else /* CONFIG_BT_GATT_DIS_SETTINGS */ -#define BT_GATT_DIS_MODEL_REF CONFIG_BT_GATT_DIS_MODEL -#define BT_GATT_DIS_MANUF_REF CONFIG_BT_GATT_DIS_MANUF +#define BT_GATT_DIS_MODEL_REF CONFIG_BT_GATT_DIS_MODEL +#define BT_GATT_DIS_MANUF_REF CONFIG_BT_GATT_DIS_MANUF #define BT_GATT_DIS_SERIAL_NUMBER_STR_REF CONFIG_BT_GATT_DIS_SERIAL_NUMBER_STR -#define BT_GATT_DIS_FW_REV_STR_REF CONFIG_BT_GATT_DIS_FW_REV_STR -#define BT_GATT_DIS_HW_REV_STR_REF CONFIG_BT_GATT_DIS_HW_REV_STR -#define BT_GATT_DIS_SW_REV_STR_REF CONFIG_BT_GATT_DIS_SW_REV_STR +#define BT_GATT_DIS_FW_REV_STR_REF CONFIG_BT_GATT_DIS_FW_REV_STR +#define BT_GATT_DIS_HW_REV_STR_REF CONFIG_BT_GATT_DIS_HW_REV_STR +#define BT_GATT_DIS_SW_REV_STR_REF CONFIG_BT_GATT_DIS_SW_REV_STR #endif /* CONFIG_BT_GATT_DIS_SETTINGS */ static ssize_t read_str(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, - strlen(attr->user_data)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, attr->user_data, + strlen(attr->user_data)); } #if CONFIG_BT_GATT_DIS_PNP static ssize_t read_pnp_id(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { - return bt_gatt_attr_read(conn, attr, buf, len, offset, &dis_pnp_id, - sizeof(dis_pnp_id)); + return bt_gatt_attr_read(conn, attr, buf, len, offset, &dis_pnp_id, + sizeof(dis_pnp_id)); } #endif /* Device Information Service Declaration */ static struct bt_gatt_attr attrs[]= { - BT_GATT_PRIMARY_SERVICE(BT_UUID_DIS), + BT_GATT_PRIMARY_SERVICE(BT_UUID_DIS), - BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MODEL_NUMBER, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_str, NULL, BT_GATT_DIS_MODEL_REF), - BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MANUFACTURER_NAME, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_str, NULL, BT_GATT_DIS_MANUF_REF), + BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MODEL_NUMBER, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_str, NULL, BT_GATT_DIS_MODEL_REF), + BT_GATT_CHARACTERISTIC(BT_UUID_DIS_MANUFACTURER_NAME, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_str, NULL, BT_GATT_DIS_MANUF_REF), #if CONFIG_BT_GATT_DIS_PNP - BT_GATT_CHARACTERISTIC(BT_UUID_DIS_PNP_ID, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_pnp_id, NULL, &dis_pnp_id), + BT_GATT_CHARACTERISTIC(BT_UUID_DIS_PNP_ID, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_pnp_id, NULL, &dis_pnp_id), #endif #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER) - BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SERIAL_NUMBER, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_str, NULL, - BT_GATT_DIS_SERIAL_NUMBER_STR_REF), + BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SERIAL_NUMBER, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_str, NULL, + BT_GATT_DIS_SERIAL_NUMBER_STR_REF), #endif #if defined(CONFIG_BT_GATT_DIS_FW_REV) - BT_GATT_CHARACTERISTIC(BT_UUID_DIS_FIRMWARE_REVISION, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_str, NULL, BT_GATT_DIS_FW_REV_STR_REF), + BT_GATT_CHARACTERISTIC(BT_UUID_DIS_FIRMWARE_REVISION, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_str, NULL, BT_GATT_DIS_FW_REV_STR_REF), #endif #if defined(CONFIG_BT_GATT_DIS_HW_REV) - BT_GATT_CHARACTERISTIC(BT_UUID_DIS_HARDWARE_REVISION, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_str, NULL, BT_GATT_DIS_HW_REV_STR_REF), + BT_GATT_CHARACTERISTIC(BT_UUID_DIS_HARDWARE_REVISION, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_str, NULL, BT_GATT_DIS_HW_REV_STR_REF), #endif #if defined(CONFIG_BT_GATT_DIS_SW_REV) - BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SOFTWARE_REVISION, - BT_GATT_CHRC_READ, BT_GATT_PERM_READ, - read_str, NULL, BT_GATT_DIS_SW_REV_STR_REF), + BT_GATT_CHARACTERISTIC(BT_UUID_DIS_SOFTWARE_REVISION, + BT_GATT_CHRC_READ, BT_GATT_PERM_READ, + read_str, NULL, BT_GATT_DIS_SW_REV_STR_REF), #endif }; @@ -165,99 +165,99 @@ void dis_init(u8_t vid_src, u16_t vid, u16_t pid, u16_t pid_ver) dis_pnp_id.pnp_vid = vid; dis_pnp_id.pnp_pid = pid; dis_pnp_id.pnp_ver = pid_ver; - bt_gatt_service_register(&dis_svc); + bt_gatt_service_register(&dis_svc); } #if defined(CONFIG_BT_SETTINGS) && defined(CONFIG_BT_GATT_DIS_SETTINGS) static int dis_set(const char *name, size_t len_rd, - settings_read_cb read_cb, void *store) + settings_read_cb read_cb, void *store) { - int len, nlen; - const char *next; + int len, nlen; + const char *next; - nlen = settings_name_next(name, &next); - if (!strncmp(name, "manuf", nlen)) { - len = read_cb(store, &dis_manuf, sizeof(dis_manuf) - 1); - if (len < 0) { - BT_ERR("Failed to read manufacturer from storage" - " (err %d)", len); - } else { - dis_manuf[len] = '\0'; + nlen = settings_name_next(name, &next); + if (!strncmp(name, "manuf", nlen)) { + len = read_cb(store, &dis_manuf, sizeof(dis_manuf) - 1); + if (len < 0) { + BT_ERR("Failed to read manufacturer from storage" + " (err %d)", len); + } else { + dis_manuf[len] = '\0'; - BT_DBG("Manufacturer set to %s", dis_manuf); - } - return 0; - } - if (!strncmp(name, "model", nlen)) { - len = read_cb(store, &dis_model, sizeof(dis_model) - 1); - if (len < 0) { - BT_ERR("Failed to read model from storage" - " (err %d)", len); - } else { - dis_model[len] = '\0'; + BT_DBG("Manufacturer set to %s", dis_manuf); + } + return 0; + } + if (!strncmp(name, "model", nlen)) { + len = read_cb(store, &dis_model, sizeof(dis_model) - 1); + if (len < 0) { + BT_ERR("Failed to read model from storage" + " (err %d)", len); + } else { + dis_model[len] = '\0'; - BT_DBG("Model set to %s", dis_model); - } - return 0; - } + BT_DBG("Model set to %s", dis_model); + } + return 0; + } #if defined(CONFIG_BT_GATT_DIS_SERIAL_NUMBER) - if (!strncmp(name, "serial", nlen)) { - len = read_cb(store, &dis_serial_number, - sizeof(dis_serial_number) - 1); - if (len < 0) { - BT_ERR("Failed to read serial number from storage" - " (err %d)", len); - } else { - dis_serial_number[len] = '\0'; + if (!strncmp(name, "serial", nlen)) { + len = read_cb(store, &dis_serial_number, + sizeof(dis_serial_number) - 1); + if (len < 0) { + BT_ERR("Failed to read serial number from storage" + " (err %d)", len); + } else { + dis_serial_number[len] = '\0'; - BT_DBG("Serial number set to %s", dis_serial_number); - } - return 0; - } + BT_DBG("Serial number set to %s", dis_serial_number); + } + return 0; + } #endif #if defined(CONFIG_BT_GATT_DIS_FW_REV) - if (!strncmp(name, "fw", nlen)) { - len = read_cb(store, &dis_fw_rev, sizeof(dis_fw_rev) - 1); - if (len < 0) { - BT_ERR("Failed to read firmware revision from storage" - " (err %d)", len); - } else { - dis_fw_rev[len] = '\0'; + if (!strncmp(name, "fw", nlen)) { + len = read_cb(store, &dis_fw_rev, sizeof(dis_fw_rev) - 1); + if (len < 0) { + BT_ERR("Failed to read firmware revision from storage" + " (err %d)", len); + } else { + dis_fw_rev[len] = '\0'; - BT_DBG("Firmware revision set to %s", dis_fw_rev); - } - return 0; - } + BT_DBG("Firmware revision set to %s", dis_fw_rev); + } + return 0; + } #endif #if defined(CONFIG_BT_GATT_DIS_HW_REV) - if (!strncmp(name, "hw", nlen)) { - len = read_cb(store, &dis_hw_rev, sizeof(dis_hw_rev) - 1); - if (len < 0) { - BT_ERR("Failed to read hardware revision from storage" - " (err %d)", len); - } else { - dis_hw_rev[len] = '\0'; + if (!strncmp(name, "hw", nlen)) { + len = read_cb(store, &dis_hw_rev, sizeof(dis_hw_rev) - 1); + if (len < 0) { + BT_ERR("Failed to read hardware revision from storage" + " (err %d)", len); + } else { + dis_hw_rev[len] = '\0'; - BT_DBG("Hardware revision set to %s", dis_hw_rev); - } - return 0; - } + BT_DBG("Hardware revision set to %s", dis_hw_rev); + } + return 0; + } #endif #if defined(CONFIG_BT_GATT_DIS_SW_REV) - if (!strncmp(name, "sw", nlen)) { - len = read_cb(store, &dis_sw_rev, sizeof(dis_sw_rev) - 1); - if (len < 0) { - BT_ERR("Failed to read software revision from storage" - " (err %d)", len); - } else { - dis_sw_rev[len] = '\0'; + if (!strncmp(name, "sw", nlen)) { + len = read_cb(store, &dis_sw_rev, sizeof(dis_sw_rev) - 1); + if (len < 0) { + BT_ERR("Failed to read software revision from storage" + " (err %d)", len); + } else { + dis_sw_rev[len] = '\0'; - BT_DBG("Software revision set to %s", dis_sw_rev); - } - return 0; - } + BT_DBG("Software revision set to %s", dis_sw_rev); + } + return 0; + } #endif - return 0; + return 0; } SETTINGS_STATIC_HANDLER_DEFINE(bt_dis, "bt/dis", NULL, dis_set, NULL, NULL); diff --git a/components/network/ble/blestack/src/services/dis.h b/components/network/ble/blestack/src/services/dis.h index 183da277..5cac6a95 100644 --- a/components/network/ble/blestack/src/services/dis.h +++ b/components/network/ble/blestack/src/services/dis.h @@ -14,7 +14,7 @@ extern "C" { #endif enum{ DIS_PNP_VID_SRC = 0x01, - USB_IMPL_VID + USB_IMPL_VID }; void dis_init(u8_t vid_src, u16_t vid, u16_t pid, u16_t pnp_ver); #ifdef __cplusplus diff --git a/components/network/ble/blestack/src/services/scps.c b/components/network/ble/blestack/src/services/scps.c index b1c280f8..21371a39 100644 --- a/components/network/ble/blestack/src/services/scps.c +++ b/components/network/ble/blestack/src/services/scps.c @@ -17,18 +17,18 @@ #include "scps.h" struct scan_intvl_win { - u16_t scan_intvl; - u16_t scan_win; + u16_t scan_intvl; + u16_t scan_win; } __packed; static struct scan_intvl_win intvl_win = { - .scan_intvl = BT_GAP_SCAN_FAST_INTERVAL, - .scan_win = BT_GAP_SCAN_FAST_WINDOW, + .scan_intvl = BT_GAP_SCAN_FAST_INTERVAL, + .scan_win = BT_GAP_SCAN_FAST_WINDOW, }; static ssize_t scan_intvl_win_write(struct bt_conn *conn, - const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, const void *buf, + u16_t len, u16_t offset, u8_t flags) { const u8_t *data = buf; intvl_win.scan_intvl = sys_get_le16(data); @@ -37,34 +37,34 @@ static ssize_t scan_intvl_win_write(struct bt_conn *conn, } static struct bt_gatt_attr attrs[]= { - BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS), - BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN, - BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_NONE, NULL, NULL, - &intvl_win) + BT_GATT_PRIMARY_SERVICE(BT_UUID_SCPS), + BT_GATT_CHARACTERISTIC(BT_UUID_SCPS_SCAN_INTVL_WIN, + BT_GATT_CHRC_WRITE_WITHOUT_RESP, + BT_GATT_PERM_NONE, NULL, NULL, + &intvl_win) }; static struct bt_gatt_service scps = BT_GATT_SERVICE(attrs); bool scps_init(u16_t scan_intvl, u16_t scan_win) -{ +{ int err; - + if (scan_intvl < 0x0004 || scan_intvl > 0x4000) { return false; } - + if (scan_win < 0x0004 || scan_win > 0x4000) { return false; } - + if (scan_win > scan_intvl) { return false; } intvl_win.scan_intvl = scan_intvl; intvl_win.scan_win = scan_win; - + err = bt_gatt_service_register(&scps); return err?false:true; diff --git a/components/network/ble/blestack/src/services/wifi_prov.c b/components/network/ble/blestack/src/services/wifi_prov.c index e958110b..891e16be 100644 --- a/components/network/ble/blestack/src/services/wifi_prov.c +++ b/components/network/ble/blestack/src/services/wifi_prov.c @@ -17,51 +17,51 @@ u8_t remote_seq_num = WIFIPROV_INVALID_SEQ; static struct conn_callback *callback; //static struct bt_gatt_ccc_cfg wifiprov_ccc_cfg[BT_GATT_CCC_MAX] = {}; static ssize_t write_data(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags); + u16_t len, u16_t offset, u8_t flags); static void wifiprov_ccc_cfg_changed(const struct bt_gatt_attr *attr,u16_t value) { - ARG_UNUSED(attr); + ARG_UNUSED(attr); BT_DBG("value 0x%02x", value); } static ssize_t read_data(struct bt_conn *conn, - const struct bt_gatt_attr *attr, void *buf, - u16_t len, u16_t offset) + const struct bt_gatt_attr *attr, void *buf, + u16_t len, u16_t offset) { /*As we donot know what info remote wants to read currently, respond value 0 by default. This part will be implemented according to specific requirements.*/ - u8_t value = 0x00; - return bt_gatt_attr_read(conn, attr, buf, len, offset, &value,sizeof(value)); + u8_t value = 0x00; + return bt_gatt_attr_read(conn, attr, buf, len, offset, &value,sizeof(value)); } static bool remote_need_ack(u8_t ack) { - return (ack & WIFIPROV_FRAME_CTRL_ACK_BITMASK) ? 1 : 0; + return (ack & WIFIPROV_FRAME_CTRL_ACK_BITMASK) ? 1 : 0; } static struct bt_gatt_attr attrs[]= { - BT_GATT_PRIMARY_SERVICE(BT_UUID_WIFI_PROV), - BT_GATT_CHARACTERISTIC(BT_UUID_WIFIPROV_READ, - BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, - BT_GATT_PERM_READ , - read_data, - NULL, - NULL), - - BT_GATT_CCC(wifiprov_ccc_cfg_changed, BT_GATT_PERM_READ_AUTHEN | BT_GATT_PERM_WRITE_AUTHEN), + BT_GATT_PRIMARY_SERVICE(BT_UUID_WIFI_PROV), + BT_GATT_CHARACTERISTIC(BT_UUID_WIFIPROV_READ, + BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY, + BT_GATT_PERM_READ , + read_data, + NULL, + NULL), - BT_GATT_CHARACTERISTIC(BT_UUID_WIFIPROV_WRITE, - BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, - BT_GATT_PERM_WRITE, - NULL, - write_data, - NULL), + BT_GATT_CCC(wifiprov_ccc_cfg_changed, BT_GATT_PERM_READ_AUTHEN | BT_GATT_PERM_WRITE_AUTHEN), + + BT_GATT_CHARACTERISTIC(BT_UUID_WIFIPROV_WRITE, + BT_GATT_CHRC_WRITE | BT_GATT_CHRC_WRITE_WITHOUT_RESP, + BT_GATT_PERM_WRITE, + NULL, + write_data, + NULL), }; static ssize_t write_data(struct bt_conn *conn, - const struct bt_gatt_attr *attr, const void *buf, - u16_t len, u16_t offset, u8_t flags) + const struct bt_gatt_attr *attr, const void *buf, + u16_t len, u16_t offset, u8_t flags) { struct wifiprov_data_format rcvd_frm; u8_t type, subtype; @@ -80,35 +80,35 @@ static ssize_t write_data(struct bt_conn *conn, } else remote_seq_num = rcvd_frm.sequence_number; - + if(rcvd_frm.len > 0) rcvd_frm.data = (u8_t *)(buf + WIFIPROV_FRAME_DATA_PYLD_OFFSET); if(remote_need_ack(rcvd_frm.frame_control)){ ack_buf[0] = WIFIPROV_TYPE_CTRL_FRAME|(SUB_TYPE_CTRL_ACK << WIFIPROV_FRAME_TYPE_OFFSET); - ack_buf[1] = WIFIPROV_FRAME_CTRL_NO_ACK; - ack_buf[2] = local_seq_num++; - ack_buf[3] = WIFIPROV_FRAME_ACK_DATA_LEN; - ack_buf[4] = rcvd_frm.sequence_number; + ack_buf[1] = WIFIPROV_FRAME_CTRL_NO_ACK; + ack_buf[2] = local_seq_num++; + ack_buf[3] = WIFIPROV_FRAME_ACK_DATA_LEN; + ack_buf[4] = rcvd_frm.sequence_number; - bt_gatt_notify(conn,&attrs[2],ack_buf,5); + bt_gatt_notify(conn,&attrs[2],ack_buf,5); } - + if(type == WIFIPROV_TYPE_CTRL_FRAME){ switch(subtype){ case SUB_TYPE_CTRL_ACK: - + break; case SUB_TYPE_CTRL_CONN_AP: if(callback && callback->local_connect_remote_ap) - callback->local_connect_remote_ap(); + callback->local_connect_remote_ap(); break; case SUB_TYPE_CTRL_DISCONN_AP: if(callback && callback->local_disconnect_remote_ap) - callback->local_disconnect_remote_ap(); + callback->local_disconnect_remote_ap(); break; - + default: BT_ERR("Invalid wifi prov frame type"); } @@ -116,26 +116,26 @@ static ssize_t write_data(struct bt_conn *conn, switch(subtype){ case SUB_TYPE_DATA_BSSID: if(callback && callback->get_remote_ap_bssid) - callback->get_remote_ap_bssid(rcvd_frm.data, rcvd_frm.len); + callback->get_remote_ap_bssid(rcvd_frm.data, rcvd_frm.len); break; case SUB_TYPE_DATA_SSID: if(callback && callback->get_remote_ap_ssid) - callback->get_remote_ap_ssid(rcvd_frm.data, rcvd_frm.len); + callback->get_remote_ap_ssid(rcvd_frm.data, rcvd_frm.len); break; case SUB_TYPE_DATA_PASSWORD: if(callback && callback->get_remote_password) - callback->get_remote_password(rcvd_frm.data, rcvd_frm.len); + callback->get_remote_password(rcvd_frm.data, rcvd_frm.len); break; - + default: BT_ERR("Invalid wifi prov frame type"); - } + } }else{ BT_ERR("Invalid wifi prov frame type"); } - - return len; + + return len; } struct bt_gatt_service wifiprov_server = BT_GATT_SERVICE(attrs); @@ -143,5 +143,5 @@ struct bt_gatt_service wifiprov_server = BT_GATT_SERVICE(attrs); void WifiProv_init(struct conn_callback *cb) { callback = cb; - bt_gatt_service_register(&wifiprov_server); + bt_gatt_service_register(&wifiprov_server); } diff --git a/components/network/ble/blestack/src/services/wifi_prov.h b/components/network/ble/blestack/src/services/wifi_prov.h index 477b155d..59dc48be 100644 --- a/components/network/ble/blestack/src/services/wifi_prov.h +++ b/components/network/ble/blestack/src/services/wifi_prov.h @@ -21,12 +21,12 @@ #define WIFIPROV_FRAME_ACK_DATA_LEN 0x01 struct conn_callback{ - void (*local_connect_remote_ap) (void); - void (*local_disconnect_remote_ap) (void); - void (*get_remote_ap_ssid)(void *args,size_t size); - void (*get_remote_ap_bssid)(void *args,size_t size); - void (*get_remote_password)(void *args,size_t size); -}; + void (*local_connect_remote_ap) (void); + void (*local_disconnect_remote_ap) (void); + void (*get_remote_ap_ssid)(void *args,size_t size); + void (*get_remote_ap_bssid)(void *args,size_t size); + void (*get_remote_password)(void *args,size_t size); +}; enum wifiprov_ctrlfrm_type{ SUB_TYPE_CTRL_ACK = 0x00, @@ -42,12 +42,12 @@ enum wifiprov_datafrm_type{ #define WIFIPROV_FRAME_DATA_PYLD_OFFSET 4 struct wifiprov_data_format{ - u8_t type; /*type : highest 2 bit ; subtype : lowest 6 bit;*/ - u8_t frame_control; /* if 5th bit set "1" indicate fragmentation frame */ - u8_t sequence_number; - u8_t len; - u8_t *data; + u8_t type; /*type : highest 2 bit ; subtype : lowest 6 bit;*/ + u8_t frame_control; /* if 5th bit set "1" indicate fragmentation frame */ + u8_t sequence_number; + u8_t len; + u8_t *data; }; void WifiProv_init(struct conn_callback *cb); -#endif +#endif diff --git a/components/network/dns_server/bouffalo.mk b/components/network/dns_server/bouffalo.mk index 838181b4..59b45987 100644 --- a/components/network/dns_server/bouffalo.mk +++ b/components/network/dns_server/bouffalo.mk @@ -2,16 +2,16 @@ # ## These include paths would be exported to project level COMPONENT_ADD_INCLUDEDIRS += include - + ## not be exported to project level -## This component's src +## This component's src COMPONENT_SRCS := src/dns_server.c \ src/web_server.c - + COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) COMPONENT_SRCDIRS := src ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/network/dns_server/include/dns_server.h b/components/network/dns_server/include/dns_server.h old mode 100755 new mode 100644 diff --git a/components/network/dns_server/include/web_server.h b/components/network/dns_server/include/web_server.h old mode 100755 new mode 100644 index dab18c0e..a8ff7bf4 --- a/components/network/dns_server/include/web_server.h +++ b/components/network/dns_server/include/web_server.h @@ -1,7 +1,7 @@ -#ifndef __WEB_SERVER_H__ -#define __WEB_SERVER_H__ - - -void web_server2(void *pvParameters); - +#ifndef __WEB_SERVER_H__ +#define __WEB_SERVER_H__ + + +void web_server2(void *pvParameters); + #endif \ No newline at end of file diff --git a/components/network/dns_server/src/dns_server.c b/components/network/dns_server/src/dns_server.c old mode 100755 new mode 100644 index 2117480c..ca7b4911 --- a/components/network/dns_server/src/dns_server.c +++ b/components/network/dns_server/src/dns_server.c @@ -48,8 +48,8 @@ struct dns_ans_ans { uint16_t cls; uint16_t point; uint16_t antyp; - uint16_t antypp; - uint16_t len; + uint16_t antypp; + uint16_t len; uint32_t time; uint32_t addr; }; @@ -80,7 +80,7 @@ static void dns_server_send(struct dns_server_ctx *dns_ctx) uint16_t query_idx, copy_len; const char *hostname, *hostname_part; struct dns_table_entry dns_server_table = { - .txid = DNS_SERVER_ID, + .txid = DNS_SERVER_ID, .flags = DNS_SERVER_FLAGS, .numque = DNS_SERVER_NUMQUE, .ansrrs = DNS_SERVER_ANSRRS, @@ -131,14 +131,14 @@ static void dns_server_send(struct dns_server_ctx *dns_ctx) qry.point = htons(entry->poiname); qry.antyp = htons(entry->anstype); qry.antypp = htons(entry->anstypee); - qry.len = htons(entry->datalen); + qry.len = htons(entry->datalen); qry.time = htonl(entry->anstime); qry.addr = htonl(entry->adress); pbuf_take_at(rp, &qry, SIZEOF_DNSANS_HDRQUE, query_idx); - + pbuf_realloc(rp, query_idx + SIZEOF_DNSANS_HDRQUE);//shrink to the real size udp_sendto(dns_ctx->upcb1, rp, dns_ctx->addr1, dns_ctx->port1); - pbuf_free(rp); + pbuf_free(rp); } } @@ -156,7 +156,7 @@ void get_dns_request(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_a LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\r\n")); /* free pbuf and return */ } else { - pbuf_copy_partial(p, &hdr, SIZEOF_DNSANS_HDR, 0); + pbuf_copy_partial(p, &hdr, SIZEOF_DNSANS_HDR, 0); dns_ctx->txid = ntohs(hdr.id); dns_ctx->nquestions = ntohs(hdr.numquestions); pbuf_copy_partial( @@ -164,7 +164,7 @@ void get_dns_request(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_a dns_ctx->name, len = p->tot_len > sizeof(dns_ctx->name) - 1 ? sizeof(dns_ctx->name) - 1 : p->tot_len, SIZEOF_DNSANS_HDR - ); + ); if (0 == utils_dns_domain_get(dns_ctx->name, dns_ctx->name, &len)) { if (len > 0 && '.' == dns_ctx->name[len - 1]) { len--; @@ -179,18 +179,18 @@ void get_dns_request(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_a void dns_server_init(void) { - struct udp_pcb *upcb; + struct udp_pcb *upcb; struct dns_server_ctx *dns_ctx; err_t err; - - upcb = udp_new(); + + upcb = udp_new(); if (NULL == upcb) { goto failed_out_1; } - err = udp_bind(upcb, IP_ADDR_ANY, 53); + err = udp_bind(upcb, IP_ADDR_ANY, 53); if (err != ERR_OK) { goto failed_out_2; - } + } dns_ctx = pvPortMalloc(sizeof(struct dns_server_ctx)); if (NULL == dns_ctx) { goto failed_out_3; diff --git a/components/network/dns_server/src/web_server.c b/components/network/dns_server/src/web_server.c old mode 100755 new mode 100644 index feb8f286..0297eac9 --- a/components/network/dns_server/src/web_server.c +++ b/components/network/dns_server/src/web_server.c @@ -1,99 +1,99 @@ - -/* Brief: This demo shows how to use BL602 as a webserver - * - * - use a sta connect to this ap - * - open the browser and input the ip_address of this BL602(the default ip_adress is: 192.168.4.1 ) - * - and you can see "Hello World, from BL602!" on this web page - * - */ -#include "FreeRTOS.h" -//#include "esp_wifi.h" -//#include "esp_system.h" -//#include "esp_event.h" -//#include "esp_event_loop.h" -//#include "nvs_flash.h" -//#include "driver/gpio.h" -#include "portmacro.h" -#include "event_groups.h" -//#include "esp_log.h" -//#include "tcpip_adapter.h" -#include "lwip/err.h" -#include "string.h" -#include "lwip/sys.h" -#include "lwip/netdb.h" -#include "lwip/api.h" -#include "web_server.h" - -#define TAG "lwip_udp" - -const static char http_html_hdr[] = - "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n"; -const static char http_index_hml[] = "" - "\n" - "\n" - " \n" - " \n" - "HELLO BL602\n" - "\n" - "\n" - "

Hello World, from BL602!

\n" - "\n" - "\n"; - -static void web_http_server(struct netconn *conn) -{ - struct netbuf *inputbuf; - char *buf; - u16_t buflen; - err_t err; - - err = netconn_recv(conn, &inputbuf); - if (err == ERR_OK) { - netbuf_data(inputbuf, (void**)&buf, &buflen); - printf("the received data:\n%s\n",buf); - /* Judge if this is an HTTP GET command */ - if (buflen >= 5 && buf[0] == 'G' && buf[1] == 'E' && buf[2] == 'T' && buf[3] == ' ' && buf[4] == '/' ) { - netconn_write(conn, http_html_hdr, sizeof(http_html_hdr)-1, NETCONN_NOCOPY); - - if(buf[5]=='h') { - netconn_write(conn, http_index_hml, sizeof(http_index_hml)-1, NETCONN_NOCOPY); - } - else if(buf[5]=='l') { - netconn_write(conn, http_index_hml, sizeof(http_index_hml)-1, NETCONN_NOCOPY); - } -// else if(buf[5]=='j') { -// netconn_write(conn, json_unformatted, strlen(json_unformatted), NETCONN_NOCOPY); -// } - else { - netconn_write(conn, http_index_hml, sizeof(http_index_hml)-1, NETCONN_NOCOPY); - } - } - } - netconn_close(conn); - netbuf_delete(inputbuf); -} - - -void web_server2(void *pvParameters) -{ - struct netconn *conn, *newconn; - err_t err; - conn = netconn_new(NETCONN_TCP); - netconn_bind(conn, NULL, 80); - netconn_listen(conn); - while (1) { - err = netconn_accept(conn, &newconn); - if (err == ERR_OK) { - web_http_server(newconn); - netconn_delete(newconn); - } - else { - netconn_close(conn); - netconn_delete(conn); - break; - } - } -} + +/* Brief: This demo shows how to use BL602 as a webserver + * + * - use a sta connect to this ap + * - open the browser and input the ip_address of this BL602(the default ip_adress is: 192.168.4.1 ) + * - and you can see "Hello World, from BL602!" on this web page + * + */ +#include "FreeRTOS.h" +//#include "esp_wifi.h" +//#include "esp_system.h" +//#include "esp_event.h" +//#include "esp_event_loop.h" +//#include "nvs_flash.h" +//#include "driver/gpio.h" +#include "portmacro.h" +#include "event_groups.h" +//#include "esp_log.h" +//#include "tcpip_adapter.h" +#include "lwip/err.h" +#include "string.h" +#include "lwip/sys.h" +#include "lwip/netdb.h" +#include "lwip/api.h" +#include "web_server.h" + +#define TAG "lwip_udp" + +const static char http_html_hdr[] = + "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n"; +const static char http_index_hml[] = "" + "\n" + "\n" + " \n" + " \n" + "HELLO BL602\n" + "\n" + "\n" + "

Hello World, from BL602!

\n" + "\n" + "\n"; + +static void web_http_server(struct netconn *conn) +{ + struct netbuf *inputbuf; + char *buf; + u16_t buflen; + err_t err; + + err = netconn_recv(conn, &inputbuf); + if (err == ERR_OK) { + netbuf_data(inputbuf, (void**)&buf, &buflen); + printf("the received data:\n%s\n",buf); + /* Judge if this is an HTTP GET command */ + if (buflen >= 5 && buf[0] == 'G' && buf[1] == 'E' && buf[2] == 'T' && buf[3] == ' ' && buf[4] == '/' ) { + netconn_write(conn, http_html_hdr, sizeof(http_html_hdr)-1, NETCONN_NOCOPY); + + if(buf[5]=='h') { + netconn_write(conn, http_index_hml, sizeof(http_index_hml)-1, NETCONN_NOCOPY); + } + else if(buf[5]=='l') { + netconn_write(conn, http_index_hml, sizeof(http_index_hml)-1, NETCONN_NOCOPY); + } +// else if(buf[5]=='j') { +// netconn_write(conn, json_unformatted, strlen(json_unformatted), NETCONN_NOCOPY); +// } + else { + netconn_write(conn, http_index_hml, sizeof(http_index_hml)-1, NETCONN_NOCOPY); + } + } + } + netconn_close(conn); + netbuf_delete(inputbuf); +} + + +void web_server2(void *pvParameters) +{ + struct netconn *conn, *newconn; + err_t err; + conn = netconn_new(NETCONN_TCP); + netconn_bind(conn, NULL, 80); + netconn_listen(conn); + while (1) { + err = netconn_accept(conn, &newconn); + if (err == ERR_OK) { + web_http_server(newconn); + netconn_delete(newconn); + } + else { + netconn_close(conn); + netconn_delete(conn); + break; + } + } +} diff --git a/components/network/httpc/bouffalo.mk b/components/network/httpc/bouffalo.mk index 40398220..c6f1970d 100644 --- a/components/network/httpc/bouffalo.mk +++ b/components/network/httpc/bouffalo.mk @@ -6,7 +6,7 @@ COMPONENT_ADD_INCLUDEDIRS += include ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src COMPONENT_SRCS := http_client.c @@ -16,4 +16,4 @@ COMPONENT_SRCDIRS := . ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/network/httpc/http_client.c b/components/network/httpc/http_client.c index bcc6ef8e..68168e9d 100644 --- a/components/network/httpc/http_client.c +++ b/components/network/httpc/http_client.c @@ -641,7 +641,7 @@ httpc_init_connection_addr(httpc_state_t **connection, const httpc_connection_t } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file by passing server IP address * * @param server_addr IP address of the server to connect @@ -686,7 +686,7 @@ httpc_get_file(const ip_addr_t* server_addr, u16_t port, const char* uri, const } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file by passing server name as string (DNS name or IP address string) * * @param server_name server name as string (DNS name or IP address string) @@ -828,7 +828,7 @@ httpc_fs_tcp_recv(void *arg, struct altcp_pcb *pcb, struct pbuf *p, err_t err) } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file to disk by passing server IP address * * @param server_addr IP address of the server to connect @@ -880,7 +880,7 @@ httpc_get_file_to_disk(const ip_addr_t* server_addr, u16_t port, const char* uri } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file to disk by passing server name as string (DNS name or IP address string) * * @param server_name server name as string (DNS name or IP address string) diff --git a/components/network/httpc/include/http_client.h b/components/network/httpc/include/http_client.h index d4f66b40..55751bd1 100644 --- a/components/network/httpc/include/http_client.h +++ b/components/network/httpc/include/http_client.h @@ -52,7 +52,7 @@ extern "C" { #endif /** - * @ingroup httpc + * @ingroup httpc * HTTPC_HAVE_FILE_IO: define this to 1 to have functions dowloading directly * to disk via fopen/fwrite. * These functions are example implementations of the interface only. @@ -62,13 +62,13 @@ extern "C" { #endif /** - * @ingroup httpc + * @ingroup httpc * The default TCP port used for HTTP */ #define HTTP_DEFAULT_PORT LWIP_IANA_PORT_HTTP /** - * @ingroup httpc + * @ingroup httpc * HTTP client result codes */ typedef enum ehttpc_result { @@ -97,7 +97,7 @@ typedef enum ehttpc_result { typedef struct _httpc_state httpc_state_t; /** - * @ingroup httpc + * @ingroup httpc * Prototype of a http client callback function * * @param arg argument specified when initiating the request @@ -110,7 +110,7 @@ typedef struct _httpc_state httpc_state_t; typedef void (*httpc_result_fn)(void *arg, httpc_result_t httpc_result, u32_t rx_content_len, u32_t srv_res, err_t err); /** - * @ingroup httpc + * @ingroup httpc * Prototype of http client callback: called when the headers are received * * @param connection http client connection diff --git a/components/network/lwip/bouffalo.mk b/components/network/lwip/bouffalo.mk index 1982db61..2e79c417 100644 --- a/components/network/lwip/bouffalo.mk +++ b/components/network/lwip/bouffalo.mk @@ -2,11 +2,11 @@ # ## These include paths would be exported to project level COMPONENT_ADD_INCLUDEDIRS += src/include lwip-port lwip-port/config lwip-port/FreeRTOS lwip-port/arch - -## not be exported to project level -COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## not be exported to project level +COMPONENT_PRIV_INCLUDEDIRS := + +## This component's src #COMPONENT_SRCS := #COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) @@ -14,4 +14,4 @@ COMPONENT_SRCDIRS := src/api src/core src/core/ipv4 src/netif lwip-port/FreeRTOS ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/network/lwip/doc/NO_SYS_SampleCode.c b/components/network/lwip/doc/NO_SYS_SampleCode.c index 71f1c9f7..0a53bcfd 100644 --- a/components/network/lwip/doc/NO_SYS_SampleCode.c +++ b/components/network/lwip/doc/NO_SYS_SampleCode.c @@ -18,7 +18,7 @@ eth_mac_irq() } } -static err_t +static err_t netif_output(struct netif *netif, struct pbuf *p) { LINK_STATS_INC(link.xmit); @@ -40,13 +40,13 @@ netif_output(struct netif *netif, struct pbuf *p) return ERR_OK; } -static void +static void netif_status_callback(struct netif *netif) { printf("netif status changed %s\n", ip4addr_ntoa(netif_ip4_addr(netif))); } -static err_t +static err_t netif_init(struct netif *netif) { netif->linkoutput = netif_output; @@ -62,7 +62,7 @@ netif_init(struct netif *netif) return ERR_OK; } -void +void main(void) { struct netif netif; @@ -77,7 +77,7 @@ main(void) netif_set_status_callback(&netif, netif_status_callback); netif_set_default(&netif); netif_set_up(&netif); - + /* Start DHCP and HTTPD */ dhcp_start(&netif ); httpd_init(); @@ -99,7 +99,7 @@ main(void) if(p != NULL) { LINK_STATS_INC(link.recv); - + /* Update SNMP stats (only if you use SNMP) */ MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len); int unicast = ((p->payload[0] & 0x01) == 0); @@ -113,10 +113,10 @@ main(void) pbuf_free(p); } } - + /* Cyclic lwIP timers check */ sys_check_timeouts(); - + /* your application goes here */ } } diff --git a/components/network/lwip/doc/ZeroCopyRx.c b/components/network/lwip/doc/ZeroCopyRx.c index 0e8219bd..8bd152ea 100644 --- a/components/network/lwip/doc/ZeroCopyRx.c +++ b/components/network/lwip/doc/ZeroCopyRx.c @@ -31,7 +31,7 @@ void eth_rx_irq() my_pbuf->dma_descriptor = dma_desc; invalidate_cpu_cache(dma_desc->rx_data, dma_desc->rx_length); - + struct pbuf* p = pbuf_alloced_custom(PBUF_RAW, dma_desc->rx_length, PBUF_REF, diff --git a/components/network/lwip/doc/doxygen/main_page.h b/components/network/lwip/doc/doxygen/main_page.h index 89d86f82..7b2472ff 100644 --- a/components/network/lwip/doc/doxygen/main_page.h +++ b/components/network/lwip/doc/doxygen/main_page.h @@ -2,14 +2,14 @@ * @defgroup lwip lwIP * * @defgroup infrastructure Infrastructure - * + * * @defgroup api APIs * lwIP provides three Application Program's Interfaces (APIs) for programs * to use for communication with the TCP/IP code: * - low-level "core" / "callback" or @ref callbackstyle_api. * - higher-level @ref sequential_api. * - BSD-style @ref socket. - * + * * The raw TCP/IP interface allows the application program to integrate * better with the TCP/IP code. Program execution is event based by * having callback functions being called from within the TCP/IP @@ -17,23 +17,23 @@ * thread. The sequential API has a much higher overhead and is not very * well suited for small systems since it forces a multithreaded paradigm * on the application. - * + * * The raw TCP/IP interface is not only faster in terms of code execution * time but is also less memory intensive. The drawback is that program * development is somewhat harder and application programs written for * the raw TCP/IP interface are more difficult to understand. Still, this * is the preferred way of writing applications that should be small in * code size and memory usage. - * + * * All APIs can be used simultaneously by different application * programs. In fact, the sequential API is implemented as an application * program using the raw TCP/IP interface. - * + * * Do not confuse the lwIP raw API with raw Ethernet or IP sockets. * The former is a way of interfacing the lwIP network stack (including * TCP and UDP), the latter refers to processing raw Ethernet or IP data * instead of TCP connections or UDP packets. - * + * * Raw API applications may never block since all packet processing * (input and output) as well as timer processing (TCP mainly) is done * in a single execution context. @@ -59,7 +59,7 @@ * receive. This API is also used by the core stack for interaction between * the various protocols. It is the only API available when running lwIP * without an operating system. - * + * * @defgroup sequential_api Sequential-style APIs * @ingroup api * Sequential-style APIs, blocking functions. More overhead, but can be called @@ -70,7 +70,7 @@ * paradigm. Since the TCP/IP stack is event based by nature, the TCP/IP * code and the application program must reside in different execution * contexts (threads). - * + * * @defgroup socket Socket API * @ingroup api * BSD-style socket API.\n @@ -83,9 +83,9 @@ * on other platforms (e.g. unix / windows etc.). However, due to limitations * in the specification of this API, there might be incompatibilities * that require small modifications of existing programs. - * + * * @defgroup netifs NETIFs - * + * * @defgroup apps Applications */ @@ -112,7 +112,7 @@ * * Add sys_mbox_trypost_fromisr() and tcpip_callbackmsg_trycallback_fromisr() * (for FreeRTOS, mainly) * * socket API: support poll(), sendmsg() and recvmsg(); fix problems on close - * + * * Detailed Changelog * ------------------ * @verbinclude "CHANGELOG" @@ -131,21 +131,21 @@ * * The most common source of lwIP problems is to have multiple execution contexts * inside the lwIP code. - * - * lwIP can be used in two basic modes: @ref lwip_nosys (no OS/RTOS + * + * lwIP can be used in two basic modes: @ref lwip_nosys (no OS/RTOS * running on target system) or @ref lwip_os (there is an OS running * on the target system). - * + * * See also: @ref multithreading (especially the part about @ref LWIP_ASSERT_CORE_LOCKED()!) * * Mainloop Mode * ------------- * In mainloop mode, only @ref callbackstyle_api can be used. - * The user has two possibilities to ensure there is only one + * The user has two possibilities to ensure there is only one * exection context at a time in lwIP: * * 1) Deliver RX ethernet packets directly in interrupt context to lwIP - * by calling netif->input directly in interrupt. This implies all lwIP + * by calling netif->input directly in interrupt. This implies all lwIP * callback functions are called in IRQ context, which may cause further * problems in application code: IRQ is blocked for a long time, multiple * execution contexts in application code etc. When the application wants @@ -168,10 +168,10 @@ * TCPIP thread. It is a common error to call these from other threads * or from IRQ contexts. ​Ethernet RX needs to deliver incoming packets * in the correct way by sending a message to TCPIP thread, this is - * implemented in tcpip_input().​​ + * implemented in tcpip_input(). * Again, ensure lwIP is _NEVER_ called from an interrupt, e.g. * some SPI IRQ wants to forward data to udp_send() or tcp_write()! - * + * * 1) tcpip_callback() can be used get called back from TCPIP thread, * it is safe to call any @ref callbackstyle_api from there. * @@ -186,7 +186,7 @@ * * DMA-capable ethernet hardware and zero-copy RX * ---------------------------------------------- - * + * * lwIP changes the content of RECEIVED pbufs in the TCP code path. * This implies one or more cacheline(s) of the RX pbuf become dirty * and need to be flushed before the memory is handed over to the @@ -225,7 +225,7 @@ * *not* *from* *interrupt* *context*. You can allocate a @ref pbuf in interrupt * context and put them into a queue which is processed from mainloop.\n * Call sys_check_timeouts() periodically in the mainloop.\n - * Porting: implement all functions in @ref sys_time, @ref sys_prot and + * Porting: implement all functions in @ref sys_time, @ref sys_prot and * @ref compiler_abstraction.\n * You can only use @ref callbackstyle_api in this mode.\n * Sample code:\n @@ -265,12 +265,12 @@ Call these functions in the order of appearance: The init function pointer must point to a initialization function for your Ethernet netif interface. The following code illustrates its use. - + @code{.c} err_t netif_if_init(struct netif *netif) { u8_t i; - + for (i = 0; i < ETHARP_HWADDR_LEN; i++) { netif->hwaddr[i] = some_eth_addr[i]; } @@ -278,11 +278,11 @@ Call these functions in the order of appearance: return ERR_OK; } @endcode - + For Ethernet drivers, the input function pointer must point to the lwIP function ethernet_input() declared in "netif/etharp.h". Other drivers must use ip_input() declared in "lwip/ip.h". - + - netif_set_default(struct netif *netif) Registers the default network interface. @@ -317,7 +317,7 @@ Call these functions in the order of appearance: * from pbuf- and memory management functions). Application threads using * the sequential- or socket API communicate with this main thread through * message passing. - * + * * As such, the list of functions that may be called from * other threads or an ISR is very limited! Only functions * from these API header files are thread-safe: @@ -328,43 +328,43 @@ Call these functions in the order of appearance: * - pppapi.h * - sockets.h * - sys.h - * + * * Additionaly, memory (de-)allocation functions may be * called from multiple threads (not ISR!) with NO_SYS=0 * since they are protected by @ref SYS_LIGHTWEIGHT_PROT and/or * semaphores. - * + * * Netconn or Socket API functions are thread safe against the * core thread but they are not reentrant at the control block * granularity level. That is, a UDP or TCP control block must * not be shared among multiple threads without proper locking. - * + * * If @ref SYS_LIGHTWEIGHT_PROT is set to 1 and * @ref LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT is set to 1, * pbuf_free() may also be called from another thread or * an ISR (since only then, mem_free - for PBUF_RAM - may * be called from an ISR: otherwise, the HEAP is only * protected by semaphores). - * + * * How to get threading done right * ------------------------------- - * + * * It is strongly recommended to implement the LWIP_ASSERT_CORE_LOCKED() * macro in an application that uses multithreading. lwIP code has * several places where a check for a correct thread context is * implemented which greatly helps the user to get threading done right. - * See the example sys_arch.c files in unix and Win32 port + * See the example sys_arch.c files in unix and Win32 port * in the contrib repository. - * - * In short: Copy the functions sys_mark_tcpip_thread() and + * + * In short: Copy the functions sys_mark_tcpip_thread() and * sys_check_core_locking() to your port and modify them to work with your OS. * Then let @ref LWIP_ASSERT_CORE_LOCKED() and @ref LWIP_MARK_TCPIP_THREAD() * point to these functions. - * + * * If you use @ref LWIP_TCPIP_CORE_LOCKING, you also need to copy and adapt * the functions sys_lock_tcpip_core() and sys_unlock_tcpip_core(). - * Let @ref LOCK_TCPIP_CORE() and @ref UNLOCK_TCPIP_CORE() point - * to these functions. + * Let @ref LOCK_TCPIP_CORE() and @ref UNLOCK_TCPIP_CORE() point + * to these functions. */ /** diff --git a/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c b/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c index 229a078e..73e0ed34 100644 --- a/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c +++ b/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c @@ -57,11 +57,11 @@ #define netifMTU (1500) -#define netifINTERFACE_TASK_STACK_SIZE ( 350 ) -#define netifINTERFACE_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) -#define netifGUARD_BLOCK_TIME ( 250 ) +#define netifINTERFACE_TASK_STACK_SIZE ( 350 ) +#define netifINTERFACE_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define netifGUARD_BLOCK_TIME ( 250 ) /* The time to block waiting for input. */ -#define emacBLOCK_TIME_WAITING_FOR_INPUT ( ( portTickType ) 100 ) +#define emacBLOCK_TIME_WAITING_FOR_INPUT ( ( portTickType ) 100 ) /* Define those to better describe your network interface. */ #define IFNAME0 's' @@ -103,8 +103,8 @@ static void low_level_init(struct netif *netif) xSemaphoreTake( s_xSemaphore, 0); } - /* initialize MAC address in ethernet MAC */ - ETH_MACAddressConfig(ETH_MAC_Address0, netif->hwaddr); + /* initialize MAC address in ethernet MAC */ + ETH_MACAddressConfig(ETH_MAC_Address0, netif->hwaddr); /* Initialize Tx Descriptors list: Chain Mode */ ETH_DMATxDescChainInit(DMATxDscrTab, &Tx_Buff[0][0], ETH_TXBUFNB); @@ -112,7 +112,7 @@ static void low_level_init(struct netif *netif) ETH_DMARxDescChainInit(DMARxDscrTab, &Rx_Buff[0][0], ETH_RXBUFNB); /* Enable Ethernet Rx interrrupt */ - { + { for(i=0; ihwaddr_len = ETHARP_HWADDR_LEN; @@ -70,9 +70,9 @@ static void low_level_init(struct netif *netif) netif->hwaddr[3] = MAC_ADDR3; netif->hwaddr[4] = MAC_ADDR4; netif->hwaddr[5] = MAC_ADDR5; - - /* initialize MAC address in ethernet MAC */ - ETH_MACAddressConfig(ETH_MAC_Address0, netif->hwaddr); + + /* initialize MAC address in ethernet MAC */ + ETH_MACAddressConfig(ETH_MAC_Address0, netif->hwaddr); /* maximum transfer unit */ netif->mtu = 1500; @@ -174,17 +174,17 @@ static err_t low_level_output(struct netif *netif, struct pbuf *p) bufferoffset = bufferoffset + byteslefttocopy; framelength = framelength + byteslefttocopy; } - - /* Note: padding and CRC for transmitted frame + + /* Note: padding and CRC for transmitted frame are automatically inserted by DMA */ - /* Prepare transmit descriptors to give to DMA*/ + /* Prepare transmit descriptors to give to DMA*/ ETH_Prepare_Transmit_Descriptors(framelength); errval = ERR_OK; error: - + /* When Transmit Underflow flag is set, clear it and issue a Transmit Poll Demand to resume transmission */ if ((ETH->DMASR & ETH_DMASR_TUS) != (uint32_t)RESET) { @@ -215,18 +215,18 @@ static struct pbuf * low_level_input(struct netif *netif) uint32_t bufferoffset = 0; uint32_t payloadoffset = 0; uint32_t byteslefttocopy = 0; - uint32_t i=0; - + uint32_t i=0; + /* get received frame */ frame = ETH_Get_Received_Frame(); - + /* Obtain the size of the packet and put it into the "len" variable. */ len = frame.length; buffer = (u8 *)frame.buffer; - + /* We allocate a pbuf chain of pbufs from the Lwip buffer pool */ p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); - + if (p != NULL) { DMARxDesc = frame.descriptor; @@ -235,17 +235,17 @@ static struct pbuf * low_level_input(struct netif *netif) { byteslefttocopy = q->len; payloadoffset = 0; - + /* Check if the length of bytes to copy in current pbuf is bigger than Rx buffer size*/ while( (byteslefttocopy + bufferoffset) > ETH_RX_BUF_SIZE ) { /* Copy data to pbuf*/ memcpy( (u8_t*)((u8_t*)q->payload + payloadoffset), (u8_t*)((u8_t*)buffer + bufferoffset), (ETH_RX_BUF_SIZE - bufferoffset)); - + /* Point to next descriptor */ DMARxDesc = (ETH_DMADESCTypeDef *)(DMARxDesc->Buffer2NextDescAddr); buffer = (unsigned char *)(DMARxDesc->Buffer1Addr); - + byteslefttocopy = byteslefttocopy - (ETH_RX_BUF_SIZE - bufferoffset); payloadoffset = payloadoffset + (ETH_RX_BUF_SIZE - bufferoffset); bufferoffset = 0; @@ -255,22 +255,22 @@ static struct pbuf * low_level_input(struct netif *netif) bufferoffset = bufferoffset + byteslefttocopy; } } - + /* Release descriptors to DMA */ DMARxDesc =frame.descriptor; /* Set Own bit in Rx descriptors: gives the buffers back to DMA */ for (i=0; iSeg_Count; i++) - { + { DMARxDesc->Status = ETH_DMARxDesc_OWN; DMARxDesc = (ETH_DMADESCTypeDef *)(DMARxDesc->Buffer2NextDescAddr); } - + /* Clear Segment_Count */ DMA_RX_FRAME_infos->Seg_Count =0; - + /* When Rx Buffer unavailable flag is set: clear it and resume reception */ - if ((ETH->DMASR & ETH_DMASR_RBUS) != (u32)RESET) + if ((ETH->DMASR & ETH_DMASR_RBUS) != (u32)RESET) { /* Clear RBUS ETHERNET DMA flag */ ETH->DMASR = ETH_DMASR_RBUS; @@ -302,7 +302,7 @@ err_t ethernetif_input(struct netif *netif) /* entry point to the LwIP stack */ err = netif->input(p, netif); - + if (err != ERR_OK) { LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n")); @@ -328,7 +328,7 @@ err_t ethernetif_init(struct netif *netif) { LWIP_ASSERT("netif != NULL", (netif != NULL)); #if 0 - + #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif->hostname = "lwip"; diff --git a/components/network/lwip/lwip-port/arch/bpstruct.h b/components/network/lwip/lwip-port/arch/bpstruct.h index 177758c5..908957f6 100644 --- a/components/network/lwip/lwip-port/arch/bpstruct.h +++ b/components/network/lwip/lwip-port/arch/bpstruct.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ diff --git a/components/network/lwip/lwip-port/arch/cc.h b/components/network/lwip/lwip-port/arch/cc.h index c3cf8dcf..2217c39a 100644 --- a/components/network/lwip/lwip-port/arch/cc.h +++ b/components/network/lwip/lwip-port/arch/cc.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ @@ -51,7 +51,7 @@ typedef int sys_prot_t; #define U32_F "u" #define S32_F "d" #define X32_F "x" -#define SZT_F "uz" +#define SZT_F "uz" #endif @@ -59,7 +59,7 @@ typedef int sys_prot_t; #if defined (__ICCARM__) #define PACK_STRUCT_BEGIN -#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_STRUCT #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(x) x #define PACK_STRUCT_USE_INCLUDES @@ -67,7 +67,7 @@ typedef int sys_prot_t; #elif defined (__CC_ARM) #define PACK_STRUCT_BEGIN __packed -#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_STRUCT #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(x) x diff --git a/components/network/lwip/lwip-port/arch/cpu.h b/components/network/lwip/lwip-port/arch/cpu.h index 650cf865..f32fb0f2 100644 --- a/components/network/lwip/lwip-port/arch/cpu.h +++ b/components/network/lwip/lwip-port/arch/cpu.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ diff --git a/components/network/lwip/lwip-port/arch/epstruct.h b/components/network/lwip/lwip-port/arch/epstruct.h index 1e1a049c..cbd9ac2d 100644 --- a/components/network/lwip/lwip-port/arch/epstruct.h +++ b/components/network/lwip/lwip-port/arch/epstruct.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ diff --git a/components/network/lwip/lwip-port/arch/init.h b/components/network/lwip/lwip-port/arch/init.h index e622c73a..c255513d 100644 --- a/components/network/lwip/lwip-port/arch/init.h +++ b/components/network/lwip/lwip-port/arch/init.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ diff --git a/components/network/lwip/lwip-port/arch/lib.h b/components/network/lwip/lwip-port/arch/lib.h index 378f25b8..480260d1 100644 --- a/components/network/lwip/lwip-port/arch/lib.h +++ b/components/network/lwip/lwip-port/arch/lib.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ diff --git a/components/network/lwip/lwip-port/arch/perf.h b/components/network/lwip/lwip-port/arch/perf.h index 334d42af..d7541570 100644 --- a/components/network/lwip/lwip-port/arch/perf.h +++ b/components/network/lwip/lwip-port/arch/perf.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ diff --git a/components/network/lwip/lwip-port/arch/sys_arch.h b/components/network/lwip/lwip-port/arch/sys_arch.h index 2e841bd0..9221a1e4 100644 --- a/components/network/lwip/lwip-port/arch/sys_arch.h +++ b/components/network/lwip/lwip-port/arch/sys_arch.h @@ -39,7 +39,7 @@ #define SYS_MBOX_NULL (xQueueHandle)0 #define SYS_SEM_NULL (xSemaphoreHandle)0 -#define SYS_DEFAULT_THREAD_STACK_DEPTH configMINIMAL_STACK_SIZE +#define SYS_DEFAULT_THREAD_STACK_DEPTH configMINIMAL_STACK_SIZE typedef xSemaphoreHandle sys_sem_t; typedef xSemaphoreHandle sys_mutex_t; @@ -48,10 +48,10 @@ typedef xTaskHandle sys_thread_t; typedef struct _sys_arch_state_t { - // Task creation data. - char cTaskName[configMAX_TASK_NAME_LEN]; - unsigned short nStackDepth; - unsigned short nTaskCount; + // Task creation data. + char cTaskName[configMAX_TASK_NAME_LEN]; + unsigned short nStackDepth; + unsigned short nTaskCount; } sys_arch_state_t; @@ -62,6 +62,6 @@ typedef struct _sys_arch_state_t //void sys_set_state(signed char *pTaskName, unsigned short nStackSize); /* Message queue constants. */ -#define archMESG_QUEUE_LENGTH ( 6 ) +#define archMESG_QUEUE_LENGTH ( 6 ) #endif /* __SYS_RTXC_H__ */ diff --git a/components/network/lwip/lwip-port/config/lwipopts.h b/components/network/lwip/lwip-port/config/lwipopts.h index 148c7953..c612f803 100644 --- a/components/network/lwip/lwip-port/config/lwipopts.h +++ b/components/network/lwip/lwip-port/config/lwipopts.h @@ -71,7 +71,7 @@ a lot of data that needs to be copied, this should be set high. */ /* NUM of sys_timeout pool*/ #define MEMP_NUM_SYS_TIMEOUT (LWIP_NUM_SYS_TIMEOUT_INTERNAL + 8 + 3) -#define MEMP_NUM_NETCONN (MEMP_NUM_TCP_PCB + MEMP_NUM_UDP_PCB + MEMP_NUM_TCP_PCB_LISTEN) +#define MEMP_NUM_NETCONN (MEMP_NUM_TCP_PCB + MEMP_NUM_UDP_PCB + MEMP_NUM_TCP_PCB_LISTEN) /* ---------- Pbuf options ---------- */ /* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ @@ -90,9 +90,9 @@ a lot of data that needs to be copied, this should be set high. */ #define TCP_QUEUE_OOSEQ 1 /* TCP Maximum segment size. */ -//#define TCP_MSS (1500 - 40) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */ -//#define TCP_MSS (1500 - 80) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */ -#define TCP_MSS (800 - 40 - 80 + 8) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */ +//#define TCP_MSS (1500 - 40) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */ +//#define TCP_MSS (1500 - 80) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */ +#define TCP_MSS (800 - 40 - 80 + 8) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */ /* TCP sender buffer space (bytes). */ #define TCP_SND_BUF (8*TCP_MSS) @@ -178,7 +178,7 @@ a lot of data that needs to be copied, this should be set high. */ /* CHECKSUM_GEN_UDP==0: Generate checksums by hardware for outgoing UDP packets.*/ #define CHECKSUM_GEN_UDP 0 /* CHECKSUM_GEN_TCP==0: Generate checksums by hardware for outgoing TCP packets.*/ - #define CHECKSUM_GEN_TCP 0 + #define CHECKSUM_GEN_TCP 0 /* CHECKSUM_CHECK_IP==0: Check checksums by hardware for incoming IP packets.*/ #define CHECKSUM_CHECK_IP 0 /* CHECKSUM_CHECK_UDP==0: Check checksums by hardware for incoming UDP packets.*/ @@ -249,7 +249,7 @@ a lot of data that needs to be copied, this should be set high. */ #define DEFAULT_TCP_RECVMBOX_SIZE 2000 #define DEFAULT_ACCEPTMBOX_SIZE 2000 #define DEFAULT_THREAD_STACKSIZE 500 -#define TCPIP_THREAD_PRIO (configMAX_PRIORITIES - 2) +#define TCPIP_THREAD_PRIO (configMAX_PRIORITIES - 2) #define LWIP_COMPAT_MUTEX 0 #define LWIP_TCPIP_CORE_LOCKING 0 diff --git a/components/network/lwip/src/Filelists.mk b/components/network/lwip/src/Filelists.mk index 828b9f2a..2de8aae3 100644 --- a/components/network/lwip/src/Filelists.mk +++ b/components/network/lwip/src/Filelists.mk @@ -1,8 +1,8 @@ # # Copyright (c) 2001, 2002 Swedish Institute of Computer Science. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, +# 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, @@ -11,21 +11,21 @@ # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. +# derived from this software without specific prior written permission. # -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. # # This file is part of the lwIP TCP/IP stack. -# +# # Author: Adam Dunkels # diff --git a/components/network/lwip/src/api/tcpip.c b/components/network/lwip/src/api/tcpip.c index 8e7eacb9..67e2f253 100644 --- a/components/network/lwip/src/api/tcpip.c +++ b/components/network/lwip/src/api/tcpip.c @@ -522,7 +522,7 @@ tcpip_api_call(tcpip_api_call_fn fn, struct tcpip_api_call_data *call) * e.g. the message is allocated once and posted several times from an IRQ * using tcpip_callbackmsg_trycallback(). * Example usage: Trigger execution of an ethernet IRQ DPC routine in lwIP thread context. - * + * * @param function the function to call * @param ctx parameter passed to function * @return a struct pointer to pass to tcpip_callbackmsg_trycallback(). diff --git a/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls.c b/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls.c index 4c1a17ab..a5fe12e0 100644 --- a/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls.c +++ b/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls.c @@ -886,7 +886,7 @@ altcp_tls_free_config(struct altcp_tls_config *conf) } if (conf->ca) { mbedtls_x509_crt_free(conf->ca); - } + } altcp_mbedtls_free_config(conf); } diff --git a/components/network/lwip/src/apps/http/http_client.c b/components/network/lwip/src/apps/http/http_client.c index 82da60d7..6fbb6915 100644 --- a/components/network/lwip/src/apps/http/http_client.c +++ b/components/network/lwip/src/apps/http/http_client.c @@ -615,7 +615,7 @@ httpc_init_connection_addr(httpc_state_t **connection, const httpc_connection_t } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file by passing server IP address * * @param server_addr IP address of the server to connect @@ -660,7 +660,7 @@ httpc_get_file(const ip_addr_t* server_addr, u16_t port, const char* uri, const } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file by passing server name as string (DNS name or IP address string) * * @param server_name server name as string (DNS name or IP address string) @@ -802,7 +802,7 @@ httpc_fs_tcp_recv(void *arg, struct altcp_pcb *pcb, struct pbuf *p, err_t err) } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file to disk by passing server IP address * * @param server_addr IP address of the server to connect @@ -854,7 +854,7 @@ httpc_get_file_to_disk(const ip_addr_t* server_addr, u16_t port, const char* uri } /** - * @ingroup httpc + * @ingroup httpc * HTTP client API: get a file to disk by passing server name as string (DNS name or IP address string) * * @param server_name server name as string (DNS name or IP address string) diff --git a/components/network/lwip/src/apps/http/httpd.c b/components/network/lwip/src/apps/http/httpd.c index ccc9ba72..6e53b484 100644 --- a/components/network/lwip/src/apps/http/httpd.c +++ b/components/network/lwip/src/apps/http/httpd.c @@ -233,7 +233,7 @@ struct http_ssi_state { struct http_ssi_tag_description { const char *lead_in; - const char *lead_out; + const char *lead_out; }; #endif /* LWIP_HTTPD_SSI */ diff --git a/components/network/lwip/src/apps/http/makefsdata/tinydir.h b/components/network/lwip/src/apps/http/makefsdata/tinydir.h index 32ae5e84..88043e8e 100644 --- a/components/network/lwip/src/apps/http/makefsdata/tinydir.h +++ b/components/network/lwip/src/apps/http/makefsdata/tinydir.h @@ -121,7 +121,7 @@ extern "C" { /* readdir_r is a POSIX-only function, and may not be available under various * environments/settings, e.g. MinGW. Use readdir fallback */ #if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE ||\ - _POSIX_SOURCE + _POSIX_SOURCE # define _TINYDIR_HAS_READDIR_R #endif #if _POSIX_C_SOURCE >= 200112L @@ -129,16 +129,16 @@ extern "C" { # include #endif #if _BSD_SOURCE || _SVID_SOURCE || \ - (_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) + (_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) # define _TINYDIR_HAS_DIRFD # include #endif #if defined _TINYDIR_HAS_FPATHCONF && defined _TINYDIR_HAS_DIRFD &&\ - defined _PC_NAME_MAX + defined _PC_NAME_MAX # define _TINYDIR_USE_FPATHCONF #endif #if defined __MINGW32__ || !defined _TINYDIR_HAS_READDIR_R ||\ - !(defined _TINYDIR_USE_FPATHCONF || defined NAME_MAX) + !(defined _TINYDIR_USE_FPATHCONF || defined NAME_MAX) # define _TINYDIR_USE_READDIR #endif @@ -172,42 +172,42 @@ extern "C" { #endif #if !defined(_TINYDIR_MALLOC) - #define _TINYDIR_MALLOC(_size) malloc(_size) - #define _TINYDIR_FREE(_ptr) free(_ptr) + #define _TINYDIR_MALLOC(_size) malloc(_size) + #define _TINYDIR_FREE(_ptr) free(_ptr) #endif /* !defined(_TINYDIR_MALLOC) */ typedef struct tinydir_file { - _tinydir_char_t path[_TINYDIR_PATH_MAX]; - _tinydir_char_t name[_TINYDIR_FILENAME_MAX]; - _tinydir_char_t *extension; - int is_dir; - int is_reg; + _tinydir_char_t path[_TINYDIR_PATH_MAX]; + _tinydir_char_t name[_TINYDIR_FILENAME_MAX]; + _tinydir_char_t *extension; + int is_dir; + int is_reg; #ifndef _MSC_VER #ifdef __MINGW32__ - struct _stat _s; + struct _stat _s; #else - struct stat _s; + struct stat _s; #endif #endif } tinydir_file; typedef struct tinydir_dir { - _tinydir_char_t path[_TINYDIR_PATH_MAX]; - int has_next; - size_t n_files; + _tinydir_char_t path[_TINYDIR_PATH_MAX]; + int has_next; + size_t n_files; - tinydir_file *_files; + tinydir_file *_files; #ifdef _MSC_VER - HANDLE _h; - WIN32_FIND_DATA _f; + HANDLE _h; + WIN32_FIND_DATA _f; #else - _TINYDIR_DIR *_d; - struct _tinydir_dirent *_e; + _TINYDIR_DIR *_d; + struct _tinydir_dirent *_e; #ifndef _TINYDIR_USE_READDIR - struct _tinydir_dirent *_ep; + struct _tinydir_dirent *_ep; #endif #endif } tinydir_dir; @@ -252,184 +252,184 @@ int tinydir_open(tinydir_dir *dir, const _tinydir_char_t *path) { #ifndef _MSC_VER #ifndef _TINYDIR_USE_READDIR - int error; - int size; /* using int size */ + int error; + int size; /* using int size */ #endif #else - _tinydir_char_t path_buf[_TINYDIR_PATH_MAX]; + _tinydir_char_t path_buf[_TINYDIR_PATH_MAX]; #endif - _tinydir_char_t *pathp; + _tinydir_char_t *pathp; - if (dir == NULL || path == NULL || _tinydir_strlen(path) == 0) - { - errno = EINVAL; - return -1; - } - if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) - { - errno = ENAMETOOLONG; - return -1; - } + if (dir == NULL || path == NULL || _tinydir_strlen(path) == 0) + { + errno = EINVAL; + return -1; + } + if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) + { + errno = ENAMETOOLONG; + return -1; + } - /* initialise dir */ - dir->_files = NULL; + /* initialise dir */ + dir->_files = NULL; #ifdef _MSC_VER - dir->_h = INVALID_HANDLE_VALUE; + dir->_h = INVALID_HANDLE_VALUE; #else - dir->_d = NULL; + dir->_d = NULL; #ifndef _TINYDIR_USE_READDIR - dir->_ep = NULL; + dir->_ep = NULL; #endif #endif - tinydir_close(dir); + tinydir_close(dir); - _tinydir_strcpy(dir->path, path); - /* Remove trailing slashes */ - pathp = &dir->path[_tinydir_strlen(dir->path) - 1]; - while (pathp != dir->path && (*pathp == TINYDIR_STRING('\\') || *pathp == TINYDIR_STRING('/'))) - { - *pathp = TINYDIR_STRING('\0'); - pathp++; - } + _tinydir_strcpy(dir->path, path); + /* Remove trailing slashes */ + pathp = &dir->path[_tinydir_strlen(dir->path) - 1]; + while (pathp != dir->path && (*pathp == TINYDIR_STRING('\\') || *pathp == TINYDIR_STRING('/'))) + { + *pathp = TINYDIR_STRING('\0'); + pathp++; + } #ifdef _MSC_VER - _tinydir_strcpy(path_buf, dir->path); - _tinydir_strcat(path_buf, TINYDIR_STRING("\\*")); + _tinydir_strcpy(path_buf, dir->path); + _tinydir_strcat(path_buf, TINYDIR_STRING("\\*")); #if (defined WINAPI_FAMILY) && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP) - dir->_h = FindFirstFileEx(path_buf, FindExInfoStandard, &dir->_f, FindExSearchNameMatch, NULL, 0); + dir->_h = FindFirstFileEx(path_buf, FindExInfoStandard, &dir->_f, FindExSearchNameMatch, NULL, 0); #else - dir->_h = FindFirstFile(path_buf, &dir->_f); + dir->_h = FindFirstFile(path_buf, &dir->_f); #endif - if (dir->_h == INVALID_HANDLE_VALUE) - { - errno = ENOENT; + if (dir->_h == INVALID_HANDLE_VALUE) + { + errno = ENOENT; #else - dir->_d = _tinydir_opendir(path); - if (dir->_d == NULL) - { + dir->_d = _tinydir_opendir(path); + if (dir->_d == NULL) + { #endif - goto bail; - } + goto bail; + } - /* read first file */ - dir->has_next = 1; + /* read first file */ + dir->has_next = 1; #ifndef _MSC_VER #ifdef _TINYDIR_USE_READDIR - dir->_e = _tinydir_readdir(dir->_d); + dir->_e = _tinydir_readdir(dir->_d); #else - /* allocate dirent buffer for readdir_r */ - size = _tinydir_dirent_buf_size(dir->_d); /* conversion to int */ - if (size == -1) return -1; - dir->_ep = (struct _tinydir_dirent*)_TINYDIR_MALLOC(size); - if (dir->_ep == NULL) return -1; + /* allocate dirent buffer for readdir_r */ + size = _tinydir_dirent_buf_size(dir->_d); /* conversion to int */ + if (size == -1) return -1; + dir->_ep = (struct _tinydir_dirent*)_TINYDIR_MALLOC(size); + if (dir->_ep == NULL) return -1; - error = readdir_r(dir->_d, dir->_ep, &dir->_e); - if (error != 0) return -1; + error = readdir_r(dir->_d, dir->_ep, &dir->_e); + if (error != 0) return -1; #endif - if (dir->_e == NULL) - { - dir->has_next = 0; - } + if (dir->_e == NULL) + { + dir->has_next = 0; + } #endif - return 0; + return 0; bail: - tinydir_close(dir); - return -1; + tinydir_close(dir); + return -1; } _TINYDIR_FUNC int tinydir_open_sorted(tinydir_dir *dir, const _tinydir_char_t *path) { - /* Count the number of files first, to pre-allocate the files array */ - size_t n_files = 0; - if (tinydir_open(dir, path) == -1) - { - return -1; - } - while (dir->has_next) - { - n_files++; - if (tinydir_next(dir) == -1) - { - goto bail; - } - } - tinydir_close(dir); + /* Count the number of files first, to pre-allocate the files array */ + size_t n_files = 0; + if (tinydir_open(dir, path) == -1) + { + return -1; + } + while (dir->has_next) + { + n_files++; + if (tinydir_next(dir) == -1) + { + goto bail; + } + } + tinydir_close(dir); - if (tinydir_open(dir, path) == -1) - { - return -1; - } + if (tinydir_open(dir, path) == -1) + { + return -1; + } - dir->n_files = 0; - dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files); - if (dir->_files == NULL) - { - goto bail; - } - while (dir->has_next) - { - tinydir_file *p_file; - dir->n_files++; + dir->n_files = 0; + dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files); + if (dir->_files == NULL) + { + goto bail; + } + while (dir->has_next) + { + tinydir_file *p_file; + dir->n_files++; - p_file = &dir->_files[dir->n_files - 1]; - if (tinydir_readfile(dir, p_file) == -1) - { - goto bail; - } + p_file = &dir->_files[dir->n_files - 1]; + if (tinydir_readfile(dir, p_file) == -1) + { + goto bail; + } - if (tinydir_next(dir) == -1) - { - goto bail; - } + if (tinydir_next(dir) == -1) + { + goto bail; + } - /* Just in case the number of files has changed between the first and - second reads, terminate without writing into unallocated memory */ - if (dir->n_files == n_files) - { - break; - } - } + /* Just in case the number of files has changed between the first and + second reads, terminate without writing into unallocated memory */ + if (dir->n_files == n_files) + { + break; + } + } - qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp); + qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp); - return 0; + return 0; bail: - tinydir_close(dir); - return -1; + tinydir_close(dir); + return -1; } _TINYDIR_FUNC void tinydir_close(tinydir_dir *dir) { - if (dir == NULL) - { - return; - } + if (dir == NULL) + { + return; + } - memset(dir->path, 0, sizeof(dir->path)); - dir->has_next = 0; - dir->n_files = 0; - _TINYDIR_FREE(dir->_files); - dir->_files = NULL; + memset(dir->path, 0, sizeof(dir->path)); + dir->has_next = 0; + dir->n_files = 0; + _TINYDIR_FREE(dir->_files); + dir->_files = NULL; #ifdef _MSC_VER - if (dir->_h != INVALID_HANDLE_VALUE) - { - FindClose(dir->_h); - } - dir->_h = INVALID_HANDLE_VALUE; + if (dir->_h != INVALID_HANDLE_VALUE) + { + FindClose(dir->_h); + } + dir->_h = INVALID_HANDLE_VALUE; #else - if (dir->_d) - { - _tinydir_closedir(dir->_d); - } - dir->_d = NULL; - dir->_e = NULL; + if (dir->_d) + { + _tinydir_closedir(dir->_d); + } + dir->_d = NULL; + dir->_e = NULL; #ifndef _TINYDIR_USE_READDIR - _TINYDIR_FREE(dir->_ep); - dir->_ep = NULL; + _TINYDIR_FREE(dir->_ep); + dir->_ep = NULL; #endif #endif } @@ -437,323 +437,323 @@ void tinydir_close(tinydir_dir *dir) _TINYDIR_FUNC int tinydir_next(tinydir_dir *dir) { - if (dir == NULL) - { - errno = EINVAL; - return -1; - } - if (!dir->has_next) - { - errno = ENOENT; - return -1; - } + if (dir == NULL) + { + errno = EINVAL; + return -1; + } + if (!dir->has_next) + { + errno = ENOENT; + return -1; + } #ifdef _MSC_VER - if (FindNextFile(dir->_h, &dir->_f) == 0) + if (FindNextFile(dir->_h, &dir->_f) == 0) #else #ifdef _TINYDIR_USE_READDIR - dir->_e = _tinydir_readdir(dir->_d); + dir->_e = _tinydir_readdir(dir->_d); #else - if (dir->_ep == NULL) - { - return -1; - } - if (readdir_r(dir->_d, dir->_ep, &dir->_e) != 0) - { - return -1; - } + if (dir->_ep == NULL) + { + return -1; + } + if (readdir_r(dir->_d, dir->_ep, &dir->_e) != 0) + { + return -1; + } #endif - if (dir->_e == NULL) + if (dir->_e == NULL) #endif - { - dir->has_next = 0; + { + dir->has_next = 0; #ifdef _MSC_VER - if (GetLastError() != ERROR_SUCCESS && - GetLastError() != ERROR_NO_MORE_FILES) - { - tinydir_close(dir); - errno = EIO; - return -1; - } + if (GetLastError() != ERROR_SUCCESS && + GetLastError() != ERROR_NO_MORE_FILES) + { + tinydir_close(dir); + errno = EIO; + return -1; + } #endif - } + } - return 0; + return 0; } _TINYDIR_FUNC int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file) { - if (dir == NULL || file == NULL) - { - errno = EINVAL; - return -1; - } + if (dir == NULL || file == NULL) + { + errno = EINVAL; + return -1; + } #ifdef _MSC_VER - if (dir->_h == INVALID_HANDLE_VALUE) + if (dir->_h == INVALID_HANDLE_VALUE) #else - if (dir->_e == NULL) + if (dir->_e == NULL) #endif - { - errno = ENOENT; - return -1; - } - if (_tinydir_strlen(dir->path) + - _tinydir_strlen( + { + errno = ENOENT; + return -1; + } + if (_tinydir_strlen(dir->path) + + _tinydir_strlen( #ifdef _MSC_VER - dir->_f.cFileName + dir->_f.cFileName #else - dir->_e->d_name + dir->_e->d_name #endif - ) + 1 + _TINYDIR_PATH_EXTRA >= - _TINYDIR_PATH_MAX) - { - /* the path for the file will be too long */ - errno = ENAMETOOLONG; - return -1; - } - if (_tinydir_strlen( + ) + 1 + _TINYDIR_PATH_EXTRA >= + _TINYDIR_PATH_MAX) + { + /* the path for the file will be too long */ + errno = ENAMETOOLONG; + return -1; + } + if (_tinydir_strlen( #ifdef _MSC_VER - dir->_f.cFileName + dir->_f.cFileName #else - dir->_e->d_name + dir->_e->d_name #endif - ) >= _TINYDIR_FILENAME_MAX) - { - errno = ENAMETOOLONG; - return -1; - } + ) >= _TINYDIR_FILENAME_MAX) + { + errno = ENAMETOOLONG; + return -1; + } - _tinydir_strcpy(file->path, dir->path); - _tinydir_strcat(file->path, TINYDIR_STRING("/")); - _tinydir_strcpy(file->name, + _tinydir_strcpy(file->path, dir->path); + _tinydir_strcat(file->path, TINYDIR_STRING("/")); + _tinydir_strcpy(file->name, #ifdef _MSC_VER - dir->_f.cFileName + dir->_f.cFileName #else - dir->_e->d_name + dir->_e->d_name #endif - ); - _tinydir_strcat(file->path, file->name); + ); + _tinydir_strcat(file->path, file->name); #ifndef _MSC_VER #ifdef __MINGW32__ - if (_tstat( + if (_tstat( #else - if (stat( + if (stat( #endif - file->path, &file->_s) == -1) - { - return -1; - } + file->path, &file->_s) == -1) + { + return -1; + } #endif - _tinydir_get_ext(file); + _tinydir_get_ext(file); - file->is_dir = + file->is_dir = #ifdef _MSC_VER - !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); + !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); #else - S_ISDIR(file->_s.st_mode); + S_ISDIR(file->_s.st_mode); #endif - file->is_reg = + file->is_reg = #ifdef _MSC_VER - !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || - ( - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) && + !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || + ( + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) && #ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) && #endif #ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) && #endif - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) && - !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)); + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)); #else - S_ISREG(file->_s.st_mode); + S_ISREG(file->_s.st_mode); #endif - return 0; + return 0; } _TINYDIR_FUNC int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, size_t i) { - if (dir == NULL || file == NULL) - { - errno = EINVAL; - return -1; - } - if (i >= dir->n_files) - { - errno = ENOENT; - return -1; - } + if (dir == NULL || file == NULL) + { + errno = EINVAL; + return -1; + } + if (i >= dir->n_files) + { + errno = ENOENT; + return -1; + } - memcpy(file, &dir->_files[i], sizeof(tinydir_file)); - _tinydir_get_ext(file); + memcpy(file, &dir->_files[i], sizeof(tinydir_file)); + _tinydir_get_ext(file); - return 0; + return 0; } _TINYDIR_FUNC int tinydir_open_subdir_n(tinydir_dir *dir, size_t i) { - _tinydir_char_t path[_TINYDIR_PATH_MAX]; - if (dir == NULL) - { - errno = EINVAL; - return -1; - } - if (i >= dir->n_files || !dir->_files[i].is_dir) - { - errno = ENOENT; - return -1; - } + _tinydir_char_t path[_TINYDIR_PATH_MAX]; + if (dir == NULL) + { + errno = EINVAL; + return -1; + } + if (i >= dir->n_files || !dir->_files[i].is_dir) + { + errno = ENOENT; + return -1; + } - _tinydir_strcpy(path, dir->_files[i].path); - tinydir_close(dir); - if (tinydir_open_sorted(dir, path) == -1) - { - return -1; - } + _tinydir_strcpy(path, dir->_files[i].path); + tinydir_close(dir); + if (tinydir_open_sorted(dir, path) == -1) + { + return -1; + } - return 0; + return 0; } /* Open a single file given its path */ _TINYDIR_FUNC int tinydir_file_open(tinydir_file *file, const _tinydir_char_t *path) { - tinydir_dir dir; - int result = 0; - int found = 0; - _tinydir_char_t dir_name_buf[_TINYDIR_PATH_MAX]; - _tinydir_char_t file_name_buf[_TINYDIR_FILENAME_MAX]; - _tinydir_char_t *dir_name; - _tinydir_char_t *base_name; + tinydir_dir dir; + int result = 0; + int found = 0; + _tinydir_char_t dir_name_buf[_TINYDIR_PATH_MAX]; + _tinydir_char_t file_name_buf[_TINYDIR_FILENAME_MAX]; + _tinydir_char_t *dir_name; + _tinydir_char_t *base_name; #if (defined _MSC_VER || defined __MINGW32__) - _tinydir_char_t drive_buf[_TINYDIR_PATH_MAX]; - _tinydir_char_t ext_buf[_TINYDIR_FILENAME_MAX]; + _tinydir_char_t drive_buf[_TINYDIR_PATH_MAX]; + _tinydir_char_t ext_buf[_TINYDIR_FILENAME_MAX]; #endif - if (file == NULL || path == NULL || _tinydir_strlen(path) == 0) - { - errno = EINVAL; - return -1; - } - if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) - { - errno = ENAMETOOLONG; - return -1; - } + if (file == NULL || path == NULL || _tinydir_strlen(path) == 0) + { + errno = EINVAL; + return -1; + } + if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) + { + errno = ENAMETOOLONG; + return -1; + } - /* Get the parent path */ + /* Get the parent path */ #if (defined _MSC_VER || defined __MINGW32__) #if ((defined _MSC_VER) && (_MSC_VER >= 1400)) - _tsplitpath_s( - path, - drive_buf, _TINYDIR_DRIVE_MAX, - dir_name_buf, _TINYDIR_FILENAME_MAX, - file_name_buf, _TINYDIR_FILENAME_MAX, - ext_buf, _TINYDIR_FILENAME_MAX); + _tsplitpath_s( + path, + drive_buf, _TINYDIR_DRIVE_MAX, + dir_name_buf, _TINYDIR_FILENAME_MAX, + file_name_buf, _TINYDIR_FILENAME_MAX, + ext_buf, _TINYDIR_FILENAME_MAX); #else - _tsplitpath( - path, - drive_buf, - dir_name_buf, - file_name_buf, - ext_buf); + _tsplitpath( + path, + drive_buf, + dir_name_buf, + file_name_buf, + ext_buf); #endif /* _splitpath_s not work fine with only filename and widechar support */ #ifdef _UNICODE - if (drive_buf[0] == L'\xFEFE') - drive_buf[0] = '\0'; - if (dir_name_buf[0] == L'\xFEFE') - dir_name_buf[0] = '\0'; + if (drive_buf[0] == L'\xFEFE') + drive_buf[0] = '\0'; + if (dir_name_buf[0] == L'\xFEFE') + dir_name_buf[0] = '\0'; #endif - if (errno) - { - errno = EINVAL; - return -1; - } - /* Emulate the behavior of dirname by returning "." for dir name if it's - empty */ - if (drive_buf[0] == '\0' && dir_name_buf[0] == '\0') - { - _tinydir_strcpy(dir_name_buf, TINYDIR_STRING(".")); - } - /* Concatenate the drive letter and dir name to form full dir name */ - _tinydir_strcat(drive_buf, dir_name_buf); - dir_name = drive_buf; - /* Concatenate the file name and extension to form base name */ - _tinydir_strcat(file_name_buf, ext_buf); - base_name = file_name_buf; + if (errno) + { + errno = EINVAL; + return -1; + } + /* Emulate the behavior of dirname by returning "." for dir name if it's + empty */ + if (drive_buf[0] == '\0' && dir_name_buf[0] == '\0') + { + _tinydir_strcpy(dir_name_buf, TINYDIR_STRING(".")); + } + /* Concatenate the drive letter and dir name to form full dir name */ + _tinydir_strcat(drive_buf, dir_name_buf); + dir_name = drive_buf; + /* Concatenate the file name and extension to form base name */ + _tinydir_strcat(file_name_buf, ext_buf); + base_name = file_name_buf; #else - _tinydir_strcpy(dir_name_buf, path); - dir_name = dirname(dir_name_buf); - _tinydir_strcpy(file_name_buf, path); - base_name =basename(file_name_buf); + _tinydir_strcpy(dir_name_buf, path); + dir_name = dirname(dir_name_buf); + _tinydir_strcpy(file_name_buf, path); + base_name =basename(file_name_buf); #endif - /* Open the parent directory */ - if (tinydir_open(&dir, dir_name) == -1) - { - return -1; - } + /* Open the parent directory */ + if (tinydir_open(&dir, dir_name) == -1) + { + return -1; + } - /* Read through the parent directory and look for the file */ - while (dir.has_next) - { - if (tinydir_readfile(&dir, file) == -1) - { - result = -1; - goto bail; - } - if (_tinydir_strcmp(file->name, base_name) == 0) - { - /* File found */ - found = 1; - break; - } - tinydir_next(&dir); - } - if (!found) - { - result = -1; - errno = ENOENT; - } + /* Read through the parent directory and look for the file */ + while (dir.has_next) + { + if (tinydir_readfile(&dir, file) == -1) + { + result = -1; + goto bail; + } + if (_tinydir_strcmp(file->name, base_name) == 0) + { + /* File found */ + found = 1; + break; + } + tinydir_next(&dir); + } + if (!found) + { + result = -1; + errno = ENOENT; + } bail: - tinydir_close(&dir); - return result; + tinydir_close(&dir); + return result; } _TINYDIR_FUNC void _tinydir_get_ext(tinydir_file *file) { - _tinydir_char_t *period = _tinydir_strrchr(file->name, TINYDIR_STRING('.')); - if (period == NULL) - { - file->extension = &(file->name[_tinydir_strlen(file->name)]); - } - else - { - file->extension = period + 1; - } + _tinydir_char_t *period = _tinydir_strrchr(file->name, TINYDIR_STRING('.')); + if (period == NULL) + { + file->extension = &(file->name[_tinydir_strlen(file->name)]); + } + else + { + file->extension = period + 1; + } } _TINYDIR_FUNC int _tinydir_file_cmp(const void *a, const void *b) { - const tinydir_file *fa = (const tinydir_file *)a; - const tinydir_file *fb = (const tinydir_file *)b; - if (fa->is_dir != fb->is_dir) - { - return -(fa->is_dir - fb->is_dir); - } - return _tinydir_strncmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX); + const tinydir_file *fa = (const tinydir_file *)a; + const tinydir_file *fb = (const tinydir_file *)b; + if (fa->is_dir != fb->is_dir) + { + return -(fa->is_dir - fb->is_dir); + } + return _tinydir_strncmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX); } #ifndef _MSC_VER @@ -772,27 +772,27 @@ from https://womble.decadent.org.uk/readdir_r-advisory.html _TINYDIR_FUNC size_t _tinydir_dirent_buf_size(_TINYDIR_DIR *dirp) { - long name_max; - size_t name_end; - /* parameter may be unused */ - (void)dirp; + long name_max; + size_t name_end; + /* parameter may be unused */ + (void)dirp; #if defined _TINYDIR_USE_FPATHCONF - name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX); - if (name_max == -1) + name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX); + if (name_max == -1) #if defined(NAME_MAX) - name_max = (NAME_MAX > 255) ? NAME_MAX : 255; + name_max = (NAME_MAX > 255) ? NAME_MAX : 255; #else - return (size_t)(-1); + return (size_t)(-1); #endif #elif defined(NAME_MAX) - name_max = (NAME_MAX > 255) ? NAME_MAX : 255; + name_max = (NAME_MAX > 255) ? NAME_MAX : 255; #else #error "buffer size for readdir_r cannot be determined" #endif - name_end = (size_t)offsetof(struct _tinydir_dirent, d_name) + name_max + 1; - return (name_end > sizeof(struct _tinydir_dirent) ? - name_end : sizeof(struct _tinydir_dirent)); + name_end = (size_t)offsetof(struct _tinydir_dirent, d_name) + name_max + 1; + return (name_end > sizeof(struct _tinydir_dirent) ? + name_end : sizeof(struct _tinydir_dirent)); } #endif #endif diff --git a/components/network/lwip/src/apps/smtp/smtp.c b/components/network/lwip/src/apps/smtp/smtp.c index 55303c35..2aa21ce0 100644 --- a/components/network/lwip/src/apps/smtp/smtp.c +++ b/components/network/lwip/src/apps/smtp/smtp.c @@ -1,12 +1,12 @@ /** * @file * SMTP client module - * + * * Author: Simon Goldschmidt * * @defgroup smtp SMTP client * @ingroup apps - * + * * This is simple SMTP client for raw API. * It is a minimal implementation of SMTP as specified in RFC 5321. * @@ -29,7 +29,7 @@ * When using from any other thread than the tcpip_thread (for NO_SYS==0), use * smtp_send_mail_int()! - * + * * SMTP_BODYDH usage: @code{.c} int my_smtp_bodydh_fn(void *arg, struct smtp_bodydh *bdh) @@ -42,11 +42,11 @@ ++bdh->state; return BDH_WORKING; } - - smtp_send_mail_bodycback("sender", "recipient", "subject", + + smtp_send_mail_bodycback("sender", "recipient", "subject", my_smtp_bodydh_fn, my_smtp_result_fn, some_argument); @endcode - * + * * @todo: * - attachments (the main difficulty here is streaming base64-encoding to * prevent having to allocate a buffer for the whole encoded file at once) diff --git a/components/network/lwip/src/core/altcp.c b/components/network/lwip/src/core/altcp.c index d46d6cdb..1156307a 100644 --- a/components/network/lwip/src/core/altcp.c +++ b/components/network/lwip/src/core/altcp.c @@ -158,7 +158,7 @@ altcp_free(struct altcp_pcb *conn) /** * @ingroup altcp - * altcp_new_ip6: @ref altcp_new for IPv6 + * altcp_new_ip6: @ref altcp_new for IPv6 */ struct altcp_pcb * altcp_new_ip6(altcp_allocator_t *allocator) @@ -166,9 +166,9 @@ altcp_new_ip6(altcp_allocator_t *allocator) return altcp_new_ip_type(allocator, IPADDR_TYPE_V6); } -/** +/** * @ingroup altcp - * altcp_new: @ref altcp_new for IPv4 + * altcp_new: @ref altcp_new for IPv4 */ struct altcp_pcb * altcp_new(altcp_allocator_t *allocator) diff --git a/components/network/lwip/src/core/ipv4/dhcp.c b/components/network/lwip/src/core/ipv4/dhcp.c index 534574fe..1427900e 100644 --- a/components/network/lwip/src/core/ipv4/dhcp.c +++ b/components/network/lwip/src/core/ipv4/dhcp.c @@ -1743,7 +1743,7 @@ decode_next: /* make sure the string is really NULL-terminated */ dhcp->boot_file_name[DHCP_FILE_LEN-1] = 0; } -#endif /* LWIP_DHCP_BOOTP_FILE */ +#endif /* LWIP_DHCP_BOOTP_FILE */ return ERR_OK; } diff --git a/components/network/lwip/src/core/ipv6/ip6.c b/components/network/lwip/src/core/ipv6/ip6.c index eda11dc8..afa69f1b 100644 --- a/components/network/lwip/src/core/ipv6/ip6.c +++ b/components/network/lwip/src/core/ipv6/ip6.c @@ -1047,7 +1047,7 @@ options_done: LWIP_DEBUGF(IP6_DEBUG, ("ip6_input: p->len %"U16_F" p->tot_len %"U16_F"\n", p->len, p->tot_len)); ip_data.current_ip_header_tot_len = hlen_tot; - + #if LWIP_RAW /* p points to IPv6 header again for raw_input. */ pbuf_add_header_force(p, hlen_tot); diff --git a/components/network/lwip/src/core/ipv6/mld6.c b/components/network/lwip/src/core/ipv6/mld6.c index 6387d468..fb4e9ef4 100644 --- a/components/network/lwip/src/core/ipv6/mld6.c +++ b/components/network/lwip/src/core/ipv6/mld6.c @@ -6,7 +6,7 @@ * @ingroup ip6 * Multicast listener discovery for IPv6. Aims to be compliant with RFC 2710. * No support for MLDv2.\n - * Note: The allnodes (ff01::1, ff02::1) group is assumed be received by your + * Note: The allnodes (ff01::1, ff02::1) group is assumed be received by your * netif since it must always be received for correct IPv6 operation (e.g. SLAAC). * Ensure the netif filters are configured accordingly!\n * The netif flags also need NETIF_FLAG_MLD6 flag set to enable MLD6 on a diff --git a/components/network/lwip/src/core/ipv6/nd6.c b/components/network/lwip/src/core/ipv6/nd6.c index db0c132e..75899c65 100644 --- a/components/network/lwip/src/core/ipv6/nd6.c +++ b/components/network/lwip/src/core/ipv6/nd6.c @@ -1835,9 +1835,9 @@ nd6_new_router(const ip6_addr_t *router_addr, struct netif *netif) for (router_index = LWIP_ND6_NUM_ROUTERS - 1; router_index >= 0; router_index--) { /* check if router already exists (this is a special case for 2 netifs on the same subnet - e.g. wifi and cable) */ - if(default_router_list[router_index].neighbor_entry == &(neighbor_cache[neighbor_index])){ - return router_index; - } + if(default_router_list[router_index].neighbor_entry == &(neighbor_cache[neighbor_index])){ + return router_index; + } if (default_router_list[router_index].neighbor_entry == NULL) { /* remember lowest free index to create a new entry */ free_router_index = router_index; diff --git a/components/network/lwip/src/core/stats.c b/components/network/lwip/src/core/stats.c index 740ae321..c9729983 100644 --- a/components/network/lwip/src/core/stats.c +++ b/components/network/lwip/src/core/stats.c @@ -190,36 +190,36 @@ stats_netstat(void *ctx) #endif #if LWIP_UDP struct udp_pcb *_udp_pcbs = udp_get_pcbs(); - struct udp_pcb *curr_udp = NULL; + struct udp_pcb *curr_udp = NULL; #endif #if LWIP_RAW struct raw_pcb *_raw_pcbs = raw_get_pcbs(); - struct raw_pcb *curr_raw = NULL; + struct raw_pcb *curr_raw = NULL; #endif LWIP_PLATFORM_DIAG(("netstat tools\r\n")); /* foreach tcp/udp/raw control block */ #if LWIP_TCP // TCP - for (i=0; inext) { + for (curr_tcp = *_tcp_pcb_list[i]; curr_tcp != NULL; curr_tcp = curr_tcp->next) { ipaddr_ntoa_r(&curr_tcp->local_ip, ip_str, sizeof ip_str); LWIP_PLATFORM_DIAG(("TCP\t%s:%"U16_F"\t", ip_str, curr_tcp->local_port)); - + ipaddr_ntoa_r(&curr_tcp->remote_ip, ip_str, sizeof ip_str); - LWIP_PLATFORM_DIAG(("%s:%"U16_F"\t%s\r\n", ip_str, curr_tcp->remote_port, + LWIP_PLATFORM_DIAG(("%s:%"U16_F"\t%s\r\n", ip_str, curr_tcp->remote_port, tcp_debug_state_str(curr_tcp->state))); } } #endif - + #if LWIP_UDP // UDP for (curr_udp = _udp_pcbs; curr_udp != NULL; curr_udp = curr_udp->next) { ipaddr_ntoa_r(&curr_udp->local_ip, ip_str, sizeof ip_str); LWIP_PLATFORM_DIAG(("UDP\t%s:%"U16_F"\t", ip_str, curr_udp->local_port)); - + ipaddr_ntoa_r(&curr_udp->remote_ip, ip_str, sizeof ip_str); LWIP_PLATFORM_DIAG(("%s:%"U16_F"\r\n", ip_str, curr_udp->remote_port)); } @@ -230,7 +230,7 @@ stats_netstat(void *ctx) for (curr_raw = _raw_pcbs; curr_raw != NULL; curr_raw = curr_raw->next) { ipaddr_ntoa_r(&curr_raw->local_ip, ip_str, sizeof ip_str); LWIP_PLATFORM_DIAG(("RAW\t%s\t", ip_str)); - + ipaddr_ntoa_r(&curr_raw->remote_ip, ip_str, sizeof ip_str); LWIP_PLATFORM_DIAG(("%s\t%d\r\n", ip_str, curr_raw->protocol)); } diff --git a/components/network/lwip/src/core/sys.c b/components/network/lwip/src/core/sys.c index 5f08352b..69d7197a 100644 --- a/components/network/lwip/src/core/sys.c +++ b/components/network/lwip/src/core/sys.c @@ -45,30 +45,30 @@ * No need to implement functions in this section in NO_SYS mode. * The OS-specific code should be implemented in arch/sys_arch.h * and sys_arch.c of your port. - * + * * The operating system emulation layer provides a common interface * between the lwIP code and the underlying operating system kernel. The * general idea is that porting lwIP to new architectures requires only * small changes to a few header files and a new sys_arch * implementation. It is also possible to do a sys_arch implementation * that does not rely on any underlying operating system. - * + * * The sys_arch provides semaphores, mailboxes and mutexes to lwIP. For the full * lwIP functionality, multiple threads support can be implemented in the * sys_arch, but this is not required for the basic lwIP * functionality. Timer scheduling is implemented in lwIP, but can be implemented * by the sys_arch port (LWIP_TIMERS_CUSTOM==1). - * + * * In addition to the source file providing the functionality of sys_arch, * the OS emulation layer must provide several header files defining * macros used throughout lwip. The files required and the macros they * must define are listed below the sys_arch description. - * + * * Since lwIP 1.4.0, semaphore, mutexes and mailbox functions are prototyped in a way that * allows both using pointers or actual OS structures to be used. This way, memory * required for such types can be either allocated in place (globally or on the * stack) or on the heap (allocated internally in the "*_new()" functions). - * + * * Note: * ----- * Be careful with using mem_malloc() in sys_arch. When malloc() refers to @@ -96,7 +96,7 @@ * Mailboxes should be implemented as a queue which allows multiple messages * to be posted (implementing as a rendez-vous point where only one message can be * posted at a time can have a highly negative impact on performance). A message - * in a mailbox is just a pointer, nothing more. + * in a mailbox is just a pointer, nothing more. * * @defgroup sys_time Time * @ingroup sys_layer diff --git a/components/network/lwip/src/core/tcp.c b/components/network/lwip/src/core/tcp.c index 0a415ba9..c3a9a2a3 100644 --- a/components/network/lwip/src/core/tcp.c +++ b/components/network/lwip/src/core/tcp.c @@ -11,7 +11,7 @@ * Common functions for the TCP implementation, such as functions * for manipulating the data structures and the TCP timer functions. TCP functions * related to input and output is found in tcp_in.c and tcp_out.c respectively.\n - * + * * TCP connection setup * -------------------- * The functions used for setting up connections is similar to that of @@ -24,7 +24,7 @@ * - tcp_listen() and tcp_listen_with_backlog() * - tcp_accept() * - tcp_connect() - * + * * Sending TCP data * ---------------- * TCP data is sent by enqueueing the data with a call to tcp_write() and @@ -34,7 +34,7 @@ * - tcp_write() * - tcp_output() * - tcp_sent() - * + * * Receiving TCP data * ------------------ * TCP data reception is callback based - an application specified @@ -44,7 +44,7 @@ * window. * - tcp_recv() * - tcp_recved() - * + * * Application polling * ------------------- * When a connection is idle (i.e., no data is either transmitted or @@ -62,7 +62,7 @@ * - tcp_close() * - tcp_abort() * - tcp_err() - * + * */ /* @@ -471,7 +471,7 @@ tcp_close_shutdown_fin(struct tcp_pcb *pcb) * a closing state), the connection is closed, and put in a closing state. * The pcb is then automatically freed in tcp_slowtmr(). It is therefore * unsafe to reference it (unless an error is returned). - * + * * The function may return ERR_MEM if no memory * was available for closing the connection. If so, the application * should wait and try again either by using the acknowledgment @@ -799,7 +799,7 @@ tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err) * When an incoming connection is accepted, the function specified with * the tcp_accept() function will be called. The pcb has to be bound * to a local port with the tcp_bind() function. - * + * * The tcp_listen() function returns a new connection identifier, and * the one passed as an argument to the function will be * deallocated. The reason for this behavior is that less memory is @@ -814,7 +814,7 @@ tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err) * The backlog limits the number of outstanding connections * in the listen queue to the value specified by the backlog argument. * To use it, your need to set TCP_LISTEN_BACKLOG=1 in your lwipopts.h. - * + * * @param pcb the original tcp_pcb * @param backlog the incoming connections queue limit * @return tcp_pcb used for listening, consumes less memory. @@ -1041,7 +1041,7 @@ again: * Connects to another host. The function given as the "connected" * argument will be called when the connection has been established. * Sets up the pcb to connect to the remote host and sends the - * initial SYN segment which opens the connection. + * initial SYN segment which opens the connection. * * The tcp_connect() function returns immediately; it does not wait for * the connection to be properly setup. Instead, it will call the @@ -1721,14 +1721,14 @@ tcp_kill_prio(u8_t prio) mprio = LWIP_MIN(TCP_PRIO_MAX, prio); - /* We want to kill connections with a lower prio, so bail out if + /* We want to kill connections with a lower prio, so bail out if * supplied prio is 0 - there can never be a lower prio */ if (mprio == 0) { return; } - /* We only want kill connections with a lower prio, so decrement prio by one + /* We only want kill connections with a lower prio, so decrement prio by one * and start searching for oldest connection with same or lower priority than mprio. * We want to find the connections with the lowest possible prio, and among * these the one with the longest inactivity time. @@ -2051,7 +2051,7 @@ tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent) * @ingroup tcp_raw * Used to specify the function that should be called when a fatal error * has occurred on the connection. - * + * * If a connection is aborted because of an error, the application is * alerted of this event by the err callback. Errors that might abort a * connection are when there is a shortage of memory. The callback @@ -2101,7 +2101,7 @@ tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept) * number of TCP coarse grained timer shots, which typically occurs * twice a second. An interval of 10 means that the application would * be polled every 5 seconds. - * + * * When a connection is idle (i.e., no data is either transmitted or * received), lwIP will repeatedly poll the application by calling a * specified callback function. This can be used either as a watchdog diff --git a/components/network/lwip/src/core/tcp_out.c b/components/network/lwip/src/core/tcp_out.c index 724df109..a00ce23f 100644 --- a/components/network/lwip/src/core/tcp_out.c +++ b/components/network/lwip/src/core/tcp_out.c @@ -355,7 +355,7 @@ tcp_write_checks(struct tcp_pcb *pcb, u16_t len) * it can send them more efficiently by combining them together). * To prompt the system to send data now, call tcp_output() after * calling tcp_write(). - * + * * This function enqueues the data pointed to by the argument dataptr. The length of * the data is passed as the len parameter. The apiflags can be one or more of: * - TCP_WRITE_FLAG_COPY: indicates whether the new memory should be allocated diff --git a/components/network/lwip/src/core/timeouts.c b/components/network/lwip/src/core/timeouts.c index f37acfec..8c8d4972 100644 --- a/components/network/lwip/src/core/timeouts.c +++ b/components/network/lwip/src/core/timeouts.c @@ -241,7 +241,7 @@ lwip_cyclic_timer(void *arg) cyclic->handler(); now = sys_now(); - next_timeout_time = (u32_t)(current_timeout_due_time + cyclic->interval_ms); /* overflow handled by TIME_LESS_THAN macro */ + next_timeout_time = (u32_t)(current_timeout_due_time + cyclic->interval_ms); /* overflow handled by TIME_LESS_THAN macro */ if (TIME_LESS_THAN(next_timeout_time, now)) { /* timer would immediately expire again -> "overload" -> restart without any correction */ #if LWIP_DEBUG_TIMERNAMES @@ -296,7 +296,7 @@ sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg) LWIP_ASSERT("Timeout time too long, max is LWIP_UINT32_MAX/4 msecs", msecs <= (LWIP_UINT32_MAX / 4)); - next_timeout_time = (u32_t)(sys_now() + msecs); /* overflow handled by TIME_LESS_THAN macro */ + next_timeout_time = (u32_t)(sys_now() + msecs); /* overflow handled by TIME_LESS_THAN macro */ #if LWIP_DEBUG_TIMERNAMES sys_timeout_abs(next_timeout_time, handler, arg, handler_name); diff --git a/components/network/lwip/src/core/udp.c b/components/network/lwip/src/core/udp.c index cb0b5276..b11363ba 100644 --- a/components/network/lwip/src/core/udp.c +++ b/components/network/lwip/src/core/udp.c @@ -911,7 +911,7 @@ udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *d /** * @ingroup udp_raw * Bind an UDP PCB. - * + * * @param pcb UDP PCB to be bound with a local address ipaddr and port. * @param ipaddr local IP address to bind with. Use IP_ANY_TYPE to * bind to all local interfaces. @@ -1168,8 +1168,8 @@ udp_recv(struct udp_pcb *pcb, udp_recv_fn recv, void *recv_arg) /** * @ingroup udp_raw - * Removes and deallocates the pcb. - * + * Removes and deallocates the pcb. + * * @param pcb UDP PCB to be removed. The PCB is removed from the list of * UDP PCB's and the data structure is freed from memory. * @@ -1242,7 +1242,7 @@ udp_new(void) * Create a UDP PCB for specific IP type. * The pcb is not active until it has either been bound to a local address * or connected to a remote address. - * + * * @param type IP address type, see @ref lwip_ip_addr_type definitions. * If you want to listen to IPv4 and IPv6 (dual-stack) packets, * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE. @@ -1314,7 +1314,7 @@ udp_debug_print(struct udp_hdr *udphdr) #if LWIP_STATS struct udp_pcb *udp_get_pcbs(void) { - return udp_pcbs; + return udp_pcbs; } #endif diff --git a/components/network/lwip/src/include/compat/posix/net/if.h b/components/network/lwip/src/include/compat/posix/net/if.h index 6b8e63a5..8b8e4819 100644 --- a/components/network/lwip/src/include/compat/posix/net/if.h +++ b/components/network/lwip/src/include/compat/posix/net/if.h @@ -7,7 +7,7 @@ * Copyright (c) 2017 Joel Cunningham, Garmin International, Inc. * All rights reserved. * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -16,17 +16,17 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. diff --git a/components/network/lwip/src/include/lwip/api.h b/components/network/lwip/src/include/lwip/api.h index c2afaf26..739f8be5 100644 --- a/components/network/lwip/src/include/lwip/api.h +++ b/components/network/lwip/src/include/lwip/api.h @@ -153,27 +153,27 @@ enum netconn_state { }; /** Used to inform the callback function about changes - * + * * Event explanation: - * + * * In the netconn implementation, there are three ways to block a client: - * + * * - accept mbox (sys_arch_mbox_fetch(&conn->acceptmbox, &accept_ptr, 0); in netconn_accept()) * - receive mbox (sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0); in netconn_recv_data()) * - send queue is full (sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); in lwip_netconn_do_write()) - * + * * The events have to be seen as events signaling the state of these mboxes/semaphores. For non-blocking * connections, you need to know in advance whether a call to a netconn function call would block or not, * and these events tell you about that. - * - * RCVPLUS events say: Safe to perform a potentially blocking call call once more. + * + * RCVPLUS events say: Safe to perform a potentially blocking call call once more. * They are counted in sockets - three RCVPLUS events for accept mbox means you are safe * to call netconn_accept 3 times without being blocked. * Same thing for receive mbox. - * + * * RCVMINUS events say: Your call to to a possibly blocking function is "acknowledged". * Socket implementation decrements the counter. - * + * * For TX, there is no need to count, its merely a flag. SENDPLUS means you may send something. * SENDPLUS occurs when enough data was delivered to peer so netconn_send() can be called again. * A SENDMINUS event occurs when the next call to a netconn_send() would be blocking. diff --git a/components/network/lwip/src/include/lwip/apps/fs.h b/components/network/lwip/src/include/lwip/apps/fs.h index 67b9a60a..5be77c1b 100644 --- a/components/network/lwip/src/include/lwip/apps/fs.h +++ b/components/network/lwip/src/include/lwip/apps/fs.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Adam Dunkels * */ diff --git a/components/network/lwip/src/include/lwip/apps/http_client.h b/components/network/lwip/src/include/lwip/apps/http_client.h index 8a063083..d39e1bf8 100644 --- a/components/network/lwip/src/include/lwip/apps/http_client.h +++ b/components/network/lwip/src/include/lwip/apps/http_client.h @@ -52,7 +52,7 @@ extern "C" { #endif /** - * @ingroup httpc + * @ingroup httpc * HTTPC_HAVE_FILE_IO: define this to 1 to have functions dowloading directly * to disk via fopen/fwrite. * These functions are example implementations of the interface only. @@ -62,13 +62,13 @@ extern "C" { #endif /** - * @ingroup httpc + * @ingroup httpc * The default TCP port used for HTTP */ #define HTTP_DEFAULT_PORT LWIP_IANA_PORT_HTTP /** - * @ingroup httpc + * @ingroup httpc * HTTP client result codes */ typedef enum ehttpc_result { @@ -97,7 +97,7 @@ typedef enum ehttpc_result { typedef struct _httpc_state httpc_state_t; /** - * @ingroup httpc + * @ingroup httpc * Prototype of a http client callback function * * @param arg argument specified when initiating the request @@ -110,7 +110,7 @@ typedef struct _httpc_state httpc_state_t; typedef void (*httpc_result_fn)(void *arg, httpc_result_t httpc_result, u32_t rx_content_len, u32_t srv_res, err_t err); /** - * @ingroup httpc + * @ingroup httpc * Prototype of http client callback: called when the headers are received * * @param connection http client connection diff --git a/components/network/lwip/src/include/lwip/apps/httpd_opts.h b/components/network/lwip/src/include/lwip/apps/httpd_opts.h index 321fd6f8..ad810fa0 100644 --- a/components/network/lwip/src/include/lwip/apps/httpd_opts.h +++ b/components/network/lwip/src/include/lwip/apps/httpd_opts.h @@ -175,7 +175,7 @@ #define HTTPD_DEBUG LWIP_DBG_OFF #endif -/** Set this to 1 to use a memp pool for allocating +/** Set this to 1 to use a memp pool for allocating * struct http_state instead of the heap. * If enabled, you'll need to define MEMP_NUM_PARALLEL_HTTPD_CONNS * (and MEMP_NUM_PARALLEL_HTTPD_SSI_CONNS for SSI) to set the size of diff --git a/components/network/lwip/src/include/lwip/apps/mqtt.h b/components/network/lwip/src/include/lwip/apps/mqtt.h index c2bb2288..f099812d 100644 --- a/components/network/lwip/src/include/lwip/apps/mqtt.h +++ b/components/network/lwip/src/include/lwip/apps/mqtt.h @@ -134,7 +134,7 @@ enum { MQTT_DATA_FLAG_LAST = 1 }; -/** +/** * @ingroup mqtt * Function prototype for MQTT incoming publish data callback function. Called when data * arrives to a subscribed topic @see mqtt_subscribe @@ -149,7 +149,7 @@ enum { typedef void (*mqtt_incoming_data_cb_t)(void *arg, const u8_t *data, u16_t len, u8_t flags); -/** +/** * @ingroup mqtt * Function prototype for MQTT incoming publish function. Called when an incoming publish * arrives to a subscribed topic @see mqtt_subscribe diff --git a/components/network/lwip/src/include/lwip/apps/smtp_opts.h b/components/network/lwip/src/include/lwip/apps/smtp_opts.h index bc743f67..4ce2d512 100644 --- a/components/network/lwip/src/include/lwip/apps/smtp_opts.h +++ b/components/network/lwip/src/include/lwip/apps/smtp_opts.h @@ -6,14 +6,14 @@ #ifdef __cplusplus extern "C" { #endif - + /** * @defgroup smtp_opts Options * @ingroup smtp - * + * * @{ */ - + /** Set this to 1 to enable data handler callback on BODY */ #ifndef SMTP_BODYDH #define SMTP_BODYDH 0 diff --git a/components/network/lwip/src/include/lwip/apps/snmp_core.h b/components/network/lwip/src/include/lwip/apps/snmp_core.h index 6021c722..5a8a49f8 100644 --- a/components/network/lwip/src/include/lwip/apps/snmp_core.h +++ b/components/network/lwip/src/include/lwip/apps/snmp_core.h @@ -101,7 +101,7 @@ extern "C" { /** error codes predefined by SNMP prot. */ typedef enum { SNMP_ERR_NOERROR = 0, -/* +/* outdated v1 error codes. do not use anmore! #define SNMP_ERR_NOSUCHNAME 2 use SNMP_ERR_NOSUCHINSTANCE instead #define SNMP_ERR_BADVALUE 3 use SNMP_ERR_WRONGTYPE,SNMP_ERR_WRONGLENGTH,SNMP_ERR_WRONGENCODING or SNMP_ERR_WRONGVALUE instead diff --git a/components/network/lwip/src/include/lwip/apps/tftp_opts.h b/components/network/lwip/src/include/lwip/apps/tftp_opts.h index 198f632b..ec0b6316 100644 --- a/components/network/lwip/src/include/lwip/apps/tftp_opts.h +++ b/components/network/lwip/src/include/lwip/apps/tftp_opts.h @@ -11,7 +11,7 @@ * */ -/* +/* * Redistribution and use in source and binary forms, with or without * modification,are permitted provided that the following conditions are met: * diff --git a/components/network/lwip/src/include/lwip/apps/tftp_server.h b/components/network/lwip/src/include/lwip/apps/tftp_server.h index 0a7fbee0..efd50a05 100644 --- a/components/network/lwip/src/include/lwip/apps/tftp_server.h +++ b/components/network/lwip/src/include/lwip/apps/tftp_server.h @@ -11,7 +11,7 @@ * */ -/* +/* * Redistribution and use in source and binary forms, with or without * modification,are permitted provided that the following conditions are met: * @@ -67,7 +67,7 @@ struct tftp_context { */ void (*close)(void* handle); /** - * Read from file + * Read from file * @param handle File handle returned by open() * @param buf Target buffer to copy read data to * @param bytes Number of bytes to copy to buf diff --git a/components/network/lwip/src/include/lwip/arch.h b/components/network/lwip/src/include/lwip/arch.h index 7f82f563..2c951dcc 100644 --- a/components/network/lwip/src/include/lwip/arch.h +++ b/components/network/lwip/src/include/lwip/arch.h @@ -74,7 +74,7 @@ /** Platform specific diagnostic output.\n * Note the default implementation pulls in printf, which may - * in turn pull in a lot of standard libary code. In resource-constrained + * in turn pull in a lot of standard libary code. In resource-constrained * systems, this should be defined to something less resource-consuming. */ #ifndef LWIP_PLATFORM_DIAG @@ -85,7 +85,7 @@ /** Platform specific assertion handling.\n * Note the default implementation pulls in printf, fflush and abort, which may - * in turn pull in a lot of standard libary code. In resource-constrained + * in turn pull in a lot of standard libary code. In resource-constrained * systems, this should be defined to something less resource-consuming. */ #ifndef LWIP_PLATFORM_ASSERT diff --git a/components/network/lwip/src/include/lwip/igmp.h b/components/network/lwip/src/include/lwip/igmp.h index ffd80e68..0a16db03 100644 --- a/components/network/lwip/src/include/lwip/igmp.h +++ b/components/network/lwip/src/include/lwip/igmp.h @@ -99,7 +99,7 @@ err_t igmp_leavegroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr); err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr); void igmp_tmr(void); -/** @ingroup igmp +/** @ingroup igmp * Get list head of IGMP groups for netif. * Note: The allsystems group IP is contained in the list as first entry. * @see @ref netif_set_igmp_mac_filter() diff --git a/components/network/lwip/src/include/lwip/ip_addr.h b/components/network/lwip/src/include/lwip/ip_addr.h index 2f977709..ee7a0c9d 100644 --- a/components/network/lwip/src/include/lwip/ip_addr.h +++ b/components/network/lwip/src/include/lwip/ip_addr.h @@ -404,7 +404,7 @@ extern const ip_addr_t ip_addr_broadcast; extern const ip_addr_t ip6_addr_any; -/** +/** * @ingroup ip6addr * IP6_ADDR_ANY can be used as a fixed ip_addr_t * for the IPv6 wildcard address diff --git a/components/network/lwip/src/include/lwip/mld6.h b/components/network/lwip/src/include/lwip/mld6.h index 7fa0797f..2764fdd4 100644 --- a/components/network/lwip/src/include/lwip/mld6.h +++ b/components/network/lwip/src/include/lwip/mld6.h @@ -84,7 +84,7 @@ err_t mld6_leavegroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); /** @ingroup mld6 * Get list head of MLD6 groups for netif. - * Note: The allnodes group IP is NOT in the list, since it must always + * Note: The allnodes group IP is NOT in the list, since it must always * be received for correct IPv6 operation. * @see @ref netif_set_mld_mac_filter() */ diff --git a/components/network/lwip/src/include/lwip/netif.h b/components/network/lwip/src/include/lwip/netif.h index 911196ab..03b48a0e 100644 --- a/components/network/lwip/src/include/lwip/netif.h +++ b/components/network/lwip/src/include/lwip/netif.h @@ -345,7 +345,7 @@ struct netif { u8_t flags; /** descriptive abbreviation */ char name[2]; - /** number of this interface. Used for @ref if_api and @ref netifapi_netif, + /** number of this interface. Used for @ref if_api and @ref netifapi_netif, * as well as for IPv6 zones */ u8_t num; #if LWIP_IPV6_AUTOCONFIG diff --git a/components/network/lwip/src/include/lwip/opt.h b/components/network/lwip/src/include/lwip/opt.h index 82c420c1..1e8eb6a3 100644 --- a/components/network/lwip/src/include/lwip/opt.h +++ b/components/network/lwip/src/include/lwip/opt.h @@ -1601,7 +1601,7 @@ #endif /** - * LWIP_NETIF_EXT_STATUS_CALLBACK==1: Support an extended callback function + * LWIP_NETIF_EXT_STATUS_CALLBACK==1: Support an extended callback function * for several netif related event that supports multiple subscribers. * @see netif_ext_status_callback */ @@ -2389,7 +2389,7 @@ * All addresses that have a scope according to the default policy (link-local * unicast addresses, interface-local and link-local multicast addresses) should * now have a zone set on them before being passed to the core API, although - * lwIP will currently attempt to select a zone on the caller's behalf when + * lwIP will currently attempt to select a zone on the caller's behalf when * necessary. Applications that directly assign IPv6 addresses to interfaces * (which is NOT recommended) must now ensure that link-local addresses carry * the netif's zone. See the new ip6_zone.h header file for more information and @@ -3027,8 +3027,8 @@ * - src: source eth address * - dst: destination eth address * - eth_type: ethernet type to packet to be sent\n - * - * + * + * * Return values: * - <0: Packet shall not contain VLAN header. * - 0 <= return value <= 0xFFFF: Packet shall contain VLAN header. Return value is prio_vid in host byte order. diff --git a/components/network/lwip/src/include/lwip/pbuf.h b/components/network/lwip/src/include/lwip/pbuf.h index 82902a4e..2ddd913a 100644 --- a/components/network/lwip/src/include/lwip/pbuf.h +++ b/components/network/lwip/src/include/lwip/pbuf.h @@ -55,7 +55,7 @@ extern "C" { #define LWIP_SUPPORT_CUSTOM_PBUF ((IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG)) #endif -/** @ingroup pbuf +/** @ingroup pbuf * PBUF_NEEDS_COPY(p): return a boolean value indicating whether the given * pbuf needs to be copied in order to be kept around beyond the current call * stack without risking being corrupted. The default setting provides safety: diff --git a/components/network/lwip/src/include/lwip/prot/ieee.h b/components/network/lwip/src/include/lwip/prot/ieee.h index abbb9e31..cd4d2dea 100644 --- a/components/network/lwip/src/include/lwip/prot/ieee.h +++ b/components/network/lwip/src/include/lwip/prot/ieee.h @@ -53,7 +53,7 @@ enum lwip_ieee_eth_type { /** Internet protocol v4 */ ETHTYPE_IP = 0x0800U, /** Address resolution protocol */ - ETHTYPE_ARP = 0x0806U, + ETHTYPE_ARP = 0x0806U, /** Wake on lan */ ETHTYPE_WOL = 0x0842U, /** RARP */ diff --git a/components/network/lwip/src/include/lwip/raw.h b/components/network/lwip/src/include/lwip/raw.h index d99784d9..4f3f2532 100644 --- a/components/network/lwip/src/include/lwip/raw.h +++ b/components/network/lwip/src/include/lwip/raw.h @@ -134,7 +134,7 @@ void raw_recv (struct raw_pcb *pcb, raw_recv_fn recv, void *re #define raw_get_multicast_ttl(pcb) ((pcb)->mcast_ttl) #endif /* LWIP_MULTICAST_TX_OPTIONS */ -#if LWIP_STATS +#if LWIP_STATS struct raw_pcb *raw_get_pcbs(void); #endif diff --git a/components/network/lwip/src/include/lwip/sys.h b/components/network/lwip/src/include/lwip/sys.h index 168e465b..cf13e1dc 100644 --- a/components/network/lwip/src/include/lwip/sys.h +++ b/components/network/lwip/src/include/lwip/sys.h @@ -130,7 +130,7 @@ typedef void (*lwip_thread_fn)(void *arg); * If the mutex has been created, ERR_OK should be returned. Returning any * other error will provide a hint what went wrong, but except for assertions, * no real error handling is implemented. - * + * * @param mutex pointer to the mutex to create * @return ERR_OK if successful, another err_t otherwise */ @@ -205,13 +205,13 @@ void sys_sem_signal(sys_sem_t *sem); * "timeout" argument is non-zero, the thread should only be blocked for the * specified time (measured in milliseconds). If the "timeout" argument is zero, * the thread should be blocked until the semaphore is signalled. - * + * * The return value is SYS_ARCH_TIMEOUT if the semaphore wasn't signaled within * the specified time or any other value if it was signaled (with or without * waiting). * Notice that lwIP implements a function with a similar name, * sys_sem_wait(), that uses the sys_arch_sem_wait() function. - * + * * @param sem the semaphore to wait for * @param timeout timeout in milliseconds to wait (0 = wait forever) * @return SYS_ARCH_TIMEOUT on timeout, any other value on success @@ -277,7 +277,7 @@ void sys_msleep(u32_t ms); /* only has a (close to) 1 ms resolution. */ * If the mailbox has been created, ERR_OK should be returned. Returning any * other error will provide a hint what went wrong, but except for assertions, * no real error handling is implemented. - * + * * @param mbox pointer to the mbox to create * @param size (minimum) number of messages in this mbox * @return ERR_OK if successful, another err_t otherwise @@ -287,7 +287,7 @@ err_t sys_mbox_new(sys_mbox_t *mbox, int size); * @ingroup sys_mbox * Post a message to an mbox - may not fail * -> blocks if full, only to be used from tasks NOT from ISR! - * + * * @param mbox mbox to posts the message * @param msg message to post (ATTENTION: can be NULL) */ @@ -297,7 +297,7 @@ void sys_mbox_post(sys_mbox_t *mbox, void *msg); * Try to post a message to an mbox - may fail if full. * Can be used from ISR (if the sys arch layer allows this). * Returns ERR_MEM if it is full, else, ERR_OK if the "msg" is posted. - * + * * @param mbox mbox to posts the message * @param msg message to post (ATTENTION: can be NULL) */ @@ -307,7 +307,7 @@ err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg); * Try to post a message to an mbox - may fail if full. * To be be used from ISR. * Returns ERR_MEM if it is full, else, ERR_OK if the "msg" is posted. - * + * * @param mbox mbox to posts the message * @param msg message to post (ATTENTION: can be NULL) */ @@ -324,10 +324,10 @@ err_t sys_mbox_trypost_fromisr(sys_mbox_t *mbox, void *msg); * The return values are the same as for the sys_arch_sem_wait() function: * SYS_ARCH_TIMEOUT if there was a timeout, any other value if a messages * is received. - * + * * Note that a function with a similar name, sys_mbox_fetch(), is - * implemented by lwIP. - * + * implemented by lwIP. + * * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @param timeout maximum time (in milliseconds) to wait for a message (0 = wait forever) @@ -346,7 +346,7 @@ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout); * example, a naive implementation could be: * \#define sys_arch_mbox_tryfetch(mbox,msg) sys_arch_mbox_fetch(mbox,msg,1) * although this would introduce unnecessary delays. - * + * * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @return 0 (milliseconds) if a message has been received @@ -363,7 +363,7 @@ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg); * Deallocates a mailbox. If there are messages still present in the * mailbox when the mailbox is deallocated, it is an indication of a * programming error in lwIP and the developer should be notified. - * + * * @param mbox mbox to delete */ void sys_mbox_free(sys_mbox_t *mbox); @@ -411,7 +411,7 @@ void sys_mbox_set_invalid(sys_mbox_t *mbox); * the "stacksize" parameter. The id of the new thread is returned. Both the id * and the priority are system dependent. * ATTENTION: although this function returns a value, it MUST NOT FAIL (ports have to assert this!) - * + * * @param name human-readable name for the thread (used for debugging purposes) * @param thread thread-function * @param arg parameter passed to 'thread' diff --git a/components/network/lwip/src/include/netif/lowpan6_ble.h b/components/network/lwip/src/include/netif/lowpan6_ble.h index 01896a7f..5190e7bc 100644 --- a/components/network/lwip/src/include/netif/lowpan6_ble.h +++ b/components/network/lwip/src/include/netif/lowpan6_ble.h @@ -6,7 +6,7 @@ /* * Copyright (c) 2017 Benjamin Aigner * Copyright (c) 2015 Inico Technologies Ltd. , Author: Ivan Delamer - * + * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -32,10 +32,10 @@ * OF SUCH DAMAGE. * * Author: Benjamin Aigner - * + * * Based on the original 6lowpan implementation of lwIP ( @see 6lowpan.c) */ - + #ifndef LWIP_HDR_LOWPAN6_BLE_H #define LWIP_HDR_LOWPAN6_BLE_H diff --git a/components/network/lwip/src/include/netif/lowpan6_opts.h b/components/network/lwip/src/include/netif/lowpan6_opts.h index 17d46cdc..32e5c5ee 100644 --- a/components/network/lwip/src/include/netif/lowpan6_opts.h +++ b/components/network/lwip/src/include/netif/lowpan6_opts.h @@ -109,7 +109,7 @@ #define LWIP_RFC7668_IP_UNCOMPRESSED_DEBUG LWIP_DBG_OFF #endif -/** LWIP_RFC7668_LINUX_WORKAROUND_PUBLIC_ADDRESS: +/** LWIP_RFC7668_LINUX_WORKAROUND_PUBLIC_ADDRESS: * Currently, the linux kernel driver for 6lowpan sets/clears a bit in * the address, depending on the BD address (either public or not). * Might not be RFC7668 conform, so you may select to do that (=1) or diff --git a/components/network/lwip/src/include/netif/ppp/ccp.h b/components/network/lwip/src/include/netif/ppp/ccp.h index b2285228..830dc313 100644 --- a/components/network/lwip/src/include/netif/ppp/ccp.h +++ b/components/network/lwip/src/include/netif/ppp/ccp.h @@ -44,48 +44,48 @@ extern "C" { * CCP codes. */ -#define CCP_CONFREQ 1 -#define CCP_CONFACK 2 -#define CCP_TERMREQ 5 -#define CCP_TERMACK 6 -#define CCP_RESETREQ 14 -#define CCP_RESETACK 15 +#define CCP_CONFREQ 1 +#define CCP_CONFACK 2 +#define CCP_TERMREQ 5 +#define CCP_TERMACK 6 +#define CCP_RESETREQ 14 +#define CCP_RESETACK 15 /* * Max # bytes for a CCP option */ -#define CCP_MAX_OPTION_LENGTH 32 +#define CCP_MAX_OPTION_LENGTH 32 /* * Parts of a CCP packet. */ -#define CCP_CODE(dp) ((dp)[0]) -#define CCP_ID(dp) ((dp)[1]) -#define CCP_LENGTH(dp) (((dp)[2] << 8) + (dp)[3]) -#define CCP_HDRLEN 4 +#define CCP_CODE(dp) ((dp)[0]) +#define CCP_ID(dp) ((dp)[1]) +#define CCP_LENGTH(dp) (((dp)[2] << 8) + (dp)[3]) +#define CCP_HDRLEN 4 -#define CCP_OPT_CODE(dp) ((dp)[0]) -#define CCP_OPT_LENGTH(dp) ((dp)[1]) -#define CCP_OPT_MINLEN 2 +#define CCP_OPT_CODE(dp) ((dp)[0]) +#define CCP_OPT_LENGTH(dp) ((dp)[1]) +#define CCP_OPT_MINLEN 2 #if BSDCOMPRESS_SUPPORT /* * Definitions for BSD-Compress. */ -#define CI_BSD_COMPRESS 21 /* config. option for BSD-Compress */ -#define CILEN_BSD_COMPRESS 3 /* length of config. option */ +#define CI_BSD_COMPRESS 21 /* config. option for BSD-Compress */ +#define CILEN_BSD_COMPRESS 3 /* length of config. option */ /* Macros for handling the 3rd byte of the BSD-Compress config option. */ -#define BSD_NBITS(x) ((x) & 0x1F) /* number of bits requested */ -#define BSD_VERSION(x) ((x) >> 5) /* version of option format */ -#define BSD_CURRENT_VERSION 1 /* current version number */ -#define BSD_MAKE_OPT(v, n) (((v) << 5) | (n)) +#define BSD_NBITS(x) ((x) & 0x1F) /* number of bits requested */ +#define BSD_VERSION(x) ((x) >> 5) /* version of option format */ +#define BSD_CURRENT_VERSION 1 /* current version number */ +#define BSD_MAKE_OPT(v, n) (((v) << 5) | (n)) -#define BSD_MIN_BITS 9 /* smallest code size supported */ -#define BSD_MAX_BITS 15 /* largest code size supported */ +#define BSD_MIN_BITS 9 /* smallest code size supported */ +#define BSD_MAX_BITS 15 /* largest code size supported */ #endif /* BSDCOMPRESS_SUPPORT */ #if DEFLATE_SUPPORT @@ -93,17 +93,17 @@ extern "C" { * Definitions for Deflate. */ -#define CI_DEFLATE 26 /* config option for Deflate */ -#define CI_DEFLATE_DRAFT 24 /* value used in original draft RFC */ -#define CILEN_DEFLATE 4 /* length of its config option */ +#define CI_DEFLATE 26 /* config option for Deflate */ +#define CI_DEFLATE_DRAFT 24 /* value used in original draft RFC */ +#define CILEN_DEFLATE 4 /* length of its config option */ -#define DEFLATE_MIN_SIZE 9 -#define DEFLATE_MAX_SIZE 15 -#define DEFLATE_METHOD_VAL 8 -#define DEFLATE_SIZE(x) (((x) >> 4) + 8) -#define DEFLATE_METHOD(x) ((x) & 0x0F) -#define DEFLATE_MAKE_OPT(w) ((((w) - 8) << 4) + DEFLATE_METHOD_VAL) -#define DEFLATE_CHK_SEQUENCE 0 +#define DEFLATE_MIN_SIZE 9 +#define DEFLATE_MAX_SIZE 15 +#define DEFLATE_METHOD_VAL 8 +#define DEFLATE_SIZE(x) (((x) >> 4) + 8) +#define DEFLATE_METHOD(x) ((x) & 0x0F) +#define DEFLATE_MAKE_OPT(w) ((((w) - 8) << 4) + DEFLATE_METHOD_VAL) +#define DEFLATE_CHK_SEQUENCE 0 #endif /* DEFLATE_SUPPORT */ #if MPPE_SUPPORT @@ -120,10 +120,10 @@ extern "C" { * Definitions for other, as yet unsupported, compression methods. */ -#define CI_PREDICTOR_1 1 /* config option for Predictor-1 */ -#define CILEN_PREDICTOR_1 2 /* length of its config option */ -#define CI_PREDICTOR_2 2 /* config option for Predictor-2 */ -#define CILEN_PREDICTOR_2 2 /* length of its config option */ +#define CI_PREDICTOR_1 1 /* config option for Predictor-1 */ +#define CILEN_PREDICTOR_1 2 /* length of its config option */ +#define CI_PREDICTOR_2 2 /* config option for Predictor-2 */ +#define CILEN_PREDICTOR_2 2 /* length of its config option */ #endif /* PREDICTOR_SUPPORT */ typedef struct ccp_options { @@ -141,15 +141,15 @@ typedef struct ccp_options { #endif /* PREDICTOR_SUPPORT */ #if MPPE_SUPPORT - u8_t mppe; /* MPPE bitfield */ + u8_t mppe; /* MPPE bitfield */ #endif /* MPPE_SUPPORT */ #if BSDCOMPRESS_SUPPORT - u_short bsd_bits; /* # bits/code for BSD Compress */ + u_short bsd_bits; /* # bits/code for BSD Compress */ #endif /* BSDCOMPRESS_SUPPORT */ #if DEFLATE_SUPPORT - u_short deflate_size; /* lg(window size) for Deflate */ + u_short deflate_size; /* lg(window size) for Deflate */ #endif /* DEFLATE_SUPPORT */ - u8_t method; /* code for chosen compression method */ + u8_t method; /* code for chosen compression method */ } ccp_options; extern const struct protent ccp_protent; diff --git a/components/network/lwip/src/include/netif/ppp/chap-new.h b/components/network/lwip/src/include/netif/ppp/chap-new.h index 2d8cd9ca..3d264136 100644 --- a/components/network/lwip/src/include/netif/ppp/chap-new.h +++ b/components/network/lwip/src/include/netif/ppp/chap-new.h @@ -43,45 +43,45 @@ extern "C" { /* * CHAP packets begin with a standard header with code, id, len (2 bytes). */ -#define CHAP_HDRLEN 4 +#define CHAP_HDRLEN 4 /* * Values for the code field. */ -#define CHAP_CHALLENGE 1 -#define CHAP_RESPONSE 2 -#define CHAP_SUCCESS 3 -#define CHAP_FAILURE 4 +#define CHAP_CHALLENGE 1 +#define CHAP_RESPONSE 2 +#define CHAP_SUCCESS 3 +#define CHAP_FAILURE 4 /* * CHAP digest codes. */ -#define CHAP_MD5 5 +#define CHAP_MD5 5 #if MSCHAP_SUPPORT -#define CHAP_MICROSOFT 0x80 -#define CHAP_MICROSOFT_V2 0x81 +#define CHAP_MICROSOFT 0x80 +#define CHAP_MICROSOFT_V2 0x81 #endif /* MSCHAP_SUPPORT */ /* * Semi-arbitrary limits on challenge and response fields. */ -#define MAX_CHALLENGE_LEN 64 -#define MAX_RESPONSE_LEN 64 +#define MAX_CHALLENGE_LEN 64 +#define MAX_RESPONSE_LEN 64 /* * These limits apply to challenge and response packets we send. * The +4 is the +1 that we actually need rounded up. */ -#define CHAL_MAX_PKTLEN (PPP_HDRLEN + CHAP_HDRLEN + 4 + MAX_CHALLENGE_LEN + MAXNAMELEN) -#define RESP_MAX_PKTLEN (PPP_HDRLEN + CHAP_HDRLEN + 4 + MAX_RESPONSE_LEN + MAXNAMELEN) +#define CHAL_MAX_PKTLEN (PPP_HDRLEN + CHAP_HDRLEN + 4 + MAX_CHALLENGE_LEN + MAXNAMELEN) +#define RESP_MAX_PKTLEN (PPP_HDRLEN + CHAP_HDRLEN + 4 + MAX_RESPONSE_LEN + MAXNAMELEN) /* bitmask of supported algorithms */ #if MSCHAP_SUPPORT -#define MDTYPE_MICROSOFT_V2 0x1 -#define MDTYPE_MICROSOFT 0x2 +#define MDTYPE_MICROSOFT_V2 0x1 +#define MDTYPE_MICROSOFT 0x2 #endif /* MSCHAP_SUPPORT */ -#define MDTYPE_MD5 0x4 -#define MDTYPE_NONE 0 +#define MDTYPE_MD5 0x4 +#define MDTYPE_NONE 0 #if MSCHAP_SUPPORT /* Return the digest alg. ID for the most preferred digest type. */ @@ -129,24 +129,24 @@ extern "C" { * The code for each digest type has to supply one of these. */ struct chap_digest_type { - int code; + int code; #if PPP_SERVER - /* - * Note: challenge and response arguments below are formatted as - * a length byte followed by the actual challenge/response data. - */ - void (*generate_challenge)(ppp_pcb *pcb, unsigned char *challenge); - int (*verify_response)(ppp_pcb *pcb, int id, const char *name, - const unsigned char *secret, int secret_len, - const unsigned char *challenge, const unsigned char *response, - char *message, int message_space); + /* + * Note: challenge and response arguments below are formatted as + * a length byte followed by the actual challenge/response data. + */ + void (*generate_challenge)(ppp_pcb *pcb, unsigned char *challenge); + int (*verify_response)(ppp_pcb *pcb, int id, const char *name, + const unsigned char *secret, int secret_len, + const unsigned char *challenge, const unsigned char *response, + char *message, int message_space); #endif /* PPP_SERVER */ - void (*make_response)(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name, - const unsigned char *challenge, const char *secret, int secret_len, - unsigned char *priv); - int (*check_success)(ppp_pcb *pcb, unsigned char *pkt, int len, unsigned char *priv); - void (*handle_failure)(ppp_pcb *pcb, unsigned char *pkt, int len); + void (*make_response)(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name, + const unsigned char *challenge, const char *secret, int secret_len, + unsigned char *priv); + int (*check_success)(ppp_pcb *pcb, unsigned char *pkt, int len, unsigned char *priv); + void (*handle_failure)(ppp_pcb *pcb, unsigned char *pkt, int len); }; /* @@ -154,21 +154,21 @@ struct chap_digest_type { */ #if CHAP_SUPPORT typedef struct chap_client_state { - u8_t flags; - const char *name; - const struct chap_digest_type *digest; - unsigned char priv[64]; /* private area for digest's use */ + u8_t flags; + const char *name; + const struct chap_digest_type *digest; + unsigned char priv[64]; /* private area for digest's use */ } chap_client_state; #if PPP_SERVER typedef struct chap_server_state { - u8_t flags; - u8_t id; - const char *name; - const struct chap_digest_type *digest; - int challenge_xmits; - int challenge_pktlen; - unsigned char challenge[CHAL_MAX_PKTLEN]; + u8_t flags; + u8_t id; + const char *name; + const struct chap_digest_type *digest; + int challenge_xmits; + int challenge_pktlen; + unsigned char challenge[CHAL_MAX_PKTLEN]; } chap_server_state; #endif /* PPP_SERVER */ #endif /* CHAP_SUPPORT */ @@ -176,9 +176,9 @@ typedef struct chap_server_state { #if 0 /* UNUSED */ /* Hook for a plugin to validate CHAP challenge */ extern int (*chap_verify_hook)(char *name, char *ourname, int id, - const struct chap_digest_type *digest, - unsigned char *challenge, unsigned char *response, - char *message, int message_space); + const struct chap_digest_type *digest, + unsigned char *challenge, unsigned char *response, + char *message, int message_space); #endif /* UNUSED */ #if PPP_SERVER diff --git a/components/network/lwip/src/include/netif/ppp/eap.h b/components/network/lwip/src/include/netif/ppp/eap.h index 3ee9aaf8..491e52ab 100644 --- a/components/network/lwip/src/include/netif/ppp/eap.h +++ b/components/network/lwip/src/include/netif/ppp/eap.h @@ -24,135 +24,135 @@ #if PPP_SUPPORT && EAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPP_EAP_H -#define PPP_EAP_H +#define PPP_EAP_H #include "ppp.h" -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif /* * Packet header = Code, id, length. */ -#define EAP_HEADERLEN 4 +#define EAP_HEADERLEN 4 /* EAP message codes. */ -#define EAP_REQUEST 1 -#define EAP_RESPONSE 2 -#define EAP_SUCCESS 3 -#define EAP_FAILURE 4 +#define EAP_REQUEST 1 +#define EAP_RESPONSE 2 +#define EAP_SUCCESS 3 +#define EAP_FAILURE 4 /* EAP types */ -#define EAPT_IDENTITY 1 -#define EAPT_NOTIFICATION 2 -#define EAPT_NAK 3 /* (response only) */ -#define EAPT_MD5CHAP 4 -#define EAPT_OTP 5 /* One-Time Password; RFC 1938 */ -#define EAPT_TOKEN 6 /* Generic Token Card */ +#define EAPT_IDENTITY 1 +#define EAPT_NOTIFICATION 2 +#define EAPT_NAK 3 /* (response only) */ +#define EAPT_MD5CHAP 4 +#define EAPT_OTP 5 /* One-Time Password; RFC 1938 */ +#define EAPT_TOKEN 6 /* Generic Token Card */ /* 7 and 8 are unassigned. */ -#define EAPT_RSA 9 /* RSA Public Key Authentication */ -#define EAPT_DSS 10 /* DSS Unilateral */ -#define EAPT_KEA 11 /* KEA */ -#define EAPT_KEA_VALIDATE 12 /* KEA-VALIDATE */ -#define EAPT_TLS 13 /* EAP-TLS */ -#define EAPT_DEFENDER 14 /* Defender Token (AXENT) */ -#define EAPT_W2K 15 /* Windows 2000 EAP */ -#define EAPT_ARCOT 16 /* Arcot Systems */ -#define EAPT_CISCOWIRELESS 17 /* Cisco Wireless */ -#define EAPT_NOKIACARD 18 /* Nokia IP smart card */ -#define EAPT_SRP 19 /* Secure Remote Password */ +#define EAPT_RSA 9 /* RSA Public Key Authentication */ +#define EAPT_DSS 10 /* DSS Unilateral */ +#define EAPT_KEA 11 /* KEA */ +#define EAPT_KEA_VALIDATE 12 /* KEA-VALIDATE */ +#define EAPT_TLS 13 /* EAP-TLS */ +#define EAPT_DEFENDER 14 /* Defender Token (AXENT) */ +#define EAPT_W2K 15 /* Windows 2000 EAP */ +#define EAPT_ARCOT 16 /* Arcot Systems */ +#define EAPT_CISCOWIRELESS 17 /* Cisco Wireless */ +#define EAPT_NOKIACARD 18 /* Nokia IP smart card */ +#define EAPT_SRP 19 /* Secure Remote Password */ /* 20 is deprecated */ /* EAP SRP-SHA1 Subtypes */ -#define EAPSRP_CHALLENGE 1 /* Request 1 - Challenge */ -#define EAPSRP_CKEY 1 /* Response 1 - Client Key */ -#define EAPSRP_SKEY 2 /* Request 2 - Server Key */ -#define EAPSRP_CVALIDATOR 2 /* Response 2 - Client Validator */ -#define EAPSRP_SVALIDATOR 3 /* Request 3 - Server Validator */ -#define EAPSRP_ACK 3 /* Response 3 - final ack */ -#define EAPSRP_LWRECHALLENGE 4 /* Req/resp 4 - Lightweight rechal */ +#define EAPSRP_CHALLENGE 1 /* Request 1 - Challenge */ +#define EAPSRP_CKEY 1 /* Response 1 - Client Key */ +#define EAPSRP_SKEY 2 /* Request 2 - Server Key */ +#define EAPSRP_CVALIDATOR 2 /* Response 2 - Client Validator */ +#define EAPSRP_SVALIDATOR 3 /* Request 3 - Server Validator */ +#define EAPSRP_ACK 3 /* Response 3 - final ack */ +#define EAPSRP_LWRECHALLENGE 4 /* Req/resp 4 - Lightweight rechal */ -#define SRPVAL_EBIT 0x00000001 /* Use shared key for ECP */ +#define SRPVAL_EBIT 0x00000001 /* Use shared key for ECP */ -#define SRP_PSEUDO_ID "pseudo_" -#define SRP_PSEUDO_LEN 7 +#define SRP_PSEUDO_ID "pseudo_" +#define SRP_PSEUDO_LEN 7 -#define MD5_SIGNATURE_SIZE 16 -#define EAP_MIN_CHALLENGE_LENGTH 17 -#define EAP_MAX_CHALLENGE_LENGTH 24 +#define MD5_SIGNATURE_SIZE 16 +#define EAP_MIN_CHALLENGE_LENGTH 17 +#define EAP_MAX_CHALLENGE_LENGTH 24 #define EAP_MIN_MAX_POWER_OF_TWO_CHALLENGE_LENGTH 3 /* 2^3-1 = 7, 17+7 = 24 */ -#define EAP_STATES \ - "Initial", "Pending", "Closed", "Listen", "Identify", \ - "SRP1", "SRP2", "SRP3", "MD5Chall", "Open", "SRP4", "BadAuth" +#define EAP_STATES \ + "Initial", "Pending", "Closed", "Listen", "Identify", \ + "SRP1", "SRP2", "SRP3", "MD5Chall", "Open", "SRP4", "BadAuth" -#define eap_client_active(pcb) ((pcb)->eap.es_client.ea_state == eapListen) +#define eap_client_active(pcb) ((pcb)->eap.es_client.ea_state == eapListen) #if PPP_SERVER -#define eap_server_active(pcb) \ - ((pcb)->eap.es_server.ea_state >= eapIdentify && \ - (pcb)->eap.es_server.ea_state <= eapMD5Chall) +#define eap_server_active(pcb) \ + ((pcb)->eap.es_server.ea_state >= eapIdentify && \ + (pcb)->eap.es_server.ea_state <= eapMD5Chall) #endif /* PPP_SERVER */ /* * Complete EAP state for one PPP session. */ enum eap_state_code { - eapInitial = 0, /* No EAP authentication yet requested */ - eapPending, /* Waiting for LCP (no timer) */ - eapClosed, /* Authentication not in use */ - eapListen, /* Client ready (and timer running) */ - eapIdentify, /* EAP Identify sent */ - eapSRP1, /* Sent EAP SRP-SHA1 Subtype 1 */ - eapSRP2, /* Sent EAP SRP-SHA1 Subtype 2 */ - eapSRP3, /* Sent EAP SRP-SHA1 Subtype 3 */ - eapMD5Chall, /* Sent MD5-Challenge */ - eapOpen, /* Completed authentication */ - eapSRP4, /* Sent EAP SRP-SHA1 Subtype 4 */ - eapBadAuth /* Failed authentication */ + eapInitial = 0, /* No EAP authentication yet requested */ + eapPending, /* Waiting for LCP (no timer) */ + eapClosed, /* Authentication not in use */ + eapListen, /* Client ready (and timer running) */ + eapIdentify, /* EAP Identify sent */ + eapSRP1, /* Sent EAP SRP-SHA1 Subtype 1 */ + eapSRP2, /* Sent EAP SRP-SHA1 Subtype 2 */ + eapSRP3, /* Sent EAP SRP-SHA1 Subtype 3 */ + eapMD5Chall, /* Sent MD5-Challenge */ + eapOpen, /* Completed authentication */ + eapSRP4, /* Sent EAP SRP-SHA1 Subtype 4 */ + eapBadAuth /* Failed authentication */ }; struct eap_auth { - const char *ea_name; /* Our name */ - char ea_peer[MAXNAMELEN +1]; /* Peer's name */ - void *ea_session; /* Authentication library linkage */ - u_char *ea_skey; /* Shared encryption key */ - u_short ea_namelen; /* Length of our name */ - u_short ea_peerlen; /* Length of peer's name */ - enum eap_state_code ea_state; - u_char ea_id; /* Current id */ - u_char ea_requests; /* Number of Requests sent/received */ - u_char ea_responses; /* Number of Responses */ - u_char ea_type; /* One of EAPT_* */ - u32_t ea_keyflags; /* SRP shared key usage flags */ + const char *ea_name; /* Our name */ + char ea_peer[MAXNAMELEN +1]; /* Peer's name */ + void *ea_session; /* Authentication library linkage */ + u_char *ea_skey; /* Shared encryption key */ + u_short ea_namelen; /* Length of our name */ + u_short ea_peerlen; /* Length of peer's name */ + enum eap_state_code ea_state; + u_char ea_id; /* Current id */ + u_char ea_requests; /* Number of Requests sent/received */ + u_char ea_responses; /* Number of Responses */ + u_char ea_type; /* One of EAPT_* */ + u32_t ea_keyflags; /* SRP shared key usage flags */ }; #ifndef EAP_MAX_CHALLENGE_LENGTH -#define EAP_MAX_CHALLENGE_LENGTH 24 +#define EAP_MAX_CHALLENGE_LENGTH 24 #endif typedef struct eap_state { - struct eap_auth es_client; /* Client (authenticatee) data */ + struct eap_auth es_client; /* Client (authenticatee) data */ #if PPP_SERVER - struct eap_auth es_server; /* Server (authenticator) data */ + struct eap_auth es_server; /* Server (authenticator) data */ #endif /* PPP_SERVER */ - int es_savedtime; /* Saved timeout */ - int es_rechallenge; /* EAP rechallenge interval */ - int es_lwrechallenge; /* SRP lightweight rechallenge inter */ - u8_t es_usepseudo; /* Use SRP Pseudonym if offered one */ - int es_usedpseudo; /* Set if we already sent PN */ - int es_challen; /* Length of challenge string */ - u_char es_challenge[EAP_MAX_CHALLENGE_LENGTH]; + int es_savedtime; /* Saved timeout */ + int es_rechallenge; /* EAP rechallenge interval */ + int es_lwrechallenge; /* SRP lightweight rechallenge inter */ + u8_t es_usepseudo; /* Use SRP Pseudonym if offered one */ + int es_usedpseudo; /* Set if we already sent PN */ + int es_challen; /* Length of challenge string */ + u_char es_challenge[EAP_MAX_CHALLENGE_LENGTH]; } eap_state; /* * Timeouts. */ #if 0 /* moved to ppp_opts.h */ -#define EAP_DEFTIMEOUT 3 /* Timeout (seconds) for rexmit */ -#define EAP_DEFTRANSMITS 10 /* max # times to transmit */ -#define EAP_DEFREQTIME 20 /* Time to wait for peer request */ -#define EAP_DEFALLOWREQ 20 /* max # times to accept requests */ +#define EAP_DEFTIMEOUT 3 /* Timeout (seconds) for rexmit */ +#define EAP_DEFTRANSMITS 10 /* max # times to transmit */ +#define EAP_DEFREQTIME 20 /* Time to wait for peer request */ +#define EAP_DEFALLOWREQ 20 /* max # times to accept requests */ #endif /* moved to ppp_opts.h */ void eap_authwithpeer(ppp_pcb *pcb, const char *localname); @@ -160,7 +160,7 @@ void eap_authpeer(ppp_pcb *pcb, const char *localname); extern const struct protent eap_protent; -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/components/network/lwip/src/include/netif/ppp/ecp.h b/components/network/lwip/src/include/netif/ppp/ecp.h index d8808c3a..fa373fe7 100644 --- a/components/network/lwip/src/include/netif/ppp/ecp.h +++ b/components/network/lwip/src/include/netif/ppp/ecp.h @@ -42,8 +42,8 @@ extern "C" { #endif typedef struct ecp_options { - bool required; /* Is ECP required? */ - unsigned enctype; /* Encryption type */ + bool required; /* Is ECP required? */ + unsigned enctype; /* Encryption type */ } ecp_options; extern fsm ecp_fsm[]; diff --git a/components/network/lwip/src/include/netif/ppp/eui64.h b/components/network/lwip/src/include/netif/ppp/eui64.h index 5adeb482..3a20081f 100644 --- a/components/network/lwip/src/include/netif/ppp/eui64.h +++ b/components/network/lwip/src/include/netif/ppp/eui64.h @@ -57,42 +57,42 @@ typedef union u32_t e32[2]; } eui64_t; -#define eui64_iszero(e) (((e).e32[0] | (e).e32[1]) == 0) -#define eui64_equals(e, o) (((e).e32[0] == (o).e32[0]) && \ - ((e).e32[1] == (o).e32[1])) -#define eui64_zero(e) (e).e32[0] = (e).e32[1] = 0; +#define eui64_iszero(e) (((e).e32[0] | (e).e32[1]) == 0) +#define eui64_equals(e, o) (((e).e32[0] == (o).e32[0]) && \ + ((e).e32[1] == (o).e32[1])) +#define eui64_zero(e) (e).e32[0] = (e).e32[1] = 0; -#define eui64_copy(s, d) memcpy(&(d), &(s), sizeof(eui64_t)) +#define eui64_copy(s, d) memcpy(&(d), &(s), sizeof(eui64_t)) -#define eui64_magic(e) do { \ - (e).e32[0] = magic(); \ - (e).e32[1] = magic(); \ - (e).e8[0] &= ~2; \ - } while (0) -#define eui64_magic_nz(x) do { \ - eui64_magic(x); \ - } while (eui64_iszero(x)) -#define eui64_magic_ne(x, y) do { \ - eui64_magic(x); \ - } while (eui64_equals(x, y)) +#define eui64_magic(e) do { \ + (e).e32[0] = magic(); \ + (e).e32[1] = magic(); \ + (e).e8[0] &= ~2; \ + } while (0) +#define eui64_magic_nz(x) do { \ + eui64_magic(x); \ + } while (eui64_iszero(x)) +#define eui64_magic_ne(x, y) do { \ + eui64_magic(x); \ + } while (eui64_equals(x, y)) -#define eui64_get(ll, cp) do { \ - eui64_copy((*cp), (ll)); \ - (cp) += sizeof(eui64_t); \ - } while (0) +#define eui64_get(ll, cp) do { \ + eui64_copy((*cp), (ll)); \ + (cp) += sizeof(eui64_t); \ + } while (0) -#define eui64_put(ll, cp) do { \ - eui64_copy((ll), (*cp)); \ - (cp) += sizeof(eui64_t); \ - } while (0) +#define eui64_put(ll, cp) do { \ + eui64_copy((ll), (*cp)); \ + (cp) += sizeof(eui64_t); \ + } while (0) -#define eui64_set32(e, l) do { \ - (e).e32[0] = 0; \ - (e).e32[1] = lwip_htonl(l); \ - } while (0) -#define eui64_setlo32(e, l) eui64_set32(e, l) +#define eui64_set32(e, l) do { \ + (e).e32[0] = 0; \ + (e).e32[1] = lwip_htonl(l); \ + } while (0) +#define eui64_setlo32(e, l) eui64_set32(e, l) -char *eui64_ntoa(eui64_t); /* Returns ascii representation of id */ +char *eui64_ntoa(eui64_t); /* Returns ascii representation of id */ #ifdef __cplusplus } diff --git a/components/network/lwip/src/include/netif/ppp/fsm.h b/components/network/lwip/src/include/netif/ppp/fsm.h index 8dec700e..69d965a5 100644 --- a/components/network/lwip/src/include/netif/ppp/fsm.h +++ b/components/network/lwip/src/include/netif/ppp/fsm.h @@ -46,7 +46,7 @@ #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef FSM_H -#define FSM_H +#define FSM_H #include "ppp.h" @@ -57,108 +57,108 @@ extern "C" { /* * Packet header = Code, id, length. */ -#define HEADERLEN 4 +#define HEADERLEN 4 /* * CP (LCP, IPCP, etc.) codes. */ -#define CONFREQ 1 /* Configuration Request */ -#define CONFACK 2 /* Configuration Ack */ -#define CONFNAK 3 /* Configuration Nak */ -#define CONFREJ 4 /* Configuration Reject */ -#define TERMREQ 5 /* Termination Request */ -#define TERMACK 6 /* Termination Ack */ -#define CODEREJ 7 /* Code Reject */ +#define CONFREQ 1 /* Configuration Request */ +#define CONFACK 2 /* Configuration Ack */ +#define CONFNAK 3 /* Configuration Nak */ +#define CONFREJ 4 /* Configuration Reject */ +#define TERMREQ 5 /* Termination Request */ +#define TERMACK 6 /* Termination Ack */ +#define CODEREJ 7 /* Code Reject */ /* * Each FSM is described by an fsm structure and fsm callbacks. */ typedef struct fsm { - ppp_pcb *pcb; /* PPP Interface */ - const struct fsm_callbacks *callbacks; /* Callback routines */ - const char *term_reason; /* Reason for closing protocol */ - u8_t seen_ack; /* Have received valid Ack/Nak/Rej to Req */ - /* -- This is our only flag, we might use u_int :1 if we have more flags */ - u16_t protocol; /* Data Link Layer Protocol field value */ - u8_t state; /* State */ - u8_t flags; /* Contains option bits */ - u8_t id; /* Current id */ - u8_t reqid; /* Current request id */ - u8_t retransmits; /* Number of retransmissions left */ - u8_t nakloops; /* Number of nak loops since last ack */ - u8_t rnakloops; /* Number of naks received */ - u8_t maxnakloops; /* Maximum number of nak loops tolerated - (necessary because IPCP require a custom large max nak loops value) */ - u8_t term_reason_len; /* Length of term_reason */ + ppp_pcb *pcb; /* PPP Interface */ + const struct fsm_callbacks *callbacks; /* Callback routines */ + const char *term_reason; /* Reason for closing protocol */ + u8_t seen_ack; /* Have received valid Ack/Nak/Rej to Req */ + /* -- This is our only flag, we might use u_int :1 if we have more flags */ + u16_t protocol; /* Data Link Layer Protocol field value */ + u8_t state; /* State */ + u8_t flags; /* Contains option bits */ + u8_t id; /* Current id */ + u8_t reqid; /* Current request id */ + u8_t retransmits; /* Number of retransmissions left */ + u8_t nakloops; /* Number of nak loops since last ack */ + u8_t rnakloops; /* Number of naks received */ + u8_t maxnakloops; /* Maximum number of nak loops tolerated + (necessary because IPCP require a custom large max nak loops value) */ + u8_t term_reason_len; /* Length of term_reason */ } fsm; typedef struct fsm_callbacks { - void (*resetci) /* Reset our Configuration Information */ - (fsm *); - int (*cilen) /* Length of our Configuration Information */ - (fsm *); - void (*addci) /* Add our Configuration Information */ - (fsm *, u_char *, int *); - int (*ackci) /* ACK our Configuration Information */ - (fsm *, u_char *, int); - int (*nakci) /* NAK our Configuration Information */ - (fsm *, u_char *, int, int); - int (*rejci) /* Reject our Configuration Information */ - (fsm *, u_char *, int); - int (*reqci) /* Request peer's Configuration Information */ - (fsm *, u_char *, int *, int); - void (*up) /* Called when fsm reaches PPP_FSM_OPENED state */ - (fsm *); - void (*down) /* Called when fsm leaves PPP_FSM_OPENED state */ - (fsm *); - void (*starting) /* Called when we want the lower layer */ - (fsm *); - void (*finished) /* Called when we don't want the lower layer */ - (fsm *); - void (*protreject) /* Called when Protocol-Reject received */ - (int); - void (*retransmit) /* Retransmission is necessary */ - (fsm *); - int (*extcode) /* Called when unknown code received */ - (fsm *, int, int, u_char *, int); - const char *proto_name; /* String name for protocol (for messages) */ + void (*resetci) /* Reset our Configuration Information */ + (fsm *); + int (*cilen) /* Length of our Configuration Information */ + (fsm *); + void (*addci) /* Add our Configuration Information */ + (fsm *, u_char *, int *); + int (*ackci) /* ACK our Configuration Information */ + (fsm *, u_char *, int); + int (*nakci) /* NAK our Configuration Information */ + (fsm *, u_char *, int, int); + int (*rejci) /* Reject our Configuration Information */ + (fsm *, u_char *, int); + int (*reqci) /* Request peer's Configuration Information */ + (fsm *, u_char *, int *, int); + void (*up) /* Called when fsm reaches PPP_FSM_OPENED state */ + (fsm *); + void (*down) /* Called when fsm leaves PPP_FSM_OPENED state */ + (fsm *); + void (*starting) /* Called when we want the lower layer */ + (fsm *); + void (*finished) /* Called when we don't want the lower layer */ + (fsm *); + void (*protreject) /* Called when Protocol-Reject received */ + (int); + void (*retransmit) /* Retransmission is necessary */ + (fsm *); + int (*extcode) /* Called when unknown code received */ + (fsm *, int, int, u_char *, int); + const char *proto_name; /* String name for protocol (for messages) */ } fsm_callbacks; /* * Link states. */ -#define PPP_FSM_INITIAL 0 /* Down, hasn't been opened */ -#define PPP_FSM_STARTING 1 /* Down, been opened */ -#define PPP_FSM_CLOSED 2 /* Up, hasn't been opened */ -#define PPP_FSM_STOPPED 3 /* Open, waiting for down event */ -#define PPP_FSM_CLOSING 4 /* Terminating the connection, not open */ -#define PPP_FSM_STOPPING 5 /* Terminating, but open */ -#define PPP_FSM_REQSENT 6 /* We've sent a Config Request */ -#define PPP_FSM_ACKRCVD 7 /* We've received a Config Ack */ -#define PPP_FSM_ACKSENT 8 /* We've sent a Config Ack */ -#define PPP_FSM_OPENED 9 /* Connection available */ +#define PPP_FSM_INITIAL 0 /* Down, hasn't been opened */ +#define PPP_FSM_STARTING 1 /* Down, been opened */ +#define PPP_FSM_CLOSED 2 /* Up, hasn't been opened */ +#define PPP_FSM_STOPPED 3 /* Open, waiting for down event */ +#define PPP_FSM_CLOSING 4 /* Terminating the connection, not open */ +#define PPP_FSM_STOPPING 5 /* Terminating, but open */ +#define PPP_FSM_REQSENT 6 /* We've sent a Config Request */ +#define PPP_FSM_ACKRCVD 7 /* We've received a Config Ack */ +#define PPP_FSM_ACKSENT 8 /* We've sent a Config Ack */ +#define PPP_FSM_OPENED 9 /* Connection available */ /* * Flags - indicate options controlling FSM operation */ -#define OPT_PASSIVE 1 /* Don't die if we don't get a response */ -#define OPT_RESTART 2 /* Treat 2nd OPEN as DOWN, UP */ -#define OPT_SILENT 4 /* Wait for peer to speak first */ +#define OPT_PASSIVE 1 /* Don't die if we don't get a response */ +#define OPT_RESTART 2 /* Treat 2nd OPEN as DOWN, UP */ +#define OPT_SILENT 4 /* Wait for peer to speak first */ /* * Timeouts. */ #if 0 /* moved to ppp_opts.h */ -#define DEFTIMEOUT 3 /* Timeout time in seconds */ -#define DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ -#define DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ -#define DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ +#define DEFTIMEOUT 3 /* Timeout time in seconds */ +#define DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ +#define DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ +#define DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ #endif /* moved to ppp_opts.h */ diff --git a/components/network/lwip/src/include/netif/ppp/ipcp.h b/components/network/lwip/src/include/netif/ppp/ipcp.h index 32fdd1c6..6d822fef 100644 --- a/components/network/lwip/src/include/netif/ppp/ipcp.h +++ b/components/network/lwip/src/include/netif/ppp/ipcp.h @@ -46,7 +46,7 @@ #if PPP_SUPPORT && PPP_IPV4_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef IPCP_H -#define IPCP_H +#define IPCP_H #ifdef __cplusplus extern "C" { @@ -55,32 +55,32 @@ extern "C" { /* * Options. */ -#define CI_ADDRS 1 /* IP Addresses */ +#define CI_ADDRS 1 /* IP Addresses */ #if VJ_SUPPORT -#define CI_COMPRESSTYPE 2 /* Compression Type */ +#define CI_COMPRESSTYPE 2 /* Compression Type */ #endif /* VJ_SUPPORT */ -#define CI_ADDR 3 +#define CI_ADDR 3 #if LWIP_DNS -#define CI_MS_DNS1 129 /* Primary DNS value */ +#define CI_MS_DNS1 129 /* Primary DNS value */ #define CI_MS_DNS2 131 /* Secondary DNS value */ #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ #define CI_MS_WINS1 130 /* Primary WINS value */ -#define CI_MS_WINS2 132 /* Secondary WINS value */ +#define CI_MS_WINS2 132 /* Secondary WINS value */ #endif /* UNUSED - WINS */ #if VJ_SUPPORT -#define MAX_STATES 16 /* from slcompress.h */ +#define MAX_STATES 16 /* from slcompress.h */ -#define IPCP_VJMODE_OLD 1 /* "old" mode (option # = 0x0037) */ -#define IPCP_VJMODE_RFC1172 2 /* "old-rfc"mode (option # = 0x002d) */ -#define IPCP_VJMODE_RFC1332 3 /* "new-rfc"mode (option # = 0x002d, */ +#define IPCP_VJMODE_OLD 1 /* "old" mode (option # = 0x0037) */ +#define IPCP_VJMODE_RFC1172 2 /* "old-rfc"mode (option # = 0x002d) */ +#define IPCP_VJMODE_RFC1332 3 /* "new-rfc"mode (option # = 0x002d, */ /* maxslot and slot number compression) */ -#define IPCP_VJ_COMP 0x002d /* current value for VJ compression option*/ -#define IPCP_VJ_COMP_OLD 0x0037 /* "old" (i.e, broken) value for VJ */ - /* compression option*/ +#define IPCP_VJ_COMP 0x002d /* current value for VJ compression option*/ +#define IPCP_VJ_COMP_OLD 0x0037 /* "old" (i.e, broken) value for VJ */ + /* compression option*/ #endif /* VJ_SUPPORT */ typedef struct ipcp_options { @@ -106,17 +106,17 @@ typedef struct ipcp_options { unsigned int req_dns2 :1; /* Ask peer to send secondary DNS address? */ #endif /* LWIP_DNS */ - u32_t ouraddr, hisaddr; /* Addresses in NETWORK BYTE ORDER */ + u32_t ouraddr, hisaddr; /* Addresses in NETWORK BYTE ORDER */ #if LWIP_DNS - u32_t dnsaddr[2]; /* Primary and secondary MS DNS entries */ + u32_t dnsaddr[2]; /* Primary and secondary MS DNS entries */ #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ - u32_t winsaddr[2]; /* Primary and secondary MS WINS entries */ + u32_t winsaddr[2]; /* Primary and secondary MS WINS entries */ #endif /* UNUSED - WINS */ #if VJ_SUPPORT - u16_t vj_protocol; /* protocol value to use in VJ option */ - u8_t maxslotindex; /* values for RFC1332 VJ compression neg. */ + u16_t vj_protocol; /* protocol value to use in VJ option */ + u8_t maxslotindex; /* values for RFC1332 VJ compression neg. */ #endif /* VJ_SUPPORT */ } ipcp_options; diff --git a/components/network/lwip/src/include/netif/ppp/ipv6cp.h b/components/network/lwip/src/include/netif/ppp/ipv6cp.h index 90999738..756b3ecd 100644 --- a/components/network/lwip/src/include/netif/ppp/ipv6cp.h +++ b/components/network/lwip/src/include/netif/ppp/ipv6cp.h @@ -73,7 +73,7 @@ between BULL S.A. and INRIA). This software is available with usual "research" terms - with the aim of retain credits of the software. + with the aim of retain credits of the software. Permission to use, copy, modify and distribute this software for any purpose and without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies, @@ -142,7 +142,7 @@ #if PPP_SUPPORT && PPP_IPV6_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef IPV6CP_H -#define IPV6CP_H +#define IPV6CP_H #include "eui64.h" @@ -153,13 +153,13 @@ extern "C" { /* * Options. */ -#define CI_IFACEID 1 /* Interface Identifier */ +#define CI_IFACEID 1 /* Interface Identifier */ #ifdef IPV6CP_COMP -#define CI_COMPRESSTYPE 2 /* Compression Type */ +#define CI_COMPRESSTYPE 2 /* Compression Type */ #endif /* IPV6CP_COMP */ /* No compression types yet defined. - *#define IPV6CP_COMP 0x004f + *#define IPV6CP_COMP 0x004f */ typedef struct ipv6cp_options { unsigned int neg_ifaceid :1; /* Negotiate interface identifier? */ diff --git a/components/network/lwip/src/include/netif/ppp/lcp.h b/components/network/lwip/src/include/netif/ppp/lcp.h index 18ad1cb2..2b49bf7e 100644 --- a/components/network/lwip/src/include/netif/ppp/lcp.h +++ b/components/network/lwip/src/include/netif/ppp/lcp.h @@ -46,7 +46,7 @@ #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef LCP_H -#define LCP_H +#define LCP_H #include "ppp.h" @@ -57,55 +57,55 @@ extern "C" { /* * Options. */ -#define CI_VENDOR 0 /* Vendor Specific */ -#define CI_MRU 1 /* Maximum Receive Unit */ -#define CI_ASYNCMAP 2 /* Async Control Character Map */ -#define CI_AUTHTYPE 3 /* Authentication Type */ -#define CI_QUALITY 4 /* Quality Protocol */ -#define CI_MAGICNUMBER 5 /* Magic Number */ -#define CI_PCOMPRESSION 7 /* Protocol Field Compression */ -#define CI_ACCOMPRESSION 8 /* Address/Control Field Compression */ -#define CI_FCSALTERN 9 /* FCS-Alternatives */ -#define CI_SDP 10 /* Self-Describing-Pad */ -#define CI_NUMBERED 11 /* Numbered-Mode */ -#define CI_CALLBACK 13 /* callback */ -#define CI_MRRU 17 /* max reconstructed receive unit; multilink */ -#define CI_SSNHF 18 /* short sequence numbers for multilink */ -#define CI_EPDISC 19 /* endpoint discriminator */ -#define CI_MPPLUS 22 /* Multi-Link-Plus-Procedure */ -#define CI_LDISC 23 /* Link-Discriminator */ -#define CI_LCPAUTH 24 /* LCP Authentication */ -#define CI_COBS 25 /* Consistent Overhead Byte Stuffing */ -#define CI_PREFELIS 26 /* Prefix Elision */ -#define CI_MPHDRFMT 27 /* MP Header Format */ -#define CI_I18N 28 /* Internationalization */ -#define CI_SDL 29 /* Simple Data Link */ +#define CI_VENDOR 0 /* Vendor Specific */ +#define CI_MRU 1 /* Maximum Receive Unit */ +#define CI_ASYNCMAP 2 /* Async Control Character Map */ +#define CI_AUTHTYPE 3 /* Authentication Type */ +#define CI_QUALITY 4 /* Quality Protocol */ +#define CI_MAGICNUMBER 5 /* Magic Number */ +#define CI_PCOMPRESSION 7 /* Protocol Field Compression */ +#define CI_ACCOMPRESSION 8 /* Address/Control Field Compression */ +#define CI_FCSALTERN 9 /* FCS-Alternatives */ +#define CI_SDP 10 /* Self-Describing-Pad */ +#define CI_NUMBERED 11 /* Numbered-Mode */ +#define CI_CALLBACK 13 /* callback */ +#define CI_MRRU 17 /* max reconstructed receive unit; multilink */ +#define CI_SSNHF 18 /* short sequence numbers for multilink */ +#define CI_EPDISC 19 /* endpoint discriminator */ +#define CI_MPPLUS 22 /* Multi-Link-Plus-Procedure */ +#define CI_LDISC 23 /* Link-Discriminator */ +#define CI_LCPAUTH 24 /* LCP Authentication */ +#define CI_COBS 25 /* Consistent Overhead Byte Stuffing */ +#define CI_PREFELIS 26 /* Prefix Elision */ +#define CI_MPHDRFMT 27 /* MP Header Format */ +#define CI_I18N 28 /* Internationalization */ +#define CI_SDL 29 /* Simple Data Link */ /* * LCP-specific packet types (code numbers). */ -#define PROTREJ 8 /* Protocol Reject */ -#define ECHOREQ 9 /* Echo Request */ -#define ECHOREP 10 /* Echo Reply */ -#define DISCREQ 11 /* Discard Request */ -#define IDENTIF 12 /* Identification */ -#define TIMEREM 13 /* Time Remaining */ +#define PROTREJ 8 /* Protocol Reject */ +#define ECHOREQ 9 /* Echo Request */ +#define ECHOREP 10 /* Echo Reply */ +#define DISCREQ 11 /* Discard Request */ +#define IDENTIF 12 /* Identification */ +#define TIMEREM 13 /* Time Remaining */ /* Value used as data for CI_CALLBACK option */ -#define CBCP_OPT 6 /* Use callback control protocol */ +#define CBCP_OPT 6 /* Use callback control protocol */ #if 0 /* moved to ppp_opts.h */ -#define DEFMRU 1500 /* Try for this */ -#define MINMRU 128 /* No MRUs below this */ -#define MAXMRU 16384 /* Normally limit MRU to this */ +#define DEFMRU 1500 /* Try for this */ +#define MINMRU 128 /* No MRUs below this */ +#define MAXMRU 16384 /* Normally limit MRU to this */ #endif /* moved to ppp_opts.h */ /* An endpoint discriminator, used with multilink. */ -#define MAX_ENDP_LEN 20 /* maximum length of discriminator value */ +#define MAX_ENDP_LEN 20 /* maximum length of discriminator value */ struct epdisc { - unsigned char class_; /* -- The word "class" is reserved in C++. */ - unsigned char length; - unsigned char value[MAX_ENDP_LEN]; + unsigned char class_; /* -- The word "class" is reserved in C++. */ + unsigned char length; + unsigned char value[MAX_ENDP_LEN]; }; /* @@ -141,20 +141,20 @@ typedef struct lcp_options { unsigned int neg_ssnhf :1; /* negotiate short sequence numbers */ unsigned int neg_endpoint :1; /* negotiate endpoint discriminator */ - u16_t mru; /* Value of MRU */ + u16_t mru; /* Value of MRU */ #ifdef HAVE_MULTILINK - u16_t mrru; /* Value of MRRU, and multilink enable */ + u16_t mrru; /* Value of MRRU, and multilink enable */ #endif /* MULTILINK */ #if CHAP_SUPPORT - u8_t chap_mdtype; /* which MD types (hashing algorithm) */ + u8_t chap_mdtype; /* which MD types (hashing algorithm) */ #endif /* CHAP_SUPPORT */ - u32_t asyncmap; /* Value of async map */ + u32_t asyncmap; /* Value of async map */ u32_t magicnumber; - u8_t numloops; /* Number of loops during magic number neg. */ + u8_t numloops; /* Number of loops during magic number neg. */ #if LQR_SUPPORT - u32_t lqr_period; /* Reporting period for LQR 1/100ths second */ + u32_t lqr_period; /* Reporting period for LQR 1/100ths second */ #endif /* LQR_SUPPORT */ - struct epdisc endpoint; /* endpoint discriminator */ + struct epdisc endpoint; /* endpoint discriminator */ } lcp_options; void lcp_open(ppp_pcb *pcb); @@ -168,7 +168,7 @@ extern const struct protent lcp_protent; #if 0 /* moved to ppp_opts.h */ /* Default number of times we receive our magic number from the peer before deciding the link is looped-back. */ -#define DEFLOOPBACKFAIL 10 +#define DEFLOOPBACKFAIL 10 #endif /* moved to ppp_opts.h */ #ifdef __cplusplus diff --git a/components/network/lwip/src/include/netif/ppp/magic.h b/components/network/lwip/src/include/netif/ppp/magic.h index a165e18f..b937ec6d 100644 --- a/components/network/lwip/src/include/netif/ppp/magic.h +++ b/components/network/lwip/src/include/netif/ppp/magic.h @@ -102,7 +102,7 @@ void magic_randomize(void); /* * Return a new random number. */ -u32_t magic(void); /* Returns the next magic number */ +u32_t magic(void); /* Returns the next magic number */ /* * Fill buffer with random bytes diff --git a/components/network/lwip/src/include/netif/ppp/mppe.h b/components/network/lwip/src/include/netif/ppp/mppe.h index 5de11284..55f0487b 100644 --- a/components/network/lwip/src/include/netif/ppp/mppe.h +++ b/components/network/lwip/src/include/netif/ppp/mppe.h @@ -45,19 +45,19 @@ extern "C" { #endif -#define MPPE_PAD 4 /* MPPE growth per frame */ -#define MPPE_MAX_KEY_LEN 16 /* largest key length (128-bit) */ +#define MPPE_PAD 4 /* MPPE growth per frame */ +#define MPPE_MAX_KEY_LEN 16 /* largest key length (128-bit) */ /* option bits for ccp_options.mppe */ -#define MPPE_OPT_40 0x01 /* 40 bit */ -#define MPPE_OPT_128 0x02 /* 128 bit */ -#define MPPE_OPT_STATEFUL 0x04 /* stateful mode */ +#define MPPE_OPT_40 0x01 /* 40 bit */ +#define MPPE_OPT_128 0x02 /* 128 bit */ +#define MPPE_OPT_STATEFUL 0x04 /* stateful mode */ /* unsupported opts */ -#define MPPE_OPT_56 0x08 /* 56 bit */ -#define MPPE_OPT_MPPC 0x10 /* MPPC compression */ -#define MPPE_OPT_D 0x20 /* Unknown */ +#define MPPE_OPT_56 0x08 /* 56 bit */ +#define MPPE_OPT_MPPC 0x10 /* MPPC compression */ +#define MPPE_OPT_D 0x20 /* Unknown */ #define MPPE_OPT_UNSUPPORTED (MPPE_OPT_56|MPPE_OPT_MPPC|MPPE_OPT_D) -#define MPPE_OPT_UNKNOWN 0x40 /* Bits !defined in RFC 3078 were set */ +#define MPPE_OPT_UNKNOWN 0x40 /* Bits !defined in RFC 3078 were set */ /* * This is not nice ... the alternative is a bitfield struct though. @@ -66,70 +66,70 @@ extern "C" { * but then we have to do a lwip_htonl() all the time and/or we still need * to know which octet is which. */ -#define MPPE_C_BIT 0x01 /* MPPC */ -#define MPPE_D_BIT 0x10 /* Obsolete, usage unknown */ -#define MPPE_L_BIT 0x20 /* 40-bit */ -#define MPPE_S_BIT 0x40 /* 128-bit */ -#define MPPE_M_BIT 0x80 /* 56-bit, not supported */ -#define MPPE_H_BIT 0x01 /* Stateless (in a different byte) */ +#define MPPE_C_BIT 0x01 /* MPPC */ +#define MPPE_D_BIT 0x10 /* Obsolete, usage unknown */ +#define MPPE_L_BIT 0x20 /* 40-bit */ +#define MPPE_S_BIT 0x40 /* 128-bit */ +#define MPPE_M_BIT 0x80 /* 56-bit, not supported */ +#define MPPE_H_BIT 0x01 /* Stateless (in a different byte) */ /* Does not include H bit; used for least significant octet only. */ #define MPPE_ALL_BITS (MPPE_D_BIT|MPPE_L_BIT|MPPE_S_BIT|MPPE_M_BIT|MPPE_H_BIT) /* Build a CI from mppe opts (see RFC 3078) */ -#define MPPE_OPTS_TO_CI(opts, ci) \ - do { \ - u_char *ptr = ci; /* u_char[4] */ \ - \ - /* H bit */ \ - if (opts & MPPE_OPT_STATEFUL) \ - *ptr++ = 0x0; \ - else \ - *ptr++ = MPPE_H_BIT; \ - *ptr++ = 0; \ - *ptr++ = 0; \ - \ - /* S,L bits */ \ - *ptr = 0; \ - if (opts & MPPE_OPT_128) \ - *ptr |= MPPE_S_BIT; \ - if (opts & MPPE_OPT_40) \ - *ptr |= MPPE_L_BIT; \ - /* M,D,C bits not supported */ \ +#define MPPE_OPTS_TO_CI(opts, ci) \ + do { \ + u_char *ptr = ci; /* u_char[4] */ \ + \ + /* H bit */ \ + if (opts & MPPE_OPT_STATEFUL) \ + *ptr++ = 0x0; \ + else \ + *ptr++ = MPPE_H_BIT; \ + *ptr++ = 0; \ + *ptr++ = 0; \ + \ + /* S,L bits */ \ + *ptr = 0; \ + if (opts & MPPE_OPT_128) \ + *ptr |= MPPE_S_BIT; \ + if (opts & MPPE_OPT_40) \ + *ptr |= MPPE_L_BIT; \ + /* M,D,C bits not supported */ \ } while (/* CONSTCOND */ 0) /* The reverse of the above */ -#define MPPE_CI_TO_OPTS(ci, opts) \ - do { \ - const u_char *ptr = ci; /* u_char[4] */ \ - \ - opts = 0; \ - \ - /* H bit */ \ - if (!(ptr[0] & MPPE_H_BIT)) \ - opts |= MPPE_OPT_STATEFUL; \ - \ - /* S,L bits */ \ - if (ptr[3] & MPPE_S_BIT) \ - opts |= MPPE_OPT_128; \ - if (ptr[3] & MPPE_L_BIT) \ - opts |= MPPE_OPT_40; \ - \ - /* M,D,C bits */ \ - if (ptr[3] & MPPE_M_BIT) \ - opts |= MPPE_OPT_56; \ - if (ptr[3] & MPPE_D_BIT) \ - opts |= MPPE_OPT_D; \ - if (ptr[3] & MPPE_C_BIT) \ - opts |= MPPE_OPT_MPPC; \ - \ - /* Other bits */ \ - if (ptr[0] & ~MPPE_H_BIT) \ - opts |= MPPE_OPT_UNKNOWN; \ - if (ptr[1] || ptr[2]) \ - opts |= MPPE_OPT_UNKNOWN; \ - if (ptr[3] & ~MPPE_ALL_BITS) \ - opts |= MPPE_OPT_UNKNOWN; \ +#define MPPE_CI_TO_OPTS(ci, opts) \ + do { \ + const u_char *ptr = ci; /* u_char[4] */ \ + \ + opts = 0; \ + \ + /* H bit */ \ + if (!(ptr[0] & MPPE_H_BIT)) \ + opts |= MPPE_OPT_STATEFUL; \ + \ + /* S,L bits */ \ + if (ptr[3] & MPPE_S_BIT) \ + opts |= MPPE_OPT_128; \ + if (ptr[3] & MPPE_L_BIT) \ + opts |= MPPE_OPT_40; \ + \ + /* M,D,C bits */ \ + if (ptr[3] & MPPE_M_BIT) \ + opts |= MPPE_OPT_56; \ + if (ptr[3] & MPPE_D_BIT) \ + opts |= MPPE_OPT_D; \ + if (ptr[3] & MPPE_C_BIT) \ + opts |= MPPE_OPT_MPPC; \ + \ + /* Other bits */ \ + if (ptr[0] & ~MPPE_H_BIT) \ + opts |= MPPE_OPT_UNKNOWN; \ + if (ptr[1] || ptr[2]) \ + opts |= MPPE_OPT_UNKNOWN; \ + if (ptr[3] & ~MPPE_ALL_BITS) \ + opts |= MPPE_OPT_UNKNOWN; \ } while (/* CONSTCOND */ 0) /* Shared MPPE padding between MSCHAP and MPPE */ @@ -152,18 +152,18 @@ static const u8_t mppe_sha1_pad2[SHA1_PAD_SIZE] = { * State for an MPPE (de)compressor. */ typedef struct ppp_mppe_state { - lwip_arc4_context arc4; - u8_t master_key[MPPE_MAX_KEY_LEN]; - u8_t session_key[MPPE_MAX_KEY_LEN]; - u8_t keylen; /* key length in bytes */ - /* NB: 128-bit == 16, 40-bit == 8! - * If we want to support 56-bit, the unit has to change to bits - */ - u8_t bits; /* MPPE control bits */ - u16_t ccount; /* 12-bit coherency count (seqno) */ - u16_t sanity_errors; /* take down LCP if too many */ - unsigned int stateful :1; /* stateful mode flag */ - unsigned int discard :1; /* stateful mode packet loss flag */ + lwip_arc4_context arc4; + u8_t master_key[MPPE_MAX_KEY_LEN]; + u8_t session_key[MPPE_MAX_KEY_LEN]; + u8_t keylen; /* key length in bytes */ + /* NB: 128-bit == 16, 40-bit == 8! + * If we want to support 56-bit, the unit has to change to bits + */ + u8_t bits; /* MPPE control bits */ + u16_t ccount; /* 12-bit coherency count (seqno) */ + u16_t sanity_errors; /* take down LCP if too many */ + unsigned int stateful :1; /* stateful mode flag */ + unsigned int discard :1; /* stateful mode packet loss flag */ } ppp_mppe_state; void mppe_set_key(ppp_pcb *pcb, ppp_mppe_state *state, u8_t *key); diff --git a/components/network/lwip/src/include/netif/ppp/polarssl/arc4.h b/components/network/lwip/src/include/netif/ppp/polarssl/arc4.h index 4af724cd..91b08e67 100644 --- a/components/network/lwip/src/include/netif/ppp/polarssl/arc4.h +++ b/components/network/lwip/src/include/netif/ppp/polarssl/arc4.h @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/include/netif/ppp/polarssl/des.h b/components/network/lwip/src/include/netif/ppp/polarssl/des.h index e893890e..5e3a0851 100644 --- a/components/network/lwip/src/include/netif/ppp/polarssl/des.h +++ b/components/network/lwip/src/include/netif/ppp/polarssl/des.h @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/include/netif/ppp/polarssl/md4.h b/components/network/lwip/src/include/netif/ppp/polarssl/md4.h index 57044568..a4aa1dcc 100644 --- a/components/network/lwip/src/include/netif/ppp/polarssl/md4.h +++ b/components/network/lwip/src/include/netif/ppp/polarssl/md4.h @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/include/netif/ppp/polarssl/md5.h b/components/network/lwip/src/include/netif/ppp/polarssl/md5.h index 12440118..4d7b04d8 100644 --- a/components/network/lwip/src/include/netif/ppp/polarssl/md5.h +++ b/components/network/lwip/src/include/netif/ppp/polarssl/md5.h @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/include/netif/ppp/polarssl/sha1.h b/components/network/lwip/src/include/netif/ppp/polarssl/sha1.h index a4c53e07..d8f347c6 100644 --- a/components/network/lwip/src/include/netif/ppp/polarssl/sha1.h +++ b/components/network/lwip/src/include/netif/ppp/polarssl/sha1.h @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/include/netif/ppp/ppp.h b/components/network/lwip/src/include/netif/ppp/ppp.h index 3d73c365..eea52f8c 100644 --- a/components/network/lwip/src/include/netif/ppp/ppp.h +++ b/components/network/lwip/src/include/netif/ppp/ppp.h @@ -7,13 +7,13 @@ * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this -* notice and the following disclaimer are included verbatim in any +* notice and the following disclaimer are included verbatim in any * distributions. No written agreement, license, or royalty fee is required * for any of the authorized uses. * * THIS SOFTWARE IS PROVIDED BY THE 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. +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE 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, @@ -107,8 +107,8 @@ extern "C" { /* * The basic PPP frame. */ -#define PPP_HDRLEN 4 /* octets for standard ppp header */ -#define PPP_FCSLEN 2 /* octets for FCS */ +#define PPP_HDRLEN 4 /* octets for standard ppp header */ +#define PPP_FCSLEN 2 /* octets for FCS */ /* * Values for phase. diff --git a/components/network/lwip/src/include/netif/ppp/ppp_impl.h b/components/network/lwip/src/include/netif/ppp/ppp_impl.h index 40843d5a..29a85c68 100644 --- a/components/network/lwip/src/include/netif/ppp/ppp_impl.h +++ b/components/network/lwip/src/include/netif/ppp/ppp_impl.h @@ -74,66 +74,66 @@ extern "C" { /* * The basic PPP frame. */ -#define PPP_ADDRESS(p) (((u_char *)(p))[0]) -#define PPP_CONTROL(p) (((u_char *)(p))[1]) -#define PPP_PROTOCOL(p) ((((u_char *)(p))[2] << 8) + ((u_char *)(p))[3]) +#define PPP_ADDRESS(p) (((u_char *)(p))[0]) +#define PPP_CONTROL(p) (((u_char *)(p))[1]) +#define PPP_PROTOCOL(p) ((((u_char *)(p))[2] << 8) + ((u_char *)(p))[3]) /* * Significant octet values. */ -#define PPP_ALLSTATIONS 0xff /* All-Stations broadcast address */ -#define PPP_UI 0x03 /* Unnumbered Information */ -#define PPP_FLAG 0x7e /* Flag Sequence */ -#define PPP_ESCAPE 0x7d /* Asynchronous Control Escape */ -#define PPP_TRANS 0x20 /* Asynchronous transparency modifier */ +#define PPP_ALLSTATIONS 0xff /* All-Stations broadcast address */ +#define PPP_UI 0x03 /* Unnumbered Information */ +#define PPP_FLAG 0x7e /* Flag Sequence */ +#define PPP_ESCAPE 0x7d /* Asynchronous Control Escape */ +#define PPP_TRANS 0x20 /* Asynchronous transparency modifier */ /* * Protocol field values. */ -#define PPP_IP 0x21 /* Internet Protocol */ +#define PPP_IP 0x21 /* Internet Protocol */ #if 0 /* UNUSED */ -#define PPP_AT 0x29 /* AppleTalk Protocol */ -#define PPP_IPX 0x2b /* IPX protocol */ +#define PPP_AT 0x29 /* AppleTalk Protocol */ +#define PPP_IPX 0x2b /* IPX protocol */ #endif /* UNUSED */ #if VJ_SUPPORT -#define PPP_VJC_COMP 0x2d /* VJ compressed TCP */ -#define PPP_VJC_UNCOMP 0x2f /* VJ uncompressed TCP */ +#define PPP_VJC_COMP 0x2d /* VJ compressed TCP */ +#define PPP_VJC_UNCOMP 0x2f /* VJ uncompressed TCP */ #endif /* VJ_SUPPORT */ #if PPP_IPV6_SUPPORT -#define PPP_IPV6 0x57 /* Internet Protocol Version 6 */ +#define PPP_IPV6 0x57 /* Internet Protocol Version 6 */ #endif /* PPP_IPV6_SUPPORT */ #if CCP_SUPPORT -#define PPP_COMP 0xfd /* compressed packet */ +#define PPP_COMP 0xfd /* compressed packet */ #endif /* CCP_SUPPORT */ -#define PPP_IPCP 0x8021 /* IP Control Protocol */ +#define PPP_IPCP 0x8021 /* IP Control Protocol */ #if 0 /* UNUSED */ -#define PPP_ATCP 0x8029 /* AppleTalk Control Protocol */ -#define PPP_IPXCP 0x802b /* IPX Control Protocol */ +#define PPP_ATCP 0x8029 /* AppleTalk Control Protocol */ +#define PPP_IPXCP 0x802b /* IPX Control Protocol */ #endif /* UNUSED */ #if PPP_IPV6_SUPPORT -#define PPP_IPV6CP 0x8057 /* IPv6 Control Protocol */ +#define PPP_IPV6CP 0x8057 /* IPv6 Control Protocol */ #endif /* PPP_IPV6_SUPPORT */ #if CCP_SUPPORT -#define PPP_CCP 0x80fd /* Compression Control Protocol */ +#define PPP_CCP 0x80fd /* Compression Control Protocol */ #endif /* CCP_SUPPORT */ #if ECP_SUPPORT -#define PPP_ECP 0x8053 /* Encryption Control Protocol */ +#define PPP_ECP 0x8053 /* Encryption Control Protocol */ #endif /* ECP_SUPPORT */ -#define PPP_LCP 0xc021 /* Link Control Protocol */ +#define PPP_LCP 0xc021 /* Link Control Protocol */ #if PAP_SUPPORT -#define PPP_PAP 0xc023 /* Password Authentication Protocol */ +#define PPP_PAP 0xc023 /* Password Authentication Protocol */ #endif /* PAP_SUPPORT */ #if LQR_SUPPORT -#define PPP_LQR 0xc025 /* Link Quality Report protocol */ +#define PPP_LQR 0xc025 /* Link Quality Report protocol */ #endif /* LQR_SUPPORT */ #if CHAP_SUPPORT -#define PPP_CHAP 0xc223 /* Cryptographic Handshake Auth. Protocol */ +#define PPP_CHAP 0xc223 /* Cryptographic Handshake Auth. Protocol */ #endif /* CHAP_SUPPORT */ #if CBCP_SUPPORT -#define PPP_CBCP 0xc029 /* Callback Control Protocol */ +#define PPP_CBCP 0xc029 /* Callback Control Protocol */ #endif /* CBCP_SUPPORT */ #if EAP_SUPPORT -#define PPP_EAP 0xc227 /* Extensible Authentication Protocol */ +#define PPP_EAP 0xc227 /* Extensible Authentication Protocol */ #endif /* EAP_SUPPORT */ /* @@ -165,59 +165,59 @@ struct link_callbacks { * What to do with network protocol (NP) packets. */ enum NPmode { - NPMODE_PASS, /* pass the packet through */ - NPMODE_DROP, /* silently drop the packet */ - NPMODE_ERROR, /* return an error */ - NPMODE_QUEUE /* save it up for later. */ + NPMODE_PASS, /* pass the packet through */ + NPMODE_DROP, /* silently drop the packet */ + NPMODE_ERROR, /* return an error */ + NPMODE_QUEUE /* save it up for later. */ }; /* * Statistics. */ #if PPP_STATS_SUPPORT -struct pppstat { - unsigned int ppp_ibytes; /* bytes received */ - unsigned int ppp_ipackets; /* packets received */ - unsigned int ppp_ierrors; /* receive errors */ - unsigned int ppp_obytes; /* bytes sent */ - unsigned int ppp_opackets; /* packets sent */ - unsigned int ppp_oerrors; /* transmit errors */ +struct pppstat { + unsigned int ppp_ibytes; /* bytes received */ + unsigned int ppp_ipackets; /* packets received */ + unsigned int ppp_ierrors; /* receive errors */ + unsigned int ppp_obytes; /* bytes sent */ + unsigned int ppp_opackets; /* packets sent */ + unsigned int ppp_oerrors; /* transmit errors */ }; #if VJ_SUPPORT struct vjstat { - unsigned int vjs_packets; /* outbound packets */ + unsigned int vjs_packets; /* outbound packets */ unsigned int vjs_compressed; /* outbound compressed packets */ - unsigned int vjs_searches; /* searches for connection state */ - unsigned int vjs_misses; /* times couldn't find conn. state */ + unsigned int vjs_searches; /* searches for connection state */ + unsigned int vjs_misses; /* times couldn't find conn. state */ unsigned int vjs_uncompressedin; /* inbound uncompressed packets */ unsigned int vjs_compressedin; /* inbound compressed packets */ - unsigned int vjs_errorin; /* inbound unknown type packets */ - unsigned int vjs_tossed; /* inbound packets tossed because of error */ + unsigned int vjs_errorin; /* inbound unknown type packets */ + unsigned int vjs_tossed; /* inbound packets tossed because of error */ }; #endif /* VJ_SUPPORT */ struct ppp_stats { - struct pppstat p; /* basic PPP statistics */ + struct pppstat p; /* basic PPP statistics */ #if VJ_SUPPORT - struct vjstat vj; /* VJ header compression statistics */ + struct vjstat vj; /* VJ header compression statistics */ #endif /* VJ_SUPPORT */ }; #if CCP_SUPPORT struct compstat { - unsigned int unc_bytes; /* total uncompressed bytes */ - unsigned int unc_packets; /* total uncompressed packets */ - unsigned int comp_bytes; /* compressed bytes */ - unsigned int comp_packets; /* compressed packets */ - unsigned int inc_bytes; /* incompressible bytes */ - unsigned int inc_packets; /* incompressible packets */ - unsigned int ratio; /* recent compression ratio << 8 */ + unsigned int unc_bytes; /* total uncompressed bytes */ + unsigned int unc_packets; /* total uncompressed packets */ + unsigned int comp_bytes; /* compressed bytes */ + unsigned int comp_packets; /* compressed packets */ + unsigned int inc_bytes; /* incompressible bytes */ + unsigned int inc_packets; /* incompressible packets */ + unsigned int ratio; /* recent compression ratio << 8 */ }; struct ppp_comp_stats { - struct compstat c; /* packet compression statistics */ - struct compstat d; /* packet decompression statistics */ + struct compstat c; /* packet compression statistics */ + struct compstat d; /* packet decompression statistics */ }; #endif /* CCP_SUPPORT */ @@ -229,37 +229,37 @@ struct ppp_comp_stats { * the last NP packet was sent or received. */ struct ppp_idle { - time_t xmit_idle; /* time since last NP packet sent */ - time_t recv_idle; /* time since last NP packet received */ + time_t xmit_idle; /* time since last NP packet sent */ + time_t recv_idle; /* time since last NP packet received */ }; #endif /* PPP_IDLETIMELIMIT */ /* values for epdisc.class */ -#define EPD_NULL 0 /* null discriminator, no data */ -#define EPD_LOCAL 1 -#define EPD_IP 2 -#define EPD_MAC 3 -#define EPD_MAGIC 4 -#define EPD_PHONENUM 5 +#define EPD_NULL 0 /* null discriminator, no data */ +#define EPD_LOCAL 1 +#define EPD_IP 2 +#define EPD_MAC 3 +#define EPD_MAGIC 4 +#define EPD_PHONENUM 5 /* * Global variables. */ #ifdef HAVE_MULTILINK -extern u8_t multilink; /* enable multilink operation */ -extern u8_t doing_multilink; -extern u8_t multilink_master; -extern u8_t bundle_eof; -extern u8_t bundle_terminating; +extern u8_t multilink; /* enable multilink operation */ +extern u8_t doing_multilink; +extern u8_t multilink_master; +extern u8_t bundle_eof; +extern u8_t bundle_terminating; #endif #ifdef MAXOCTETS -extern unsigned int maxoctets; /* Maximum octetes per session (in bytes) */ +extern unsigned int maxoctets; /* Maximum octetes per session (in bytes) */ extern int maxoctets_dir; /* Direction : - 0 - in+out (default) - 1 - in - 2 - out - 3 - max(in,out) */ + 0 - in+out (default) + 1 - in + 2 - out + 3 - max(in,out) */ extern int maxoctets_timeout; /* Timeout for check of octets limit */ #define PPP_OCTETS_DIRECTION_SUM 0 #define PPP_OCTETS_DIRECTION_IN 1 @@ -279,7 +279,7 @@ extern int maxoctets_timeout; /* Timeout for check of octets limit */ * for a particular protocol. */ struct protent { - u_short protocol; /* PPP protocol number */ + u_short protocol; /* PPP protocol number */ /* Initialization procedure */ void (*init) (ppp_pcb *pcb); /* Process a received packet */ @@ -297,19 +297,19 @@ struct protent { #if PRINTPKT_SUPPORT /* Print a packet in readable form */ int (*printpkt) (const u_char *pkt, int len, - void (*printer) (void *, const char *, ...), - void *arg); + void (*printer) (void *, const char *, ...), + void *arg); #endif /* PRINTPKT_SUPPORT */ #if PPP_DATAINPUT /* Process a received data packet */ void (*datainput) (ppp_pcb *pcb, u_char *pkt, int len); #endif /* PPP_DATAINPUT */ #if PRINTPKT_SUPPORT - const char *name; /* Text name of protocol */ - const char *data_name; /* Text name of corresponding data protocol */ + const char *name; /* Text name of protocol */ + const char *data_name; /* Text name of corresponding data protocol */ #endif /* PRINTPKT_SUPPORT */ #if PPP_OPTIONS - option_t *options; /* List of command-line options */ + option_t *options; /* List of command-line options */ /* Check requested options, assign defaults */ void (*check_options) (void); #endif /* PPP_OPTIONS */ @@ -327,28 +327,28 @@ extern const struct protent* const protocols[]; /* Values for auth_pending, auth_done */ #if PAP_SUPPORT -#define PAP_WITHPEER 0x1 -#define PAP_PEER 0x2 +#define PAP_WITHPEER 0x1 +#define PAP_PEER 0x2 #endif /* PAP_SUPPORT */ #if CHAP_SUPPORT -#define CHAP_WITHPEER 0x4 -#define CHAP_PEER 0x8 +#define CHAP_WITHPEER 0x4 +#define CHAP_PEER 0x8 #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT -#define EAP_WITHPEER 0x10 -#define EAP_PEER 0x20 +#define EAP_WITHPEER 0x10 +#define EAP_PEER 0x20 #endif /* EAP_SUPPORT */ /* Values for auth_done only */ #if CHAP_SUPPORT -#define CHAP_MD5_WITHPEER 0x40 -#define CHAP_MD5_PEER 0x80 +#define CHAP_MD5_WITHPEER 0x40 +#define CHAP_MD5_PEER 0x80 #if MSCHAP_SUPPORT -#define CHAP_MS_SHIFT 8 /* LSB position for MS auths */ -#define CHAP_MS_WITHPEER 0x100 -#define CHAP_MS_PEER 0x200 -#define CHAP_MS2_WITHPEER 0x400 -#define CHAP_MS2_PEER 0x800 +#define CHAP_MS_SHIFT 8 /* LSB position for MS auths */ +#define CHAP_MS_WITHPEER 0x100 +#define CHAP_MS_PEER 0x200 +#define CHAP_MS2_WITHPEER 0x400 +#define CHAP_MS2_PEER 0x800 #endif /* MSCHAP_SUPPORT */ #endif /* CHAP_SUPPORT */ @@ -370,10 +370,10 @@ extern const struct protent* const protocols[]; * PPP statistics structure */ struct pppd_stats { - unsigned int bytes_in; - unsigned int bytes_out; - unsigned int pkts_in; - unsigned int pkts_out; + unsigned int bytes_in; + unsigned int bytes_out; + unsigned int pkts_in; + unsigned int pkts_out; }; #endif /* PPP_STATS_SUPPORT */ @@ -382,7 +382,7 @@ struct pppd_stats { * PPP private functions */ - + /* * Functions called from lwIP core. */ @@ -500,34 +500,34 @@ void update_link_stats(int u); /* Get stats at link termination */ * cp MUST be u_char *. */ #define GETCHAR(c, cp) { \ - (c) = *(cp)++; \ + (c) = *(cp)++; \ } #define PUTCHAR(c, cp) { \ - *(cp)++ = (u_char) (c); \ + *(cp)++ = (u_char) (c); \ } #define GETSHORT(s, cp) { \ - (s) = *(cp)++ << 8; \ - (s) |= *(cp)++; \ + (s) = *(cp)++ << 8; \ + (s) |= *(cp)++; \ } #define PUTSHORT(s, cp) { \ - *(cp)++ = (u_char) ((s) >> 8); \ - *(cp)++ = (u_char) (s); \ + *(cp)++ = (u_char) ((s) >> 8); \ + *(cp)++ = (u_char) (s); \ } #define GETLONG(l, cp) { \ - (l) = *(cp)++ << 8; \ - (l) |= *(cp)++; (l) <<= 8; \ - (l) |= *(cp)++; (l) <<= 8; \ - (l) |= *(cp)++; \ + (l) = *(cp)++ << 8; \ + (l) |= *(cp)++; (l) <<= 8; \ + (l) |= *(cp)++; (l) <<= 8; \ + (l) |= *(cp)++; \ } #define PUTLONG(l, cp) { \ - *(cp)++ = (u_char) ((l) >> 24); \ - *(cp)++ = (u_char) ((l) >> 16); \ - *(cp)++ = (u_char) ((l) >> 8); \ - *(cp)++ = (u_char) (l); \ + *(cp)++ = (u_char) ((l) >> 24); \ + *(cp)++ = (u_char) ((l) >> 16); \ + *(cp)++ = (u_char) ((l) >> 8); \ + *(cp)++ = (u_char) (l); \ } -#define INCPTR(n, cp) ((cp) += (n)) -#define DECPTR(n, cp) ((cp) -= (n)) +#define INCPTR(n, cp) ((cp) += (n)) +#define DECPTR(n, cp) ((cp) -= (n)) /* * System dependent definitions for user-level 4.3BSD UNIX implementation. @@ -536,10 +536,10 @@ void update_link_stats(int u); /* Get stats at link termination */ #define TIMEOUTMS(f, a, t) do { sys_untimeout((f), (a)); sys_timeout((t), (f), (a)); } while(0) #define UNTIMEOUT(f, a) sys_untimeout((f), (a)) -#define BZERO(s, n) memset(s, 0, n) -#define BCMP(s1, s2, l) memcmp(s1, s2, l) +#define BZERO(s, n) memset(s, 0, n) +#define BCMP(s1, s2, l) memcmp(s1, s2, l) -#define PRINTMSG(m, l) { ppp_info("Remote message: %0.*v", l, m); } +#define PRINTMSG(m, l) { ppp_info("Remote message: %0.*v", l, m); } /* * MAKEHEADER - Add Header fields to a packet. @@ -552,7 +552,7 @@ void update_link_stats(int u); /* Get stats at link termination */ /* Procedures exported from auth.c */ void link_required(ppp_pcb *pcb); /* we are starting to use the link */ void link_terminated(ppp_pcb *pcb); /* we are finished with the link */ -void link_down(ppp_pcb *pcb); /* the LCP layer has left the Opened state */ +void link_down(ppp_pcb *pcb); /* the LCP layer has left the Opened state */ void upper_layers_down(ppp_pcb *pcb); /* take all NCPs down */ void link_established(ppp_pcb *pcb); /* the link is up; authenticate now */ void start_networks(ppp_pcb *pcb); /* start all the network control protos */ @@ -562,21 +562,21 @@ void continue_networks(ppp_pcb *pcb); /* start network [ip, etc] control protos int auth_check_passwd(ppp_pcb *pcb, char *auser, int userlen, char *apasswd, int passwdlen, const char **msg, int *msglen); /* check the user name and passwd against configuration */ void auth_peer_fail(ppp_pcb *pcb, int protocol); - /* peer failed to authenticate itself */ + /* peer failed to authenticate itself */ void auth_peer_success(ppp_pcb *pcb, int protocol, int prot_flavor, const char *name, int namelen); - /* peer successfully authenticated itself */ + /* peer successfully authenticated itself */ #endif /* PPP_SERVER */ void auth_withpeer_fail(ppp_pcb *pcb, int protocol); - /* we failed to authenticate ourselves */ + /* we failed to authenticate ourselves */ void auth_withpeer_success(ppp_pcb *pcb, int protocol, int prot_flavor); - /* we successfully authenticated ourselves */ + /* we successfully authenticated ourselves */ #endif /* PPP_AUTH_SUPPORT */ void np_up(ppp_pcb *pcb, int proto); /* a network protocol has come up */ void np_down(ppp_pcb *pcb, int proto); /* a network protocol has gone down */ void np_finished(ppp_pcb *pcb, int proto); /* a network protocol no longer needs link */ #if PPP_AUTH_SUPPORT int get_secret(ppp_pcb *pcb, const char *client, const char *server, char *secret, int *secret_len, int am_server); - /* get "secret" for chap */ + /* get "secret" for chap */ #endif /* PPP_AUTH_SUPPORT */ /* Procedures exported from ipcp.c */ @@ -584,8 +584,8 @@ int get_secret(ppp_pcb *pcb, const char *client, const char *server, char *secre /* Procedures exported from demand.c */ #if DEMAND_SUPPORT -void demand_conf (void); /* config interface(s) for demand-dial */ -void demand_block (void); /* set all NPs to queue up packets */ +void demand_conf (void); /* config interface(s) for demand-dial */ +void demand_block (void); /* set all NPs to queue up packets */ void demand_unblock (void); /* set all NPs to pass packets */ void demand_discard (void); /* set all NPs to discard packets */ void demand_rexmit (int, u32_t); /* retransmit saved frames for an NP*/ @@ -602,10 +602,10 @@ void mp_bundle_terminated (void); char *epdisc_to_str (struct epdisc *); /* string from endpoint discrim. */ int str_to_epdisc (struct epdisc *, char *); /* endpt disc. from str */ #else -#define mp_bundle_terminated() /* nothing */ -#define mp_exit_bundle() /* nothing */ -#define doing_multilink 0 -#define multilink_master 0 +#define mp_bundle_terminated() /* nothing */ +#define mp_exit_bundle() /* nothing */ +#define doing_multilink 0 +#define multilink_master 0 #endif /* Procedures exported from utils.c. */ diff --git a/components/network/lwip/src/include/netif/ppp/pppcrypt.h b/components/network/lwip/src/include/netif/ppp/pppcrypt.h index c0230bbc..2531ee0a 100644 --- a/components/network/lwip/src/include/netif/ppp/pppcrypt.h +++ b/components/network/lwip/src/include/netif/ppp/pppcrypt.h @@ -36,7 +36,7 @@ /* This header file is included in all PPP modules needing hashes and/or ciphers */ #ifndef PPPCRYPT_H -#define PPPCRYPT_H +#define PPPCRYPT_H /* * If included PolarSSL copy is not used, user is expected to include diff --git a/components/network/lwip/src/include/netif/ppp/pppdebug.h b/components/network/lwip/src/include/netif/ppp/pppdebug.h index 36ee4f9b..5e6741bf 100644 --- a/components/network/lwip/src/include/netif/ppp/pppdebug.h +++ b/components/network/lwip/src/include/netif/ppp/pppdebug.h @@ -8,13 +8,13 @@ * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this -* notice and the following disclaimer are included verbatim in any +* notice and the following disclaimer are included verbatim in any * distributions. No written agreement, license, or royalty fee is required * for any of the authorized uses. * * THIS SOFTWARE IS PROVIDED BY THE 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. +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE 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, diff --git a/components/network/lwip/src/include/netif/ppp/pppoe.h b/components/network/lwip/src/include/netif/ppp/pppoe.h index 08ab7ab5..c96eb784 100644 --- a/components/network/lwip/src/include/netif/ppp/pppoe.h +++ b/components/network/lwip/src/include/netif/ppp/pppoe.h @@ -6,13 +6,13 @@ * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this -* notice and the following disclaimer are included verbatim in any +* notice and the following disclaimer are included verbatim in any * distributions. No written agreement, license, or royalty fee is required * for any of the authorized uses. * * THIS SOFTWARE IS PROVIDED BY THE 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. +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE 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, diff --git a/components/network/lwip/src/include/netif/ppp/upap.h b/components/network/lwip/src/include/netif/ppp/upap.h index 540d9814..caf81939 100644 --- a/components/network/lwip/src/include/netif/ppp/upap.h +++ b/components/network/lwip/src/include/netif/ppp/upap.h @@ -57,44 +57,44 @@ extern "C" { /* * Packet header = Code, id, length. */ -#define UPAP_HEADERLEN 4 +#define UPAP_HEADERLEN 4 /* * UPAP codes. */ -#define UPAP_AUTHREQ 1 /* Authenticate-Request */ -#define UPAP_AUTHACK 2 /* Authenticate-Ack */ -#define UPAP_AUTHNAK 3 /* Authenticate-Nak */ +#define UPAP_AUTHREQ 1 /* Authenticate-Request */ +#define UPAP_AUTHACK 2 /* Authenticate-Ack */ +#define UPAP_AUTHNAK 3 /* Authenticate-Nak */ /* * Client states. */ -#define UPAPCS_INITIAL 0 /* Connection down */ -#define UPAPCS_CLOSED 1 /* Connection up, haven't requested auth */ -#define UPAPCS_PENDING 2 /* Connection down, have requested auth */ -#define UPAPCS_AUTHREQ 3 /* We've sent an Authenticate-Request */ -#define UPAPCS_OPEN 4 /* We've received an Ack */ -#define UPAPCS_BADAUTH 5 /* We've received a Nak */ +#define UPAPCS_INITIAL 0 /* Connection down */ +#define UPAPCS_CLOSED 1 /* Connection up, haven't requested auth */ +#define UPAPCS_PENDING 2 /* Connection down, have requested auth */ +#define UPAPCS_AUTHREQ 3 /* We've sent an Authenticate-Request */ +#define UPAPCS_OPEN 4 /* We've received an Ack */ +#define UPAPCS_BADAUTH 5 /* We've received a Nak */ /* * Server states. */ -#define UPAPSS_INITIAL 0 /* Connection down */ -#define UPAPSS_CLOSED 1 /* Connection up, haven't requested auth */ -#define UPAPSS_PENDING 2 /* Connection down, have requested auth */ -#define UPAPSS_LISTEN 3 /* Listening for an Authenticate */ -#define UPAPSS_OPEN 4 /* We've sent an Ack */ -#define UPAPSS_BADAUTH 5 /* We've sent a Nak */ +#define UPAPSS_INITIAL 0 /* Connection down */ +#define UPAPSS_CLOSED 1 /* Connection up, haven't requested auth */ +#define UPAPSS_PENDING 2 /* Connection down, have requested auth */ +#define UPAPSS_LISTEN 3 /* Listening for an Authenticate */ +#define UPAPSS_OPEN 4 /* We've sent an Ack */ +#define UPAPSS_BADAUTH 5 /* We've sent a Nak */ /* * Timeouts. */ #if 0 /* moved to ppp_opts.h */ -#define UPAP_DEFTIMEOUT 3 /* Timeout (seconds) for retransmitting req */ -#define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ +#define UPAP_DEFTIMEOUT 3 /* Timeout (seconds) for retransmitting req */ +#define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ #endif /* moved to ppp_opts.h */ /* @@ -102,16 +102,16 @@ extern "C" { */ #if PAP_SUPPORT typedef struct upap_state { - const char *us_user; /* User */ - u8_t us_userlen; /* User length */ - const char *us_passwd; /* Password */ - u8_t us_passwdlen; /* Password length */ - u8_t us_clientstate; /* Client state */ + const char *us_user; /* User */ + u8_t us_userlen; /* User length */ + const char *us_passwd; /* Password */ + u8_t us_passwdlen; /* Password length */ + u8_t us_clientstate; /* Client state */ #if PPP_SERVER - u8_t us_serverstate; /* Server state */ + u8_t us_serverstate; /* Server state */ #endif /* PPP_SERVER */ - u8_t us_id; /* Current id */ - u8_t us_transmits; /* Number of auth-reqs sent */ + u8_t us_id; /* Current id */ + u8_t us_transmits; /* Number of auth-reqs sent */ } upap_state; #endif /* PAP_SUPPORT */ diff --git a/components/network/lwip/src/netif/bridgeif_fdb.c b/components/network/lwip/src/netif/bridgeif_fdb.c index 6739fc24..2f052ec0 100644 --- a/components/network/lwip/src/netif/bridgeif_fdb.c +++ b/components/network/lwip/src/netif/bridgeif_fdb.c @@ -69,7 +69,7 @@ typedef struct bridgeif_dfdb_s { * remembers known src mac addresses to know which port to send frames destined for that * mac address. * - * ATTENTION: This is meant as an example only, in real-world use, you should + * ATTENTION: This is meant as an example only, in real-world use, you should * provide a better implementation :-) */ void @@ -120,9 +120,9 @@ bridgeif_fdb_update_src(void *fdb_ptr, struct eth_addr *src_addr, u8_t port_idx) /* not found, no free entry -> flood */ } -/** +/** * @ingroup bridgeif_fdb - * Walk our list of auto-learnt fdb entries and return a port to forward or BR_FLOOD if unknown + * Walk our list of auto-learnt fdb entries and return a port to forward or BR_FLOOD if unknown */ bridgeif_portmask_t bridgeif_fdb_get_dst_ports(void *fdb_ptr, struct eth_addr *dst_addr) diff --git a/components/network/lwip/src/netif/lowpan6_ble.c b/components/network/lwip/src/netif/lowpan6_ble.c index d89816d3..d59b432f 100644 --- a/components/network/lwip/src/netif/lowpan6_ble.c +++ b/components/network/lwip/src/netif/lowpan6_ble.c @@ -6,7 +6,7 @@ /* * Copyright (c) 2017 Benjamin Aigner * Copyright (c) 2015 Inico Technologies Ltd. , Author: Ivan Delamer - * + * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -32,7 +32,7 @@ * OF SUCH DAMAGE. * * Author: Benjamin Aigner - * + * * Based on the original 6lowpan implementation of lwIP ( @see 6lowpan.c) */ @@ -95,15 +95,15 @@ static struct lowpan6_link_addr rfc7668_peer_addr; /** * @ingroup rfc7668if * convert BT address to EUI64 addr - * + * * This method converts a Bluetooth MAC address to an EUI64 address, * which is used within IPv6 communication - * + * * @param dst IPv6 destination space * @param src BLE MAC address source * @param public_addr If the LWIP_RFC7668_LINUX_WORKAROUND_PUBLIC_ADDRESS * option is set, bit 0x02 will be set if param=0 (no public addr); cleared otherwise - * + * * @see LWIP_RFC7668_LINUX_WORKAROUND_PUBLIC_ADDRESS */ void @@ -128,12 +128,12 @@ ble_addr_to_eui64(uint8_t *dst, const uint8_t *src, int public_addr) /** * @ingroup rfc7668if * convert EUI64 address to Bluetooth MAC addr - * + * * This method converts an EUI64 address to a Bluetooth MAC address, - * + * * @param dst BLE MAC address destination * @param src IPv6 source - * + * */ void eui64_to_ble_addr(uint8_t *dst, const uint8_t *src) @@ -214,16 +214,16 @@ rfc7668_set_peer_addr_mac48(struct netif *netif, const u8_t *peer_addr, size_t p } /** Encapsulate IPv6 frames for BLE transmission - * + * * This method implements the IPv6 header compression: * *) According to RFC6282 * *) See Figure 2, contains base format of bit positions * *) Fragmentation not necessary (done at L2CAP layer of BLE) * @note Currently the pbuf allocation uses 256 bytes. If longer packets are used (possible due to MTU=1480Bytes), increase it here! - * + * * @param p Pbuf struct, containing the payload data * @param netif Output network interface. Should be of RFC7668 type - * + * * @return Same as netif->output. */ static err_t @@ -340,7 +340,7 @@ rfc7668_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr) * @param p the received packet, p->payload pointing to the * IPv6 header (maybe compressed) * @param netif the network interface on which the packet was received - * + * * @return ERR_OK if everything was fine */ err_t @@ -352,7 +352,7 @@ rfc7668_input(struct pbuf * p, struct netif *netif) /* Load first header byte */ puc = (u8_t*)p->payload; - + /* no IP header compression */ if (*puc == 0x41) { LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Completed packet, removing dispatch: 0x%2x \n", *puc)); @@ -398,12 +398,12 @@ rfc7668_input(struct pbuf * p, struct netif *netif) /** * @ingroup rfc7668if * Initialize the netif - * + * * No flags are used (broadcast not possible, not ethernet, ...) * The shortname for this netif is "BT" * * @param netif the network interface to be initialized as RFC7668 netif - * + * * @return ERR_OK if everything went fine */ err_t @@ -433,7 +433,7 @@ rfc7668_if_init(struct netif *netif) * @param p the received packet, p->payload pointing to the * IEEE 802.15.4 header. * @param inp the network interface on which the packet was received - * + * * @return see @ref tcpip_inpkt, same return values */ err_t diff --git a/components/network/lwip/src/netif/lowpan6_common.c b/components/network/lwip/src/netif/lowpan6_common.c index baea206a..89758d94 100644 --- a/components/network/lwip/src/netif/lowpan6_common.c +++ b/components/network/lwip/src/netif/lowpan6_common.c @@ -430,7 +430,7 @@ lowpan6_decompress_hdr(u8_t *lowpan6_buffer, size_t lowpan6_bufsize, /* offset for inline IP headers (RFC 6282 ch3)*/ lowpan6_offset = 2; - /* if CID is set (context identifier), the context byte + /* if CID is set (context identifier), the context byte * follows immediately after the header, so other IPHC fields are @+3 */ if (lowpan6_buffer[1] & 0x80) { lowpan6_offset++; diff --git a/components/network/lwip/src/netif/ppp/auth.c b/components/network/lwip/src/netif/ppp/auth.c index c8673ad0..480a653d 100644 --- a/components/network/lwip/src/netif/ppp/auth.c +++ b/components/network/lwip/src/netif/ppp/auth.c @@ -133,10 +133,10 @@ #if 0 /* UNUSED */ /* Bits in scan_authfile return value */ -#define NONWILD_SERVER 1 -#define NONWILD_CLIENT 2 +#define NONWILD_SERVER 1 +#define NONWILD_CLIENT 2 -#define ISWILD(word) (word[0] == '*' && word[1] == 0) +#define ISWILD(word) (word[0] == '*' && word[1] == 0) #endif /* UNUSED */ #if 0 /* UNUSED */ @@ -169,8 +169,8 @@ int (*pap_check_hook) (void) = NULL; /* Hook for a plugin to check the PAP user and password */ int (*pap_auth_hook) (char *user, char *passwd, char **msgp, - struct wordlist **paddrs, - struct wordlist **popts) = NULL; + struct wordlist **paddrs, + struct wordlist **popts) = NULL; /* Hook for a plugin to know about the PAP user logout */ void (*pap_logout_hook) (void) = NULL; @@ -187,7 +187,7 @@ int (*chap_passwd_hook) (char *user, char *passwd) = NULL; /* Hook for a plugin to say whether it is OK if the peer refuses to authenticate. */ int (*null_auth_hook) (struct wordlist **paddrs, - struct wordlist **popts) = NULL; + struct wordlist **popts) = NULL; int (*allowed_address_hook) (u32_t addr) = NULL; #endif /* UNUSED */ @@ -210,27 +210,27 @@ struct notifier *link_down_notifier = NULL; * Option variables. */ #if 0 /* MOVED TO ppp_settings */ -bool uselogin = 0; /* Use /etc/passwd for checking PAP */ -bool session_mgmt = 0; /* Do session management (login records) */ -bool cryptpap = 0; /* Passwords in pap-secrets are encrypted */ -bool refuse_pap = 0; /* Don't wanna auth. ourselves with PAP */ -bool refuse_chap = 0; /* Don't wanna auth. ourselves with CHAP */ -bool refuse_eap = 0; /* Don't wanna auth. ourselves with EAP */ +bool uselogin = 0; /* Use /etc/passwd for checking PAP */ +bool session_mgmt = 0; /* Do session management (login records) */ +bool cryptpap = 0; /* Passwords in pap-secrets are encrypted */ +bool refuse_pap = 0; /* Don't wanna auth. ourselves with PAP */ +bool refuse_chap = 0; /* Don't wanna auth. ourselves with CHAP */ +bool refuse_eap = 0; /* Don't wanna auth. ourselves with EAP */ #if MSCHAP_SUPPORT -bool refuse_mschap = 0; /* Don't wanna auth. ourselves with MS-CHAP */ -bool refuse_mschap_v2 = 0; /* Don't wanna auth. ourselves with MS-CHAPv2 */ +bool refuse_mschap = 0; /* Don't wanna auth. ourselves with MS-CHAP */ +bool refuse_mschap_v2 = 0; /* Don't wanna auth. ourselves with MS-CHAPv2 */ #else /* MSCHAP_SUPPORT */ -bool refuse_mschap = 1; /* Don't wanna auth. ourselves with MS-CHAP */ -bool refuse_mschap_v2 = 1; /* Don't wanna auth. ourselves with MS-CHAPv2 */ +bool refuse_mschap = 1; /* Don't wanna auth. ourselves with MS-CHAP */ +bool refuse_mschap_v2 = 1; /* Don't wanna auth. ourselves with MS-CHAPv2 */ #endif /* MSCHAP_SUPPORT */ -bool usehostname = 0; /* Use hostname for our_name */ -bool auth_required = 0; /* Always require authentication from peer */ -bool allow_any_ip = 0; /* Allow peer to use any IP address */ -bool explicit_remote = 0; /* User specified explicit remote name */ -bool explicit_user = 0; /* Set if "user" option supplied */ -bool explicit_passwd = 0; /* Set if "password" option supplied */ -char remote_name[MAXNAMELEN]; /* Peer's name for authentication */ -static char *uafname; /* name of most recent +ua file */ +bool usehostname = 0; /* Use hostname for our_name */ +bool auth_required = 0; /* Always require authentication from peer */ +bool allow_any_ip = 0; /* Allow peer to use any IP address */ +bool explicit_remote = 0; /* User specified explicit remote name */ +bool explicit_user = 0; /* Set if "user" option supplied */ +bool explicit_passwd = 0; /* Set if "password" option supplied */ +char remote_name[MAXNAMELEN]; /* Peer's name for authentication */ +static char *uafname; /* name of most recent +ua file */ extern char *crypt (const char *, const char *); #endif /* UNUSED */ @@ -252,8 +252,8 @@ static int have_srp_secret (char *client, char *server, int need_ip, int *lacks_ipp); static int ip_addr_check (u32_t, struct permitted_ip *); static int scan_authfile (FILE *, char *, char *, char *, - struct wordlist **, struct wordlist **, - char *, int); + struct wordlist **, struct wordlist **, + char *, int); static void free_wordlist (struct wordlist *); static void set_allowed_addrs (int, struct wordlist *, struct wordlist *); static int some_ip_ok (struct wordlist *); @@ -427,46 +427,46 @@ setupapfile(argv) /* open user info file */ fname = strdup(*argv); if (fname == NULL) - novm("+ua file name"); + novm("+ua file name"); euid = geteuid(); if (seteuid(getuid()) == -1) { - option_error("unable to reset uid before opening %s: %m", fname); - return 0; + option_error("unable to reset uid before opening %s: %m", fname); + return 0; } ufile = fopen(fname, "r"); if (seteuid(euid) == -1) - fatal("unable to regain privileges: %m"); + fatal("unable to regain privileges: %m"); if (ufile == NULL) { - option_error("unable to open user login data file %s", fname); - return 0; + option_error("unable to open user login data file %s", fname); + return 0; } check_access(ufile, fname); uafname = fname; /* get username */ if (fgets(u, MAXNAMELEN - 1, ufile) == NULL - || fgets(p, MAXSECRETLEN - 1, ufile) == NULL) { - fclose(ufile); - option_error("unable to read user login data file %s", fname); - return 0; + || fgets(p, MAXSECRETLEN - 1, ufile) == NULL) { + fclose(ufile); + option_error("unable to read user login data file %s", fname); + return 0; } fclose(ufile); /* get rid of newlines */ l = strlen(u); if (l > 0 && u[l-1] == '\n') - u[l-1] = 0; + u[l-1] = 0; l = strlen(p); if (l > 0 && p[l-1] == '\n') - p[l-1] = 0; + p[l-1] = 0; if (override_value("user", option_priority, fname)) { - strlcpy(ppp_settings.user, u, sizeof(ppp_settings.user)); - explicit_user = 1; + strlcpy(ppp_settings.user, u, sizeof(ppp_settings.user)); + explicit_user = 1; } if (override_value("passwd", option_priority, fname)) { - strlcpy(ppp_settings.passwd, p, sizeof(ppp_settings.passwd)); - explicit_passwd = 1; + strlcpy(ppp_settings.passwd, p, sizeof(ppp_settings.passwd)); + explicit_passwd = 1; } return (1); @@ -484,14 +484,14 @@ privgroup(argv) g = getgrnam(*argv); if (g == 0) { - option_error("group %s is unknown", *argv); - return 0; + option_error("group %s is unknown", *argv); + return 0; } for (i = 0; i < ngroups; ++i) { - if (groups[i] == g->gr_gid) { - privileged = 1; - break; - } + if (groups[i] == g->gr_gid) { + privileged = 1; + break; + } } return 1; } @@ -511,7 +511,7 @@ set_noauth_addr(argv) wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l); if (wp == NULL) - novm("allow-ip argument"); + novm("allow-ip argument"); wp->word = (char *) (wp + 1); wp->next = noauth_addrs; MEMCPY(wp->word, addr, l); @@ -533,7 +533,7 @@ set_permitted_number(argv) wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l); if (wp == NULL) - novm("allow-number argument"); + novm("allow-number argument"); wp->word = (char *) (wp + 1); wp->next = permitted_numbers; MEMCPY(wp->word, number, l); @@ -566,7 +566,7 @@ void start_link(unit) devfd = the_channel->connect(); msg = "Connect script failed"; if (devfd < 0) - goto fail; + goto fail; /* set up the serial device as a ppp interface */ /* @@ -579,21 +579,21 @@ void start_link(unit) fd_ppp = the_channel->establish_ppp(devfd); msg = "ppp establishment failed"; if (fd_ppp < 0) { - status = EXIT_FATAL_ERROR; - goto disconnect; + status = EXIT_FATAL_ERROR; + goto disconnect; } if (!demand && ifunit >= 0) - set_ifunit(1); + set_ifunit(1); /* * Start opening the connection and wait for * incoming events (reply, timeout, etc.). */ if (ifunit >= 0) - ppp_notice("Connect: %s <--> %s", ifname, ppp_devnam); + ppp_notice("Connect: %s <--> %s", ifname, ppp_devnam); else - ppp_notice("Starting negotiation on %s", ppp_devnam); + ppp_notice("Starting negotiation on %s", ppp_devnam); add_fd(fd_ppp); new_phase(pcb, PPP_PHASE_ESTABLISH); @@ -604,12 +604,12 @@ void start_link(unit) disconnect: new_phase(pcb, PPP_PHASE_DISCONNECT); if (the_channel->disconnect) - the_channel->disconnect(); + the_channel->disconnect(); fail: new_phase(pcb, PPP_PHASE_DEAD); if (the_channel->cleanup) - (*the_channel->cleanup)(); + (*the_channel->cleanup)(); } #endif @@ -623,23 +623,23 @@ void link_terminated(ppp_pcb *pcb) { || pcb->phase == PPP_PHASE_MASTER #endif /* HAVE_MULTILINK */ ) - return; + return; new_phase(pcb, PPP_PHASE_DISCONNECT); #if 0 /* UNUSED */ if (pap_logout_hook) { - pap_logout_hook(); + pap_logout_hook(); } session_end(devnam); #endif /* UNUSED */ if (!doing_multilink) { - ppp_notice("Connection terminated."); + ppp_notice("Connection terminated."); #if PPP_STATS_SUPPORT - print_link_stats(); + print_link_stats(); #endif /* PPP_STATS_SUPPORT */ } else - ppp_notice("Link terminated."); + ppp_notice("Link terminated."); lcp_lowerdown(pcb); @@ -651,7 +651,7 @@ void link_terminated(ppp_pcb *pcb) { * we delete its pid file. */ if (!doing_multilink && !demand) - remove_pidfiles(); + remove_pidfiles(); /* * If we may want to bring the link up again, transfer @@ -659,36 +659,36 @@ void link_terminated(ppp_pcb *pcb) { * real serial device back to its normal mode of operation. */ if (fd_ppp >= 0) { - remove_fd(fd_ppp); - clean_check(); - the_channel->disestablish_ppp(devfd); - if (doing_multilink) - mp_exit_bundle(); - fd_ppp = -1; + remove_fd(fd_ppp); + clean_check(); + the_channel->disestablish_ppp(devfd); + if (doing_multilink) + mp_exit_bundle(); + fd_ppp = -1; } if (!hungup) - lcp_lowerdown(pcb); + lcp_lowerdown(pcb); if (!doing_multilink && !demand) - script_unsetenv("IFNAME"); + script_unsetenv("IFNAME"); /* * Run disconnector script, if requested. * XXX we may not be able to do this if the line has hung up! */ if (devfd >= 0 && the_channel->disconnect) { - the_channel->disconnect(); - devfd = -1; + the_channel->disconnect(); + devfd = -1; } if (the_channel->cleanup) - (*the_channel->cleanup)(); + (*the_channel->cleanup)(); if (doing_multilink && multilink_master) { - if (!bundle_terminating) - new_phase(pcb, PPP_PHASE_MASTER); - else - mp_bundle_terminated(); + if (!bundle_terminating) + new_phase(pcb, PPP_PHASE_MASTER); + else + mp_bundle_terminated(); } else - new_phase(pcb, PPP_PHASE_DEAD); + new_phase(pcb, PPP_PHASE_DEAD); #endif } @@ -701,13 +701,13 @@ void link_down(ppp_pcb *pcb) { #endif /* PPP_NOTIFY */ if (!doing_multilink) { - upper_layers_down(pcb); - if (pcb->phase != PPP_PHASE_DEAD + upper_layers_down(pcb); + if (pcb->phase != PPP_PHASE_DEAD #ifdef HAVE_MULTILINK - && pcb->phase != PPP_PHASE_MASTER + && pcb->phase != PPP_PHASE_MASTER #endif /* HAVE_MULTILINK */ - ) - new_phase(pcb, PPP_PHASE_ESTABLISH); + ) + new_phase(pcb, PPP_PHASE_ESTABLISH); } /* XXX if doing_multilink, should do something to stop network-layer traffic on the link */ @@ -719,9 +719,9 @@ void upper_layers_down(ppp_pcb *pcb) { for (i = 0; (protp = protocols[i]) != NULL; ++i) { if (protp->protocol != PPP_LCP && protp->lowerdown != NULL) - (*protp->lowerdown)(pcb); + (*protp->lowerdown)(pcb); if (protp->protocol < 0xC000 && protp->close != NULL) - (*protp->close)(pcb, "LCP down"); + (*protp->close)(pcb, "LCP down"); } pcb->num_np_open = 0; pcb->num_np_up = 0; @@ -749,56 +749,56 @@ void link_established(ppp_pcb *pcb) { * Tell higher-level protocols that LCP is up. */ if (!doing_multilink) { - for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (protp->protocol != PPP_LCP - && protp->lowerup != NULL) - (*protp->lowerup)(pcb); + for (i = 0; (protp = protocols[i]) != NULL; ++i) + if (protp->protocol != PPP_LCP + && protp->lowerup != NULL) + (*protp->lowerup)(pcb); } #if PPP_AUTH_SUPPORT #if PPP_SERVER #if PPP_ALLOWED_ADDRS if (!auth_required && noauth_addrs != NULL) - set_allowed_addrs(unit, NULL, NULL); + set_allowed_addrs(unit, NULL, NULL); #endif /* PPP_ALLOWED_ADDRS */ if (pcb->settings.auth_required && !(0 #if PAP_SUPPORT - || go->neg_upap + || go->neg_upap #endif /* PAP_SUPPORT */ #if CHAP_SUPPORT - || go->neg_chap + || go->neg_chap #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT - || go->neg_eap + || go->neg_eap #endif /* EAP_SUPPORT */ - )) { + )) { #if PPP_ALLOWED_ADDRS - /* - * We wanted the peer to authenticate itself, and it refused: - * if we have some address(es) it can use without auth, fine, - * otherwise treat it as though it authenticated with PAP using - * a username of "" and a password of "". If that's not OK, - * boot it out. - */ - if (noauth_addrs != NULL) { - set_allowed_addrs(unit, NULL, NULL); - } else + /* + * We wanted the peer to authenticate itself, and it refused: + * if we have some address(es) it can use without auth, fine, + * otherwise treat it as though it authenticated with PAP using + * a username of "" and a password of "". If that's not OK, + * boot it out. + */ + if (noauth_addrs != NULL) { + set_allowed_addrs(unit, NULL, NULL); + } else #endif /* PPP_ALLOWED_ADDRS */ - if (!pcb->settings.null_login + if (!pcb->settings.null_login #if PAP_SUPPORT - || !wo->neg_upap + || !wo->neg_upap #endif /* PAP_SUPPORT */ - ) { - ppp_warn("peer refused to authenticate: terminating link"); + ) { + ppp_warn("peer refused to authenticate: terminating link"); #if 0 /* UNUSED */ - status = EXIT_PEER_AUTH_FAILED; + status = EXIT_PEER_AUTH_FAILED; #endif /* UNUSED */ - pcb->err_code = PPPERR_AUTHFAIL; - lcp_close(pcb, "peer refused to authenticate"); - return; - } + pcb->err_code = PPPERR_AUTHFAIL; + lcp_close(pcb, "peer refused to authenticate"); + return; + } } #endif /* PPP_SERVER */ @@ -807,20 +807,20 @@ void link_established(ppp_pcb *pcb) { #if PPP_SERVER #if EAP_SUPPORT if (go->neg_eap) { - eap_authpeer(pcb, PPP_OUR_NAME); - auth |= EAP_PEER; + eap_authpeer(pcb, PPP_OUR_NAME); + auth |= EAP_PEER; } else #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT if (go->neg_chap) { - chap_auth_peer(pcb, PPP_OUR_NAME, CHAP_DIGEST(go->chap_mdtype)); - auth |= CHAP_PEER; + chap_auth_peer(pcb, PPP_OUR_NAME, CHAP_DIGEST(go->chap_mdtype)); + auth |= CHAP_PEER; } else #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT if (go->neg_upap) { - upap_authpeer(pcb); - auth |= PAP_PEER; + upap_authpeer(pcb); + auth |= PAP_PEER; } else #endif /* PAP_SUPPORT */ {} @@ -828,20 +828,20 @@ void link_established(ppp_pcb *pcb) { #if EAP_SUPPORT if (ho->neg_eap) { - eap_authwithpeer(pcb, pcb->settings.user); - auth |= EAP_WITHPEER; + eap_authwithpeer(pcb, pcb->settings.user); + auth |= EAP_WITHPEER; } else #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT if (ho->neg_chap) { - chap_auth_with_peer(pcb, pcb->settings.user, CHAP_DIGEST(ho->chap_mdtype)); - auth |= CHAP_WITHPEER; + chap_auth_with_peer(pcb, pcb->settings.user, CHAP_DIGEST(ho->chap_mdtype)); + auth |= CHAP_WITHPEER; } else #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT if (ho->neg_upap) { - upap_authwithpeer(pcb, pcb->settings.user, pcb->settings.passwd); - auth |= PAP_WITHPEER; + upap_authwithpeer(pcb, pcb->settings.user, pcb->settings.passwd); + auth |= PAP_WITHPEER; } else #endif /* PAP_SUPPORT */ {} @@ -851,7 +851,7 @@ void link_established(ppp_pcb *pcb) { if (!auth) #endif /* PPP_AUTH_SUPPORT */ - network_phase(pcb); + network_phase(pcb); } /* @@ -868,7 +868,7 @@ static void network_phase(ppp_pcb *pcb) { #if 0 /* UNUSED */ /* Log calling number. */ if (*remote_number) - ppp_notice("peer from calling number %q authorized", remote_number); + ppp_notice("peer from calling number %q authorized", remote_number); #endif /* UNUSED */ #if PPP_NOTIFY @@ -877,16 +877,16 @@ static void network_phase(ppp_pcb *pcb) { */ if (0 #if CHAP_SUPPORT - || go->neg_chap + || go->neg_chap #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - || go->neg_upap + || go->neg_upap #endif /* PAP_SUPPORT */ #if EAP_SUPPORT - || go->neg_eap + || go->neg_eap #endif /* EAP_SUPPORT */ - ) { - notify(auth_up_notifier, 0); + ) { + notify(auth_up_notifier, 0); } #endif /* PPP_NOTIFY */ @@ -895,9 +895,9 @@ static void network_phase(ppp_pcb *pcb) { * If we negotiated callback, do it now. */ if (go->neg_cbcp) { - new_phase(pcb, PPP_PHASE_CALLBACK); - (*cbcp_protent.open)(pcb); - return; + new_phase(pcb, PPP_PHASE_CALLBACK); + (*cbcp_protent.open)(pcb); + return; } #endif @@ -906,9 +906,9 @@ static void network_phase(ppp_pcb *pcb) { * Process extra options from the secrets file */ if (extra_options) { - options_from_list(extra_options, 1); - free_wordlist(extra_options); - extra_options = 0; + options_from_list(extra_options, 1); + free_wordlist(extra_options); + extra_options = 0; } #endif /* PPP_OPTIONS */ start_networks(pcb); @@ -924,34 +924,34 @@ void start_networks(ppp_pcb *pcb) { #ifdef HAVE_MULTILINK if (multilink) { - if (mp_join_bundle()) { - if (multilink_join_hook) - (*multilink_join_hook)(); - if (updetach && !nodetach) - detach(); - return; - } + if (mp_join_bundle()) { + if (multilink_join_hook) + (*multilink_join_hook)(); + if (updetach && !nodetach) + detach(); + return; + } } #endif /* HAVE_MULTILINK */ #ifdef PPP_FILTER if (!demand) - set_filters(&pass_filter, &active_filter); + set_filters(&pass_filter, &active_filter); #endif #if CCP_SUPPORT || ECP_SUPPORT /* Start CCP and ECP */ for (i = 0; (protp = protocols[i]) != NULL; ++i) - if ( - (0 + if ( + (0 #if ECP_SUPPORT - || protp->protocol == PPP_ECP + || protp->protocol == PPP_ECP #endif /* ECP_SUPPORT */ #if CCP_SUPPORT - || protp->protocol == PPP_CCP + || protp->protocol == PPP_CCP #endif /* CCP_SUPPORT */ - ) - && protp->open != NULL) - (*protp->open)(pcb); + ) + && protp->open != NULL) + (*protp->open)(pcb); #endif /* CCP_SUPPORT || ECP_SUPPORT */ /* @@ -965,7 +965,7 @@ void start_networks(ppp_pcb *pcb) { && !pcb->ccp_gotoptions.mppe #endif /* MPPE_SUPPORT */ ) - continue_networks(pcb); + continue_networks(pcb); } void continue_networks(ppp_pcb *pcb) { @@ -976,21 +976,21 @@ void continue_networks(ppp_pcb *pcb) { * Start the "real" network protocols. */ for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (protp->protocol < 0xC000 + if (protp->protocol < 0xC000 #if CCP_SUPPORT - && protp->protocol != PPP_CCP + && protp->protocol != PPP_CCP #endif /* CCP_SUPPORT */ #if ECP_SUPPORT - && protp->protocol != PPP_ECP + && protp->protocol != PPP_ECP #endif /* ECP_SUPPORT */ - && protp->open != NULL) { - (*protp->open)(pcb); - ++pcb->num_np_open; - } + && protp->open != NULL) { + (*protp->open)(pcb); + ++pcb->num_np_open; + } if (pcb->num_np_open == 0) - /* nothing to do */ - lcp_close(pcb, "No network protocols running"); + /* nothing to do */ + lcp_close(pcb, "No network protocols running"); } #if PPP_AUTH_SUPPORT @@ -1053,37 +1053,37 @@ void auth_peer_success(ppp_pcb *pcb, int protocol, int prot_flavor, const char * switch (protocol) { #if CHAP_SUPPORT case PPP_CHAP: - bit = CHAP_PEER; - switch (prot_flavor) { - case CHAP_MD5: - bit |= CHAP_MD5_PEER; - break; + bit = CHAP_PEER; + switch (prot_flavor) { + case CHAP_MD5: + bit |= CHAP_MD5_PEER; + break; #if MSCHAP_SUPPORT - case CHAP_MICROSOFT: - bit |= CHAP_MS_PEER; - break; - case CHAP_MICROSOFT_V2: - bit |= CHAP_MS2_PEER; - break; + case CHAP_MICROSOFT: + bit |= CHAP_MS_PEER; + break; + case CHAP_MICROSOFT_V2: + bit |= CHAP_MS2_PEER; + break; #endif /* MSCHAP_SUPPORT */ - default: - break; - } - break; + default: + break; + } + break; #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT case PPP_PAP: - bit = PAP_PEER; - break; + bit = PAP_PEER; + break; #endif /* PAP_SUPPORT */ #if EAP_SUPPORT case PPP_EAP: - bit = EAP_PEER; - break; + bit = EAP_PEER; + break; #endif /* EAP_SUPPORT */ default: - ppp_warn("auth_peer_success: unknown protocol %x", protocol); - return; + ppp_warn("auth_peer_success: unknown protocol %x", protocol); + return; } #ifdef HAVE_MULTILINK @@ -1091,7 +1091,7 @@ void auth_peer_success(ppp_pcb *pcb, int protocol, int prot_flavor, const char * * Save the authenticated name of the peer for later. */ if (namelen > (int)sizeof(pcb->peer_authname) - 1) - namelen = (int)sizeof(pcb->peer_authname) - 1; + namelen = (int)sizeof(pcb->peer_authname) - 1; MEMCPY(pcb->peer_authname, name, namelen); pcb->peer_authname[namelen] = 0; #endif /* HAVE_MULTILINK */ @@ -1140,41 +1140,41 @@ void auth_withpeer_success(ppp_pcb *pcb, int protocol, int prot_flavor) { switch (protocol) { #if CHAP_SUPPORT case PPP_CHAP: - bit = CHAP_WITHPEER; - prot = "CHAP"; - switch (prot_flavor) { - case CHAP_MD5: - bit |= CHAP_MD5_WITHPEER; - break; + bit = CHAP_WITHPEER; + prot = "CHAP"; + switch (prot_flavor) { + case CHAP_MD5: + bit |= CHAP_MD5_WITHPEER; + break; #if MSCHAP_SUPPORT - case CHAP_MICROSOFT: - bit |= CHAP_MS_WITHPEER; - break; - case CHAP_MICROSOFT_V2: - bit |= CHAP_MS2_WITHPEER; - break; + case CHAP_MICROSOFT: + bit |= CHAP_MS_WITHPEER; + break; + case CHAP_MICROSOFT_V2: + bit |= CHAP_MS2_WITHPEER; + break; #endif /* MSCHAP_SUPPORT */ - default: - break; - } - break; + default: + break; + } + break; #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT case PPP_PAP: - bit = PAP_WITHPEER; - prot = "PAP"; - break; + bit = PAP_WITHPEER; + prot = "PAP"; + break; #endif /* PAP_SUPPORT */ #if EAP_SUPPORT case PPP_EAP: - bit = EAP_WITHPEER; - prot = "EAP"; - break; + bit = EAP_WITHPEER; + prot = "EAP"; + break; #endif /* EAP_SUPPORT */ default: - ppp_warn("auth_withpeer_success: unknown protocol %x", protocol); - bit = 0; - /* no break */ + ppp_warn("auth_withpeer_success: unknown protocol %x", protocol); + bit = 0; + /* no break */ } ppp_notice("%s authentication succeeded", prot); @@ -1187,7 +1187,7 @@ void auth_withpeer_success(ppp_pcb *pcb, int protocol, int prot_flavor) { * proceed to the network (or callback) phase. */ if ((pcb->auth_pending &= ~bit) == 0) - network_phase(pcb); + network_phase(pcb); } #endif /* PPP_AUTH_SUPPORT */ @@ -1202,42 +1202,42 @@ void np_up(ppp_pcb *pcb, int proto) { LWIP_UNUSED_ARG(proto); if (pcb->num_np_up == 0) { - /* - * At this point we consider that the link has come up successfully. - */ - new_phase(pcb, PPP_PHASE_RUNNING); + /* + * At this point we consider that the link has come up successfully. + */ + new_phase(pcb, PPP_PHASE_RUNNING); #if PPP_IDLETIMELIMIT #if 0 /* UNUSED */ - if (idle_time_hook != 0) - tlim = (*idle_time_hook)(NULL); - else + if (idle_time_hook != 0) + tlim = (*idle_time_hook)(NULL); + else #endif /* UNUSED */ - tlim = pcb->settings.idle_time_limit; - if (tlim > 0) - TIMEOUT(check_idle, (void*)pcb, tlim); + tlim = pcb->settings.idle_time_limit; + if (tlim > 0) + TIMEOUT(check_idle, (void*)pcb, tlim); #endif /* PPP_IDLETIMELIMIT */ #if PPP_MAXCONNECT - /* - * Set a timeout to close the connection once the maximum - * connect time has expired. - */ - if (pcb->settings.maxconnect > 0) - TIMEOUT(connect_time_expired, (void*)pcb, pcb->settings.maxconnect); + /* + * Set a timeout to close the connection once the maximum + * connect time has expired. + */ + if (pcb->settings.maxconnect > 0) + TIMEOUT(connect_time_expired, (void*)pcb, pcb->settings.maxconnect); #endif /* PPP_MAXCONNECT */ #ifdef MAXOCTETS - if (maxoctets > 0) - TIMEOUT(check_maxoctets, NULL, maxoctets_timeout); + if (maxoctets > 0) + TIMEOUT(check_maxoctets, NULL, maxoctets_timeout); #endif #if 0 /* Unused */ - /* - * Detach now, if the updetach option was given. - */ - if (updetach && !nodetach) - detach(); + /* + * Detach now, if the updetach option was given. + */ + if (updetach && !nodetach) + detach(); #endif /* Unused */ } ++pcb->num_np_up; @@ -1250,15 +1250,15 @@ void np_down(ppp_pcb *pcb, int proto) { LWIP_UNUSED_ARG(proto); if (--pcb->num_np_up == 0) { #if PPP_IDLETIMELIMIT - UNTIMEOUT(check_idle, (void*)pcb); + UNTIMEOUT(check_idle, (void*)pcb); #endif /* PPP_IDLETIMELIMIT */ #if PPP_MAXCONNECT - UNTIMEOUT(connect_time_expired, NULL); + UNTIMEOUT(connect_time_expired, NULL); #endif /* PPP_MAXCONNECT */ #ifdef MAXOCTETS - UNTIMEOUT(check_maxoctets, NULL); + UNTIMEOUT(check_maxoctets, NULL); #endif - new_phase(pcb, PPP_PHASE_NETWORK); + new_phase(pcb, PPP_PHASE_NETWORK); } } @@ -1268,8 +1268,8 @@ void np_down(ppp_pcb *pcb, int proto) { void np_finished(ppp_pcb *pcb, int proto) { LWIP_UNUSED_ARG(proto); if (--pcb->num_np_open <= 0) { - /* no further use for the link: shut up shop. */ - lcp_close(pcb, "No network protocols running"); + /* no further use for the link: shut up shop. */ + lcp_close(pcb, "No network protocols running"); } } @@ -1285,26 +1285,26 @@ check_maxoctets(arg) link_stats_valid=0; switch(maxoctets_dir) { - case PPP_OCTETS_DIRECTION_IN: - used = link_stats.bytes_in; - break; - case PPP_OCTETS_DIRECTION_OUT: - used = link_stats.bytes_out; - break; - case PPP_OCTETS_DIRECTION_MAXOVERAL: - case PPP_OCTETS_DIRECTION_MAXSESSION: - used = (link_stats.bytes_in > link_stats.bytes_out) ? link_stats.bytes_in : link_stats.bytes_out; - break; - default: - used = link_stats.bytes_in+link_stats.bytes_out; - break; + case PPP_OCTETS_DIRECTION_IN: + used = link_stats.bytes_in; + break; + case PPP_OCTETS_DIRECTION_OUT: + used = link_stats.bytes_out; + break; + case PPP_OCTETS_DIRECTION_MAXOVERAL: + case PPP_OCTETS_DIRECTION_MAXSESSION: + used = (link_stats.bytes_in > link_stats.bytes_out) ? link_stats.bytes_in : link_stats.bytes_out; + break; + default: + used = link_stats.bytes_in+link_stats.bytes_out; + break; } if (used > maxoctets) { - ppp_notice("Traffic limit reached. Limit: %u Used: %u", maxoctets, used); - status = EXIT_TRAFFIC_LIMIT; - lcp_close(pcb, "Traffic limit"); + ppp_notice("Traffic limit reached. Limit: %u Used: %u", maxoctets, used); + status = EXIT_TRAFFIC_LIMIT; + lcp_close(pcb, "Traffic limit"); #if 0 /* UNUSED */ - need_holdoff = 0; + need_holdoff = 0; #endif /* UNUSED */ } else { TIMEOUT(check_maxoctets, NULL, maxoctets_timeout); @@ -1325,27 +1325,27 @@ static void check_idle(void *arg) { int tlim; if (!get_idle_time(pcb, &idle)) - return; + return; #if 0 /* UNUSED */ if (idle_time_hook != 0) { - tlim = idle_time_hook(&idle); + tlim = idle_time_hook(&idle); } else { #endif /* UNUSED */ - itime = LWIP_MIN(idle.xmit_idle, idle.recv_idle); - tlim = pcb->settings.idle_time_limit - itime; + itime = LWIP_MIN(idle.xmit_idle, idle.recv_idle); + tlim = pcb->settings.idle_time_limit - itime; #if 0 /* UNUSED */ } #endif /* UNUSED */ if (tlim <= 0) { - /* link is idle: shut it down. */ - ppp_notice("Terminating connection due to lack of activity."); - pcb->err_code = PPPERR_IDLETIMEOUT; - lcp_close(pcb, "Link inactive"); + /* link is idle: shut it down. */ + ppp_notice("Terminating connection due to lack of activity."); + pcb->err_code = PPPERR_IDLETIMEOUT; + lcp_close(pcb, "Link inactive"); #if 0 /* UNUSED */ - need_holdoff = 0; + need_holdoff = 0; #endif /* UNUSED */ } else { - TIMEOUT(check_idle, (void*)pcb, tlim); + TIMEOUT(check_idle, (void*)pcb, tlim); } } #endif /* PPP_IDLETIMELIMIT */ @@ -1358,7 +1358,7 @@ static void connect_time_expired(void *arg) { ppp_pcb *pcb = (ppp_pcb*)arg; ppp_info("Connect time expired"); pcb->err_code = PPPERR_CONNECTTIME; - lcp_close(pcb, "Connect time expired"); /* Close connection */ + lcp_close(pcb, "Connect time expired"); /* Close connection */ } #endif /* PPP_MAXCONNECT */ @@ -1375,62 +1375,62 @@ auth_check_options() /* Default our_name to hostname, and user to our_name */ if (our_name[0] == 0 || usehostname) - strlcpy(our_name, hostname, sizeof(our_name)); + strlcpy(our_name, hostname, sizeof(our_name)); /* If a blank username was explicitly given as an option, trust the user and don't use our_name */ if (ppp_settings.user[0] == 0 && !explicit_user) - strlcpy(ppp_settings.user, our_name, sizeof(ppp_settings.user)); + strlcpy(ppp_settings.user, our_name, sizeof(ppp_settings.user)); /* * If we have a default route, require the peer to authenticate * unless the noauth option was given or the real user is root. */ if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) { - auth_required = 1; - default_auth = 1; + auth_required = 1; + default_auth = 1; } #if CHAP_SUPPORT /* If we selected any CHAP flavors, we should probably negotiate it. :-) */ if (wo->chap_mdtype) - wo->neg_chap = 1; + wo->neg_chap = 1; #endif /* CHAP_SUPPORT */ /* If authentication is required, ask peer for CHAP, PAP, or EAP. */ if (auth_required) { - allow_any_ip = 0; - if (1 + allow_any_ip = 0; + if (1 #if CHAP_SUPPORT - && !wo->neg_chap + && !wo->neg_chap #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - && !wo->neg_upap + && !wo->neg_upap #endif /* PAP_SUPPORT */ #if EAP_SUPPORT - && !wo->neg_eap + && !wo->neg_eap #endif /* EAP_SUPPORT */ - ) { + ) { #if CHAP_SUPPORT - wo->neg_chap = CHAP_MDTYPE_SUPPORTED != MDTYPE_NONE; - wo->chap_mdtype = CHAP_MDTYPE_SUPPORTED; + wo->neg_chap = CHAP_MDTYPE_SUPPORTED != MDTYPE_NONE; + wo->chap_mdtype = CHAP_MDTYPE_SUPPORTED; #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - wo->neg_upap = 1; + wo->neg_upap = 1; #endif /* PAP_SUPPORT */ #if EAP_SUPPORT - wo->neg_eap = 1; + wo->neg_eap = 1; #endif /* EAP_SUPPORT */ - } + } } else { #if CHAP_SUPPORT - wo->neg_chap = 0; - wo->chap_mdtype = MDTYPE_NONE; + wo->neg_chap = 0; + wo->chap_mdtype = MDTYPE_NONE; #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - wo->neg_upap = 0; + wo->neg_upap = 0; #endif /* PAP_SUPPORT */ #if EAP_SUPPORT - wo->neg_eap = 0; + wo->neg_eap = 0; #endif /* EAP_SUPPORT */ } @@ -1447,56 +1447,56 @@ auth_check_options() #endif /* PAP_SUPPORT */ if (!can_auth && (0 #if CHAP_SUPPORT - || wo->neg_chap + || wo->neg_chap #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT - || wo->neg_eap + || wo->neg_eap #endif /* EAP_SUPPORT */ - )) { + )) { #if CHAP_SUPPORT - can_auth = have_chap_secret((explicit_remote? remote_name: NULL), - our_name, 1, &lacks_ip); + can_auth = have_chap_secret((explicit_remote? remote_name: NULL), + our_name, 1, &lacks_ip); #else - can_auth = 0; + can_auth = 0; #endif } if (!can_auth #if EAP_SUPPORT - && wo->neg_eap + && wo->neg_eap #endif /* EAP_SUPPORT */ - ) { - can_auth = have_srp_secret((explicit_remote? remote_name: NULL), - our_name, 1, &lacks_ip); + ) { + can_auth = have_srp_secret((explicit_remote? remote_name: NULL), + our_name, 1, &lacks_ip); } if (auth_required && !can_auth && noauth_addrs == NULL) { - if (default_auth) { - option_error( + if (default_auth) { + option_error( "By default the remote system is required to authenticate itself"); - option_error( + option_error( "(because this system has a default route to the internet)"); - } else if (explicit_remote) - option_error( + } else if (explicit_remote) + option_error( "The remote system (%s) is required to authenticate itself", - remote_name); - else - option_error( + remote_name); + else + option_error( "The remote system is required to authenticate itself"); - option_error( + option_error( "but I couldn't find any suitable secret (password) for it to use to do so."); - if (lacks_ip) - option_error( + if (lacks_ip) + option_error( "(None of the available passwords would let it use an IP address.)"); - exit(1); + exit(1); } /* * Early check for remote number authorization. */ if (!auth_number()) { - ppp_warn("calling number %q is not authorized", remote_number); - exit(EXIT_CNID_AUTH_FAILED); + ppp_warn("calling number %q is not authorized", remote_number); + exit(EXIT_CNID_AUTH_FAILED); } } #endif /* PPP_OPTIONS */ @@ -1518,30 +1518,30 @@ auth_reset(unit) hadchap = -1; ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL)); ao->neg_chap = (!refuse_chap || !refuse_mschap || !refuse_mschap_v2) - && (passwd[0] != 0 || - (hadchap = have_chap_secret(user, (explicit_remote? remote_name: - NULL), 0, NULL))); + && (passwd[0] != 0 || + (hadchap = have_chap_secret(user, (explicit_remote? remote_name: + NULL), 0, NULL))); ao->neg_eap = !refuse_eap && ( - passwd[0] != 0 || - (hadchap == 1 || (hadchap == -1 && have_chap_secret(user, - (explicit_remote? remote_name: NULL), 0, NULL))) || - have_srp_secret(user, (explicit_remote? remote_name: NULL), 0, NULL)); + passwd[0] != 0 || + (hadchap == 1 || (hadchap == -1 && have_chap_secret(user, + (explicit_remote? remote_name: NULL), 0, NULL))) || + have_srp_secret(user, (explicit_remote? remote_name: NULL), 0, NULL)); hadchap = -1; if (go->neg_upap && !uselogin && !have_pap_secret(NULL)) - go->neg_upap = 0; + go->neg_upap = 0; if (go->neg_chap) { - if (!(hadchap = have_chap_secret((explicit_remote? remote_name: NULL), - our_name, 1, NULL))) - go->neg_chap = 0; + if (!(hadchap = have_chap_secret((explicit_remote? remote_name: NULL), + our_name, 1, NULL))) + go->neg_chap = 0; } if (go->neg_eap && - (hadchap == 0 || (hadchap == -1 && - !have_chap_secret((explicit_remote? remote_name: NULL), our_name, - 1, NULL))) && - !have_srp_secret((explicit_remote? remote_name: NULL), our_name, 1, - NULL)) - go->neg_eap = 0; + (hadchap == 0 || (hadchap == -1 && + !have_chap_secret((explicit_remote? remote_name: NULL), our_name, + 1, NULL))) && + !have_srp_secret((explicit_remote? remote_name: NULL), our_name, 1, + NULL)) + go->neg_eap = 0; } /* @@ -1550,8 +1550,8 @@ auth_reset(unit) * and login the user if OK. * * returns: - * UPAP_AUTHNAK: Authentication failed. - * UPAP_AUTHACK: Authentication succeeded. + * UPAP_AUTHNAK: Authentication failed. + * UPAP_AUTHACK: Authentication succeeded. * In either case, msg points to an appropriate message. */ int @@ -1585,19 +1585,19 @@ check_passwd(unit, auser, userlen, apasswd, passwdlen, msg) * Check if a plugin wants to handle this. */ if (pap_auth_hook) { - ret = (*pap_auth_hook)(ppp_settings.user, ppp_settings.passwd, msg, &addrs, &opts); - if (ret >= 0) { - /* note: set_allowed_addrs() saves opts (but not addrs): - don't free it! */ - if (ret) - set_allowed_addrs(unit, addrs, opts); - else if (opts != 0) - free_wordlist(opts); - if (addrs != 0) - free_wordlist(addrs); - BZERO(ppp_settings.passwd, sizeof(ppp_settings.passwd)); - return ret? UPAP_AUTHACK: UPAP_AUTHNAK; - } + ret = (*pap_auth_hook)(ppp_settings.user, ppp_settings.passwd, msg, &addrs, &opts); + if (ret >= 0) { + /* note: set_allowed_addrs() saves opts (but not addrs): + don't free it! */ + if (ret) + set_allowed_addrs(unit, addrs, opts); + else if (opts != 0) + free_wordlist(opts); + if (addrs != 0) + free_wordlist(addrs); + BZERO(ppp_settings.passwd, sizeof(ppp_settings.passwd)); + return ret? UPAP_AUTHACK: UPAP_AUTHNAK; + } } /* @@ -1609,67 +1609,67 @@ check_passwd(unit, auser, userlen, apasswd, passwdlen, msg) ret = UPAP_AUTHNAK; f = fopen(filename, "r"); if (f == NULL) { - ppp_error("Can't open PAP password file %s: %m", filename); + ppp_error("Can't open PAP password file %s: %m", filename); } else { - check_access(f, filename); - if (scan_authfile(f, ppp_settings.user, our_name, secret, &addrs, &opts, filename, 0) < 0) { - ppp_warn("no PAP secret found for %s", user); - } else { - /* - * If the secret is "@login", it means to check - * the password against the login database. - */ - int login_secret = strcmp(secret, "@login") == 0; - ret = UPAP_AUTHACK; - if (uselogin || login_secret) { - /* login option or secret is @login */ - if (session_full(ppp_settings.user, ppp_settings.passwd, devnam, msg) == 0) { - ret = UPAP_AUTHNAK; - } - } else if (session_mgmt) { - if (session_check(ppp_settings.user, NULL, devnam, NULL) == 0) { - ppp_warn("Peer %q failed PAP Session verification", user); - ret = UPAP_AUTHNAK; - } - } - if (secret[0] != 0 && !login_secret) { - /* password given in pap-secrets - must match */ - if ((cryptpap || strcmp(ppp_settings.passwd, secret) != 0) - && strcmp(crypt(ppp_settings.passwd, secret), secret) != 0) - ret = UPAP_AUTHNAK; - } - } - fclose(f); + check_access(f, filename); + if (scan_authfile(f, ppp_settings.user, our_name, secret, &addrs, &opts, filename, 0) < 0) { + ppp_warn("no PAP secret found for %s", user); + } else { + /* + * If the secret is "@login", it means to check + * the password against the login database. + */ + int login_secret = strcmp(secret, "@login") == 0; + ret = UPAP_AUTHACK; + if (uselogin || login_secret) { + /* login option or secret is @login */ + if (session_full(ppp_settings.user, ppp_settings.passwd, devnam, msg) == 0) { + ret = UPAP_AUTHNAK; + } + } else if (session_mgmt) { + if (session_check(ppp_settings.user, NULL, devnam, NULL) == 0) { + ppp_warn("Peer %q failed PAP Session verification", user); + ret = UPAP_AUTHNAK; + } + } + if (secret[0] != 0 && !login_secret) { + /* password given in pap-secrets - must match */ + if ((cryptpap || strcmp(ppp_settings.passwd, secret) != 0) + && strcmp(crypt(ppp_settings.passwd, secret), secret) != 0) + ret = UPAP_AUTHNAK; + } + } + fclose(f); } if (ret == UPAP_AUTHNAK) { if (**msg == 0) - *msg = "Login incorrect"; - /* - * XXX can we ever get here more than once?? - * Frustrate passwd stealer programs. - * Allow 10 tries, but start backing off after 3 (stolen from login). - * On 10'th, drop the connection. - */ - if (attempts++ >= 10) { - ppp_warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user); - lcp_close(pcb, "login failed"); - } - if (attempts > 3) - sleep((u_int) (attempts - 3) * 5); - if (opts != NULL) - free_wordlist(opts); + *msg = "Login incorrect"; + /* + * XXX can we ever get here more than once?? + * Frustrate passwd stealer programs. + * Allow 10 tries, but start backing off after 3 (stolen from login). + * On 10'th, drop the connection. + */ + if (attempts++ >= 10) { + ppp_warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user); + lcp_close(pcb, "login failed"); + } + if (attempts > 3) + sleep((u_int) (attempts - 3) * 5); + if (opts != NULL) + free_wordlist(opts); } else { - attempts = 0; /* Reset count */ - if (**msg == 0) - *msg = "Login ok"; - set_allowed_addrs(unit, addrs, opts); + attempts = 0; /* Reset count */ + if (**msg == 0) + *msg = "Login ok"; + set_allowed_addrs(unit, addrs, opts); } if (addrs != NULL) - free_wordlist(addrs); + free_wordlist(addrs); BZERO(ppp_settings.passwd, sizeof(ppp_settings.passwd)); BZERO(secret, sizeof(secret)); @@ -1696,31 +1696,31 @@ null_login(unit) */ ret = -1; if (null_auth_hook) - ret = (*null_auth_hook)(&addrs, &opts); + ret = (*null_auth_hook)(&addrs, &opts); /* * Open the file of pap secrets and scan for a suitable secret. */ if (ret <= 0) { - filename = _PATH_UPAPFILE; - addrs = NULL; - f = fopen(filename, "r"); - if (f == NULL) - return 0; - check_access(f, filename); + filename = _PATH_UPAPFILE; + addrs = NULL; + f = fopen(filename, "r"); + if (f == NULL) + return 0; + check_access(f, filename); - i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename, 0); - ret = i >= 0 && secret[0] == 0; - BZERO(secret, sizeof(secret)); - fclose(f); + i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename, 0); + ret = i >= 0 && secret[0] == 0; + BZERO(secret, sizeof(secret)); + fclose(f); } if (ret) - set_allowed_addrs(unit, addrs, opts); + set_allowed_addrs(unit, addrs, opts); else if (opts != 0) - free_wordlist(opts); + free_wordlist(opts); if (addrs != 0) - free_wordlist(addrs); + free_wordlist(addrs); return ret; } @@ -1744,24 +1744,24 @@ get_pap_passwd(passwd) * Check whether a plugin wants to supply this. */ if (pap_passwd_hook) { - ret = (*pap_passwd_hook)(ppp_settings,user, ppp_settings.passwd); - if (ret >= 0) - return ret; + ret = (*pap_passwd_hook)(ppp_settings,user, ppp_settings.passwd); + if (ret >= 0) + return ret; } filename = _PATH_UPAPFILE; f = fopen(filename, "r"); if (f == NULL) - return 0; + return 0; check_access(f, filename); ret = scan_authfile(f, user, - (remote_name[0]? remote_name: NULL), - secret, NULL, NULL, filename, 0); + (remote_name[0]? remote_name: NULL), + secret, NULL, NULL, filename, 0); fclose(f); if (ret < 0) - return 0; + return 0; if (passwd != NULL) - strlcpy(passwd, secret, MAXSECRETLEN); + strlcpy(passwd, secret, MAXSECRETLEN); BZERO(secret, sizeof(secret)); return 1; } @@ -1781,26 +1781,26 @@ have_pap_secret(lacks_ipp) /* let the plugin decide, if there is one */ if (pap_check_hook) { - ret = (*pap_check_hook)(); - if (ret >= 0) - return ret; + ret = (*pap_check_hook)(); + if (ret >= 0) + return ret; } filename = _PATH_UPAPFILE; f = fopen(filename, "r"); if (f == NULL) - return 0; + return 0; ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name, - NULL, &addrs, NULL, filename, 0); + NULL, &addrs, NULL, filename, 0); fclose(f); if (ret >= 0 && !some_ip_ok(addrs)) { - if (lacks_ipp != 0) - *lacks_ipp = 1; - ret = -1; + if (lacks_ipp != 0) + *lacks_ipp = 1; + ret = -1; } if (addrs != 0) - free_wordlist(addrs); + free_wordlist(addrs); return ret >= 0; } @@ -1824,31 +1824,31 @@ have_chap_secret(client, server, need_ip, lacks_ipp) struct wordlist *addrs; if (chap_check_hook) { - ret = (*chap_check_hook)(); - if (ret >= 0) { - return ret; - } + ret = (*chap_check_hook)(); + if (ret >= 0) { + return ret; + } } filename = _PATH_CHAPFILE; f = fopen(filename, "r"); if (f == NULL) - return 0; + return 0; if (client != NULL && client[0] == 0) - client = NULL; + client = NULL; else if (server != NULL && server[0] == 0) - server = NULL; + server = NULL; ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename, 0); fclose(f); if (ret >= 0 && need_ip && !some_ip_ok(addrs)) { - if (lacks_ipp != 0) - *lacks_ipp = 1; - ret = -1; + if (lacks_ipp != 0) + *lacks_ipp = 1; + ret = -1; } if (addrs != 0) - free_wordlist(addrs); + free_wordlist(addrs); return ret >= 0; } @@ -1874,22 +1874,22 @@ have_srp_secret(client, server, need_ip, lacks_ipp) filename = _PATH_SRPFILE; f = fopen(filename, "r"); if (f == NULL) - return 0; + return 0; if (client != NULL && client[0] == 0) - client = NULL; + client = NULL; else if (server != NULL && server[0] == 0) - server = NULL; + server = NULL; ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename, 0); fclose(f); if (ret >= 0 && need_ip && !some_ip_ok(addrs)) { - if (lacks_ipp != 0) - *lacks_ipp = 1; - ret = -1; + if (lacks_ipp != 0) + *lacks_ipp = 1; + ret = -1; } if (addrs != 0) - free_wordlist(addrs); + free_wordlist(addrs); return ret >= 0; } @@ -1930,42 +1930,42 @@ int get_secret(ppp_pcb *pcb, const char *client, const char *server, char *secre addrs = NULL; if (!am_server && ppp_settings.passwd[0] != 0) { - strlcpy(secbuf, ppp_settings.passwd, sizeof(secbuf)); + strlcpy(secbuf, ppp_settings.passwd, sizeof(secbuf)); } else if (!am_server && chap_passwd_hook) { - if ( (*chap_passwd_hook)(client, secbuf) < 0) { - ppp_error("Unable to obtain CHAP password for %s on %s from plugin", - client, server); - return 0; - } + if ( (*chap_passwd_hook)(client, secbuf) < 0) { + ppp_error("Unable to obtain CHAP password for %s on %s from plugin", + client, server); + return 0; + } } else { - filename = _PATH_CHAPFILE; - addrs = NULL; - secbuf[0] = 0; + filename = _PATH_CHAPFILE; + addrs = NULL; + secbuf[0] = 0; - f = fopen(filename, "r"); - if (f == NULL) { - ppp_error("Can't open chap secret file %s: %m", filename); - return 0; - } - check_access(f, filename); + f = fopen(filename, "r"); + if (f == NULL) { + ppp_error("Can't open chap secret file %s: %m", filename); + return 0; + } + check_access(f, filename); - ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename, 0); - fclose(f); - if (ret < 0) - return 0; + ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename, 0); + fclose(f); + if (ret < 0) + return 0; - if (am_server) - set_allowed_addrs(unit, addrs, opts); - else if (opts != 0) - free_wordlist(opts); - if (addrs != 0) - free_wordlist(addrs); + if (am_server) + set_allowed_addrs(unit, addrs, opts); + else if (opts != 0) + free_wordlist(opts); + if (addrs != 0) + free_wordlist(addrs); } len = strlen(secbuf); if (len > MAXSECRETLEN) { - ppp_error("Secret for %s on %s is too long", client, server); - len = MAXSECRETLEN; + ppp_error("Secret for %s on %s is too long", client, server); + len = MAXSECRETLEN; } MEMCPY(secret, secbuf, len); BZERO(secbuf, sizeof(secbuf)); @@ -1997,31 +1997,31 @@ get_srp_secret(unit, client, server, secret, am_server) struct wordlist *addrs, *opts; if (!am_server && ppp_settings.passwd[0] != '\0') { - strlcpy(secret, ppp_settings.passwd, MAXWORDLEN); + strlcpy(secret, ppp_settings.passwd, MAXWORDLEN); } else { - filename = _PATH_SRPFILE; - addrs = NULL; + filename = _PATH_SRPFILE; + addrs = NULL; - fp = fopen(filename, "r"); - if (fp == NULL) { - ppp_error("Can't open srp secret file %s: %m", filename); - return 0; - } - check_access(fp, filename); + fp = fopen(filename, "r"); + if (fp == NULL) { + ppp_error("Can't open srp secret file %s: %m", filename); + return 0; + } + check_access(fp, filename); - secret[0] = '\0'; - ret = scan_authfile(fp, client, server, secret, &addrs, &opts, - filename, am_server); - fclose(fp); - if (ret < 0) - return 0; + secret[0] = '\0'; + ret = scan_authfile(fp, client, server, secret, &addrs, &opts, + filename, am_server); + fclose(fp); + if (ret < 0) + return 0; - if (am_server) - set_allowed_addrs(unit, addrs, opts); - else if (opts != NULL) - free_wordlist(opts); - if (addrs != NULL) - free_wordlist(addrs); + if (am_server) + set_allowed_addrs(unit, addrs, opts); + else if (opts != NULL) + free_wordlist(opts); + if (addrs != NULL) + free_wordlist(addrs); } return 1; @@ -2049,10 +2049,10 @@ set_allowed_addrs(unit, addrs, opts) u32_t suggested_ip = 0; if (addresses[unit] != NULL) - free(addresses[unit]); + free(addresses[unit]); addresses[unit] = NULL; if (extra_options != NULL) - free_wordlist(extra_options); + free_wordlist(extra_options); extra_options = opts; /* @@ -2060,109 +2060,109 @@ set_allowed_addrs(unit, addrs, opts) */ n = wordlist_count(addrs) + wordlist_count(noauth_addrs); if (n == 0) - return; + return; ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip)); if (ip == 0) - return; + return; /* temporarily append the noauth_addrs list to addrs */ for (plink = &addrs; *plink != NULL; plink = &(*plink)->next) - ; + ; *plink = noauth_addrs; n = 0; for (ap = addrs; ap != NULL; ap = ap->next) { - /* "-" means no addresses authorized, "*" means any address allowed */ - ptr_word = ap->word; - if (strcmp(ptr_word, "-") == 0) - break; - if (strcmp(ptr_word, "*") == 0) { - ip[n].permit = 1; - ip[n].base = ip[n].mask = 0; - ++n; - break; - } + /* "-" means no addresses authorized, "*" means any address allowed */ + ptr_word = ap->word; + if (strcmp(ptr_word, "-") == 0) + break; + if (strcmp(ptr_word, "*") == 0) { + ip[n].permit = 1; + ip[n].base = ip[n].mask = 0; + ++n; + break; + } - ip[n].permit = 1; - if (*ptr_word == '!') { - ip[n].permit = 0; - ++ptr_word; - } + ip[n].permit = 1; + if (*ptr_word == '!') { + ip[n].permit = 0; + ++ptr_word; + } - mask = ~ (u32_t) 0; - offset = 0; - ptr_mask = strchr (ptr_word, '/'); - if (ptr_mask != NULL) { - int bit_count; - char *endp; + mask = ~ (u32_t) 0; + offset = 0; + ptr_mask = strchr (ptr_word, '/'); + if (ptr_mask != NULL) { + int bit_count; + char *endp; - bit_count = (int) strtol (ptr_mask+1, &endp, 10); - if (bit_count <= 0 || bit_count > 32) { - ppp_warn("invalid address length %v in auth. address list", - ptr_mask+1); - continue; - } - bit_count = 32 - bit_count; /* # bits in host part */ - if (*endp == '+') { - offset = ifunit + 1; - ++endp; - } - if (*endp != 0) { - ppp_warn("invalid address length syntax: %v", ptr_mask+1); - continue; - } - *ptr_mask = '\0'; - mask <<= bit_count; - } + bit_count = (int) strtol (ptr_mask+1, &endp, 10); + if (bit_count <= 0 || bit_count > 32) { + ppp_warn("invalid address length %v in auth. address list", + ptr_mask+1); + continue; + } + bit_count = 32 - bit_count; /* # bits in host part */ + if (*endp == '+') { + offset = ifunit + 1; + ++endp; + } + if (*endp != 0) { + ppp_warn("invalid address length syntax: %v", ptr_mask+1); + continue; + } + *ptr_mask = '\0'; + mask <<= bit_count; + } - hp = gethostbyname(ptr_word); - if (hp != NULL && hp->h_addrtype == AF_INET) { - a = *(u32_t *)hp->h_addr; - } else { - np = getnetbyname (ptr_word); - if (np != NULL && np->n_addrtype == AF_INET) { - a = lwip_htonl ((u32_t)np->n_net); - if (ptr_mask == NULL) { - /* calculate appropriate mask for net */ - ah = lwip_ntohl(a); - if (IN_CLASSA(ah)) - mask = IN_CLASSA_NET; - else if (IN_CLASSB(ah)) - mask = IN_CLASSB_NET; - else if (IN_CLASSC(ah)) - mask = IN_CLASSC_NET; - } - } else { - a = inet_addr (ptr_word); - } - } + hp = gethostbyname(ptr_word); + if (hp != NULL && hp->h_addrtype == AF_INET) { + a = *(u32_t *)hp->h_addr; + } else { + np = getnetbyname (ptr_word); + if (np != NULL && np->n_addrtype == AF_INET) { + a = lwip_htonl ((u32_t)np->n_net); + if (ptr_mask == NULL) { + /* calculate appropriate mask for net */ + ah = lwip_ntohl(a); + if (IN_CLASSA(ah)) + mask = IN_CLASSA_NET; + else if (IN_CLASSB(ah)) + mask = IN_CLASSB_NET; + else if (IN_CLASSC(ah)) + mask = IN_CLASSC_NET; + } + } else { + a = inet_addr (ptr_word); + } + } - if (ptr_mask != NULL) - *ptr_mask = '/'; + if (ptr_mask != NULL) + *ptr_mask = '/'; - if (a == (u32_t)-1L) { - ppp_warn("unknown host %s in auth. address list", ap->word); - continue; - } - if (offset != 0) { - if (offset >= ~mask) { - ppp_warn("interface unit %d too large for subnet %v", - ifunit, ptr_word); - continue; - } - a = lwip_htonl((lwip_ntohl(a) & mask) + offset); - mask = ~(u32_t)0; - } - ip[n].mask = lwip_htonl(mask); - ip[n].base = a & ip[n].mask; - ++n; - if (~mask == 0 && suggested_ip == 0) - suggested_ip = a; + if (a == (u32_t)-1L) { + ppp_warn("unknown host %s in auth. address list", ap->word); + continue; + } + if (offset != 0) { + if (offset >= ~mask) { + ppp_warn("interface unit %d too large for subnet %v", + ifunit, ptr_word); + continue; + } + a = lwip_htonl((lwip_ntohl(a) & mask) + offset); + mask = ~(u32_t)0; + } + ip[n].mask = lwip_htonl(mask); + ip[n].base = a & ip[n].mask; + ++n; + if (~mask == 0 && suggested_ip == 0) + suggested_ip = a; } *plink = NULL; - ip[n].permit = 0; /* make the last entry forbid all addresses */ - ip[n].base = 0; /* to terminate the list */ + ip[n].permit = 0; /* make the last entry forbid all addresses */ + ip[n].base = 0; /* to terminate the list */ ip[n].mask = 0; addresses[unit] = ip; @@ -2173,14 +2173,14 @@ set_allowed_addrs(unit, addrs, opts) * which is a single host, then use that if we find one. */ if (suggested_ip != 0 - && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr))) { - wo->hisaddr = suggested_ip; - /* - * Do we insist on this address? No, if there are other - * addresses authorized than the suggested one. - */ - if (n > 1) - wo->accept_remote = 1; + && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr))) { + wo->hisaddr = suggested_ip; + /* + * Do we insist on this address? No, if there are other + * addresses authorized than the suggested one. + */ + if (n > 1) + wo->accept_remote = 1; } } @@ -2197,21 +2197,21 @@ auth_ip_addr(unit, addr) /* don't allow loopback or multicast address */ if (bad_ip_adrs(addr)) - return 0; + return 0; if (allowed_address_hook) { - ok = allowed_address_hook(addr); - if (ok >= 0) return ok; + ok = allowed_address_hook(addr); + if (ok >= 0) return ok; } if (addresses[unit] != NULL) { - ok = ip_addr_check(addr, addresses[unit]); - if (ok >= 0) - return ok; + ok = ip_addr_check(addr, addresses[unit]); + if (ok >= 0) + return ok; } if (auth_required) - return 0; /* no addresses authorized */ + return 0; /* no addresses authorized */ return allow_any_ip || privileged || !have_route_to(addr); } @@ -2221,8 +2221,8 @@ ip_addr_check(addr, addrs) struct permitted_ip *addrs; { for (; ; ++addrs) - if ((addr & addrs->mask) == addrs->base) - return addrs->permit; + if ((addr & addrs->mask) == addrs->base) + return addrs->permit; } /* @@ -2236,7 +2236,7 @@ bad_ip_adrs(addr) { addr = lwip_ntohl(addr); return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET - || IN_MULTICAST(addr) || IN_BADCLASS(addr); + || IN_MULTICAST(addr) || IN_BADCLASS(addr); } /* @@ -2248,10 +2248,10 @@ some_ip_ok(addrs) struct wordlist *addrs; { for (; addrs != 0; addrs = addrs->next) { - if (addrs->word[0] == '-') - break; - if (addrs->word[0] != '!') - return 1; /* some IP address is allowed */ + if (addrs->word[0] == '-') + break; + if (addrs->word[0] != '!') + return 1; /* some IP address is allowed */ } return 0; } @@ -2268,17 +2268,17 @@ auth_number() /* Allow all if no authorization list. */ if (!wp) - return 1; + return 1; /* Allow if we have a match in the authorization list. */ while (wp) { - /* trailing '*' wildcard */ - l = strlen(wp->word); - if ((wp->word)[l - 1] == '*') - l--; - if (!strncasecmp(wp->word, remote_number, l)) - return 1; - wp = wp->next; + /* trailing '*' wildcard */ + l = strlen(wp->word); + if ((wp->word)[l - 1] == '*') + l--; + if (!strncasecmp(wp->word, remote_number, l)) + return 1; + wp = wp->next; } return 0; @@ -2295,10 +2295,10 @@ check_access(f, filename) struct stat sbuf; if (fstat(fileno(f), &sbuf) < 0) { - ppp_warn("cannot stat secret file %s: %m", filename); + ppp_warn("cannot stat secret file %s: %m", filename); } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) { - ppp_warn("Warning - secret file %s has world and/or group access", - filename); + ppp_warn("Warning - secret file %s has world and/or group access", + filename); } } @@ -2337,141 +2337,141 @@ scan_authfile(f, client, server, secret, addrs, opts, filename, flags) char *cp; if (addrs != NULL) - *addrs = NULL; + *addrs = NULL; if (opts != NULL) - *opts = NULL; + *opts = NULL; addr_list = NULL; if (!getword(f, word, &newline, filename)) - return -1; /* file is empty??? */ + return -1; /* file is empty??? */ newline = 1; best_flag = -1; for (;;) { - /* - * Skip until we find a word at the start of a line. - */ - while (!newline && getword(f, word, &newline, filename)) - ; - if (!newline) - break; /* got to end of file */ + /* + * Skip until we find a word at the start of a line. + */ + while (!newline && getword(f, word, &newline, filename)) + ; + if (!newline) + break; /* got to end of file */ - /* - * Got a client - check if it's a match or a wildcard. - */ - got_flag = 0; - if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) { - newline = 0; - continue; - } - if (!ISWILD(word)) - got_flag = NONWILD_CLIENT; + /* + * Got a client - check if it's a match or a wildcard. + */ + got_flag = 0; + if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) { + newline = 0; + continue; + } + if (!ISWILD(word)) + got_flag = NONWILD_CLIENT; - /* - * Now get a server and check if it matches. - */ - if (!getword(f, word, &newline, filename)) - break; - if (newline) - continue; - if (!ISWILD(word)) { - if (server != NULL && strcmp(word, server) != 0) - continue; - got_flag |= NONWILD_SERVER; - } + /* + * Now get a server and check if it matches. + */ + if (!getword(f, word, &newline, filename)) + break; + if (newline) + continue; + if (!ISWILD(word)) { + if (server != NULL && strcmp(word, server) != 0) + continue; + got_flag |= NONWILD_SERVER; + } - /* - * Got some sort of a match - see if it's better than what - * we have already. - */ - if (got_flag <= best_flag) - continue; + /* + * Got some sort of a match - see if it's better than what + * we have already. + */ + if (got_flag <= best_flag) + continue; - /* - * Get the secret. - */ - if (!getword(f, word, &newline, filename)) - break; - if (newline) - continue; + /* + * Get the secret. + */ + if (!getword(f, word, &newline, filename)) + break; + if (newline) + continue; - /* - * SRP-SHA1 authenticator should never be reading secrets from - * a file. (Authenticatee may, though.) - */ - if (flags && ((cp = strchr(word, ':')) == NULL || - strchr(cp + 1, ':') == NULL)) - continue; + /* + * SRP-SHA1 authenticator should never be reading secrets from + * a file. (Authenticatee may, though.) + */ + if (flags && ((cp = strchr(word, ':')) == NULL || + strchr(cp + 1, ':') == NULL)) + continue; - if (secret != NULL) { - /* - * Special syntax: @/pathname means read secret from file. - */ - if (word[0] == '@' && word[1] == '/') { - strlcpy(atfile, word+1, sizeof(atfile)); - if ((sf = fopen(atfile, "r")) == NULL) { - ppp_warn("can't open indirect secret file %s", atfile); - continue; - } - check_access(sf, atfile); - if (!getword(sf, word, &xxx, atfile)) { - ppp_warn("no secret in indirect secret file %s", atfile); - fclose(sf); - continue; - } - fclose(sf); - } - strlcpy(lsecret, word, sizeof(lsecret)); - } + if (secret != NULL) { + /* + * Special syntax: @/pathname means read secret from file. + */ + if (word[0] == '@' && word[1] == '/') { + strlcpy(atfile, word+1, sizeof(atfile)); + if ((sf = fopen(atfile, "r")) == NULL) { + ppp_warn("can't open indirect secret file %s", atfile); + continue; + } + check_access(sf, atfile); + if (!getword(sf, word, &xxx, atfile)) { + ppp_warn("no secret in indirect secret file %s", atfile); + fclose(sf); + continue; + } + fclose(sf); + } + strlcpy(lsecret, word, sizeof(lsecret)); + } - /* - * Now read address authorization info and make a wordlist. - */ - app = &alist; - for (;;) { - if (!getword(f, word, &newline, filename) || newline) - break; - ap = (struct wordlist *) - malloc(sizeof(struct wordlist) + strlen(word) + 1); - if (ap == NULL) - novm("authorized addresses"); - ap->word = (char *) (ap + 1); - strcpy(ap->word, word); - *app = ap; - app = &ap->next; - } - *app = NULL; + /* + * Now read address authorization info and make a wordlist. + */ + app = &alist; + for (;;) { + if (!getword(f, word, &newline, filename) || newline) + break; + ap = (struct wordlist *) + malloc(sizeof(struct wordlist) + strlen(word) + 1); + if (ap == NULL) + novm("authorized addresses"); + ap->word = (char *) (ap + 1); + strcpy(ap->word, word); + *app = ap; + app = &ap->next; + } + *app = NULL; - /* - * This is the best so far; remember it. - */ - best_flag = got_flag; - if (addr_list) - free_wordlist(addr_list); - addr_list = alist; - if (secret != NULL) - strlcpy(secret, lsecret, MAXWORDLEN); + /* + * This is the best so far; remember it. + */ + best_flag = got_flag; + if (addr_list) + free_wordlist(addr_list); + addr_list = alist; + if (secret != NULL) + strlcpy(secret, lsecret, MAXWORDLEN); - if (!newline) - break; + if (!newline) + break; } /* scan for a -- word indicating the start of options */ for (app = &addr_list; (ap = *app) != NULL; app = &ap->next) - if (strcmp(ap->word, "--") == 0) - break; + if (strcmp(ap->word, "--") == 0) + break; /* ap = start of options */ if (ap != NULL) { - ap = ap->next; /* first option */ - free(*app); /* free the "--" word */ - *app = NULL; /* terminate addr list */ + ap = ap->next; /* first option */ + free(*app); /* free the "--" word */ + *app = NULL; /* terminate addr list */ } if (opts != NULL) - *opts = ap; + *opts = ap; else if (ap != NULL) - free_wordlist(ap); + free_wordlist(ap); if (addrs != NULL) - *addrs = addr_list; + *addrs = addr_list; else if (addr_list != NULL) - free_wordlist(addr_list); + free_wordlist(addr_list); return best_flag; } @@ -2486,7 +2486,7 @@ wordlist_count(wp) int n; for (n = 0; wp != NULL; wp = wp->next) - ++n; + ++n; return n; } @@ -2500,9 +2500,9 @@ free_wordlist(wp) struct wordlist *next; while (wp != NULL) { - next = wp->next; - free(wp); - wp = next; + next = wp->next; + free(wp); + wp = next; } } #endif /* UNUSED */ diff --git a/components/network/lwip/src/netif/ppp/ccp.c b/components/network/lwip/src/netif/ppp/ccp.c index f8519ebe..5e5b75c3 100644 --- a/components/network/lwip/src/netif/ppp/ccp.c +++ b/components/network/lwip/src/netif/ppp/ccp.c @@ -40,8 +40,8 @@ #include "netif/ppp/ccp.h" #if MPPE_SUPPORT -#include "netif/ppp/lcp.h" /* lcp_close(), lcp_fsm */ -#include "netif/ppp/mppe.h" /* mppe_init() */ +#include "netif/ppp/lcp.h" /* lcp_close(), lcp_fsm */ +#include "netif/ppp/mppe.h" /* mppe_init() */ #endif /* MPPE_SUPPORT */ /* @@ -51,7 +51,7 @@ * Until this is fixed we only accept sizes in the range 9 .. 15. * Thanks to James Carlson for pointing this out. */ -#define DEFLATE_MIN_WORKS 9 +#define DEFLATE_MIN_WORKS 9 /* * Command-line options. @@ -66,7 +66,7 @@ static char deflate_value[8]; * Option variables. */ #if MPPE_SUPPORT -bool refuse_mppe_stateful = 1; /* Allow stateful mode? */ +bool refuse_mppe_stateful = 1; /* Allow stateful mode? */ #endif /* MPPE_SUPPORT */ static option_t ccp_option_list[] = { @@ -248,27 +248,27 @@ static const fsm_callbacks ccp_callbacks = { static int ccp_anycompress(ccp_options *opt) { return (0 #if DEFLATE_SUPPORT - || (opt)->deflate + || (opt)->deflate #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT - || (opt)->bsd_compress + || (opt)->bsd_compress #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT - || (opt)->predictor_1 || (opt)->predictor_2 + || (opt)->predictor_1 || (opt)->predictor_2 #endif /* PREDICTOR_SUPPORT */ #if MPPE_SUPPORT - || (opt)->mppe + || (opt)->mppe #endif /* MPPE_SUPPORT */ - ); + ); } /* * Local state (mainly for handling reset-reqs and reset-acks). */ -#define RACK_PENDING 1 /* waiting for reset-ack */ -#define RREQ_REPEAT 2 /* send another reset-req if no reset-ack */ +#define RACK_PENDING 1 /* waiting for reset-ack */ +#define RREQ_REPEAT 2 /* send another reset-req if no reset-ack */ -#define RACKTIMEOUT 1 /* second */ +#define RACKTIMEOUT 1 /* second */ #if PPP_OPTIONS /* @@ -284,31 +284,31 @@ setbsdcomp(argv) str = *argv; abits = rbits = strtol(str, &endp, 0); if (endp != str && *endp == ',') { - str = endp + 1; - abits = strtol(str, &endp, 0); + str = endp + 1; + abits = strtol(str, &endp, 0); } if (*endp != 0 || endp == str) { - option_error("invalid parameter '%s' for bsdcomp option", *argv); - return 0; + option_error("invalid parameter '%s' for bsdcomp option", *argv); + return 0; } if ((rbits != 0 && (rbits < BSD_MIN_BITS || rbits > BSD_MAX_BITS)) - || (abits != 0 && (abits < BSD_MIN_BITS || abits > BSD_MAX_BITS))) { - option_error("bsdcomp option values must be 0 or %d .. %d", - BSD_MIN_BITS, BSD_MAX_BITS); - return 0; + || (abits != 0 && (abits < BSD_MIN_BITS || abits > BSD_MAX_BITS))) { + option_error("bsdcomp option values must be 0 or %d .. %d", + BSD_MIN_BITS, BSD_MAX_BITS); + return 0; } if (rbits > 0) { - ccp_wantoptions[0].bsd_compress = 1; - ccp_wantoptions[0].bsd_bits = rbits; + ccp_wantoptions[0].bsd_compress = 1; + ccp_wantoptions[0].bsd_bits = rbits; } else - ccp_wantoptions[0].bsd_compress = 0; + ccp_wantoptions[0].bsd_compress = 0; if (abits > 0) { - ccp_allowoptions[0].bsd_compress = 1; - ccp_allowoptions[0].bsd_bits = abits; + ccp_allowoptions[0].bsd_compress = 1; + ccp_allowoptions[0].bsd_bits = abits; } else - ccp_allowoptions[0].bsd_compress = 0; + ccp_allowoptions[0].bsd_compress = 0; ppp_slprintf(bsd_value, sizeof(bsd_value), - rbits == abits? "%d": "%d,%d", rbits, abits); + rbits == abits? "%d": "%d,%d", rbits, abits); return 1; } @@ -323,40 +323,40 @@ setdeflate(argv) str = *argv; abits = rbits = strtol(str, &endp, 0); if (endp != str && *endp == ',') { - str = endp + 1; - abits = strtol(str, &endp, 0); + str = endp + 1; + abits = strtol(str, &endp, 0); } if (*endp != 0 || endp == str) { - option_error("invalid parameter '%s' for deflate option", *argv); - return 0; + option_error("invalid parameter '%s' for deflate option", *argv); + return 0; } if ((rbits != 0 && (rbits < DEFLATE_MIN_SIZE || rbits > DEFLATE_MAX_SIZE)) - || (abits != 0 && (abits < DEFLATE_MIN_SIZE - || abits > DEFLATE_MAX_SIZE))) { - option_error("deflate option values must be 0 or %d .. %d", - DEFLATE_MIN_SIZE, DEFLATE_MAX_SIZE); - return 0; + || (abits != 0 && (abits < DEFLATE_MIN_SIZE + || abits > DEFLATE_MAX_SIZE))) { + option_error("deflate option values must be 0 or %d .. %d", + DEFLATE_MIN_SIZE, DEFLATE_MAX_SIZE); + return 0; } if (rbits == DEFLATE_MIN_SIZE || abits == DEFLATE_MIN_SIZE) { - if (rbits == DEFLATE_MIN_SIZE) - rbits = DEFLATE_MIN_WORKS; - if (abits == DEFLATE_MIN_SIZE) - abits = DEFLATE_MIN_WORKS; - warn("deflate option value of %d changed to %d to avoid zlib bug", - DEFLATE_MIN_SIZE, DEFLATE_MIN_WORKS); + if (rbits == DEFLATE_MIN_SIZE) + rbits = DEFLATE_MIN_WORKS; + if (abits == DEFLATE_MIN_SIZE) + abits = DEFLATE_MIN_WORKS; + warn("deflate option value of %d changed to %d to avoid zlib bug", + DEFLATE_MIN_SIZE, DEFLATE_MIN_WORKS); } if (rbits > 0) { - ccp_wantoptions[0].deflate = 1; - ccp_wantoptions[0].deflate_size = rbits; + ccp_wantoptions[0].deflate = 1; + ccp_wantoptions[0].deflate_size = rbits; } else - ccp_wantoptions[0].deflate = 0; + ccp_wantoptions[0].deflate = 0; if (abits > 0) { - ccp_allowoptions[0].deflate = 1; - ccp_allowoptions[0].deflate_size = abits; + ccp_allowoptions[0].deflate = 1; + ccp_allowoptions[0].deflate_size = abits; } else - ccp_allowoptions[0].deflate = 0; + ccp_allowoptions[0].deflate = 0; ppp_slprintf(deflate_value, sizeof(deflate_value), - rbits == abits? "%d": "%d,%d", rbits, abits); + rbits == abits? "%d": "%d,%d", rbits, abits); return 1; } @@ -411,7 +411,7 @@ static void ccp_open(ppp_pcb *pcb) { ccp_options *go = &pcb->ccp_gotoptions; if (f->state != PPP_FSM_OPENED) - ccp_set(pcb, 1, 0, 0, 0); + ccp_set(pcb, 1, 0, 0, 0); /* * Find out which compressors the kernel supports before @@ -419,7 +419,7 @@ static void ccp_open(ppp_pcb *pcb) { */ ccp_resetci(f); if (!ccp_anycompress(go)) - f->flags |= OPT_SILENT; + f->flags |= OPT_SILENT; fsm_open(f); } @@ -463,12 +463,12 @@ static void ccp_input(ppp_pcb *pcb, u_char *p, int len) { oldstate = f->state; fsm_input(f, p, len); if (oldstate == PPP_FSM_OPENED && p[0] == TERMREQ && f->state != PPP_FSM_OPENED) { - ppp_notice("Compression disabled by peer."); + ppp_notice("Compression disabled by peer."); #if MPPE_SUPPORT - if (go->mppe) { - ppp_error("MPPE disabled, closing LCP"); - lcp_close(pcb, "MPPE disabled by peer"); - } + if (go->mppe) { + ppp_error("MPPE disabled, closing LCP"); + lcp_close(pcb, "MPPE disabled by peer"); + } #endif /* MPPE_SUPPORT */ } @@ -477,8 +477,8 @@ static void ccp_input(ppp_pcb *pcb, u_char *p, int len) { * close CCP. */ if (oldstate == PPP_FSM_REQSENT && p[0] == TERMACK - && !ccp_anycompress(go)) - ccp_close(pcb, "No compression negotiated"); + && !ccp_anycompress(go)) + ccp_close(pcb, "No compression negotiated"); } /* @@ -491,24 +491,24 @@ static int ccp_extcode(fsm *f, int code, int id, u_char *p, int len) { switch (code) { case CCP_RESETREQ: - if (f->state != PPP_FSM_OPENED) - break; - ccp_reset_comp(pcb); - /* send a reset-ack, which the transmitter will see and - reset its compression state. */ - fsm_sdata(f, CCP_RESETACK, id, NULL, 0); - break; + if (f->state != PPP_FSM_OPENED) + break; + ccp_reset_comp(pcb); + /* send a reset-ack, which the transmitter will see and + reset its compression state. */ + fsm_sdata(f, CCP_RESETACK, id, NULL, 0); + break; case CCP_RESETACK: - if ((pcb->ccp_localstate & RACK_PENDING) && id == f->reqid) { - pcb->ccp_localstate &= ~(RACK_PENDING | RREQ_REPEAT); - UNTIMEOUT(ccp_rack_timeout, f); - ccp_reset_decomp(pcb); - } - break; + if ((pcb->ccp_localstate & RACK_PENDING) && id == f->reqid) { + pcb->ccp_localstate &= ~(RACK_PENDING | RREQ_REPEAT); + UNTIMEOUT(ccp_rack_timeout, f); + ccp_reset_decomp(pcb); + } + break; default: - return 0; + return 0; } return 1; @@ -528,8 +528,8 @@ static void ccp_protrej(ppp_pcb *pcb) { #if MPPE_SUPPORT if (go->mppe) { - ppp_error("MPPE required but peer negotiation failed"); - lcp_close(pcb, "MPPE required but peer negotiation failed"); + ppp_error("MPPE required but peer negotiation failed"); + lcp_close(pcb, "MPPE required but peer negotiation failed"); } #endif /* MPPE_SUPPORT */ @@ -554,9 +554,9 @@ static void ccp_resetci(fsm *f) { #if MPPE_SUPPORT if (pcb->settings.require_mppe) { - wo->mppe = ao->mppe = - (pcb->settings.refuse_mppe_40 ? 0 : MPPE_OPT_40) - | (pcb->settings.refuse_mppe_128 ? 0 : MPPE_OPT_128); + wo->mppe = ao->mppe = + (pcb->settings.refuse_mppe_40 ? 0 : MPPE_OPT_40) + | (pcb->settings.refuse_mppe_128 ? 0 : MPPE_OPT_128); } #endif /* MPPE_SUPPORT */ @@ -565,78 +565,78 @@ static void ccp_resetci(fsm *f) { #if MPPE_SUPPORT if (go->mppe) { - int auth_mschap_bits = pcb->auth_done; - int numbits; + int auth_mschap_bits = pcb->auth_done; + int numbits; - /* - * Start with a basic sanity check: mschap[v2] auth must be in - * exactly one direction. RFC 3079 says that the keys are - * 'derived from the credentials of the peer that initiated the call', - * however the PPP protocol doesn't have such a concept, and pppd - * cannot get this info externally. Instead we do the best we can. - * NB: If MPPE is required, all other compression opts are invalid. - * So, we return right away if we can't do it. - */ + /* + * Start with a basic sanity check: mschap[v2] auth must be in + * exactly one direction. RFC 3079 says that the keys are + * 'derived from the credentials of the peer that initiated the call', + * however the PPP protocol doesn't have such a concept, and pppd + * cannot get this info externally. Instead we do the best we can. + * NB: If MPPE is required, all other compression opts are invalid. + * So, we return right away if we can't do it. + */ - /* Leave only the mschap auth bits set */ - auth_mschap_bits &= (CHAP_MS_WITHPEER | CHAP_MS_PEER | - CHAP_MS2_WITHPEER | CHAP_MS2_PEER); - /* Count the mschap auths */ - auth_mschap_bits >>= CHAP_MS_SHIFT; - numbits = 0; - do { - numbits += auth_mschap_bits & 1; - auth_mschap_bits >>= 1; - } while (auth_mschap_bits); - if (numbits > 1) { - ppp_error("MPPE required, but auth done in both directions."); - lcp_close(pcb, "MPPE required but not available"); - return; - } - if (!numbits) { - ppp_error("MPPE required, but MS-CHAP[v2] auth not performed."); - lcp_close(pcb, "MPPE required but not available"); - return; - } + /* Leave only the mschap auth bits set */ + auth_mschap_bits &= (CHAP_MS_WITHPEER | CHAP_MS_PEER | + CHAP_MS2_WITHPEER | CHAP_MS2_PEER); + /* Count the mschap auths */ + auth_mschap_bits >>= CHAP_MS_SHIFT; + numbits = 0; + do { + numbits += auth_mschap_bits & 1; + auth_mschap_bits >>= 1; + } while (auth_mschap_bits); + if (numbits > 1) { + ppp_error("MPPE required, but auth done in both directions."); + lcp_close(pcb, "MPPE required but not available"); + return; + } + if (!numbits) { + ppp_error("MPPE required, but MS-CHAP[v2] auth not performed."); + lcp_close(pcb, "MPPE required but not available"); + return; + } - /* A plugin (eg radius) may not have obtained key material. */ - if (!pcb->mppe_keys_set) { - ppp_error("MPPE required, but keys are not available. " - "Possible plugin problem?"); - lcp_close(pcb, "MPPE required but not available"); - return; - } + /* A plugin (eg radius) may not have obtained key material. */ + if (!pcb->mppe_keys_set) { + ppp_error("MPPE required, but keys are not available. " + "Possible plugin problem?"); + lcp_close(pcb, "MPPE required but not available"); + return; + } - /* LM auth not supported for MPPE */ - if (pcb->auth_done & (CHAP_MS_WITHPEER | CHAP_MS_PEER)) { - /* This might be noise */ - if (go->mppe & MPPE_OPT_40) { - ppp_notice("Disabling 40-bit MPPE; MS-CHAP LM not supported"); - go->mppe &= ~MPPE_OPT_40; - wo->mppe &= ~MPPE_OPT_40; - } - } + /* LM auth not supported for MPPE */ + if (pcb->auth_done & (CHAP_MS_WITHPEER | CHAP_MS_PEER)) { + /* This might be noise */ + if (go->mppe & MPPE_OPT_40) { + ppp_notice("Disabling 40-bit MPPE; MS-CHAP LM not supported"); + go->mppe &= ~MPPE_OPT_40; + wo->mppe &= ~MPPE_OPT_40; + } + } - /* Last check: can we actually negotiate something? */ - if (!(go->mppe & (MPPE_OPT_40 | MPPE_OPT_128))) { - /* Could be misconfig, could be 40-bit disabled above. */ - ppp_error("MPPE required, but both 40-bit and 128-bit disabled."); - lcp_close(pcb, "MPPE required but not available"); - return; - } + /* Last check: can we actually negotiate something? */ + if (!(go->mppe & (MPPE_OPT_40 | MPPE_OPT_128))) { + /* Could be misconfig, could be 40-bit disabled above. */ + ppp_error("MPPE required, but both 40-bit and 128-bit disabled."); + lcp_close(pcb, "MPPE required but not available"); + return; + } - /* sync options */ - ao->mppe = go->mppe; - /* MPPE is not compatible with other compression types */ + /* sync options */ + ao->mppe = go->mppe; + /* MPPE is not compatible with other compression types */ #if BSDCOMPRESS_SUPPORT - ao->bsd_compress = go->bsd_compress = 0; + ao->bsd_compress = go->bsd_compress = 0; #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT - ao->predictor_1 = go->predictor_1 = 0; - ao->predictor_2 = go->predictor_2 = 0; + ao->predictor_1 = go->predictor_1 = 0; + ao->predictor_2 = go->predictor_2 = 0; #endif /* PREDICTOR_SUPPORT */ #if DEFLATE_SUPPORT - ao->deflate = go->deflate = 0; + ao->deflate = go->deflate = 0; #endif /* DEFLATE_SUPPORT */ } #endif /* MPPE_SUPPORT */ @@ -650,23 +650,23 @@ static void ccp_resetci(fsm *f) { * if BSDCOMPRESS_SUPPORT is set, it is. */ if (go->bsd_compress) { - opt_buf[0] = CI_BSD_COMPRESS; - opt_buf[1] = CILEN_BSD_COMPRESS; - for (;;) { - if (go->bsd_bits < BSD_MIN_BITS) { - go->bsd_compress = 0; - break; - } - opt_buf[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits); - res = ccp_test(pcb, opt_buf, CILEN_BSD_COMPRESS, 0); - if (res > 0) { - break; - } else if (res < 0) { - go->bsd_compress = 0; - break; - } - go->bsd_bits--; - } + opt_buf[0] = CI_BSD_COMPRESS; + opt_buf[1] = CILEN_BSD_COMPRESS; + for (;;) { + if (go->bsd_bits < BSD_MIN_BITS) { + go->bsd_compress = 0; + break; + } + opt_buf[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits); + res = ccp_test(pcb, opt_buf, CILEN_BSD_COMPRESS, 0); + if (res > 0) { + break; + } else if (res < 0) { + go->bsd_compress = 0; + break; + } + go->bsd_bits--; + } } #endif /* BSDCOMPRESS_SUPPORT */ #if DEFLATE_SUPPORT @@ -674,48 +674,48 @@ static void ccp_resetci(fsm *f) { * if DEFLATE_SUPPORT is set, it is. */ if (go->deflate) { - if (go->deflate_correct) { - opt_buf[0] = CI_DEFLATE; - opt_buf[1] = CILEN_DEFLATE; - opt_buf[3] = DEFLATE_CHK_SEQUENCE; - for (;;) { - if (go->deflate_size < DEFLATE_MIN_WORKS) { - go->deflate_correct = 0; - break; - } - opt_buf[2] = DEFLATE_MAKE_OPT(go->deflate_size); - res = ccp_test(pcb, opt_buf, CILEN_DEFLATE, 0); - if (res > 0) { - break; - } else if (res < 0) { - go->deflate_correct = 0; - break; - } - go->deflate_size--; - } - } - if (go->deflate_draft) { - opt_buf[0] = CI_DEFLATE_DRAFT; - opt_buf[1] = CILEN_DEFLATE; - opt_buf[3] = DEFLATE_CHK_SEQUENCE; - for (;;) { - if (go->deflate_size < DEFLATE_MIN_WORKS) { - go->deflate_draft = 0; - break; - } - opt_buf[2] = DEFLATE_MAKE_OPT(go->deflate_size); - res = ccp_test(pcb, opt_buf, CILEN_DEFLATE, 0); - if (res > 0) { - break; - } else if (res < 0) { - go->deflate_draft = 0; - break; - } - go->deflate_size--; - } - } - if (!go->deflate_correct && !go->deflate_draft) - go->deflate = 0; + if (go->deflate_correct) { + opt_buf[0] = CI_DEFLATE; + opt_buf[1] = CILEN_DEFLATE; + opt_buf[3] = DEFLATE_CHK_SEQUENCE; + for (;;) { + if (go->deflate_size < DEFLATE_MIN_WORKS) { + go->deflate_correct = 0; + break; + } + opt_buf[2] = DEFLATE_MAKE_OPT(go->deflate_size); + res = ccp_test(pcb, opt_buf, CILEN_DEFLATE, 0); + if (res > 0) { + break; + } else if (res < 0) { + go->deflate_correct = 0; + break; + } + go->deflate_size--; + } + } + if (go->deflate_draft) { + opt_buf[0] = CI_DEFLATE_DRAFT; + opt_buf[1] = CILEN_DEFLATE; + opt_buf[3] = DEFLATE_CHK_SEQUENCE; + for (;;) { + if (go->deflate_size < DEFLATE_MIN_WORKS) { + go->deflate_draft = 0; + break; + } + opt_buf[2] = DEFLATE_MAKE_OPT(go->deflate_size); + res = ccp_test(pcb, opt_buf, CILEN_DEFLATE, 0); + if (res > 0) { + break; + } else if (res < 0) { + go->deflate_draft = 0; + break; + } + go->deflate_size--; + } + } + if (!go->deflate_correct && !go->deflate_draft) + go->deflate = 0; } #endif /* DEFLATE_SUPPORT */ #if PREDICTOR_SUPPORT @@ -723,16 +723,16 @@ static void ccp_resetci(fsm *f) { * if PREDICTOR_SUPPORT is set, it is. */ if (go->predictor_1) { - opt_buf[0] = CI_PREDICTOR_1; - opt_buf[1] = CILEN_PREDICTOR_1; - if (ccp_test(pcb, opt_buf, CILEN_PREDICTOR_1, 0) <= 0) - go->predictor_1 = 0; + opt_buf[0] = CI_PREDICTOR_1; + opt_buf[1] = CILEN_PREDICTOR_1; + if (ccp_test(pcb, opt_buf, CILEN_PREDICTOR_1, 0) <= 0) + go->predictor_1 = 0; } if (go->predictor_2) { - opt_buf[0] = CI_PREDICTOR_2; - opt_buf[1] = CILEN_PREDICTOR_2; - if (ccp_test(pcb, opt_buf, CILEN_PREDICTOR_2, 0) <= 0) - go->predictor_2 = 0; + opt_buf[0] = CI_PREDICTOR_2; + opt_buf[1] = CILEN_PREDICTOR_2; + if (ccp_test(pcb, opt_buf, CILEN_PREDICTOR_2, 0) <= 0) + go->predictor_2 = 0; } #endif /* PREDICTOR_SUPPORT */ } @@ -746,20 +746,20 @@ static int ccp_cilen(fsm *f) { return 0 #if BSDCOMPRESS_SUPPORT - + (go->bsd_compress? CILEN_BSD_COMPRESS: 0) + + (go->bsd_compress? CILEN_BSD_COMPRESS: 0) #endif /* BSDCOMPRESS_SUPPORT */ #if DEFLATE_SUPPORT - + (go->deflate && go->deflate_correct? CILEN_DEFLATE: 0) - + (go->deflate && go->deflate_draft? CILEN_DEFLATE: 0) + + (go->deflate && go->deflate_correct? CILEN_DEFLATE: 0) + + (go->deflate && go->deflate_draft? CILEN_DEFLATE: 0) #endif /* DEFLATE_SUPPORT */ #if PREDICTOR_SUPPORT - + (go->predictor_1? CILEN_PREDICTOR_1: 0) - + (go->predictor_2? CILEN_PREDICTOR_2: 0) + + (go->predictor_1? CILEN_PREDICTOR_1: 0) + + (go->predictor_2? CILEN_PREDICTOR_2: 0) #endif /* PREDICTOR_SUPPORT */ #if MPPE_SUPPORT - + (go->mppe? CILEN_MPPE: 0) + + (go->mppe? CILEN_MPPE: 0) #endif /* MPPE_SUPPORT */ - ; + ; } /* @@ -776,50 +776,50 @@ static void ccp_addci(fsm *f, u_char *p, int *lenp) { */ #if MPPE_SUPPORT if (go->mppe) { - p[0] = CI_MPPE; - p[1] = CILEN_MPPE; - MPPE_OPTS_TO_CI(go->mppe, &p[2]); - mppe_init(pcb, &pcb->mppe_decomp, go->mppe); - p += CILEN_MPPE; + p[0] = CI_MPPE; + p[1] = CILEN_MPPE; + MPPE_OPTS_TO_CI(go->mppe, &p[2]); + mppe_init(pcb, &pcb->mppe_decomp, go->mppe); + p += CILEN_MPPE; } #endif /* MPPE_SUPPORT */ #if DEFLATE_SUPPORT if (go->deflate) { - if (go->deflate_correct) { - p[0] = CI_DEFLATE; - p[1] = CILEN_DEFLATE; - p[2] = DEFLATE_MAKE_OPT(go->deflate_size); - p[3] = DEFLATE_CHK_SEQUENCE; - p += CILEN_DEFLATE; - } - if (go->deflate_draft) { - p[0] = CI_DEFLATE_DRAFT; - p[1] = CILEN_DEFLATE; - p[2] = p[2 - CILEN_DEFLATE]; - p[3] = DEFLATE_CHK_SEQUENCE; - p += CILEN_DEFLATE; - } + if (go->deflate_correct) { + p[0] = CI_DEFLATE; + p[1] = CILEN_DEFLATE; + p[2] = DEFLATE_MAKE_OPT(go->deflate_size); + p[3] = DEFLATE_CHK_SEQUENCE; + p += CILEN_DEFLATE; + } + if (go->deflate_draft) { + p[0] = CI_DEFLATE_DRAFT; + p[1] = CILEN_DEFLATE; + p[2] = p[2 - CILEN_DEFLATE]; + p[3] = DEFLATE_CHK_SEQUENCE; + p += CILEN_DEFLATE; + } } #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT if (go->bsd_compress) { - p[0] = CI_BSD_COMPRESS; - p[1] = CILEN_BSD_COMPRESS; - p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits); - p += CILEN_BSD_COMPRESS; + p[0] = CI_BSD_COMPRESS; + p[1] = CILEN_BSD_COMPRESS; + p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits); + p += CILEN_BSD_COMPRESS; } #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT /* XXX Should Predictor 2 be preferable to Predictor 1? */ if (go->predictor_1) { - p[0] = CI_PREDICTOR_1; - p[1] = CILEN_PREDICTOR_1; - p += CILEN_PREDICTOR_1; + p[0] = CI_PREDICTOR_1; + p[1] = CILEN_PREDICTOR_1; + p += CILEN_PREDICTOR_1; } if (go->predictor_2) { - p[0] = CI_PREDICTOR_2; - p[1] = CILEN_PREDICTOR_2; - p += CILEN_PREDICTOR_2; + p[0] = CI_PREDICTOR_2; + p[1] = CILEN_PREDICTOR_2; + p += CILEN_PREDICTOR_2; } #endif /* PREDICTOR_SUPPORT */ @@ -841,83 +841,83 @@ static int ccp_ackci(fsm *f, u_char *p, int len) { #if MPPE_SUPPORT if (go->mppe) { - u_char opt_buf[CILEN_MPPE]; + u_char opt_buf[CILEN_MPPE]; - opt_buf[0] = CI_MPPE; - opt_buf[1] = CILEN_MPPE; - MPPE_OPTS_TO_CI(go->mppe, &opt_buf[2]); - if (len < CILEN_MPPE || memcmp(opt_buf, p, CILEN_MPPE)) - return 0; - p += CILEN_MPPE; - len -= CILEN_MPPE; - /* XXX Cope with first/fast ack */ - if (len == 0) - return 1; + opt_buf[0] = CI_MPPE; + opt_buf[1] = CILEN_MPPE; + MPPE_OPTS_TO_CI(go->mppe, &opt_buf[2]); + if (len < CILEN_MPPE || memcmp(opt_buf, p, CILEN_MPPE)) + return 0; + p += CILEN_MPPE; + len -= CILEN_MPPE; + /* XXX Cope with first/fast ack */ + if (len == 0) + return 1; } #endif /* MPPE_SUPPORT */ #if DEFLATE_SUPPORT if (go->deflate) { - if (len < CILEN_DEFLATE - || p[0] != (go->deflate_correct? CI_DEFLATE: CI_DEFLATE_DRAFT) - || p[1] != CILEN_DEFLATE - || p[2] != DEFLATE_MAKE_OPT(go->deflate_size) - || p[3] != DEFLATE_CHK_SEQUENCE) - return 0; - p += CILEN_DEFLATE; - len -= CILEN_DEFLATE; - /* XXX Cope with first/fast ack */ - if (len == 0) - return 1; - if (go->deflate_correct && go->deflate_draft) { - if (len < CILEN_DEFLATE - || p[0] != CI_DEFLATE_DRAFT - || p[1] != CILEN_DEFLATE - || p[2] != DEFLATE_MAKE_OPT(go->deflate_size) - || p[3] != DEFLATE_CHK_SEQUENCE) - return 0; - p += CILEN_DEFLATE; - len -= CILEN_DEFLATE; - } + if (len < CILEN_DEFLATE + || p[0] != (go->deflate_correct? CI_DEFLATE: CI_DEFLATE_DRAFT) + || p[1] != CILEN_DEFLATE + || p[2] != DEFLATE_MAKE_OPT(go->deflate_size) + || p[3] != DEFLATE_CHK_SEQUENCE) + return 0; + p += CILEN_DEFLATE; + len -= CILEN_DEFLATE; + /* XXX Cope with first/fast ack */ + if (len == 0) + return 1; + if (go->deflate_correct && go->deflate_draft) { + if (len < CILEN_DEFLATE + || p[0] != CI_DEFLATE_DRAFT + || p[1] != CILEN_DEFLATE + || p[2] != DEFLATE_MAKE_OPT(go->deflate_size) + || p[3] != DEFLATE_CHK_SEQUENCE) + return 0; + p += CILEN_DEFLATE; + len -= CILEN_DEFLATE; + } } #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT if (go->bsd_compress) { - if (len < CILEN_BSD_COMPRESS - || p[0] != CI_BSD_COMPRESS || p[1] != CILEN_BSD_COMPRESS - || p[2] != BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits)) - return 0; - p += CILEN_BSD_COMPRESS; - len -= CILEN_BSD_COMPRESS; - /* XXX Cope with first/fast ack */ - if (p == p0 && len == 0) - return 1; + if (len < CILEN_BSD_COMPRESS + || p[0] != CI_BSD_COMPRESS || p[1] != CILEN_BSD_COMPRESS + || p[2] != BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits)) + return 0; + p += CILEN_BSD_COMPRESS; + len -= CILEN_BSD_COMPRESS; + /* XXX Cope with first/fast ack */ + if (p == p0 && len == 0) + return 1; } #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT if (go->predictor_1) { - if (len < CILEN_PREDICTOR_1 - || p[0] != CI_PREDICTOR_1 || p[1] != CILEN_PREDICTOR_1) - return 0; - p += CILEN_PREDICTOR_1; - len -= CILEN_PREDICTOR_1; - /* XXX Cope with first/fast ack */ - if (p == p0 && len == 0) - return 1; + if (len < CILEN_PREDICTOR_1 + || p[0] != CI_PREDICTOR_1 || p[1] != CILEN_PREDICTOR_1) + return 0; + p += CILEN_PREDICTOR_1; + len -= CILEN_PREDICTOR_1; + /* XXX Cope with first/fast ack */ + if (p == p0 && len == 0) + return 1; } if (go->predictor_2) { - if (len < CILEN_PREDICTOR_2 - || p[0] != CI_PREDICTOR_2 || p[1] != CILEN_PREDICTOR_2) - return 0; - p += CILEN_PREDICTOR_2; - len -= CILEN_PREDICTOR_2; - /* XXX Cope with first/fast ack */ - if (p == p0 && len == 0) - return 1; + if (len < CILEN_PREDICTOR_2 + || p[0] != CI_PREDICTOR_2 || p[1] != CILEN_PREDICTOR_2) + return 0; + p += CILEN_PREDICTOR_2; + len -= CILEN_PREDICTOR_2; + /* XXX Cope with first/fast ack */ + if (p == p0 && len == 0) + return 1; } #endif /* PREDICTOR_SUPPORT */ if (len != 0) - return 0; + return 0; return 1; } @@ -928,8 +928,8 @@ static int ccp_ackci(fsm *f, u_char *p, int len) { static int ccp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { ppp_pcb *pcb = f->pcb; ccp_options *go = &pcb->ccp_gotoptions; - ccp_options no; /* options we've seen already */ - ccp_options try_; /* options to ask for next time */ + ccp_options no; /* options we've seen already */ + ccp_options try_; /* options to ask for next time */ LWIP_UNUSED_ARG(treat_as_reject); #if !MPPE_SUPPORT && !DEFLATE_SUPPORT && !BSDCOMPRESS_SUPPORT LWIP_UNUSED_ARG(p); @@ -941,66 +941,66 @@ static int ccp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { #if MPPE_SUPPORT if (go->mppe && len >= CILEN_MPPE - && p[0] == CI_MPPE && p[1] == CILEN_MPPE) { - no.mppe = 1; - /* - * Peer wants us to use a different strength or other setting. - * Fail if we aren't willing to use his suggestion. - */ - MPPE_CI_TO_OPTS(&p[2], try_.mppe); - if ((try_.mppe & MPPE_OPT_STATEFUL) && pcb->settings.refuse_mppe_stateful) { - ppp_error("Refusing MPPE stateful mode offered by peer"); - try_.mppe = 0; - } else if (((go->mppe | MPPE_OPT_STATEFUL) & try_.mppe) != try_.mppe) { - /* Peer must have set options we didn't request (suggest) */ - try_.mppe = 0; - } + && p[0] == CI_MPPE && p[1] == CILEN_MPPE) { + no.mppe = 1; + /* + * Peer wants us to use a different strength or other setting. + * Fail if we aren't willing to use his suggestion. + */ + MPPE_CI_TO_OPTS(&p[2], try_.mppe); + if ((try_.mppe & MPPE_OPT_STATEFUL) && pcb->settings.refuse_mppe_stateful) { + ppp_error("Refusing MPPE stateful mode offered by peer"); + try_.mppe = 0; + } else if (((go->mppe | MPPE_OPT_STATEFUL) & try_.mppe) != try_.mppe) { + /* Peer must have set options we didn't request (suggest) */ + try_.mppe = 0; + } - if (!try_.mppe) { - ppp_error("MPPE required but peer negotiation failed"); - lcp_close(pcb, "MPPE required but peer negotiation failed"); - } + if (!try_.mppe) { + ppp_error("MPPE required but peer negotiation failed"); + lcp_close(pcb, "MPPE required but peer negotiation failed"); + } } #endif /* MPPE_SUPPORT */ #if DEFLATE_SUPPORT if (go->deflate && len >= CILEN_DEFLATE - && p[0] == (go->deflate_correct? CI_DEFLATE: CI_DEFLATE_DRAFT) - && p[1] == CILEN_DEFLATE) { - no.deflate = 1; - /* - * Peer wants us to use a different code size or something. - * Stop asking for Deflate if we don't understand his suggestion. - */ - if (DEFLATE_METHOD(p[2]) != DEFLATE_METHOD_VAL - || DEFLATE_SIZE(p[2]) < DEFLATE_MIN_WORKS - || p[3] != DEFLATE_CHK_SEQUENCE) - try_.deflate = 0; - else if (DEFLATE_SIZE(p[2]) < go->deflate_size) - try_.deflate_size = DEFLATE_SIZE(p[2]); - p += CILEN_DEFLATE; - len -= CILEN_DEFLATE; - if (go->deflate_correct && go->deflate_draft - && len >= CILEN_DEFLATE && p[0] == CI_DEFLATE_DRAFT - && p[1] == CILEN_DEFLATE) { - p += CILEN_DEFLATE; - len -= CILEN_DEFLATE; - } + && p[0] == (go->deflate_correct? CI_DEFLATE: CI_DEFLATE_DRAFT) + && p[1] == CILEN_DEFLATE) { + no.deflate = 1; + /* + * Peer wants us to use a different code size or something. + * Stop asking for Deflate if we don't understand his suggestion. + */ + if (DEFLATE_METHOD(p[2]) != DEFLATE_METHOD_VAL + || DEFLATE_SIZE(p[2]) < DEFLATE_MIN_WORKS + || p[3] != DEFLATE_CHK_SEQUENCE) + try_.deflate = 0; + else if (DEFLATE_SIZE(p[2]) < go->deflate_size) + try_.deflate_size = DEFLATE_SIZE(p[2]); + p += CILEN_DEFLATE; + len -= CILEN_DEFLATE; + if (go->deflate_correct && go->deflate_draft + && len >= CILEN_DEFLATE && p[0] == CI_DEFLATE_DRAFT + && p[1] == CILEN_DEFLATE) { + p += CILEN_DEFLATE; + len -= CILEN_DEFLATE; + } } #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT if (go->bsd_compress && len >= CILEN_BSD_COMPRESS - && p[0] == CI_BSD_COMPRESS && p[1] == CILEN_BSD_COMPRESS) { - no.bsd_compress = 1; - /* - * Peer wants us to use a different number of bits - * or a different version. - */ - if (BSD_VERSION(p[2]) != BSD_CURRENT_VERSION) - try_.bsd_compress = 0; - else if (BSD_NBITS(p[2]) < go->bsd_bits) - try_.bsd_bits = BSD_NBITS(p[2]); - p += CILEN_BSD_COMPRESS; - len -= CILEN_BSD_COMPRESS; + && p[0] == CI_BSD_COMPRESS && p[1] == CILEN_BSD_COMPRESS) { + no.bsd_compress = 1; + /* + * Peer wants us to use a different number of bits + * or a different version. + */ + if (BSD_VERSION(p[2]) != BSD_CURRENT_VERSION) + try_.bsd_compress = 0; + else if (BSD_NBITS(p[2]) < go->bsd_bits) + try_.bsd_bits = BSD_NBITS(p[2]); + p += CILEN_BSD_COMPRESS; + len -= CILEN_BSD_COMPRESS; } #endif /* BSDCOMPRESS_SUPPORT */ @@ -1011,7 +1011,7 @@ static int ccp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { */ if (f->state != PPP_FSM_OPENED) - *go = try_; + *go = try_; return 1; } @@ -1021,7 +1021,7 @@ static int ccp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { static int ccp_rejci(fsm *f, u_char *p, int len) { ppp_pcb *pcb = f->pcb; ccp_options *go = &pcb->ccp_gotoptions; - ccp_options try_; /* options to request next time */ + ccp_options try_; /* options to request next time */ try_ = *go; @@ -1030,69 +1030,69 @@ static int ccp_rejci(fsm *f, u_char *p, int len) { * configure-requests. */ if (len == 0 && pcb->ccp_all_rejected) - return -1; + return -1; #if MPPE_SUPPORT if (go->mppe && len >= CILEN_MPPE - && p[0] == CI_MPPE && p[1] == CILEN_MPPE) { - ppp_error("MPPE required but peer refused"); - lcp_close(pcb, "MPPE required but peer refused"); - p += CILEN_MPPE; - len -= CILEN_MPPE; + && p[0] == CI_MPPE && p[1] == CILEN_MPPE) { + ppp_error("MPPE required but peer refused"); + lcp_close(pcb, "MPPE required but peer refused"); + p += CILEN_MPPE; + len -= CILEN_MPPE; } #endif /* MPPE_SUPPORT */ #if DEFLATE_SUPPORT if (go->deflate_correct && len >= CILEN_DEFLATE - && p[0] == CI_DEFLATE && p[1] == CILEN_DEFLATE) { - if (p[2] != DEFLATE_MAKE_OPT(go->deflate_size) - || p[3] != DEFLATE_CHK_SEQUENCE) - return 0; /* Rej is bad */ - try_.deflate_correct = 0; - p += CILEN_DEFLATE; - len -= CILEN_DEFLATE; + && p[0] == CI_DEFLATE && p[1] == CILEN_DEFLATE) { + if (p[2] != DEFLATE_MAKE_OPT(go->deflate_size) + || p[3] != DEFLATE_CHK_SEQUENCE) + return 0; /* Rej is bad */ + try_.deflate_correct = 0; + p += CILEN_DEFLATE; + len -= CILEN_DEFLATE; } if (go->deflate_draft && len >= CILEN_DEFLATE - && p[0] == CI_DEFLATE_DRAFT && p[1] == CILEN_DEFLATE) { - if (p[2] != DEFLATE_MAKE_OPT(go->deflate_size) - || p[3] != DEFLATE_CHK_SEQUENCE) - return 0; /* Rej is bad */ - try_.deflate_draft = 0; - p += CILEN_DEFLATE; - len -= CILEN_DEFLATE; + && p[0] == CI_DEFLATE_DRAFT && p[1] == CILEN_DEFLATE) { + if (p[2] != DEFLATE_MAKE_OPT(go->deflate_size) + || p[3] != DEFLATE_CHK_SEQUENCE) + return 0; /* Rej is bad */ + try_.deflate_draft = 0; + p += CILEN_DEFLATE; + len -= CILEN_DEFLATE; } if (!try_.deflate_correct && !try_.deflate_draft) - try_.deflate = 0; + try_.deflate = 0; #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT if (go->bsd_compress && len >= CILEN_BSD_COMPRESS - && p[0] == CI_BSD_COMPRESS && p[1] == CILEN_BSD_COMPRESS) { - if (p[2] != BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits)) - return 0; - try_.bsd_compress = 0; - p += CILEN_BSD_COMPRESS; - len -= CILEN_BSD_COMPRESS; + && p[0] == CI_BSD_COMPRESS && p[1] == CILEN_BSD_COMPRESS) { + if (p[2] != BSD_MAKE_OPT(BSD_CURRENT_VERSION, go->bsd_bits)) + return 0; + try_.bsd_compress = 0; + p += CILEN_BSD_COMPRESS; + len -= CILEN_BSD_COMPRESS; } #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT if (go->predictor_1 && len >= CILEN_PREDICTOR_1 - && p[0] == CI_PREDICTOR_1 && p[1] == CILEN_PREDICTOR_1) { - try_.predictor_1 = 0; - p += CILEN_PREDICTOR_1; - len -= CILEN_PREDICTOR_1; + && p[0] == CI_PREDICTOR_1 && p[1] == CILEN_PREDICTOR_1) { + try_.predictor_1 = 0; + p += CILEN_PREDICTOR_1; + len -= CILEN_PREDICTOR_1; } if (go->predictor_2 && len >= CILEN_PREDICTOR_2 - && p[0] == CI_PREDICTOR_2 && p[1] == CILEN_PREDICTOR_2) { - try_.predictor_2 = 0; - p += CILEN_PREDICTOR_2; - len -= CILEN_PREDICTOR_2; + && p[0] == CI_PREDICTOR_2 && p[1] == CILEN_PREDICTOR_2) { + try_.predictor_2 = 0; + p += CILEN_PREDICTOR_2; + len -= CILEN_PREDICTOR_2; } #endif /* PREDICTOR_SUPPORT */ if (len != 0) - return 0; + return 0; if (f->state != PPP_FSM_OPENED) - *go = try_; + *go = try_; return 1; } @@ -1114,8 +1114,8 @@ static int ccp_reqci(fsm *f, u_char *p, int *lenp, int dont_nak) { u_char *p0, *retp; int len, clen, type; #if MPPE_SUPPORT - u8_t rej_for_ci_mppe = 1; /* Are we rejecting based on a bad/missing */ - /* CI_MPPE, or due to other options? */ + u8_t rej_for_ci_mppe = 1; /* Are we rejecting based on a bad/missing */ + /* CI_MPPE, or due to other options? */ #endif /* MPPE_SUPPORT */ ret = CONFACK; @@ -1126,257 +1126,257 @@ static int ccp_reqci(fsm *f, u_char *p, int *lenp, int dont_nak) { ho->method = (len > 0)? p[0]: 0; while (len > 0) { - newret = CONFACK; - if (len < 2 || p[1] < 2 || p[1] > len) { - /* length is bad */ - clen = len; - newret = CONFREJ; + newret = CONFACK; + if (len < 2 || p[1] < 2 || p[1] > len) { + /* length is bad */ + clen = len; + newret = CONFREJ; - } else { - type = p[0]; - clen = p[1]; + } else { + type = p[0]; + clen = p[1]; - switch (type) { + switch (type) { #if MPPE_SUPPORT - case CI_MPPE: - if (!ao->mppe || clen != CILEN_MPPE) { - newret = CONFREJ; - break; - } - MPPE_CI_TO_OPTS(&p[2], ho->mppe); + case CI_MPPE: + if (!ao->mppe || clen != CILEN_MPPE) { + newret = CONFREJ; + break; + } + MPPE_CI_TO_OPTS(&p[2], ho->mppe); - /* Nak if anything unsupported or unknown are set. */ - if (ho->mppe & MPPE_OPT_UNSUPPORTED) { - newret = CONFNAK; - ho->mppe &= ~MPPE_OPT_UNSUPPORTED; - } - if (ho->mppe & MPPE_OPT_UNKNOWN) { - newret = CONFNAK; - ho->mppe &= ~MPPE_OPT_UNKNOWN; - } + /* Nak if anything unsupported or unknown are set. */ + if (ho->mppe & MPPE_OPT_UNSUPPORTED) { + newret = CONFNAK; + ho->mppe &= ~MPPE_OPT_UNSUPPORTED; + } + if (ho->mppe & MPPE_OPT_UNKNOWN) { + newret = CONFNAK; + ho->mppe &= ~MPPE_OPT_UNKNOWN; + } - /* Check state opt */ - if (ho->mppe & MPPE_OPT_STATEFUL) { - /* - * We can Nak and request stateless, but it's a - * lot easier to just assume the peer will request - * it if he can do it; stateful mode is bad over - * the Internet -- which is where we expect MPPE. - */ - if (pcb->settings.refuse_mppe_stateful) { - ppp_error("Refusing MPPE stateful mode offered by peer"); - newret = CONFREJ; - break; - } - } + /* Check state opt */ + if (ho->mppe & MPPE_OPT_STATEFUL) { + /* + * We can Nak and request stateless, but it's a + * lot easier to just assume the peer will request + * it if he can do it; stateful mode is bad over + * the Internet -- which is where we expect MPPE. + */ + if (pcb->settings.refuse_mppe_stateful) { + ppp_error("Refusing MPPE stateful mode offered by peer"); + newret = CONFREJ; + break; + } + } - /* Find out which of {S,L} are set. */ - if ((ho->mppe & MPPE_OPT_128) - && (ho->mppe & MPPE_OPT_40)) { - /* Both are set, negotiate the strongest. */ - newret = CONFNAK; - if (ao->mppe & MPPE_OPT_128) - ho->mppe &= ~MPPE_OPT_40; - else if (ao->mppe & MPPE_OPT_40) - ho->mppe &= ~MPPE_OPT_128; - else { - newret = CONFREJ; - break; - } - } else if (ho->mppe & MPPE_OPT_128) { - if (!(ao->mppe & MPPE_OPT_128)) { - newret = CONFREJ; - break; - } - } else if (ho->mppe & MPPE_OPT_40) { - if (!(ao->mppe & MPPE_OPT_40)) { - newret = CONFREJ; - break; - } - } else { - /* Neither are set. */ - /* We cannot accept this. */ - newret = CONFNAK; - /* Give the peer our idea of what can be used, - so it can choose and confirm */ - ho->mppe = ao->mppe; - } + /* Find out which of {S,L} are set. */ + if ((ho->mppe & MPPE_OPT_128) + && (ho->mppe & MPPE_OPT_40)) { + /* Both are set, negotiate the strongest. */ + newret = CONFNAK; + if (ao->mppe & MPPE_OPT_128) + ho->mppe &= ~MPPE_OPT_40; + else if (ao->mppe & MPPE_OPT_40) + ho->mppe &= ~MPPE_OPT_128; + else { + newret = CONFREJ; + break; + } + } else if (ho->mppe & MPPE_OPT_128) { + if (!(ao->mppe & MPPE_OPT_128)) { + newret = CONFREJ; + break; + } + } else if (ho->mppe & MPPE_OPT_40) { + if (!(ao->mppe & MPPE_OPT_40)) { + newret = CONFREJ; + break; + } + } else { + /* Neither are set. */ + /* We cannot accept this. */ + newret = CONFNAK; + /* Give the peer our idea of what can be used, + so it can choose and confirm */ + ho->mppe = ao->mppe; + } - /* rebuild the opts */ - MPPE_OPTS_TO_CI(ho->mppe, &p[2]); - if (newret == CONFACK) { - int mtu; + /* rebuild the opts */ + MPPE_OPTS_TO_CI(ho->mppe, &p[2]); + if (newret == CONFACK) { + int mtu; - mppe_init(pcb, &pcb->mppe_comp, ho->mppe); - /* - * We need to decrease the interface MTU by MPPE_PAD - * because MPPE frames **grow**. The kernel [must] - * allocate MPPE_PAD extra bytes in xmit buffers. - */ - mtu = netif_get_mtu(pcb); - if (mtu) - netif_set_mtu(pcb, mtu - MPPE_PAD); - else - newret = CONFREJ; - } + mppe_init(pcb, &pcb->mppe_comp, ho->mppe); + /* + * We need to decrease the interface MTU by MPPE_PAD + * because MPPE frames **grow**. The kernel [must] + * allocate MPPE_PAD extra bytes in xmit buffers. + */ + mtu = netif_get_mtu(pcb); + if (mtu) + netif_set_mtu(pcb, mtu - MPPE_PAD); + else + newret = CONFREJ; + } - /* - * We have accepted MPPE or are willing to negotiate - * MPPE parameters. A CONFREJ is due to subsequent - * (non-MPPE) processing. - */ - rej_for_ci_mppe = 0; - break; + /* + * We have accepted MPPE or are willing to negotiate + * MPPE parameters. A CONFREJ is due to subsequent + * (non-MPPE) processing. + */ + rej_for_ci_mppe = 0; + break; #endif /* MPPE_SUPPORT */ #if DEFLATE_SUPPORT - case CI_DEFLATE: - case CI_DEFLATE_DRAFT: - if (!ao->deflate || clen != CILEN_DEFLATE - || (!ao->deflate_correct && type == CI_DEFLATE) - || (!ao->deflate_draft && type == CI_DEFLATE_DRAFT)) { - newret = CONFREJ; - break; - } + case CI_DEFLATE: + case CI_DEFLATE_DRAFT: + if (!ao->deflate || clen != CILEN_DEFLATE + || (!ao->deflate_correct && type == CI_DEFLATE) + || (!ao->deflate_draft && type == CI_DEFLATE_DRAFT)) { + newret = CONFREJ; + break; + } - ho->deflate = 1; - ho->deflate_size = nb = DEFLATE_SIZE(p[2]); - if (DEFLATE_METHOD(p[2]) != DEFLATE_METHOD_VAL - || p[3] != DEFLATE_CHK_SEQUENCE - || nb > ao->deflate_size || nb < DEFLATE_MIN_WORKS) { - newret = CONFNAK; - if (!dont_nak) { - p[2] = DEFLATE_MAKE_OPT(ao->deflate_size); - p[3] = DEFLATE_CHK_SEQUENCE; - /* fall through to test this #bits below */ - } else - break; - } + ho->deflate = 1; + ho->deflate_size = nb = DEFLATE_SIZE(p[2]); + if (DEFLATE_METHOD(p[2]) != DEFLATE_METHOD_VAL + || p[3] != DEFLATE_CHK_SEQUENCE + || nb > ao->deflate_size || nb < DEFLATE_MIN_WORKS) { + newret = CONFNAK; + if (!dont_nak) { + p[2] = DEFLATE_MAKE_OPT(ao->deflate_size); + p[3] = DEFLATE_CHK_SEQUENCE; + /* fall through to test this #bits below */ + } else + break; + } - /* - * Check whether we can do Deflate with the window - * size they want. If the window is too big, reduce - * it until the kernel can cope and nak with that. - * We only check this for the first option. - */ - if (p == p0) { - for (;;) { - res = ccp_test(pcb, p, CILEN_DEFLATE, 1); - if (res > 0) - break; /* it's OK now */ - if (res < 0 || nb == DEFLATE_MIN_WORKS || dont_nak) { - newret = CONFREJ; - p[2] = DEFLATE_MAKE_OPT(ho->deflate_size); - break; - } - newret = CONFNAK; - --nb; - p[2] = DEFLATE_MAKE_OPT(nb); - } - } - break; + /* + * Check whether we can do Deflate with the window + * size they want. If the window is too big, reduce + * it until the kernel can cope and nak with that. + * We only check this for the first option. + */ + if (p == p0) { + for (;;) { + res = ccp_test(pcb, p, CILEN_DEFLATE, 1); + if (res > 0) + break; /* it's OK now */ + if (res < 0 || nb == DEFLATE_MIN_WORKS || dont_nak) { + newret = CONFREJ; + p[2] = DEFLATE_MAKE_OPT(ho->deflate_size); + break; + } + newret = CONFNAK; + --nb; + p[2] = DEFLATE_MAKE_OPT(nb); + } + } + break; #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT - case CI_BSD_COMPRESS: - if (!ao->bsd_compress || clen != CILEN_BSD_COMPRESS) { - newret = CONFREJ; - break; - } + case CI_BSD_COMPRESS: + if (!ao->bsd_compress || clen != CILEN_BSD_COMPRESS) { + newret = CONFREJ; + break; + } - ho->bsd_compress = 1; - ho->bsd_bits = nb = BSD_NBITS(p[2]); - if (BSD_VERSION(p[2]) != BSD_CURRENT_VERSION - || nb > ao->bsd_bits || nb < BSD_MIN_BITS) { - newret = CONFNAK; - if (!dont_nak) { - p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, ao->bsd_bits); - /* fall through to test this #bits below */ - } else - break; - } + ho->bsd_compress = 1; + ho->bsd_bits = nb = BSD_NBITS(p[2]); + if (BSD_VERSION(p[2]) != BSD_CURRENT_VERSION + || nb > ao->bsd_bits || nb < BSD_MIN_BITS) { + newret = CONFNAK; + if (!dont_nak) { + p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, ao->bsd_bits); + /* fall through to test this #bits below */ + } else + break; + } - /* - * Check whether we can do BSD-Compress with the code - * size they want. If the code size is too big, reduce - * it until the kernel can cope and nak with that. - * We only check this for the first option. - */ - if (p == p0) { - for (;;) { - res = ccp_test(pcb, p, CILEN_BSD_COMPRESS, 1); - if (res > 0) - break; - if (res < 0 || nb == BSD_MIN_BITS || dont_nak) { - newret = CONFREJ; - p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, - ho->bsd_bits); - break; - } - newret = CONFNAK; - --nb; - p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, nb); - } - } - break; + /* + * Check whether we can do BSD-Compress with the code + * size they want. If the code size is too big, reduce + * it until the kernel can cope and nak with that. + * We only check this for the first option. + */ + if (p == p0) { + for (;;) { + res = ccp_test(pcb, p, CILEN_BSD_COMPRESS, 1); + if (res > 0) + break; + if (res < 0 || nb == BSD_MIN_BITS || dont_nak) { + newret = CONFREJ; + p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, + ho->bsd_bits); + break; + } + newret = CONFNAK; + --nb; + p[2] = BSD_MAKE_OPT(BSD_CURRENT_VERSION, nb); + } + } + break; #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT - case CI_PREDICTOR_1: - if (!ao->predictor_1 || clen != CILEN_PREDICTOR_1) { - newret = CONFREJ; - break; - } + case CI_PREDICTOR_1: + if (!ao->predictor_1 || clen != CILEN_PREDICTOR_1) { + newret = CONFREJ; + break; + } - ho->predictor_1 = 1; - if (p == p0 - && ccp_test(pcb, p, CILEN_PREDICTOR_1, 1) <= 0) { - newret = CONFREJ; - } - break; + ho->predictor_1 = 1; + if (p == p0 + && ccp_test(pcb, p, CILEN_PREDICTOR_1, 1) <= 0) { + newret = CONFREJ; + } + break; - case CI_PREDICTOR_2: - if (!ao->predictor_2 || clen != CILEN_PREDICTOR_2) { - newret = CONFREJ; - break; - } + case CI_PREDICTOR_2: + if (!ao->predictor_2 || clen != CILEN_PREDICTOR_2) { + newret = CONFREJ; + break; + } - ho->predictor_2 = 1; - if (p == p0 - && ccp_test(pcb, p, CILEN_PREDICTOR_2, 1) <= 0) { - newret = CONFREJ; - } - break; + ho->predictor_2 = 1; + if (p == p0 + && ccp_test(pcb, p, CILEN_PREDICTOR_2, 1) <= 0) { + newret = CONFREJ; + } + break; #endif /* PREDICTOR_SUPPORT */ - default: - newret = CONFREJ; - } - } + default: + newret = CONFREJ; + } + } - if (newret == CONFNAK && dont_nak) - newret = CONFREJ; - if (!(newret == CONFACK || (newret == CONFNAK && ret == CONFREJ))) { - /* we're returning this option */ - if (newret == CONFREJ && ret == CONFNAK) - retp = p0; - ret = newret; - if (p != retp) - MEMCPY(retp, p, clen); - retp += clen; - } + if (newret == CONFNAK && dont_nak) + newret = CONFREJ; + if (!(newret == CONFACK || (newret == CONFNAK && ret == CONFREJ))) { + /* we're returning this option */ + if (newret == CONFREJ && ret == CONFNAK) + retp = p0; + ret = newret; + if (p != retp) + MEMCPY(retp, p, clen); + retp += clen; + } - p += clen; - len -= clen; + p += clen; + len -= clen; } if (ret != CONFACK) { - if (ret == CONFREJ && *lenp == retp - p0) - pcb->ccp_all_rejected = 1; - else - *lenp = retp - p0; + if (ret == CONFREJ && *lenp == retp - p0) + pcb->ccp_all_rejected = 1; + else + *lenp = retp - p0; } #if MPPE_SUPPORT if (ret == CONFREJ && ao->mppe && rej_for_ci_mppe) { - ppp_error("MPPE required but peer negotiation failed"); - lcp_close(pcb, "MPPE required but peer negotiation failed"); + ppp_error("MPPE required but peer negotiation failed"); + lcp_close(pcb, "MPPE required but peer negotiation failed"); } #endif /* MPPE_SUPPORT */ return ret; @@ -1392,63 +1392,63 @@ static const char *method_name(ccp_options *opt, ccp_options *opt2) { #endif /* !DEFLATE_SUPPORT && !BSDCOMPRESS_SUPPORT */ if (!ccp_anycompress(opt)) - return "(none)"; + return "(none)"; switch (opt->method) { #if MPPE_SUPPORT case CI_MPPE: { - char *p = result; - char *q = result + sizeof(result); /* 1 past result */ + char *p = result; + char *q = result + sizeof(result); /* 1 past result */ - ppp_slprintf(p, q - p, "MPPE "); - p += 5; - if (opt->mppe & MPPE_OPT_128) { - ppp_slprintf(p, q - p, "128-bit "); - p += 8; - } - if (opt->mppe & MPPE_OPT_40) { - ppp_slprintf(p, q - p, "40-bit "); - p += 7; - } - if (opt->mppe & MPPE_OPT_STATEFUL) - ppp_slprintf(p, q - p, "stateful"); - else - ppp_slprintf(p, q - p, "stateless"); + ppp_slprintf(p, q - p, "MPPE "); + p += 5; + if (opt->mppe & MPPE_OPT_128) { + ppp_slprintf(p, q - p, "128-bit "); + p += 8; + } + if (opt->mppe & MPPE_OPT_40) { + ppp_slprintf(p, q - p, "40-bit "); + p += 7; + } + if (opt->mppe & MPPE_OPT_STATEFUL) + ppp_slprintf(p, q - p, "stateful"); + else + ppp_slprintf(p, q - p, "stateless"); - break; + break; } #endif /* MPPE_SUPPORT */ #if DEFLATE_SUPPORT case CI_DEFLATE: case CI_DEFLATE_DRAFT: - if (opt2 != NULL && opt2->deflate_size != opt->deflate_size) - ppp_slprintf(result, sizeof(result), "Deflate%s (%d/%d)", - (opt->method == CI_DEFLATE_DRAFT? "(old#)": ""), - opt->deflate_size, opt2->deflate_size); - else - ppp_slprintf(result, sizeof(result), "Deflate%s (%d)", - (opt->method == CI_DEFLATE_DRAFT? "(old#)": ""), - opt->deflate_size); - break; + if (opt2 != NULL && opt2->deflate_size != opt->deflate_size) + ppp_slprintf(result, sizeof(result), "Deflate%s (%d/%d)", + (opt->method == CI_DEFLATE_DRAFT? "(old#)": ""), + opt->deflate_size, opt2->deflate_size); + else + ppp_slprintf(result, sizeof(result), "Deflate%s (%d)", + (opt->method == CI_DEFLATE_DRAFT? "(old#)": ""), + opt->deflate_size); + break; #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT case CI_BSD_COMPRESS: - if (opt2 != NULL && opt2->bsd_bits != opt->bsd_bits) - ppp_slprintf(result, sizeof(result), "BSD-Compress (%d/%d)", - opt->bsd_bits, opt2->bsd_bits); - else - ppp_slprintf(result, sizeof(result), "BSD-Compress (%d)", - opt->bsd_bits); - break; + if (opt2 != NULL && opt2->bsd_bits != opt->bsd_bits) + ppp_slprintf(result, sizeof(result), "BSD-Compress (%d/%d)", + opt->bsd_bits, opt2->bsd_bits); + else + ppp_slprintf(result, sizeof(result), "BSD-Compress (%d)", + opt->bsd_bits); + break; #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT case CI_PREDICTOR_1: - return "Predictor 1"; + return "Predictor 1"; case CI_PREDICTOR_2: - return "Predictor 2"; + return "Predictor 2"; #endif /* PREDICTOR_SUPPORT */ default: - ppp_slprintf(result, sizeof(result), "Method %d", opt->method); + ppp_slprintf(result, sizeof(result), "Method %d", opt->method); } return result; } @@ -1464,21 +1464,21 @@ static void ccp_up(fsm *f) { ccp_set(pcb, 1, 1, go->method, ho->method); if (ccp_anycompress(go)) { - if (ccp_anycompress(ho)) { - if (go->method == ho->method) { - ppp_notice("%s compression enabled", method_name(go, ho)); - } else { - ppp_strlcpy(method1, method_name(go, NULL), sizeof(method1)); - ppp_notice("%s / %s compression enabled", - method1, method_name(ho, NULL)); - } - } else - ppp_notice("%s receive compression enabled", method_name(go, NULL)); + if (ccp_anycompress(ho)) { + if (go->method == ho->method) { + ppp_notice("%s compression enabled", method_name(go, ho)); + } else { + ppp_strlcpy(method1, method_name(go, NULL), sizeof(method1)); + ppp_notice("%s / %s compression enabled", + method1, method_name(ho, NULL)); + } + } else + ppp_notice("%s receive compression enabled", method_name(go, NULL)); } else if (ccp_anycompress(ho)) - ppp_notice("%s transmit compression enabled", method_name(ho, NULL)); + ppp_notice("%s transmit compression enabled", method_name(ho, NULL)); #if MPPE_SUPPORT if (go->mppe) { - continue_networks(pcb); /* Bring up IP et al */ + continue_networks(pcb); /* Bring up IP et al */ } #endif /* MPPE_SUPPORT */ } @@ -1493,17 +1493,17 @@ static void ccp_down(fsm *f) { #endif /* MPPE_SUPPORT */ if (pcb->ccp_localstate & RACK_PENDING) - UNTIMEOUT(ccp_rack_timeout, f); + UNTIMEOUT(ccp_rack_timeout, f); pcb->ccp_localstate = 0; ccp_set(pcb, 1, 0, 0, 0); #if MPPE_SUPPORT if (go->mppe) { - go->mppe = 0; - if (pcb->lcp_fsm.state == PPP_FSM_OPENED) { - /* If LCP is not already going down, make sure it does. */ - ppp_error("MPPE disabled"); - lcp_close(pcb, "MPPE disabled"); - } + go->mppe = 0; + if (pcb->lcp_fsm.state == PPP_FSM_OPENED) { + /* If LCP is not already going down, make sure it does. */ + ppp_error("MPPE disabled"); + lcp_close(pcb, "MPPE disabled"); + } } #endif /* MPPE_SUPPORT */ } @@ -1526,17 +1526,17 @@ static int ccp_printpkt(const u_char *p, int plen, void (*printer) (void *, cons p0 = p; if (plen < HEADERLEN) - return 0; + return 0; code = p[0]; id = p[1]; len = (p[2] << 8) + p[3]; if (len < HEADERLEN || len > plen) - return 0; + return 0; if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(ccp_codenames) && ccp_codenames[code-1] != NULL) - printer(arg, " %s", ccp_codenames[code-1]); + printer(arg, " %s", ccp_codenames[code-1]); else - printer(arg, " code=0x%x", code); + printer(arg, " code=0x%x", code); printer(arg, " id=0x%x", id); len -= HEADERLEN; p += HEADERLEN; @@ -1546,99 +1546,99 @@ static int ccp_printpkt(const u_char *p, int plen, void (*printer) (void *, cons case CONFACK: case CONFNAK: case CONFREJ: - /* print list of possible compression methods */ - while (len >= 2) { - code = p[0]; - optlen = p[1]; - if (optlen < 2 || optlen > len) - break; - printer(arg, " <"); - len -= optlen; - optend = p + optlen; - switch (code) { + /* print list of possible compression methods */ + while (len >= 2) { + code = p[0]; + optlen = p[1]; + if (optlen < 2 || optlen > len) + break; + printer(arg, " <"); + len -= optlen; + optend = p + optlen; + switch (code) { #if MPPE_SUPPORT - case CI_MPPE: - if (optlen >= CILEN_MPPE) { - u_char mppe_opts; + case CI_MPPE: + if (optlen >= CILEN_MPPE) { + u_char mppe_opts; - MPPE_CI_TO_OPTS(&p[2], mppe_opts); - printer(arg, "mppe %s %s %s %s %s %s%s", - (p[2] & MPPE_H_BIT)? "+H": "-H", - (p[5] & MPPE_M_BIT)? "+M": "-M", - (p[5] & MPPE_S_BIT)? "+S": "-S", - (p[5] & MPPE_L_BIT)? "+L": "-L", - (p[5] & MPPE_D_BIT)? "+D": "-D", - (p[5] & MPPE_C_BIT)? "+C": "-C", - (mppe_opts & MPPE_OPT_UNKNOWN)? " +U": ""); - if (mppe_opts & MPPE_OPT_UNKNOWN) - printer(arg, " (%.2x %.2x %.2x %.2x)", - p[2], p[3], p[4], p[5]); - p += CILEN_MPPE; - } - break; + MPPE_CI_TO_OPTS(&p[2], mppe_opts); + printer(arg, "mppe %s %s %s %s %s %s%s", + (p[2] & MPPE_H_BIT)? "+H": "-H", + (p[5] & MPPE_M_BIT)? "+M": "-M", + (p[5] & MPPE_S_BIT)? "+S": "-S", + (p[5] & MPPE_L_BIT)? "+L": "-L", + (p[5] & MPPE_D_BIT)? "+D": "-D", + (p[5] & MPPE_C_BIT)? "+C": "-C", + (mppe_opts & MPPE_OPT_UNKNOWN)? " +U": ""); + if (mppe_opts & MPPE_OPT_UNKNOWN) + printer(arg, " (%.2x %.2x %.2x %.2x)", + p[2], p[3], p[4], p[5]); + p += CILEN_MPPE; + } + break; #endif /* MPPE_SUPPORT */ #if DEFLATE_SUPPORT - case CI_DEFLATE: - case CI_DEFLATE_DRAFT: - if (optlen >= CILEN_DEFLATE) { - printer(arg, "deflate%s %d", - (code == CI_DEFLATE_DRAFT? "(old#)": ""), - DEFLATE_SIZE(p[2])); - if (DEFLATE_METHOD(p[2]) != DEFLATE_METHOD_VAL) - printer(arg, " method %d", DEFLATE_METHOD(p[2])); - if (p[3] != DEFLATE_CHK_SEQUENCE) - printer(arg, " check %d", p[3]); - p += CILEN_DEFLATE; - } - break; + case CI_DEFLATE: + case CI_DEFLATE_DRAFT: + if (optlen >= CILEN_DEFLATE) { + printer(arg, "deflate%s %d", + (code == CI_DEFLATE_DRAFT? "(old#)": ""), + DEFLATE_SIZE(p[2])); + if (DEFLATE_METHOD(p[2]) != DEFLATE_METHOD_VAL) + printer(arg, " method %d", DEFLATE_METHOD(p[2])); + if (p[3] != DEFLATE_CHK_SEQUENCE) + printer(arg, " check %d", p[3]); + p += CILEN_DEFLATE; + } + break; #endif /* DEFLATE_SUPPORT */ #if BSDCOMPRESS_SUPPORT - case CI_BSD_COMPRESS: - if (optlen >= CILEN_BSD_COMPRESS) { - printer(arg, "bsd v%d %d", BSD_VERSION(p[2]), - BSD_NBITS(p[2])); - p += CILEN_BSD_COMPRESS; - } - break; + case CI_BSD_COMPRESS: + if (optlen >= CILEN_BSD_COMPRESS) { + printer(arg, "bsd v%d %d", BSD_VERSION(p[2]), + BSD_NBITS(p[2])); + p += CILEN_BSD_COMPRESS; + } + break; #endif /* BSDCOMPRESS_SUPPORT */ #if PREDICTOR_SUPPORT - case CI_PREDICTOR_1: - if (optlen >= CILEN_PREDICTOR_1) { - printer(arg, "predictor 1"); - p += CILEN_PREDICTOR_1; - } - break; - case CI_PREDICTOR_2: - if (optlen >= CILEN_PREDICTOR_2) { - printer(arg, "predictor 2"); - p += CILEN_PREDICTOR_2; - } - break; + case CI_PREDICTOR_1: + if (optlen >= CILEN_PREDICTOR_1) { + printer(arg, "predictor 1"); + p += CILEN_PREDICTOR_1; + } + break; + case CI_PREDICTOR_2: + if (optlen >= CILEN_PREDICTOR_2) { + printer(arg, "predictor 2"); + p += CILEN_PREDICTOR_2; + } + break; #endif /* PREDICTOR_SUPPORT */ - default: + default: break; - } - while (p < optend) - printer(arg, " %.2x", *p++); - printer(arg, ">"); - } - break; + } + while (p < optend) + printer(arg, " %.2x", *p++); + printer(arg, ">"); + } + break; case TERMACK: case TERMREQ: - if (len > 0 && *p >= ' ' && *p < 0x7f) { - ppp_print_string(p, len, printer, arg); - p += len; - len = 0; - } - break; + if (len > 0 && *p >= ' ' && *p < 0x7f) { + ppp_print_string(p, len, printer, arg); + p += len; + len = 0; + } + break; default: break; } /* dump out the rest of the packet in hex */ while (--len >= 0) - printer(arg, " %.2x", *p++); + printer(arg, " %.2x", *p++); return p - p0; } @@ -1667,34 +1667,34 @@ static void ccp_datainput(ppp_pcb *pcb, u_char *pkt, int len) { f = &pcb->ccp_fsm; if (f->state == PPP_FSM_OPENED) { - if (ccp_fatal_error(pcb)) { - /* - * Disable compression by taking CCP down. - */ - ppp_error("Lost compression sync: disabling compression"); - ccp_close(pcb, "Lost compression sync"); + if (ccp_fatal_error(pcb)) { + /* + * Disable compression by taking CCP down. + */ + ppp_error("Lost compression sync: disabling compression"); + ccp_close(pcb, "Lost compression sync"); #if MPPE_SUPPORT - /* - * If we were doing MPPE, we must also take the link down. - */ - if (go->mppe) { - ppp_error("Too many MPPE errors, closing LCP"); - lcp_close(pcb, "Too many MPPE errors"); - } + /* + * If we were doing MPPE, we must also take the link down. + */ + if (go->mppe) { + ppp_error("Too many MPPE errors, closing LCP"); + lcp_close(pcb, "Too many MPPE errors"); + } #endif /* MPPE_SUPPORT */ - } else { - /* - * Send a reset-request to reset the peer's compressor. - * We don't do that if we are still waiting for an - * acknowledgement to a previous reset-request. - */ - if (!(pcb->ccp_localstate & RACK_PENDING)) { - fsm_sdata(f, CCP_RESETREQ, f->reqid = ++f->id, NULL, 0); - TIMEOUT(ccp_rack_timeout, f, RACKTIMEOUT); - pcb->ccp_localstate |= RACK_PENDING; - } else - pcb->ccp_localstate |= RREQ_REPEAT; - } + } else { + /* + * Send a reset-request to reset the peer's compressor. + * We don't do that if we are still waiting for an + * acknowledgement to a previous reset-request. + */ + if (!(pcb->ccp_localstate & RACK_PENDING)) { + fsm_sdata(f, CCP_RESETREQ, f->reqid = ++f->id, NULL, 0); + TIMEOUT(ccp_rack_timeout, f, RACKTIMEOUT); + pcb->ccp_localstate |= RACK_PENDING; + } else + pcb->ccp_localstate |= RREQ_REPEAT; + } } } #endif /* PPP_DATAINPUT */ @@ -1707,7 +1707,7 @@ void ccp_resetrequest(ppp_pcb *pcb) { fsm *f = &pcb->ccp_fsm; if (f->state != PPP_FSM_OPENED) - return; + return; /* * Send a reset-request to reset the peer's compressor. @@ -1715,11 +1715,11 @@ void ccp_resetrequest(ppp_pcb *pcb) { * acknowledgement to a previous reset-request. */ if (!(pcb->ccp_localstate & RACK_PENDING)) { - fsm_sdata(f, CCP_RESETREQ, f->reqid = ++f->id, NULL, 0); - TIMEOUT(ccp_rack_timeout, f, RACKTIMEOUT); - pcb->ccp_localstate |= RACK_PENDING; + fsm_sdata(f, CCP_RESETREQ, f->reqid = ++f->id, NULL, 0); + TIMEOUT(ccp_rack_timeout, f, RACKTIMEOUT); + pcb->ccp_localstate |= RACK_PENDING; } else - pcb->ccp_localstate |= RREQ_REPEAT; + pcb->ccp_localstate |= RREQ_REPEAT; } /* @@ -1730,11 +1730,11 @@ static void ccp_rack_timeout(void *arg) { ppp_pcb *pcb = f->pcb; if (f->state == PPP_FSM_OPENED && (pcb->ccp_localstate & RREQ_REPEAT)) { - fsm_sdata(f, CCP_RESETREQ, f->reqid, NULL, 0); - TIMEOUT(ccp_rack_timeout, f, RACKTIMEOUT); - pcb->ccp_localstate &= ~RREQ_REPEAT; + fsm_sdata(f, CCP_RESETREQ, f->reqid, NULL, 0); + TIMEOUT(ccp_rack_timeout, f, RACKTIMEOUT); + pcb->ccp_localstate &= ~RREQ_REPEAT; } else - pcb->ccp_localstate &= ~RACK_PENDING; + pcb->ccp_localstate &= ~RACK_PENDING; } #endif /* PPP_SUPPORT && CCP_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/chap-md5.c b/components/network/lwip/src/netif/ppp/chap-md5.c index 88f069f0..2b7c9b36 100644 --- a/components/network/lwip/src/netif/ppp/chap-md5.c +++ b/components/network/lwip/src/netif/ppp/chap-md5.c @@ -43,84 +43,84 @@ #include "netif/ppp/magic.h" #include "netif/ppp/pppcrypt.h" -#define MD5_HASH_SIZE 16 -#define MD5_MIN_CHALLENGE 17 -#define MD5_MAX_CHALLENGE 24 +#define MD5_HASH_SIZE 16 +#define MD5_MIN_CHALLENGE 17 +#define MD5_MAX_CHALLENGE 24 #define MD5_MIN_MAX_POWER_OF_TWO_CHALLENGE 3 /* 2^3-1 = 7, 17+7 = 24 */ #if PPP_SERVER static void chap_md5_generate_challenge(ppp_pcb *pcb, unsigned char *cp) { - int clen; - LWIP_UNUSED_ARG(pcb); + int clen; + LWIP_UNUSED_ARG(pcb); - clen = MD5_MIN_CHALLENGE + magic_pow(MD5_MIN_MAX_POWER_OF_TWO_CHALLENGE); - *cp++ = clen; - magic_random_bytes(cp, clen); + clen = MD5_MIN_CHALLENGE + magic_pow(MD5_MIN_MAX_POWER_OF_TWO_CHALLENGE); + *cp++ = clen; + magic_random_bytes(cp, clen); } static int chap_md5_verify_response(ppp_pcb *pcb, int id, const char *name, - const unsigned char *secret, int secret_len, - const unsigned char *challenge, const unsigned char *response, - char *message, int message_space) { - lwip_md5_context ctx; - unsigned char idbyte = id; - unsigned char hash[MD5_HASH_SIZE]; - int challenge_len, response_len; - LWIP_UNUSED_ARG(name); - LWIP_UNUSED_ARG(pcb); + const unsigned char *secret, int secret_len, + const unsigned char *challenge, const unsigned char *response, + char *message, int message_space) { + lwip_md5_context ctx; + unsigned char idbyte = id; + unsigned char hash[MD5_HASH_SIZE]; + int challenge_len, response_len; + LWIP_UNUSED_ARG(name); + LWIP_UNUSED_ARG(pcb); - challenge_len = *challenge++; - response_len = *response++; - if (response_len == MD5_HASH_SIZE) { - /* Generate hash of ID, secret, challenge */ - lwip_md5_init(&ctx); - lwip_md5_starts(&ctx); - lwip_md5_update(&ctx, &idbyte, 1); - lwip_md5_update(&ctx, secret, secret_len); - lwip_md5_update(&ctx, challenge, challenge_len); - lwip_md5_finish(&ctx, hash); - lwip_md5_free(&ctx); + challenge_len = *challenge++; + response_len = *response++; + if (response_len == MD5_HASH_SIZE) { + /* Generate hash of ID, secret, challenge */ + lwip_md5_init(&ctx); + lwip_md5_starts(&ctx); + lwip_md5_update(&ctx, &idbyte, 1); + lwip_md5_update(&ctx, secret, secret_len); + lwip_md5_update(&ctx, challenge, challenge_len); + lwip_md5_finish(&ctx, hash); + lwip_md5_free(&ctx); - /* Test if our hash matches the peer's response */ - if (memcmp(hash, response, MD5_HASH_SIZE) == 0) { - ppp_slprintf(message, message_space, "Access granted"); - return 1; - } - } - ppp_slprintf(message, message_space, "Access denied"); - return 0; + /* Test if our hash matches the peer's response */ + if (memcmp(hash, response, MD5_HASH_SIZE) == 0) { + ppp_slprintf(message, message_space, "Access granted"); + return 1; + } + } + ppp_slprintf(message, message_space, "Access denied"); + return 0; } #endif /* PPP_SERVER */ static void chap_md5_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name, - const unsigned char *challenge, const char *secret, int secret_len, - unsigned char *private_) { - lwip_md5_context ctx; - unsigned char idbyte = id; - int challenge_len = *challenge++; - LWIP_UNUSED_ARG(our_name); - LWIP_UNUSED_ARG(private_); - LWIP_UNUSED_ARG(pcb); + const unsigned char *challenge, const char *secret, int secret_len, + unsigned char *private_) { + lwip_md5_context ctx; + unsigned char idbyte = id; + int challenge_len = *challenge++; + LWIP_UNUSED_ARG(our_name); + LWIP_UNUSED_ARG(private_); + LWIP_UNUSED_ARG(pcb); - lwip_md5_init(&ctx); - lwip_md5_starts(&ctx); - lwip_md5_update(&ctx, &idbyte, 1); - lwip_md5_update(&ctx, (const u_char *)secret, secret_len); - lwip_md5_update(&ctx, challenge, challenge_len); - lwip_md5_finish(&ctx, &response[1]); - lwip_md5_free(&ctx); - response[0] = MD5_HASH_SIZE; + lwip_md5_init(&ctx); + lwip_md5_starts(&ctx); + lwip_md5_update(&ctx, &idbyte, 1); + lwip_md5_update(&ctx, (const u_char *)secret, secret_len); + lwip_md5_update(&ctx, challenge, challenge_len); + lwip_md5_finish(&ctx, &response[1]); + lwip_md5_free(&ctx); + response[0] = MD5_HASH_SIZE; } const struct chap_digest_type md5_digest = { - CHAP_MD5, /* code */ + CHAP_MD5, /* code */ #if PPP_SERVER - chap_md5_generate_challenge, - chap_md5_verify_response, + chap_md5_generate_challenge, + chap_md5_verify_response, #endif /* PPP_SERVER */ - chap_md5_make_response, - NULL, /* check_success */ - NULL, /* handle_failure */ + chap_md5_make_response, + NULL, /* check_success */ + NULL, /* handle_failure */ }; #endif /* PPP_SUPPORT && CHAP_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/chap-new.c b/components/network/lwip/src/netif/ppp/chap-new.c index 485122d2..e599f3eb 100644 --- a/components/network/lwip/src/netif/ppp/chap-new.c +++ b/components/network/lwip/src/netif/ppp/chap-new.c @@ -52,9 +52,9 @@ #if 0 /* UNUSED */ /* Hook for a plugin to validate CHAP challenge */ int (*chap_verify_hook)(const char *name, const char *ourname, int id, - const struct chap_digest_type *digest, - const unsigned char *challenge, const unsigned char *response, - char *message, int message_space) = NULL; + const struct chap_digest_type *digest, + const unsigned char *challenge, const unsigned char *response, + char *message, int message_space) = NULL; #endif /* UNUSED */ #if PPP_OPTIONS @@ -62,24 +62,24 @@ int (*chap_verify_hook)(const char *name, const char *ourname, int id, * Command-line options. */ static option_t chap_option_list[] = { - { "chap-restart", o_int, &chap_timeout_time, - "Set timeout for CHAP", OPT_PRIO }, - { "chap-max-challenge", o_int, &pcb->settings.chap_max_transmits, - "Set max #xmits for challenge", OPT_PRIO }, - { "chap-interval", o_int, &pcb->settings.chap_rechallenge_time, - "Set interval for rechallenge", OPT_PRIO }, - { NULL } + { "chap-restart", o_int, &chap_timeout_time, + "Set timeout for CHAP", OPT_PRIO }, + { "chap-max-challenge", o_int, &pcb->settings.chap_max_transmits, + "Set max #xmits for challenge", OPT_PRIO }, + { "chap-interval", o_int, &pcb->settings.chap_rechallenge_time, + "Set interval for rechallenge", OPT_PRIO }, + { NULL } }; #endif /* PPP_OPTIONS */ /* Values for flags in chap_client_state and chap_server_state */ -#define LOWERUP 1 -#define AUTH_STARTED 2 -#define AUTH_DONE 4 -#define AUTH_FAILED 8 -#define TIMEOUT_PENDING 0x10 -#define CHALLENGE_VALID 0x20 +#define LOWERUP 1 +#define AUTH_STARTED 2 +#define AUTH_DONE 4 +#define AUTH_FAILED 8 +#define TIMEOUT_PENDING 0x10 +#define CHALLENGE_VALID 0x20 /* * Prototypes. @@ -91,21 +91,21 @@ static void chap_lowerdown(ppp_pcb *pcb); static void chap_timeout(void *arg); static void chap_generate_challenge(ppp_pcb *pcb); static void chap_handle_response(ppp_pcb *pcb, int code, - unsigned char *pkt, int len); + unsigned char *pkt, int len); static int chap_verify_response(ppp_pcb *pcb, const char *name, const char *ourname, int id, - const struct chap_digest_type *digest, - const unsigned char *challenge, const unsigned char *response, - char *message, int message_space); + const struct chap_digest_type *digest, + const unsigned char *challenge, const unsigned char *response, + char *message, int message_space); #endif /* PPP_SERVER */ static void chap_respond(ppp_pcb *pcb, int id, - unsigned char *pkt, int len); + unsigned char *pkt, int len); static void chap_handle_status(ppp_pcb *pcb, int code, int id, - unsigned char *pkt, int len); + unsigned char *pkt, int len); static void chap_protrej(ppp_pcb *pcb); static void chap_input(ppp_pcb *pcb, unsigned char *pkt, int pktlen); #if PRINTPKT_SUPPORT static int chap_print_pkt(const unsigned char *p, int plen, - void (*printer) (void *, const char *, ...), void *arg); + void (*printer) (void *, const char *, ...), void *arg); #endif /* PRINTPKT_SUPPORT */ /* List of digest types that we know about */ @@ -122,12 +122,12 @@ static const struct chap_digest_type* const chap_digests[] = { * chap_init - reset to initial state. */ static void chap_init(ppp_pcb *pcb) { - LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(pcb); #if 0 /* Not necessary, everything is cleared in ppp_new() */ - memset(&pcb->chap_client, 0, sizeof(chap_client_state)); + memset(&pcb->chap_client, 0, sizeof(chap_client_state)); #if PPP_SERVER - memset(&pcb->chap_server, 0, sizeof(chap_server_state)); + memset(&pcb->chap_server, 0, sizeof(chap_server_state)); #endif /* PPP_SERVER */ #endif /* 0 */ } @@ -137,21 +137,21 @@ static void chap_init(ppp_pcb *pcb) { */ static void chap_lowerup(ppp_pcb *pcb) { - pcb->chap_client.flags |= LOWERUP; + pcb->chap_client.flags |= LOWERUP; #if PPP_SERVER - pcb->chap_server.flags |= LOWERUP; - if (pcb->chap_server.flags & AUTH_STARTED) - chap_timeout(pcb); + pcb->chap_server.flags |= LOWERUP; + if (pcb->chap_server.flags & AUTH_STARTED) + chap_timeout(pcb); #endif /* PPP_SERVER */ } static void chap_lowerdown(ppp_pcb *pcb) { - pcb->chap_client.flags = 0; + pcb->chap_client.flags = 0; #if PPP_SERVER - if (pcb->chap_server.flags & TIMEOUT_PENDING) - UNTIMEOUT(chap_timeout, pcb); - pcb->chap_server.flags = 0; + if (pcb->chap_server.flags & TIMEOUT_PENDING) + UNTIMEOUT(chap_timeout, pcb); + pcb->chap_server.flags = 0; #endif /* PPP_SERVER */ } @@ -162,27 +162,27 @@ static void chap_lowerdown(ppp_pcb *pcb) { * otherwise we wait for the lower layer to come up. */ void chap_auth_peer(ppp_pcb *pcb, const char *our_name, int digest_code) { - const struct chap_digest_type *dp; - int i; + const struct chap_digest_type *dp; + int i; - if (pcb->chap_server.flags & AUTH_STARTED) { - ppp_error("CHAP: peer authentication already started!"); - return; - } - for (i = 0; (dp = chap_digests[i]) != NULL; ++i) - if (dp->code == digest_code) - break; - if (dp == NULL) - ppp_fatal("CHAP digest 0x%x requested but not available", - digest_code); + if (pcb->chap_server.flags & AUTH_STARTED) { + ppp_error("CHAP: peer authentication already started!"); + return; + } + for (i = 0; (dp = chap_digests[i]) != NULL; ++i) + if (dp->code == digest_code) + break; + if (dp == NULL) + ppp_fatal("CHAP digest 0x%x requested but not available", + digest_code); - pcb->chap_server.digest = dp; - pcb->chap_server.name = our_name; - /* Start with a random ID value */ - pcb->chap_server.id = magic(); - pcb->chap_server.flags |= AUTH_STARTED; - if (pcb->chap_server.flags & LOWERUP) - chap_timeout(pcb); + pcb->chap_server.digest = dp; + pcb->chap_server.name = our_name; + /* Start with a random ID value */ + pcb->chap_server.id = magic(); + pcb->chap_server.flags |= AUTH_STARTED; + if (pcb->chap_server.flags & LOWERUP) + chap_timeout(pcb); } #endif /* PPP_SERVER */ @@ -191,27 +191,27 @@ void chap_auth_peer(ppp_pcb *pcb, const char *our_name, int digest_code) { * There isn't much to do until we receive a challenge. */ void chap_auth_with_peer(ppp_pcb *pcb, const char *our_name, int digest_code) { - const struct chap_digest_type *dp; - int i; + const struct chap_digest_type *dp; + int i; - if(NULL == our_name) - return; + if(NULL == our_name) + return; - if (pcb->chap_client.flags & AUTH_STARTED) { - ppp_error("CHAP: authentication with peer already started!"); - return; - } - for (i = 0; (dp = chap_digests[i]) != NULL; ++i) - if (dp->code == digest_code) - break; + if (pcb->chap_client.flags & AUTH_STARTED) { + ppp_error("CHAP: authentication with peer already started!"); + return; + } + for (i = 0; (dp = chap_digests[i]) != NULL; ++i) + if (dp->code == digest_code) + break; - if (dp == NULL) - ppp_fatal("CHAP digest 0x%x requested but not available", - digest_code); + if (dp == NULL) + ppp_fatal("CHAP digest 0x%x requested but not available", + digest_code); - pcb->chap_client.digest = dp; - pcb->chap_client.name = our_name; - pcb->chap_client.flags |= AUTH_STARTED; + pcb->chap_client.digest = dp; + pcb->chap_client.name = our_name; + pcb->chap_client.flags |= AUTH_STARTED; } #if PPP_SERVER @@ -221,33 +221,33 @@ void chap_auth_with_peer(ppp_pcb *pcb, const char *our_name, int digest_code) { * or a new challenge to start re-authentication. */ static void chap_timeout(void *arg) { - ppp_pcb *pcb = (ppp_pcb*)arg; - struct pbuf *p; + ppp_pcb *pcb = (ppp_pcb*)arg; + struct pbuf *p; - pcb->chap_server.flags &= ~TIMEOUT_PENDING; - if ((pcb->chap_server.flags & CHALLENGE_VALID) == 0) { - pcb->chap_server.challenge_xmits = 0; - chap_generate_challenge(pcb); - pcb->chap_server.flags |= CHALLENGE_VALID; - } else if (pcb->chap_server.challenge_xmits >= pcb->settings.chap_max_transmits) { - pcb->chap_server.flags &= ~CHALLENGE_VALID; - pcb->chap_server.flags |= AUTH_DONE | AUTH_FAILED; - auth_peer_fail(pcb, PPP_CHAP); - return; - } + pcb->chap_server.flags &= ~TIMEOUT_PENDING; + if ((pcb->chap_server.flags & CHALLENGE_VALID) == 0) { + pcb->chap_server.challenge_xmits = 0; + chap_generate_challenge(pcb); + pcb->chap_server.flags |= CHALLENGE_VALID; + } else if (pcb->chap_server.challenge_xmits >= pcb->settings.chap_max_transmits) { + pcb->chap_server.flags &= ~CHALLENGE_VALID; + pcb->chap_server.flags |= AUTH_DONE | AUTH_FAILED; + auth_peer_fail(pcb, PPP_CHAP); + return; + } - p = pbuf_alloc(PBUF_RAW, (u16_t)(pcb->chap_server.challenge_pktlen), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } - MEMCPY(p->payload, pcb->chap_server.challenge, pcb->chap_server.challenge_pktlen); - ppp_write(pcb, p); - ++pcb->chap_server.challenge_xmits; - pcb->chap_server.flags |= TIMEOUT_PENDING; - TIMEOUT(chap_timeout, arg, pcb->settings.chap_timeout_time); + p = pbuf_alloc(PBUF_RAW, (u16_t)(pcb->chap_server.challenge_pktlen), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } + MEMCPY(p->payload, pcb->chap_server.challenge, pcb->chap_server.challenge_pktlen); + ppp_write(pcb, p); + ++pcb->chap_server.challenge_xmits; + pcb->chap_server.flags |= TIMEOUT_PENDING; + TIMEOUT(chap_timeout, arg, pcb->settings.chap_timeout_time); } /* @@ -255,152 +255,152 @@ static void chap_timeout(void *arg) { * the challenge packet in pcb->chap_server.challenge_pkt. */ static void chap_generate_challenge(ppp_pcb *pcb) { - int clen = 1, nlen, len; - unsigned char *p; + int clen = 1, nlen, len; + unsigned char *p; - p = pcb->chap_server.challenge; - MAKEHEADER(p, PPP_CHAP); - p += CHAP_HDRLEN; - pcb->chap_server.digest->generate_challenge(pcb, p); - clen = *p; - nlen = strlen(pcb->chap_server.name); - memcpy(p + 1 + clen, pcb->chap_server.name, nlen); + p = pcb->chap_server.challenge; + MAKEHEADER(p, PPP_CHAP); + p += CHAP_HDRLEN; + pcb->chap_server.digest->generate_challenge(pcb, p); + clen = *p; + nlen = strlen(pcb->chap_server.name); + memcpy(p + 1 + clen, pcb->chap_server.name, nlen); - len = CHAP_HDRLEN + 1 + clen + nlen; - pcb->chap_server.challenge_pktlen = PPP_HDRLEN + len; + len = CHAP_HDRLEN + 1 + clen + nlen; + pcb->chap_server.challenge_pktlen = PPP_HDRLEN + len; - p = pcb->chap_server.challenge + PPP_HDRLEN; - p[0] = CHAP_CHALLENGE; - p[1] = ++pcb->chap_server.id; - p[2] = len >> 8; - p[3] = len; + p = pcb->chap_server.challenge + PPP_HDRLEN; + p[0] = CHAP_CHALLENGE; + p[1] = ++pcb->chap_server.id; + p[2] = len >> 8; + p[3] = len; } /* * chap_handle_response - check the response to our challenge. */ static void chap_handle_response(ppp_pcb *pcb, int id, - unsigned char *pkt, int len) { - int response_len, ok, mlen; - const unsigned char *response; - unsigned char *outp; - struct pbuf *p; - const char *name = NULL; /* initialized to shut gcc up */ + unsigned char *pkt, int len) { + int response_len, ok, mlen; + const unsigned char *response; + unsigned char *outp; + struct pbuf *p; + const char *name = NULL; /* initialized to shut gcc up */ #if 0 /* UNUSED */ - int (*verifier)(const char *, const char *, int, const struct chap_digest_type *, - const unsigned char *, const unsigned char *, char *, int); + int (*verifier)(const char *, const char *, int, const struct chap_digest_type *, + const unsigned char *, const unsigned char *, char *, int); #endif /* UNUSED */ - char rname[MAXNAMELEN+1]; - char message[256]; + char rname[MAXNAMELEN+1]; + char message[256]; - if ((pcb->chap_server.flags & LOWERUP) == 0) - return; - if (id != pcb->chap_server.challenge[PPP_HDRLEN+1] || len < 2) - return; - if (pcb->chap_server.flags & CHALLENGE_VALID) { - response = pkt; - GETCHAR(response_len, pkt); - len -= response_len + 1; /* length of name */ - name = (char *)pkt + response_len; - if (len < 0) - return; + if ((pcb->chap_server.flags & LOWERUP) == 0) + return; + if (id != pcb->chap_server.challenge[PPP_HDRLEN+1] || len < 2) + return; + if (pcb->chap_server.flags & CHALLENGE_VALID) { + response = pkt; + GETCHAR(response_len, pkt); + len -= response_len + 1; /* length of name */ + name = (char *)pkt + response_len; + if (len < 0) + return; - if (pcb->chap_server.flags & TIMEOUT_PENDING) { - pcb->chap_server.flags &= ~TIMEOUT_PENDING; - UNTIMEOUT(chap_timeout, pcb); - } + if (pcb->chap_server.flags & TIMEOUT_PENDING) { + pcb->chap_server.flags &= ~TIMEOUT_PENDING; + UNTIMEOUT(chap_timeout, pcb); + } #if PPP_REMOTENAME - if (pcb->settings.explicit_remote) { - name = pcb->remote_name; - } else + if (pcb->settings.explicit_remote) { + name = pcb->remote_name; + } else #endif /* PPP_REMOTENAME */ - { - /* Null terminate and clean remote name. */ - ppp_slprintf(rname, sizeof(rname), "%.*v", len, name); - name = rname; - } + { + /* Null terminate and clean remote name. */ + ppp_slprintf(rname, sizeof(rname), "%.*v", len, name); + name = rname; + } #if 0 /* UNUSED */ - if (chap_verify_hook) - verifier = chap_verify_hook; - else - verifier = chap_verify_response; - ok = (*verifier)(name, pcb->chap_server.name, id, pcb->chap_server.digest, - pcb->chap_server.challenge + PPP_HDRLEN + CHAP_HDRLEN, - response, pcb->chap_server.message, sizeof(pcb->chap_server.message)); + if (chap_verify_hook) + verifier = chap_verify_hook; + else + verifier = chap_verify_response; + ok = (*verifier)(name, pcb->chap_server.name, id, pcb->chap_server.digest, + pcb->chap_server.challenge + PPP_HDRLEN + CHAP_HDRLEN, + response, pcb->chap_server.message, sizeof(pcb->chap_server.message)); #endif /* UNUSED */ - ok = chap_verify_response(pcb, name, pcb->chap_server.name, id, pcb->chap_server.digest, + ok = chap_verify_response(pcb, name, pcb->chap_server.name, id, pcb->chap_server.digest, pcb->chap_server.challenge + PPP_HDRLEN + CHAP_HDRLEN, response, message, sizeof(message)); #if 0 /* UNUSED */ - if (!ok || !auth_number()) { + if (!ok || !auth_number()) { #endif /* UNUSED */ - if (!ok) { - pcb->chap_server.flags |= AUTH_FAILED; - ppp_warn("Peer %q failed CHAP authentication", name); - } - } else if ((pcb->chap_server.flags & AUTH_DONE) == 0) - return; + if (!ok) { + pcb->chap_server.flags |= AUTH_FAILED; + ppp_warn("Peer %q failed CHAP authentication", name); + } + } else if ((pcb->chap_server.flags & AUTH_DONE) == 0) + return; - /* send the response */ - mlen = strlen(message); - len = CHAP_HDRLEN + mlen; - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN +len), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + /* send the response */ + mlen = strlen(message); + len = CHAP_HDRLEN + mlen; + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN +len), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = (unsigned char *)p->payload; - MAKEHEADER(outp, PPP_CHAP); + outp = (unsigned char *)p->payload; + MAKEHEADER(outp, PPP_CHAP); - outp[0] = (pcb->chap_server.flags & AUTH_FAILED)? CHAP_FAILURE: CHAP_SUCCESS; - outp[1] = id; - outp[2] = len >> 8; - outp[3] = len; - if (mlen > 0) - memcpy(outp + CHAP_HDRLEN, message, mlen); - ppp_write(pcb, p); + outp[0] = (pcb->chap_server.flags & AUTH_FAILED)? CHAP_FAILURE: CHAP_SUCCESS; + outp[1] = id; + outp[2] = len >> 8; + outp[3] = len; + if (mlen > 0) + memcpy(outp + CHAP_HDRLEN, message, mlen); + ppp_write(pcb, p); - if (pcb->chap_server.flags & CHALLENGE_VALID) { - pcb->chap_server.flags &= ~CHALLENGE_VALID; - if (!(pcb->chap_server.flags & AUTH_DONE) && !(pcb->chap_server.flags & AUTH_FAILED)) { + if (pcb->chap_server.flags & CHALLENGE_VALID) { + pcb->chap_server.flags &= ~CHALLENGE_VALID; + if (!(pcb->chap_server.flags & AUTH_DONE) && !(pcb->chap_server.flags & AUTH_FAILED)) { #if 0 /* UNUSED */ - /* - * Auth is OK, so now we need to check session restrictions - * to ensure everything is OK, but only if we used a - * plugin, and only if we're configured to check. This - * allows us to do PAM checks on PPP servers that - * authenticate against ActiveDirectory, and use AD for - * account info (like when using Winbind integrated with - * PAM). - */ - if (session_mgmt && - session_check(name, NULL, devnam, NULL) == 0) { - pcb->chap_server.flags |= AUTH_FAILED; - ppp_warn("Peer %q failed CHAP Session verification", name); - } + /* + * Auth is OK, so now we need to check session restrictions + * to ensure everything is OK, but only if we used a + * plugin, and only if we're configured to check. This + * allows us to do PAM checks on PPP servers that + * authenticate against ActiveDirectory, and use AD for + * account info (like when using Winbind integrated with + * PAM). + */ + if (session_mgmt && + session_check(name, NULL, devnam, NULL) == 0) { + pcb->chap_server.flags |= AUTH_FAILED; + ppp_warn("Peer %q failed CHAP Session verification", name); + } #endif /* UNUSED */ - } - if (pcb->chap_server.flags & AUTH_FAILED) { - auth_peer_fail(pcb, PPP_CHAP); - } else { - if ((pcb->chap_server.flags & AUTH_DONE) == 0) - auth_peer_success(pcb, PPP_CHAP, - pcb->chap_server.digest->code, - name, strlen(name)); - if (pcb->settings.chap_rechallenge_time) { - pcb->chap_server.flags |= TIMEOUT_PENDING; - TIMEOUT(chap_timeout, pcb, - pcb->settings.chap_rechallenge_time); - } - } - pcb->chap_server.flags |= AUTH_DONE; - } + } + if (pcb->chap_server.flags & AUTH_FAILED) { + auth_peer_fail(pcb, PPP_CHAP); + } else { + if ((pcb->chap_server.flags & AUTH_DONE) == 0) + auth_peer_success(pcb, PPP_CHAP, + pcb->chap_server.digest->code, + name, strlen(name)); + if (pcb->settings.chap_rechallenge_time) { + pcb->chap_server.flags |= TIMEOUT_PENDING; + TIMEOUT(chap_timeout, pcb, + pcb->settings.chap_rechallenge_time); + } + } + pcb->chap_server.flags |= AUTH_DONE; + } } /* @@ -409,23 +409,23 @@ static void chap_handle_response(ppp_pcb *pcb, int id, * succeeded), or 0 if it doesn't. */ static int chap_verify_response(ppp_pcb *pcb, const char *name, const char *ourname, int id, - const struct chap_digest_type *digest, - const unsigned char *challenge, const unsigned char *response, - char *message, int message_space) { - int ok; - unsigned char secret[MAXSECRETLEN]; - int secret_len; + const struct chap_digest_type *digest, + const unsigned char *challenge, const unsigned char *response, + char *message, int message_space) { + int ok; + unsigned char secret[MAXSECRETLEN]; + int secret_len; - /* Get the secret that the peer is supposed to know */ - if (!get_secret(pcb, name, ourname, (char *)secret, &secret_len, 1)) { - ppp_error("No CHAP secret found for authenticating %q", name); - return 0; - } - ok = digest->verify_response(pcb, id, name, secret, secret_len, challenge, - response, message, message_space); - memset(secret, 0, sizeof(secret)); + /* Get the secret that the peer is supposed to know */ + if (!get_secret(pcb, name, ourname, (char *)secret, &secret_len, 1)) { + ppp_error("No CHAP secret found for authenticating %q", name); + return 0; + } + ok = digest->verify_response(pcb, id, name, secret, secret_len, challenge, + response, message, message_space); + memset(secret, 0, sizeof(secret)); - return ok; + return ok; } #endif /* PPP_SERVER */ @@ -433,153 +433,153 @@ static int chap_verify_response(ppp_pcb *pcb, const char *name, const char *ourn * chap_respond - Generate and send a response to a challenge. */ static void chap_respond(ppp_pcb *pcb, int id, - unsigned char *pkt, int len) { - int clen, nlen; - int secret_len; - struct pbuf *p; - u_char *outp; - char rname[MAXNAMELEN+1]; - char secret[MAXSECRETLEN+1]; + unsigned char *pkt, int len) { + int clen, nlen; + int secret_len; + struct pbuf *p; + u_char *outp; + char rname[MAXNAMELEN+1]; + char secret[MAXSECRETLEN+1]; - p = pbuf_alloc(PBUF_RAW, (u16_t)(RESP_MAX_PKTLEN), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + p = pbuf_alloc(PBUF_RAW, (u16_t)(RESP_MAX_PKTLEN), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - if ((pcb->chap_client.flags & (LOWERUP | AUTH_STARTED)) != (LOWERUP | AUTH_STARTED)) - return; /* not ready */ - if (len < 2 || len < pkt[0] + 1) - return; /* too short */ - clen = pkt[0]; - nlen = len - (clen + 1); + if ((pcb->chap_client.flags & (LOWERUP | AUTH_STARTED)) != (LOWERUP | AUTH_STARTED)) + return; /* not ready */ + if (len < 2 || len < pkt[0] + 1) + return; /* too short */ + clen = pkt[0]; + nlen = len - (clen + 1); - /* Null terminate and clean remote name. */ - ppp_slprintf(rname, sizeof(rname), "%.*v", nlen, pkt + clen + 1); + /* Null terminate and clean remote name. */ + ppp_slprintf(rname, sizeof(rname), "%.*v", nlen, pkt + clen + 1); #if PPP_REMOTENAME - /* Microsoft doesn't send their name back in the PPP packet */ - if (pcb->settings.explicit_remote || (pcb->settings.remote_name[0] != 0 && rname[0] == 0)) - strlcpy(rname, pcb->settings.remote_name, sizeof(rname)); + /* Microsoft doesn't send their name back in the PPP packet */ + if (pcb->settings.explicit_remote || (pcb->settings.remote_name[0] != 0 && rname[0] == 0)) + strlcpy(rname, pcb->settings.remote_name, sizeof(rname)); #endif /* PPP_REMOTENAME */ - /* get secret for authenticating ourselves with the specified host */ - if (!get_secret(pcb, pcb->chap_client.name, rname, secret, &secret_len, 0)) { - secret_len = 0; /* assume null secret if can't find one */ - ppp_warn("No CHAP secret found for authenticating us to %q", rname); - } + /* get secret for authenticating ourselves with the specified host */ + if (!get_secret(pcb, pcb->chap_client.name, rname, secret, &secret_len, 0)) { + secret_len = 0; /* assume null secret if can't find one */ + ppp_warn("No CHAP secret found for authenticating us to %q", rname); + } - outp = (u_char*)p->payload; - MAKEHEADER(outp, PPP_CHAP); - outp += CHAP_HDRLEN; + outp = (u_char*)p->payload; + MAKEHEADER(outp, PPP_CHAP); + outp += CHAP_HDRLEN; - pcb->chap_client.digest->make_response(pcb, outp, id, pcb->chap_client.name, pkt, - secret, secret_len, pcb->chap_client.priv); - memset(secret, 0, secret_len); + pcb->chap_client.digest->make_response(pcb, outp, id, pcb->chap_client.name, pkt, + secret, secret_len, pcb->chap_client.priv); + memset(secret, 0, secret_len); - clen = *outp; - nlen = strlen(pcb->chap_client.name); - memcpy(outp + clen + 1, pcb->chap_client.name, nlen); + clen = *outp; + nlen = strlen(pcb->chap_client.name); + memcpy(outp + clen + 1, pcb->chap_client.name, nlen); - outp = (u_char*)p->payload + PPP_HDRLEN; - len = CHAP_HDRLEN + clen + 1 + nlen; - outp[0] = CHAP_RESPONSE; - outp[1] = id; - outp[2] = len >> 8; - outp[3] = len; + outp = (u_char*)p->payload + PPP_HDRLEN; + len = CHAP_HDRLEN + clen + 1 + nlen; + outp[0] = CHAP_RESPONSE; + outp[1] = id; + outp[2] = len >> 8; + outp[3] = len; - pbuf_realloc(p, PPP_HDRLEN + len); - ppp_write(pcb, p); + pbuf_realloc(p, PPP_HDRLEN + len); + ppp_write(pcb, p); } static void chap_handle_status(ppp_pcb *pcb, int code, int id, - unsigned char *pkt, int len) { - const char *msg = NULL; - LWIP_UNUSED_ARG(id); + unsigned char *pkt, int len) { + const char *msg = NULL; + LWIP_UNUSED_ARG(id); - if ((pcb->chap_client.flags & (AUTH_DONE|AUTH_STARTED|LOWERUP)) - != (AUTH_STARTED|LOWERUP)) - return; - pcb->chap_client.flags |= AUTH_DONE; + if ((pcb->chap_client.flags & (AUTH_DONE|AUTH_STARTED|LOWERUP)) + != (AUTH_STARTED|LOWERUP)) + return; + pcb->chap_client.flags |= AUTH_DONE; - if (code == CHAP_SUCCESS) { - /* used for MS-CHAP v2 mutual auth, yuck */ - if (pcb->chap_client.digest->check_success != NULL) { - if (!(*pcb->chap_client.digest->check_success)(pcb, pkt, len, pcb->chap_client.priv)) - code = CHAP_FAILURE; - } else - msg = "CHAP authentication succeeded"; - } else { - if (pcb->chap_client.digest->handle_failure != NULL) - (*pcb->chap_client.digest->handle_failure)(pcb, pkt, len); - else - msg = "CHAP authentication failed"; - } - if (msg) { - if (len > 0) - ppp_info("%s: %.*v", msg, len, pkt); - else - ppp_info("%s", msg); - } - if (code == CHAP_SUCCESS) - auth_withpeer_success(pcb, PPP_CHAP, pcb->chap_client.digest->code); - else { - pcb->chap_client.flags |= AUTH_FAILED; - ppp_error("CHAP authentication failed"); - auth_withpeer_fail(pcb, PPP_CHAP); - } + if (code == CHAP_SUCCESS) { + /* used for MS-CHAP v2 mutual auth, yuck */ + if (pcb->chap_client.digest->check_success != NULL) { + if (!(*pcb->chap_client.digest->check_success)(pcb, pkt, len, pcb->chap_client.priv)) + code = CHAP_FAILURE; + } else + msg = "CHAP authentication succeeded"; + } else { + if (pcb->chap_client.digest->handle_failure != NULL) + (*pcb->chap_client.digest->handle_failure)(pcb, pkt, len); + else + msg = "CHAP authentication failed"; + } + if (msg) { + if (len > 0) + ppp_info("%s: %.*v", msg, len, pkt); + else + ppp_info("%s", msg); + } + if (code == CHAP_SUCCESS) + auth_withpeer_success(pcb, PPP_CHAP, pcb->chap_client.digest->code); + else { + pcb->chap_client.flags |= AUTH_FAILED; + ppp_error("CHAP authentication failed"); + auth_withpeer_fail(pcb, PPP_CHAP); + } } static void chap_input(ppp_pcb *pcb, unsigned char *pkt, int pktlen) { - unsigned char code, id; - int len; + unsigned char code, id; + int len; - if (pktlen < CHAP_HDRLEN) - return; - GETCHAR(code, pkt); - GETCHAR(id, pkt); - GETSHORT(len, pkt); - if (len < CHAP_HDRLEN || len > pktlen) - return; - len -= CHAP_HDRLEN; + if (pktlen < CHAP_HDRLEN) + return; + GETCHAR(code, pkt); + GETCHAR(id, pkt); + GETSHORT(len, pkt); + if (len < CHAP_HDRLEN || len > pktlen) + return; + len -= CHAP_HDRLEN; - switch (code) { - case CHAP_CHALLENGE: - chap_respond(pcb, id, pkt, len); - break; + switch (code) { + case CHAP_CHALLENGE: + chap_respond(pcb, id, pkt, len); + break; #if PPP_SERVER - case CHAP_RESPONSE: - chap_handle_response(pcb, id, pkt, len); - break; + case CHAP_RESPONSE: + chap_handle_response(pcb, id, pkt, len); + break; #endif /* PPP_SERVER */ - case CHAP_FAILURE: - case CHAP_SUCCESS: - chap_handle_status(pcb, code, id, pkt, len); - break; - default: - break; - } + case CHAP_FAILURE: + case CHAP_SUCCESS: + chap_handle_status(pcb, code, id, pkt, len); + break; + default: + break; + } } static void chap_protrej(ppp_pcb *pcb) { #if PPP_SERVER - if (pcb->chap_server.flags & TIMEOUT_PENDING) { - pcb->chap_server.flags &= ~TIMEOUT_PENDING; - UNTIMEOUT(chap_timeout, pcb); - } - if (pcb->chap_server.flags & AUTH_STARTED) { - pcb->chap_server.flags = 0; - auth_peer_fail(pcb, PPP_CHAP); - } + if (pcb->chap_server.flags & TIMEOUT_PENDING) { + pcb->chap_server.flags &= ~TIMEOUT_PENDING; + UNTIMEOUT(chap_timeout, pcb); + } + if (pcb->chap_server.flags & AUTH_STARTED) { + pcb->chap_server.flags = 0; + auth_peer_fail(pcb, PPP_CHAP); + } #endif /* PPP_SERVER */ - if ((pcb->chap_client.flags & (AUTH_STARTED|AUTH_DONE)) == AUTH_STARTED) { - pcb->chap_client.flags &= ~AUTH_STARTED; - ppp_error("CHAP authentication failed due to protocol-reject"); - auth_withpeer_fail(pcb, PPP_CHAP); - } + if ((pcb->chap_client.flags & (AUTH_STARTED|AUTH_DONE)) == AUTH_STARTED) { + pcb->chap_client.flags &= ~AUTH_STARTED; + ppp_error("CHAP authentication failed due to protocol-reject"); + auth_withpeer_fail(pcb, PPP_CHAP); + } } #if PRINTPKT_SUPPORT @@ -587,90 +587,90 @@ static void chap_protrej(ppp_pcb *pcb) { * chap_print_pkt - print the contents of a CHAP packet. */ static const char* const chap_code_names[] = { - "Challenge", "Response", "Success", "Failure" + "Challenge", "Response", "Success", "Failure" }; static int chap_print_pkt(const unsigned char *p, int plen, - void (*printer) (void *, const char *, ...), void *arg) { - int code, id, len; - int clen, nlen; - unsigned char x; + void (*printer) (void *, const char *, ...), void *arg) { + int code, id, len; + int clen, nlen; + unsigned char x; - if (plen < CHAP_HDRLEN) - return 0; - GETCHAR(code, p); - GETCHAR(id, p); - GETSHORT(len, p); - if (len < CHAP_HDRLEN || len > plen) - return 0; + if (plen < CHAP_HDRLEN) + return 0; + GETCHAR(code, p); + GETCHAR(id, p); + GETSHORT(len, p); + if (len < CHAP_HDRLEN || len > plen) + return 0; - if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(chap_code_names)) - printer(arg, " %s", chap_code_names[code-1]); - else - printer(arg, " code=0x%x", code); - printer(arg, " id=0x%x", id); - len -= CHAP_HDRLEN; - switch (code) { - case CHAP_CHALLENGE: - case CHAP_RESPONSE: - if (len < 1) - break; - clen = p[0]; - if (len < clen + 1) - break; - ++p; - nlen = len - clen - 1; - printer(arg, " <"); - for (; clen > 0; --clen) { - GETCHAR(x, p); - printer(arg, "%.2x", x); - } - printer(arg, ">, name = "); - ppp_print_string(p, nlen, printer, arg); - break; - case CHAP_FAILURE: - case CHAP_SUCCESS: - printer(arg, " "); - ppp_print_string(p, len, printer, arg); - break; - default: - for (clen = len; clen > 0; --clen) { - GETCHAR(x, p); - printer(arg, " %.2x", x); - } - /* no break */ - } + if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(chap_code_names)) + printer(arg, " %s", chap_code_names[code-1]); + else + printer(arg, " code=0x%x", code); + printer(arg, " id=0x%x", id); + len -= CHAP_HDRLEN; + switch (code) { + case CHAP_CHALLENGE: + case CHAP_RESPONSE: + if (len < 1) + break; + clen = p[0]; + if (len < clen + 1) + break; + ++p; + nlen = len - clen - 1; + printer(arg, " <"); + for (; clen > 0; --clen) { + GETCHAR(x, p); + printer(arg, "%.2x", x); + } + printer(arg, ">, name = "); + ppp_print_string(p, nlen, printer, arg); + break; + case CHAP_FAILURE: + case CHAP_SUCCESS: + printer(arg, " "); + ppp_print_string(p, len, printer, arg); + break; + default: + for (clen = len; clen > 0; --clen) { + GETCHAR(x, p); + printer(arg, " %.2x", x); + } + /* no break */ + } - return len + CHAP_HDRLEN; + return len + CHAP_HDRLEN; } #endif /* PRINTPKT_SUPPORT */ const struct protent chap_protent = { - PPP_CHAP, - chap_init, - chap_input, - chap_protrej, - chap_lowerup, - chap_lowerdown, - NULL, /* open */ - NULL, /* close */ + PPP_CHAP, + chap_init, + chap_input, + chap_protrej, + chap_lowerup, + chap_lowerdown, + NULL, /* open */ + NULL, /* close */ #if PRINTPKT_SUPPORT - chap_print_pkt, + chap_print_pkt, #endif /* PRINTPKT_SUPPORT */ #if PPP_DATAINPUT - NULL, /* datainput */ + NULL, /* datainput */ #endif /* PPP_DATAINPUT */ #if PRINTPKT_SUPPORT - "CHAP", /* name */ - NULL, /* data_name */ + "CHAP", /* name */ + NULL, /* data_name */ #endif /* PRINTPKT_SUPPORT */ #if PPP_OPTIONS - chap_option_list, - NULL, /* check_options */ + chap_option_list, + NULL, /* check_options */ #endif /* PPP_OPTIONS */ #if DEMAND_SUPPORT - NULL, - NULL + NULL, + NULL #endif /* DEMAND_SUPPORT */ }; diff --git a/components/network/lwip/src/netif/ppp/chap_ms.c b/components/network/lwip/src/netif/ppp/chap_ms.c index 5a989c9b..b050aa1c 100644 --- a/components/network/lwip/src/netif/ppp/chap_ms.c +++ b/components/network/lwip/src/netif/ppp/chap_ms.c @@ -97,41 +97,41 @@ #include "netif/ppp/mppe.h" /* For mppe_sha1_pad*, mppe_set_key() */ #endif /* MPPE_SUPPORT */ -#define SHA1_SIGNATURE_SIZE 20 -#define MD4_SIGNATURE_SIZE 16 /* 16 bytes in a MD4 message digest */ -#define MAX_NT_PASSWORD 256 /* Max (Unicode) chars in an NT pass */ +#define SHA1_SIGNATURE_SIZE 20 +#define MD4_SIGNATURE_SIZE 16 /* 16 bytes in a MD4 message digest */ +#define MAX_NT_PASSWORD 256 /* Max (Unicode) chars in an NT pass */ -#define MS_CHAP_RESPONSE_LEN 49 /* Response length for MS-CHAP */ -#define MS_CHAP2_RESPONSE_LEN 49 /* Response length for MS-CHAPv2 */ -#define MS_AUTH_RESPONSE_LENGTH 40 /* MS-CHAPv2 authenticator response, */ - /* as ASCII */ +#define MS_CHAP_RESPONSE_LEN 49 /* Response length for MS-CHAP */ +#define MS_CHAP2_RESPONSE_LEN 49 /* Response length for MS-CHAPv2 */ +#define MS_AUTH_RESPONSE_LENGTH 40 /* MS-CHAPv2 authenticator response, */ + /* as ASCII */ /* Error codes for MS-CHAP failure messages. */ -#define MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS 646 -#define MS_CHAP_ERROR_ACCT_DISABLED 647 -#define MS_CHAP_ERROR_PASSWD_EXPIRED 648 -#define MS_CHAP_ERROR_NO_DIALIN_PERMISSION 649 -#define MS_CHAP_ERROR_AUTHENTICATION_FAILURE 691 -#define MS_CHAP_ERROR_CHANGING_PASSWORD 709 +#define MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS 646 +#define MS_CHAP_ERROR_ACCT_DISABLED 647 +#define MS_CHAP_ERROR_PASSWD_EXPIRED 648 +#define MS_CHAP_ERROR_NO_DIALIN_PERMISSION 649 +#define MS_CHAP_ERROR_AUTHENTICATION_FAILURE 691 +#define MS_CHAP_ERROR_CHANGING_PASSWORD 709 /* * Offsets within the response field for MS-CHAP */ -#define MS_CHAP_LANMANRESP 0 -#define MS_CHAP_LANMANRESP_LEN 24 -#define MS_CHAP_NTRESP 24 -#define MS_CHAP_NTRESP_LEN 24 -#define MS_CHAP_USENT 48 +#define MS_CHAP_LANMANRESP 0 +#define MS_CHAP_LANMANRESP_LEN 24 +#define MS_CHAP_NTRESP 24 +#define MS_CHAP_NTRESP_LEN 24 +#define MS_CHAP_USENT 48 /* * Offsets within the response field for MS-CHAP2 */ -#define MS_CHAP2_PEER_CHALLENGE 0 -#define MS_CHAP2_PEER_CHAL_LEN 16 -#define MS_CHAP2_RESERVED_LEN 8 -#define MS_CHAP2_NTRESP 24 -#define MS_CHAP2_NTRESP_LEN 24 -#define MS_CHAP2_FLAGS 48 +#define MS_CHAP2_PEER_CHALLENGE 0 +#define MS_CHAP2_PEER_CHAL_LEN 16 +#define MS_CHAP2_RESERVED_LEN 8 +#define MS_CHAP2_NTRESP 24 +#define MS_CHAP2_NTRESP_LEN 24 +#define MS_CHAP2_FLAGS 48 #if MPPE_SUPPORT #if 0 /* UNUSED */ @@ -150,37 +150,37 @@ extern void set_mppe_enc_types(int, int); #define MS_CHAP2_AUTHENTICATEE 0 #define MS_CHAP2_AUTHENTICATOR 1 -static void ascii2unicode (const char[], int, u_char[]); -static void NTPasswordHash (u_char *, int, u_char[MD4_SIGNATURE_SIZE]); -static void ChallengeResponse (const u_char *, const u_char *, u_char[24]); -static void ChallengeHash (const u_char[16], const u_char *, const char *, u_char[8]); -static void ChapMS_NT (const u_char *, const char *, int, u_char[24]); -static void ChapMS2_NT (const u_char *, const u_char[16], const char *, const char *, int, - u_char[24]); -static void GenerateAuthenticatorResponsePlain - (const char*, int, u_char[24], const u_char[16], const u_char *, - const char *, u_char[41]); +static void ascii2unicode (const char[], int, u_char[]); +static void NTPasswordHash (u_char *, int, u_char[MD4_SIGNATURE_SIZE]); +static void ChallengeResponse (const u_char *, const u_char *, u_char[24]); +static void ChallengeHash (const u_char[16], const u_char *, const char *, u_char[8]); +static void ChapMS_NT (const u_char *, const char *, int, u_char[24]); +static void ChapMS2_NT (const u_char *, const u_char[16], const char *, const char *, int, + u_char[24]); +static void GenerateAuthenticatorResponsePlain + (const char*, int, u_char[24], const u_char[16], const u_char *, + const char *, u_char[41]); #ifdef MSLANMAN -static void ChapMS_LANMan (u_char *, char *, int, u_char *); +static void ChapMS_LANMan (u_char *, char *, int, u_char *); #endif static void GenerateAuthenticatorResponse(const u_char PasswordHashHash[MD4_SIGNATURE_SIZE], - u_char NTResponse[24], const u_char PeerChallenge[16], - const u_char *rchallenge, const char *username, - u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]); + u_char NTResponse[24], const u_char PeerChallenge[16], + const u_char *rchallenge, const char *username, + u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]); #if MPPE_SUPPORT -static void Set_Start_Key (ppp_pcb *pcb, const u_char *, const char *, int); -static void SetMasterKeys (ppp_pcb *pcb, const char *, int, u_char[24], int); +static void Set_Start_Key (ppp_pcb *pcb, const u_char *, const char *, int); +static void SetMasterKeys (ppp_pcb *pcb, const char *, int, u_char[24], int); #endif /* MPPE_SUPPORT */ static void ChapMS (ppp_pcb *pcb, const u_char *, const char *, int, u_char *); static void ChapMS2 (ppp_pcb *pcb, const u_char *, const u_char *, const char *, const char *, int, - u_char *, u_char[MS_AUTH_RESPONSE_LENGTH+1], int); + u_char *, u_char[MS_AUTH_RESPONSE_LENGTH+1], int); #ifdef MSLANMAN -bool ms_lanman = 0; /* Use LanMan password instead of NT */ - /* Has meaning only with MS-CHAP challenges */ +bool ms_lanman = 0; /* Use LanMan password instead of NT */ + /* Has meaning only with MS-CHAP challenges */ #endif #if MPPE_SUPPORT @@ -192,7 +192,7 @@ static char *mschap_challenge = NULL; static char *mschap2_peer_challenge = NULL; #endif -#include "netif/ppp/fsm.h" /* Need to poke MPPE options */ +#include "netif/ppp/fsm.h" /* Need to poke MPPE options */ #include "netif/ppp/ccp.h" #endif /* MPPE_SUPPORT */ @@ -202,16 +202,16 @@ static char *mschap2_peer_challenge = NULL; */ static option_t chapms_option_list[] = { #ifdef MSLANMAN - { "ms-lanman", o_bool, &ms_lanman, - "Use LanMan passwd when using MS-CHAP", 1 }, + { "ms-lanman", o_bool, &ms_lanman, + "Use LanMan passwd when using MS-CHAP", 1 }, #endif #ifdef DEBUGMPPEKEY - { "mschap-challenge", o_string, &mschap_challenge, - "specify CHAP challenge" }, - { "mschap2-peer-challenge", o_string, &mschap2_peer_challenge, - "specify CHAP peer challenge" }, + { "mschap-challenge", o_string, &mschap_challenge, + "specify CHAP challenge" }, + { "mschap2-peer-challenge", o_string, &mschap2_peer_challenge, + "specify CHAP peer challenge" }, #endif - { NULL } + { NULL } }; #endif /* PPP_OPTIONS */ @@ -223,279 +223,279 @@ static option_t chapms_option_list[] = { * at challenge[1]. */ static void chapms_generate_challenge(ppp_pcb *pcb, unsigned char *challenge) { - LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(pcb); - *challenge++ = 8; + *challenge++ = 8; #ifdef DEBUGMPPEKEY - if (mschap_challenge && strlen(mschap_challenge) == 8) - memcpy(challenge, mschap_challenge, 8); - else + if (mschap_challenge && strlen(mschap_challenge) == 8) + memcpy(challenge, mschap_challenge, 8); + else #endif - magic_random_bytes(challenge, 8); + magic_random_bytes(challenge, 8); } static void chapms2_generate_challenge(ppp_pcb *pcb, unsigned char *challenge) { - LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(pcb); - *challenge++ = 16; + *challenge++ = 16; #ifdef DEBUGMPPEKEY - if (mschap_challenge && strlen(mschap_challenge) == 16) - memcpy(challenge, mschap_challenge, 16); - else + if (mschap_challenge && strlen(mschap_challenge) == 16) + memcpy(challenge, mschap_challenge, 16); + else #endif - magic_random_bytes(challenge, 16); + magic_random_bytes(challenge, 16); } static int chapms_verify_response(ppp_pcb *pcb, int id, const char *name, - const unsigned char *secret, int secret_len, - const unsigned char *challenge, const unsigned char *response, - char *message, int message_space) { - unsigned char md[MS_CHAP_RESPONSE_LEN]; - int diff; - int challenge_len, response_len; - LWIP_UNUSED_ARG(id); - LWIP_UNUSED_ARG(name); + const unsigned char *secret, int secret_len, + const unsigned char *challenge, const unsigned char *response, + char *message, int message_space) { + unsigned char md[MS_CHAP_RESPONSE_LEN]; + int diff; + int challenge_len, response_len; + LWIP_UNUSED_ARG(id); + LWIP_UNUSED_ARG(name); - challenge_len = *challenge++; /* skip length, is 8 */ - response_len = *response++; - if (response_len != MS_CHAP_RESPONSE_LEN) - goto bad; + challenge_len = *challenge++; /* skip length, is 8 */ + response_len = *response++; + if (response_len != MS_CHAP_RESPONSE_LEN) + goto bad; #ifndef MSLANMAN - if (!response[MS_CHAP_USENT]) { - /* Should really propagate this into the error packet. */ - ppp_notice("Peer request for LANMAN auth not supported"); - goto bad; - } + if (!response[MS_CHAP_USENT]) { + /* Should really propagate this into the error packet. */ + ppp_notice("Peer request for LANMAN auth not supported"); + goto bad; + } #endif - /* Generate the expected response. */ - ChapMS(pcb, (const u_char *)challenge, (const char *)secret, secret_len, md); + /* Generate the expected response. */ + ChapMS(pcb, (const u_char *)challenge, (const char *)secret, secret_len, md); #ifdef MSLANMAN - /* Determine which part of response to verify against */ - if (!response[MS_CHAP_USENT]) - diff = memcmp(&response[MS_CHAP_LANMANRESP], - &md[MS_CHAP_LANMANRESP], MS_CHAP_LANMANRESP_LEN); - else + /* Determine which part of response to verify against */ + if (!response[MS_CHAP_USENT]) + diff = memcmp(&response[MS_CHAP_LANMANRESP], + &md[MS_CHAP_LANMANRESP], MS_CHAP_LANMANRESP_LEN); + else #endif - diff = memcmp(&response[MS_CHAP_NTRESP], &md[MS_CHAP_NTRESP], - MS_CHAP_NTRESP_LEN); + diff = memcmp(&response[MS_CHAP_NTRESP], &md[MS_CHAP_NTRESP], + MS_CHAP_NTRESP_LEN); - if (diff == 0) { - ppp_slprintf(message, message_space, "Access granted"); - return 1; - } + if (diff == 0) { + ppp_slprintf(message, message_space, "Access granted"); + return 1; + } bad: - /* See comments below for MS-CHAP V2 */ - ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0", - challenge_len, challenge); - return 0; + /* See comments below for MS-CHAP V2 */ + ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0", + challenge_len, challenge); + return 0; } static int chapms2_verify_response(ppp_pcb *pcb, int id, const char *name, - const unsigned char *secret, int secret_len, - const unsigned char *challenge, const unsigned char *response, - char *message, int message_space) { - unsigned char md[MS_CHAP2_RESPONSE_LEN]; - char saresponse[MS_AUTH_RESPONSE_LENGTH+1]; - int challenge_len, response_len; - LWIP_UNUSED_ARG(id); + const unsigned char *secret, int secret_len, + const unsigned char *challenge, const unsigned char *response, + char *message, int message_space) { + unsigned char md[MS_CHAP2_RESPONSE_LEN]; + char saresponse[MS_AUTH_RESPONSE_LENGTH+1]; + int challenge_len, response_len; + LWIP_UNUSED_ARG(id); - challenge_len = *challenge++; /* skip length, is 16 */ - response_len = *response++; - if (response_len != MS_CHAP2_RESPONSE_LEN) - goto bad; /* not even the right length */ + challenge_len = *challenge++; /* skip length, is 16 */ + response_len = *response++; + if (response_len != MS_CHAP2_RESPONSE_LEN) + goto bad; /* not even the right length */ - /* Generate the expected response and our mutual auth. */ - ChapMS2(pcb, (const u_char*)challenge, (const u_char*)&response[MS_CHAP2_PEER_CHALLENGE], name, - (const char *)secret, secret_len, md, - (unsigned char *)saresponse, MS_CHAP2_AUTHENTICATOR); + /* Generate the expected response and our mutual auth. */ + ChapMS2(pcb, (const u_char*)challenge, (const u_char*)&response[MS_CHAP2_PEER_CHALLENGE], name, + (const char *)secret, secret_len, md, + (unsigned char *)saresponse, MS_CHAP2_AUTHENTICATOR); - /* compare MDs and send the appropriate status */ - /* - * Per RFC 2759, success message must be formatted as - * "S= M=" - * where - * is the Authenticator Response (mutual auth) - * is a text message - * - * However, some versions of Windows (win98 tested) do not know - * about the M= part (required per RFC 2759) and flag - * it as an error (reported incorrectly as an encryption error - * to the user). Since the RFC requires it, and it can be - * useful information, we supply it if the peer is a conforming - * system. Luckily (?), win98 sets the Flags field to 0x04 - * (contrary to RFC requirements) so we can use that to - * distinguish between conforming and non-conforming systems. - * - * Special thanks to Alex Swiridov for - * help debugging this. - */ - if (memcmp(&md[MS_CHAP2_NTRESP], &response[MS_CHAP2_NTRESP], - MS_CHAP2_NTRESP_LEN) == 0) { - if (response[MS_CHAP2_FLAGS]) - ppp_slprintf(message, message_space, "S=%s", saresponse); - else - ppp_slprintf(message, message_space, "S=%s M=%s", - saresponse, "Access granted"); - return 1; - } + /* compare MDs and send the appropriate status */ + /* + * Per RFC 2759, success message must be formatted as + * "S= M=" + * where + * is the Authenticator Response (mutual auth) + * is a text message + * + * However, some versions of Windows (win98 tested) do not know + * about the M= part (required per RFC 2759) and flag + * it as an error (reported incorrectly as an encryption error + * to the user). Since the RFC requires it, and it can be + * useful information, we supply it if the peer is a conforming + * system. Luckily (?), win98 sets the Flags field to 0x04 + * (contrary to RFC requirements) so we can use that to + * distinguish between conforming and non-conforming systems. + * + * Special thanks to Alex Swiridov for + * help debugging this. + */ + if (memcmp(&md[MS_CHAP2_NTRESP], &response[MS_CHAP2_NTRESP], + MS_CHAP2_NTRESP_LEN) == 0) { + if (response[MS_CHAP2_FLAGS]) + ppp_slprintf(message, message_space, "S=%s", saresponse); + else + ppp_slprintf(message, message_space, "S=%s M=%s", + saresponse, "Access granted"); + return 1; + } bad: - /* - * Failure message must be formatted as - * "E=e R=r C=c V=v M=m" - * where - * e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE) - * r = retry (we use 1, ok to retry) - * c = challenge to use for next response, we reuse previous - * v = Change Password version supported, we use 0 - * m = text message - * - * The M=m part is only for MS-CHAPv2. Neither win2k nor - * win98 (others untested) display the message to the user anyway. - * They also both ignore the E=e code. - * - * Note that it's safe to reuse the same challenge as we don't - * actually accept another response based on the error message - * (and no clients try to resend a response anyway). - * - * Basically, this whole bit is useless code, even the small - * implementation here is only because of overspecification. - */ - ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0 M=%s", - challenge_len, challenge, "Access denied"); - return 0; + /* + * Failure message must be formatted as + * "E=e R=r C=c V=v M=m" + * where + * e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE) + * r = retry (we use 1, ok to retry) + * c = challenge to use for next response, we reuse previous + * v = Change Password version supported, we use 0 + * m = text message + * + * The M=m part is only for MS-CHAPv2. Neither win2k nor + * win98 (others untested) display the message to the user anyway. + * They also both ignore the E=e code. + * + * Note that it's safe to reuse the same challenge as we don't + * actually accept another response based on the error message + * (and no clients try to resend a response anyway). + * + * Basically, this whole bit is useless code, even the small + * implementation here is only because of overspecification. + */ + ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0 M=%s", + challenge_len, challenge, "Access denied"); + return 0; } #endif /* PPP_SERVER */ static void chapms_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name, - const unsigned char *challenge, const char *secret, int secret_len, - unsigned char *private_) { - LWIP_UNUSED_ARG(id); - LWIP_UNUSED_ARG(our_name); - LWIP_UNUSED_ARG(private_); - challenge++; /* skip length, should be 8 */ - *response++ = MS_CHAP_RESPONSE_LEN; - ChapMS(pcb, challenge, secret, secret_len, response); + const unsigned char *challenge, const char *secret, int secret_len, + unsigned char *private_) { + LWIP_UNUSED_ARG(id); + LWIP_UNUSED_ARG(our_name); + LWIP_UNUSED_ARG(private_); + challenge++; /* skip length, should be 8 */ + *response++ = MS_CHAP_RESPONSE_LEN; + ChapMS(pcb, challenge, secret, secret_len, response); } static void chapms2_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name, - const unsigned char *challenge, const char *secret, int secret_len, - unsigned char *private_) { - LWIP_UNUSED_ARG(id); - challenge++; /* skip length, should be 16 */ - *response++ = MS_CHAP2_RESPONSE_LEN; - ChapMS2(pcb, challenge, + const unsigned char *challenge, const char *secret, int secret_len, + unsigned char *private_) { + LWIP_UNUSED_ARG(id); + challenge++; /* skip length, should be 16 */ + *response++ = MS_CHAP2_RESPONSE_LEN; + ChapMS2(pcb, challenge, #ifdef DEBUGMPPEKEY - mschap2_peer_challenge, + mschap2_peer_challenge, #else - NULL, + NULL, #endif - our_name, secret, secret_len, response, private_, - MS_CHAP2_AUTHENTICATEE); + our_name, secret, secret_len, response, private_, + MS_CHAP2_AUTHENTICATEE); } static int chapms2_check_success(ppp_pcb *pcb, unsigned char *msg, int len, unsigned char *private_) { - LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(pcb); - if ((len < MS_AUTH_RESPONSE_LENGTH + 2) || - strncmp((char *)msg, "S=", 2) != 0) { - /* Packet does not start with "S=" */ - ppp_error("MS-CHAPv2 Success packet is badly formed."); - return 0; - } - msg += 2; - len -= 2; - if (len < MS_AUTH_RESPONSE_LENGTH - || memcmp(msg, private_, MS_AUTH_RESPONSE_LENGTH)) { - /* Authenticator Response did not match expected. */ - ppp_error("MS-CHAPv2 mutual authentication failed."); - return 0; - } - /* Authenticator Response matches. */ - msg += MS_AUTH_RESPONSE_LENGTH; /* Eat it */ - len -= MS_AUTH_RESPONSE_LENGTH; - if ((len >= 3) && !strncmp((char *)msg, " M=", 3)) { - msg += 3; /* Eat the delimiter */ - } else if (len) { - /* Packet has extra text which does not begin " M=" */ - ppp_error("MS-CHAPv2 Success packet is badly formed."); - return 0; - } - return 1; + if ((len < MS_AUTH_RESPONSE_LENGTH + 2) || + strncmp((char *)msg, "S=", 2) != 0) { + /* Packet does not start with "S=" */ + ppp_error("MS-CHAPv2 Success packet is badly formed."); + return 0; + } + msg += 2; + len -= 2; + if (len < MS_AUTH_RESPONSE_LENGTH + || memcmp(msg, private_, MS_AUTH_RESPONSE_LENGTH)) { + /* Authenticator Response did not match expected. */ + ppp_error("MS-CHAPv2 mutual authentication failed."); + return 0; + } + /* Authenticator Response matches. */ + msg += MS_AUTH_RESPONSE_LENGTH; /* Eat it */ + len -= MS_AUTH_RESPONSE_LENGTH; + if ((len >= 3) && !strncmp((char *)msg, " M=", 3)) { + msg += 3; /* Eat the delimiter */ + } else if (len) { + /* Packet has extra text which does not begin " M=" */ + ppp_error("MS-CHAPv2 Success packet is badly formed."); + return 0; + } + return 1; } static void chapms_handle_failure(ppp_pcb *pcb, unsigned char *inp, int len) { - int err; - const char *p; - char msg[64]; - LWIP_UNUSED_ARG(pcb); + int err; + const char *p; + char msg[64]; + LWIP_UNUSED_ARG(pcb); - /* We want a null-terminated string for strxxx(). */ - len = LWIP_MIN(len, 63); - MEMCPY(msg, inp, len); - msg[len] = 0; - p = msg; + /* We want a null-terminated string for strxxx(). */ + len = LWIP_MIN(len, 63); + MEMCPY(msg, inp, len); + msg[len] = 0; + p = msg; - /* - * Deal with MS-CHAP formatted failure messages; just print the - * M= part (if any). For MS-CHAP we're not really supposed - * to use M=, but it shouldn't hurt. See - * chapms[2]_verify_response. - */ - if (!strncmp(p, "E=", 2)) - err = strtol(p+2, NULL, 10); /* Remember the error code. */ - else - goto print_msg; /* Message is badly formatted. */ + /* + * Deal with MS-CHAP formatted failure messages; just print the + * M= part (if any). For MS-CHAP we're not really supposed + * to use M=, but it shouldn't hurt. See + * chapms[2]_verify_response. + */ + if (!strncmp(p, "E=", 2)) + err = strtol(p+2, NULL, 10); /* Remember the error code. */ + else + goto print_msg; /* Message is badly formatted. */ - if (len && ((p = strstr(p, " M=")) != NULL)) { - /* M= field found. */ - p += 3; - } else { - /* No M=; use the error code. */ - switch (err) { - case MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS: - p = "E=646 Restricted logon hours"; - break; + if (len && ((p = strstr(p, " M=")) != NULL)) { + /* M= field found. */ + p += 3; + } else { + /* No M=; use the error code. */ + switch (err) { + case MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS: + p = "E=646 Restricted logon hours"; + break; - case MS_CHAP_ERROR_ACCT_DISABLED: - p = "E=647 Account disabled"; - break; + case MS_CHAP_ERROR_ACCT_DISABLED: + p = "E=647 Account disabled"; + break; - case MS_CHAP_ERROR_PASSWD_EXPIRED: - p = "E=648 Password expired"; - break; + case MS_CHAP_ERROR_PASSWD_EXPIRED: + p = "E=648 Password expired"; + break; - case MS_CHAP_ERROR_NO_DIALIN_PERMISSION: - p = "E=649 No dialin permission"; - break; + case MS_CHAP_ERROR_NO_DIALIN_PERMISSION: + p = "E=649 No dialin permission"; + break; - case MS_CHAP_ERROR_AUTHENTICATION_FAILURE: - p = "E=691 Authentication failure"; - break; + case MS_CHAP_ERROR_AUTHENTICATION_FAILURE: + p = "E=691 Authentication failure"; + break; - case MS_CHAP_ERROR_CHANGING_PASSWORD: - /* Should never see this, we don't support Change Password. */ - p = "E=709 Error changing password"; - break; + case MS_CHAP_ERROR_CHANGING_PASSWORD: + /* Should never see this, we don't support Change Password. */ + p = "E=709 Error changing password"; + break; - default: - ppp_error("Unknown MS-CHAP authentication failure: %.*v", - len, inp); - return; - } - } + default: + ppp_error("Unknown MS-CHAP authentication failure: %.*v", + len, inp); + return; + } + } print_msg: - if (p != NULL) - ppp_error("MS-CHAP authentication failed: %v", p); + if (p != NULL) + ppp_error("MS-CHAP authentication failed: %v", p); } static void ChallengeResponse(const u_char *challenge, - const u_char PasswordHash[MD4_SIGNATURE_SIZE], - u_char response[24]) { + const u_char PasswordHash[MD4_SIGNATURE_SIZE], + u_char response[24]) { u_char ZPasswordHash[21]; lwip_des_context des; u_char des_key[8]; @@ -505,7 +505,7 @@ static void ChallengeResponse(const u_char *challenge, #if 0 dbglog("ChallengeResponse - ZPasswordHash %.*B", - sizeof(ZPasswordHash), ZPasswordHash); + sizeof(ZPasswordHash), ZPasswordHash); #endif pppcrypt_56_to_64_bit_key(ZPasswordHash + 0, des_key); @@ -532,16 +532,16 @@ static void ChallengeResponse(const u_char *challenge, } static void ChallengeHash(const u_char PeerChallenge[16], const u_char *rchallenge, - const char *username, u_char Challenge[8]) { - lwip_sha1_context sha1Context; - u_char sha1Hash[SHA1_SIGNATURE_SIZE]; - const char *user; + const char *username, u_char Challenge[8]) { + lwip_sha1_context sha1Context; + u_char sha1Hash[SHA1_SIGNATURE_SIZE]; + const char *user; /* remove domain from "domain\username" */ if ((user = strrchr(username, '\\')) != NULL) - ++user; + ++user; else - user = username; + user = username; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); @@ -566,11 +566,11 @@ static void ascii2unicode(const char ascii[], int ascii_len, u_char unicode[]) { BZERO(unicode, ascii_len * 2); for (i = 0; i < ascii_len; i++) - unicode[i * 2] = (u_char) ascii[i]; + unicode[i * 2] = (u_char) ascii[i]; } static void NTPasswordHash(u_char *secret, int secret_len, u_char hash[MD4_SIGNATURE_SIZE]) { - lwip_md4_context md4Context; + lwip_md4_context md4Context; lwip_md4_init(&md4Context); lwip_md4_starts(&md4Context); @@ -580,9 +580,9 @@ static void NTPasswordHash(u_char *secret, int secret_len, u_char hash[MD4_SIGNA } static void ChapMS_NT(const u_char *rchallenge, const char *secret, int secret_len, - u_char NTResponse[24]) { - u_char unicodePassword[MAX_NT_PASSWORD * 2]; - u_char PasswordHash[MD4_SIGNATURE_SIZE]; + u_char NTResponse[24]) { + u_char unicodePassword[MAX_NT_PASSWORD * 2]; + u_char PasswordHash[MD4_SIGNATURE_SIZE]; /* Hash the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); @@ -592,10 +592,10 @@ static void ChapMS_NT(const u_char *rchallenge, const char *secret, int secret_l } static void ChapMS2_NT(const u_char *rchallenge, const u_char PeerChallenge[16], const char *username, - const char *secret, int secret_len, u_char NTResponse[24]) { - u_char unicodePassword[MAX_NT_PASSWORD * 2]; - u_char PasswordHash[MD4_SIGNATURE_SIZE]; - u_char Challenge[8]; + const char *secret, int secret_len, u_char NTResponse[24]) { + u_char unicodePassword[MAX_NT_PASSWORD * 2]; + u_char PasswordHash[MD4_SIGNATURE_SIZE]; + u_char Challenge[8]; ChallengeHash(PeerChallenge, rchallenge, username, Challenge); @@ -610,10 +610,10 @@ static void ChapMS2_NT(const u_char *rchallenge, const u_char PeerChallenge[16], static u_char *StdText = (u_char *)"KGS!@#$%"; /* key from rasapi32.dll */ static void ChapMS_LANMan(u_char *rchallenge, char *secret, int secret_len, - unsigned char *response) { - int i; - u_char UcasePassword[MAX_NT_PASSWORD]; /* max is actually 14 */ - u_char PasswordHash[MD4_SIGNATURE_SIZE]; + unsigned char *response) { + int i; + u_char UcasePassword[MAX_NT_PASSWORD]; /* max is actually 14 */ + u_char PasswordHash[MD4_SIGNATURE_SIZE]; lwip_des_context des; u_char des_key[8]; @@ -640,28 +640,28 @@ static void ChapMS_LANMan(u_char *rchallenge, char *secret, int secret_len, static void GenerateAuthenticatorResponse(const u_char PasswordHashHash[MD4_SIGNATURE_SIZE], - u_char NTResponse[24], const u_char PeerChallenge[16], - const u_char *rchallenge, const char *username, - u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) { + u_char NTResponse[24], const u_char PeerChallenge[16], + const u_char *rchallenge, const char *username, + u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) { /* * "Magic" constants used in response generation, from RFC 2759. */ static const u_char Magic1[39] = /* "Magic server to client signing constant" */ - { 0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76, - 0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65, - 0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67, - 0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74 }; + { 0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76, + 0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65, + 0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67, + 0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74 }; static const u_char Magic2[41] = /* "Pad to make it do more than one iteration" */ - { 0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B, - 0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F, - 0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E, - 0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F, - 0x6E }; + { 0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B, + 0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F, + 0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E, + 0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F, + 0x6E }; - int i; - lwip_sha1_context sha1Context; - u_char Digest[SHA1_SIGNATURE_SIZE]; - u_char Challenge[8]; + int i; + lwip_sha1_context sha1Context; + u_char Digest[SHA1_SIGNATURE_SIZE]; + u_char Challenge[8]; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); @@ -683,27 +683,27 @@ static void GenerateAuthenticatorResponse(const u_char PasswordHashHash[MD4_SIGN /* Convert to ASCII hex string. */ for (i = 0; i < LWIP_MAX((MS_AUTH_RESPONSE_LENGTH / 2), (int)sizeof(Digest)); i++) - sprintf((char *)&authResponse[i * 2], "%02X", Digest[i]); + sprintf((char *)&authResponse[i * 2], "%02X", Digest[i]); } static void GenerateAuthenticatorResponsePlain( - const char *secret, int secret_len, - u_char NTResponse[24], const u_char PeerChallenge[16], - const u_char *rchallenge, const char *username, - u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) { - u_char unicodePassword[MAX_NT_PASSWORD * 2]; - u_char PasswordHash[MD4_SIGNATURE_SIZE]; - u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; + const char *secret, int secret_len, + u_char NTResponse[24], const u_char PeerChallenge[16], + const u_char *rchallenge, const char *username, + u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) { + u_char unicodePassword[MAX_NT_PASSWORD * 2]; + u_char PasswordHash[MD4_SIGNATURE_SIZE]; + u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; /* Hash (x2) the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash); NTPasswordHash(PasswordHash, sizeof(PasswordHash), - PasswordHashHash); + PasswordHashHash); GenerateAuthenticatorResponse(PasswordHashHash, NTResponse, PeerChallenge, - rchallenge, username, authResponse); + rchallenge, username, authResponse); } @@ -712,11 +712,11 @@ static void GenerateAuthenticatorResponsePlain( * Set mppe_xxxx_key from MS-CHAP credentials. (see RFC 3079) */ static void Set_Start_Key(ppp_pcb *pcb, const u_char *rchallenge, const char *secret, int secret_len) { - u_char unicodePassword[MAX_NT_PASSWORD * 2]; - u_char PasswordHash[MD4_SIGNATURE_SIZE]; - u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; - lwip_sha1_context sha1Context; - u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ + u_char unicodePassword[MAX_NT_PASSWORD * 2]; + u_char PasswordHash[MD4_SIGNATURE_SIZE]; + u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; + lwip_sha1_context sha1Context; + u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ /* Hash (x2) the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); @@ -742,43 +742,43 @@ static void Set_Start_Key(ppp_pcb *pcb, const u_char *rchallenge, const char *se * Set mppe_xxxx_key from MS-CHAPv2 credentials. (see RFC 3079) */ static void SetMasterKeys(ppp_pcb *pcb, const char *secret, int secret_len, u_char NTResponse[24], int IsServer) { - u_char unicodePassword[MAX_NT_PASSWORD * 2]; - u_char PasswordHash[MD4_SIGNATURE_SIZE]; - u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; - lwip_sha1_context sha1Context; - u_char MasterKey[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ - u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ + u_char unicodePassword[MAX_NT_PASSWORD * 2]; + u_char PasswordHash[MD4_SIGNATURE_SIZE]; + u_char PasswordHashHash[MD4_SIGNATURE_SIZE]; + lwip_sha1_context sha1Context; + u_char MasterKey[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ + u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */ const u_char *s; /* "This is the MPPE Master Key" */ static const u_char Magic1[27] = - { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, - 0x68, 0x65, 0x20, 0x4d, 0x50, 0x50, 0x45, 0x20, 0x4d, - 0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x65, 0x79 }; + { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, + 0x68, 0x65, 0x20, 0x4d, 0x50, 0x50, 0x45, 0x20, 0x4d, + 0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x65, 0x79 }; /* "On the client side, this is the send key; " "on the server side, it is the receive key." */ static const u_char Magic2[84] = - { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, - 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, - 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79, - 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, - 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65, - 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, - 0x6b, 0x65, 0x79, 0x2e }; + { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, + 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79, + 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, + 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65, + 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, + 0x6b, 0x65, 0x79, 0x2e }; /* "On the client side, this is the receive key; " "on the server side, it is the send key." */ static const u_char Magic3[84] = - { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, - 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, - 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, - 0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, - 0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, - 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, - 0x6b, 0x65, 0x79, 0x2e }; + { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20, + 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20, + 0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, + 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, + 0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, + 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, + 0x6b, 0x65, 0x79, 0x2e }; /* Hash (x2) the Unicode version of the secret (== password). */ ascii2unicode(secret, secret_len, unicodePassword); @@ -797,9 +797,9 @@ static void SetMasterKeys(ppp_pcb *pcb, const char *secret, int secret_len, u_ch * generate send key */ if (IsServer) - s = Magic3; + s = Magic3; else - s = Magic2; + s = Magic2; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, MasterKey, 16); @@ -815,9 +815,9 @@ static void SetMasterKeys(ppp_pcb *pcb, const char *secret, int secret_len, u_ch * generate recv key */ if (IsServer) - s = Magic2; + s = Magic2; else - s = Magic3; + s = Magic3; lwip_sha1_init(&sha1Context); lwip_sha1_starts(&sha1Context); lwip_sha1_update(&sha1Context, MasterKey, 16); @@ -846,7 +846,7 @@ static void ChapMS(ppp_pcb *pcb, const u_char *rchallenge, const char *secret, i #ifdef MSLANMAN ChapMS_LANMan(rchallenge, secret, secret_len, - &response[MS_CHAP_LANMANRESP]); + &response[MS_CHAP_LANMANRESP]); /* preferred method is set by option */ response[MS_CHAP_USENT] = !ms_lanman; @@ -871,8 +871,8 @@ static void ChapMS(ppp_pcb *pcb, const u_char *rchallenge, const char *secret, i * Authenticator Response. */ static void ChapMS2(ppp_pcb *pcb, const u_char *rchallenge, const u_char *PeerChallenge, - const char *user, const char *secret, int secret_len, unsigned char *response, - u_char authResponse[], int authenticator) { + const char *user, const char *secret, int secret_len, unsigned char *response, + u_char authResponse[], int authenticator) { /* ARGSUSED */ LWIP_UNUSED_ARG(authenticator); #if !MPPE_SUPPORT @@ -883,24 +883,24 @@ static void ChapMS2(ppp_pcb *pcb, const u_char *rchallenge, const u_char *PeerCh /* Generate the Peer-Challenge if requested, or copy it if supplied. */ if (!PeerChallenge) - magic_random_bytes(&response[MS_CHAP2_PEER_CHALLENGE], MS_CHAP2_PEER_CHAL_LEN); + magic_random_bytes(&response[MS_CHAP2_PEER_CHALLENGE], MS_CHAP2_PEER_CHAL_LEN); else - MEMCPY(&response[MS_CHAP2_PEER_CHALLENGE], PeerChallenge, - MS_CHAP2_PEER_CHAL_LEN); + MEMCPY(&response[MS_CHAP2_PEER_CHALLENGE], PeerChallenge, + MS_CHAP2_PEER_CHAL_LEN); /* Generate the NT-Response */ ChapMS2_NT(rchallenge, &response[MS_CHAP2_PEER_CHALLENGE], user, - secret, secret_len, &response[MS_CHAP2_NTRESP]); + secret, secret_len, &response[MS_CHAP2_NTRESP]); /* Generate the Authenticator Response. */ GenerateAuthenticatorResponsePlain(secret, secret_len, - &response[MS_CHAP2_NTRESP], - &response[MS_CHAP2_PEER_CHALLENGE], - rchallenge, user, authResponse); + &response[MS_CHAP2_NTRESP], + &response[MS_CHAP2_PEER_CHALLENGE], + rchallenge, user, authResponse); #if MPPE_SUPPORT SetMasterKeys(pcb, secret, secret_len, - &response[MS_CHAP2_NTRESP], authenticator); + &response[MS_CHAP2_NTRESP], authenticator); #endif /* MPPE_SUPPORT */ } @@ -912,51 +912,51 @@ static void ChapMS2(ppp_pcb *pcb, const u_char *rchallenge, const u_char *PeerCh void set_mppe_enc_types(int policy, int types) { /* Early exit for unknown policies. */ if (policy != MPPE_ENC_POL_ENC_ALLOWED || - policy != MPPE_ENC_POL_ENC_REQUIRED) - return; + policy != MPPE_ENC_POL_ENC_REQUIRED) + return; /* Don't modify MPPE if it's optional and wasn't already configured. */ if (policy == MPPE_ENC_POL_ENC_ALLOWED && !ccp_wantoptions[0].mppe) - return; + return; /* * Disable undesirable encryption types. Note that we don't ENABLE * any encryption types, to avoid overriding manual configuration. */ switch(types) { - case MPPE_ENC_TYPES_RC4_40: - ccp_wantoptions[0].mppe &= ~MPPE_OPT_128; /* disable 128-bit */ - break; - case MPPE_ENC_TYPES_RC4_128: - ccp_wantoptions[0].mppe &= ~MPPE_OPT_40; /* disable 40-bit */ - break; - default: - break; + case MPPE_ENC_TYPES_RC4_40: + ccp_wantoptions[0].mppe &= ~MPPE_OPT_128; /* disable 128-bit */ + break; + case MPPE_ENC_TYPES_RC4_128: + ccp_wantoptions[0].mppe &= ~MPPE_OPT_40; /* disable 40-bit */ + break; + default: + break; } } #endif /* MPPE_SUPPORT */ #endif /* UNUSED */ const struct chap_digest_type chapms_digest = { - CHAP_MICROSOFT, /* code */ + CHAP_MICROSOFT, /* code */ #if PPP_SERVER - chapms_generate_challenge, - chapms_verify_response, + chapms_generate_challenge, + chapms_verify_response, #endif /* PPP_SERVER */ - chapms_make_response, - NULL, /* check_success */ - chapms_handle_failure, + chapms_make_response, + NULL, /* check_success */ + chapms_handle_failure, }; const struct chap_digest_type chapms2_digest = { - CHAP_MICROSOFT_V2, /* code */ + CHAP_MICROSOFT_V2, /* code */ #if PPP_SERVER - chapms2_generate_challenge, - chapms2_verify_response, + chapms2_generate_challenge, + chapms2_verify_response, #endif /* PPP_SERVER */ - chapms2_make_response, - chapms2_check_success, - chapms_handle_failure, + chapms2_make_response, + chapms2_check_success, + chapms_handle_failure, }; #endif /* PPP_SUPPORT && MSCHAP_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/demand.c b/components/network/lwip/src/netif/ppp/demand.c index 26c6c30d..f3774e08 100644 --- a/components/network/lwip/src/netif/ppp/demand.c +++ b/components/network/lwip/src/netif/ppp/demand.c @@ -87,11 +87,11 @@ demand_conf() /* framemax = lcp_allowoptions[0].mru; if (framemax < PPP_MRU) */ - framemax = PPP_MRU; + framemax = PPP_MRU; framemax += PPP_HDRLEN + PPP_FCSLEN; frame = malloc(framemax); if (frame == NULL) - novm("demand frame"); + novm("demand frame"); framelen = 0; pend_q = NULL; escape_flag = 0; @@ -100,8 +100,8 @@ demand_conf() netif_set_mtu(pcb, LWIP_MIN(lcp_allowoptions[0].mru, PPP_MRU)); if (ppp_send_config(pcb, PPP_MRU, (u32_t) 0, 0, 0) < 0 - || ppp_recv_config(pcb, PPP_MRU, (u32_t) 0, 0, 0) < 0) - fatal("Couldn't set up demand-dialled PPP interface: %m"); + || ppp_recv_config(pcb, PPP_MRU, (u32_t) 0, 0, 0) < 0) + fatal("Couldn't set up demand-dialled PPP interface: %m"); #ifdef PPP_FILTER set_filters(&pass_filter, &active_filter); @@ -111,12 +111,12 @@ demand_conf() * Call the demand_conf procedure for each protocol that's got one. */ for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (protp->demand_conf != NULL) - ((*protp->demand_conf)(pcb)); + if (protp->demand_conf != NULL) + ((*protp->demand_conf)(pcb)); /* FIXME: find a way to die() here */ #if 0 - if (!((*protp->demand_conf)(pcb))) - die(1); + if (!((*protp->demand_conf)(pcb))) + die(1); #endif } @@ -131,8 +131,8 @@ demand_block() const struct protent *protp; for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (protp->demand_conf != NULL) - sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_QUEUE); + if (protp->demand_conf != NULL) + sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_QUEUE); get_loop_output(); } @@ -148,14 +148,14 @@ demand_discard() const struct protent *protp; for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (protp->demand_conf != NULL) - sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_ERROR); + if (protp->demand_conf != NULL) + sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_ERROR); get_loop_output(); /* discard all saved packets */ for (pkt = pend_q; pkt != NULL; pkt = nextpkt) { - nextpkt = pkt->next; - free(pkt); + nextpkt = pkt->next; + free(pkt); } pend_q = NULL; framelen = 0; @@ -174,46 +174,46 @@ demand_unblock() const struct protent *protp; for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (protp->demand_conf != NULL) - sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_PASS); + if (protp->demand_conf != NULL) + sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_PASS); } /* * FCS lookup table as calculated by genfcstab. */ static u_short fcstab[256] = { - 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, - 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, - 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, - 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, - 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, - 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, - 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, - 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, - 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, - 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, - 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, - 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, - 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, - 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, - 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, - 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, - 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, - 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, - 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, - 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, - 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, - 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, - 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, - 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, - 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, - 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, - 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, - 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, - 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, - 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, - 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, - 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 + 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, + 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, + 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, + 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, + 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, + 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, + 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, + 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, + 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, + 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, + 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, + 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, + 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, + 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, + 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, + 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, + 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, + 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, + 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, + 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, + 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, + 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, + 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, + 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, + 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, + 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, + 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, + 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, + 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, + 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, + 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, + 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 }; /* @@ -238,35 +238,35 @@ loop_chars(p, n) } for (; n > 0; --n) { - c = *p++; - if (c == PPP_FLAG) { - if (!escape_flag && !flush_flag - && framelen > 2 && fcs == PPP_GOODFCS) { - framelen -= 2; - if (loop_frame((unsigned char *)frame, framelen)) - rv = 1; - } - framelen = 0; - flush_flag = 0; - escape_flag = 0; - fcs = PPP_INITFCS; - continue; - } - if (flush_flag) - continue; - if (escape_flag) { - c ^= PPP_TRANS; - escape_flag = 0; - } else if (c == PPP_ESCAPE) { - escape_flag = 1; - continue; - } - if (framelen >= framemax) { - flush_flag = 1; - continue; - } - frame[framelen++] = c; - fcs = PPP_FCS(fcs, c); + c = *p++; + if (c == PPP_FLAG) { + if (!escape_flag && !flush_flag + && framelen > 2 && fcs == PPP_GOODFCS) { + framelen -= 2; + if (loop_frame((unsigned char *)frame, framelen)) + rv = 1; + } + framelen = 0; + flush_flag = 0; + escape_flag = 0; + fcs = PPP_INITFCS; + continue; + } + if (flush_flag) + continue; + if (escape_flag) { + c ^= PPP_TRANS; + escape_flag = 0; + } else if (c == PPP_ESCAPE) { + escape_flag = 1; + continue; + } + if (framelen >= framemax) { + flush_flag = 1; + continue; + } + frame[framelen++] = c; + fcs = PPP_FCS(fcs, c); } return rv; } @@ -290,22 +290,22 @@ loop_frame(frame, len) /* dbglog("from loop: %P", frame, len); */ if (len < PPP_HDRLEN) - return 0; + return 0; if ((PPP_PROTOCOL(frame) & 0x8000) != 0) - return 0; /* shouldn't get any of these anyway */ + return 0; /* shouldn't get any of these anyway */ if (!active_packet(frame, len)) - return 0; + return 0; pkt = (struct packet *) malloc(sizeof(struct packet) + len); if (pkt != NULL) { - pkt->length = len; - pkt->next = NULL; - memcpy(pkt->data, frame, len); - if (pend_q == NULL) - pend_q = pkt; - else - pend_qtail->next = pkt; - pend_qtail = pkt; + pkt->length = len; + pkt->next = NULL; + memcpy(pkt->data, frame, len); + if (pend_q == NULL) + pend_q = pkt; + else + pend_qtail->next = pkt; + pend_qtail = pkt; } return 1; } @@ -332,23 +332,23 @@ demand_rexmit(proto, newip) pend_q = NULL; tv.tv_sec = 1; tv.tv_usec = 0; - select(0,NULL,NULL,NULL,&tv); /* Sleep for 1 Seconds */ + select(0,NULL,NULL,NULL,&tv); /* Sleep for 1 Seconds */ for (; pkt != NULL; pkt = nextpkt) { - nextpkt = pkt->next; - if (PPP_PROTOCOL(pkt->data) == proto) { + nextpkt = pkt->next; + if (PPP_PROTOCOL(pkt->data) == proto) { if ( (proto == PPP_IP) && newip ) { - /* Get old checksum */ + /* Get old checksum */ - iphdr = (pkt->data[4] & 15) << 2; - checksum = *((unsigned short *) (pkt->data+14)); + iphdr = (pkt->data[4] & 15) << 2; + checksum = *((unsigned short *) (pkt->data+14)); if (checksum == 0xFFFF) { checksum = 0; } - + if (pkt->data[13] == 17) { pkt_checksum = *((unsigned short *) (pkt->data+10+iphdr)); - if (pkt_checksum) { + if (pkt_checksum) { cv = 1; if (pkt_checksum == 0xFFFF) { pkt_checksum = 0; @@ -359,71 +359,71 @@ demand_rexmit(proto, newip) } } - if (pkt->data[13] == 6) { - pkt_checksum = *((unsigned short *) (pkt->data+20+iphdr)); - cv = 1; + if (pkt->data[13] == 6) { + pkt_checksum = *((unsigned short *) (pkt->data+20+iphdr)); + cv = 1; if (pkt_checksum == 0xFFFF) { pkt_checksum = 0; } - } + } - /* Delete old Source-IP-Address */ + /* Delete old Source-IP-Address */ checksum -= *((unsigned short *) (pkt->data+16)) ^ 0xFFFF; checksum -= *((unsigned short *) (pkt->data+18)) ^ 0xFFFF; - pkt_checksum -= *((unsigned short *) (pkt->data+16)) ^ 0xFFFF; - pkt_checksum -= *((unsigned short *) (pkt->data+18)) ^ 0xFFFF; + pkt_checksum -= *((unsigned short *) (pkt->data+16)) ^ 0xFFFF; + pkt_checksum -= *((unsigned short *) (pkt->data+18)) ^ 0xFFFF; - /* Change Source-IP-Address */ + /* Change Source-IP-Address */ * ((u32_t *) (pkt->data + 16)) = newip; - /* Add new Source-IP-Address */ + /* Add new Source-IP-Address */ checksum += *((unsigned short *) (pkt->data+16)) ^ 0xFFFF; checksum += *((unsigned short *) (pkt->data+18)) ^ 0xFFFF; pkt_checksum += *((unsigned short *) (pkt->data+16)) ^ 0xFFFF; pkt_checksum += *((unsigned short *) (pkt->data+18)) ^ 0xFFFF; - /* Write new checksum */ + /* Write new checksum */ if (!checksum) { checksum = 0xFFFF; } *((unsigned short *) (pkt->data+14)) = checksum; - if (pkt->data[13] == 6) { - *((unsigned short *) (pkt->data+20+iphdr)) = pkt_checksum; - } - if (cv && (pkt->data[13] == 17) ) { - *((unsigned short *) (pkt->data+10+iphdr)) = pkt_checksum; - } + if (pkt->data[13] == 6) { + *((unsigned short *) (pkt->data+20+iphdr)) = pkt_checksum; + } + if (cv && (pkt->data[13] == 17) ) { + *((unsigned short *) (pkt->data+10+iphdr)) = pkt_checksum; + } - /* Log Packet */ - strcpy(ipstr,inet_ntoa(*( (struct in_addr *) (pkt->data+16)))); - if (pkt->data[13] == 1) { - syslog(LOG_INFO,"Open ICMP %s -> %s\n", - ipstr, - inet_ntoa(*( (struct in_addr *) (pkt->data+20)))); - } else { - syslog(LOG_INFO,"Open %s %s:%d -> %s:%d\n", - pkt->data[13] == 6 ? "TCP" : "UDP", - ipstr, - ntohs(*( (short *) (pkt->data+iphdr+4))), - inet_ntoa(*( (struct in_addr *) (pkt->data+20))), - ntohs(*( (short *) (pkt->data+iphdr+6)))); + /* Log Packet */ + strcpy(ipstr,inet_ntoa(*( (struct in_addr *) (pkt->data+16)))); + if (pkt->data[13] == 1) { + syslog(LOG_INFO,"Open ICMP %s -> %s\n", + ipstr, + inet_ntoa(*( (struct in_addr *) (pkt->data+20)))); + } else { + syslog(LOG_INFO,"Open %s %s:%d -> %s:%d\n", + pkt->data[13] == 6 ? "TCP" : "UDP", + ipstr, + ntohs(*( (short *) (pkt->data+iphdr+4))), + inet_ntoa(*( (struct in_addr *) (pkt->data+20))), + ntohs(*( (short *) (pkt->data+iphdr+6)))); } } - output(pcb, pkt->data, pkt->length); - free(pkt); - } else { - if (prev == NULL) - pend_q = pkt; - else - prev->next = pkt; - prev = pkt; - } + output(pcb, pkt->data, pkt->length); + free(pkt); + } else { + if (prev == NULL) + pend_q = pkt; + else + prev->next = pkt; + prev = pkt; + } } pend_qtail = prev; if (prev != NULL) - prev->next = NULL; + prev->next = NULL; } /* @@ -439,27 +439,27 @@ active_packet(p, len) const struct protent *protp; if (len < PPP_HDRLEN) - return 0; + return 0; proto = PPP_PROTOCOL(p); #ifdef PPP_FILTER - p[0] = 1; /* outbound packet indicator */ + p[0] = 1; /* outbound packet indicator */ if ((pass_filter.bf_len != 0 - && bpf_filter(pass_filter.bf_insns, p, len, len) == 0) - || (active_filter.bf_len != 0 - && bpf_filter(active_filter.bf_insns, p, len, len) == 0)) { - p[0] = 0xff; - return 0; + && bpf_filter(pass_filter.bf_insns, p, len, len) == 0) + || (active_filter.bf_len != 0 + && bpf_filter(active_filter.bf_insns, p, len, len) == 0)) { + p[0] = 0xff; + return 0; } p[0] = 0xff; #endif for (i = 0; (protp = protocols[i]) != NULL; ++i) { - if (protp->protocol < 0xC000 && (protp->protocol & ~0x8000) == proto) { - if (protp->active_pkt == NULL) - return 1; - return (*protp->active_pkt)(p, len); - } + if (protp->protocol < 0xC000 && (protp->protocol & ~0x8000) == proto) { + if (protp->active_pkt == NULL) + return 1; + return (*protp->active_pkt)(p, len); } - return 0; /* not a supported protocol !!?? */ + } + return 0; /* not a supported protocol !!?? */ } #endif /* PPP_SUPPORT && DEMAND_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/eap.c b/components/network/lwip/src/netif/ppp/eap.c index 4c627f97..8db756e4 100644 --- a/components/network/lwip/src/netif/ppp/eap.c +++ b/components/network/lwip/src/netif/ppp/eap.c @@ -58,11 +58,11 @@ #endif /* USE_SRP */ #ifndef SHA_DIGESTSIZE -#define SHA_DIGESTSIZE 20 +#define SHA_DIGESTSIZE 20 #endif #ifdef USE_SRP -static char *pn_secret = NULL; /* Pseudonym generating secret */ +static char *pn_secret = NULL; /* Pseudonym generating secret */ #endif #if PPP_OPTIONS @@ -106,31 +106,31 @@ static int eap_printpkt(const u_char *inp, int inlen, #endif /* PRINTPKT_SUPPORT */ const struct protent eap_protent = { - PPP_EAP, /* protocol number */ - eap_init, /* initialization procedure */ - eap_input, /* process a received packet */ - eap_protrej, /* process a received protocol-reject */ - eap_lowerup, /* lower layer has gone up */ - eap_lowerdown, /* lower layer has gone down */ - NULL, /* open the protocol */ - NULL, /* close the protocol */ + PPP_EAP, /* protocol number */ + eap_init, /* initialization procedure */ + eap_input, /* process a received packet */ + eap_protrej, /* process a received protocol-reject */ + eap_lowerup, /* lower layer has gone up */ + eap_lowerdown, /* lower layer has gone down */ + NULL, /* open the protocol */ + NULL, /* close the protocol */ #if PRINTPKT_SUPPORT - eap_printpkt, /* print a packet in readable form */ + eap_printpkt, /* print a packet in readable form */ #endif /* PRINTPKT_SUPPORT */ #if PPP_DATAINPUT - NULL, /* process a received data packet */ + NULL, /* process a received data packet */ #endif /* PPP_DATAINPUT */ #if PRINTPKT_SUPPORT - "EAP", /* text name of protocol */ - NULL, /* text name of corresponding data protocol */ + "EAP", /* text name of protocol */ + NULL, /* text name of corresponding data protocol */ #endif /* PRINTPKT_SUPPORT */ #if PPP_OPTIONS - eap_option_list, /* list of command-line options */ - NULL, /* check requested options; assign defaults */ + eap_option_list, /* list of command-line options */ + NULL, /* check requested options; assign defaults */ #endif /* PPP_OPTIONS */ #if DEMAND_SUPPORT - NULL, /* configure interface for demand-dial */ - NULL /* say whether to bring up link for this pkt */ + NULL, /* configure interface for demand-dial */ + NULL /* say whether to bring up link for this pkt */ #endif /* DEMAND_SUPPORT */ }; @@ -139,38 +139,38 @@ const struct protent eap_protent = { * A well-known 2048 bit modulus. */ static const u_char wkmodulus[] = { - 0xAC, 0x6B, 0xDB, 0x41, 0x32, 0x4A, 0x9A, 0x9B, - 0xF1, 0x66, 0xDE, 0x5E, 0x13, 0x89, 0x58, 0x2F, - 0xAF, 0x72, 0xB6, 0x65, 0x19, 0x87, 0xEE, 0x07, - 0xFC, 0x31, 0x92, 0x94, 0x3D, 0xB5, 0x60, 0x50, - 0xA3, 0x73, 0x29, 0xCB, 0xB4, 0xA0, 0x99, 0xED, - 0x81, 0x93, 0xE0, 0x75, 0x77, 0x67, 0xA1, 0x3D, - 0xD5, 0x23, 0x12, 0xAB, 0x4B, 0x03, 0x31, 0x0D, - 0xCD, 0x7F, 0x48, 0xA9, 0xDA, 0x04, 0xFD, 0x50, - 0xE8, 0x08, 0x39, 0x69, 0xED, 0xB7, 0x67, 0xB0, - 0xCF, 0x60, 0x95, 0x17, 0x9A, 0x16, 0x3A, 0xB3, - 0x66, 0x1A, 0x05, 0xFB, 0xD5, 0xFA, 0xAA, 0xE8, - 0x29, 0x18, 0xA9, 0x96, 0x2F, 0x0B, 0x93, 0xB8, - 0x55, 0xF9, 0x79, 0x93, 0xEC, 0x97, 0x5E, 0xEA, - 0xA8, 0x0D, 0x74, 0x0A, 0xDB, 0xF4, 0xFF, 0x74, - 0x73, 0x59, 0xD0, 0x41, 0xD5, 0xC3, 0x3E, 0xA7, - 0x1D, 0x28, 0x1E, 0x44, 0x6B, 0x14, 0x77, 0x3B, - 0xCA, 0x97, 0xB4, 0x3A, 0x23, 0xFB, 0x80, 0x16, - 0x76, 0xBD, 0x20, 0x7A, 0x43, 0x6C, 0x64, 0x81, - 0xF1, 0xD2, 0xB9, 0x07, 0x87, 0x17, 0x46, 0x1A, - 0x5B, 0x9D, 0x32, 0xE6, 0x88, 0xF8, 0x77, 0x48, - 0x54, 0x45, 0x23, 0xB5, 0x24, 0xB0, 0xD5, 0x7D, - 0x5E, 0xA7, 0x7A, 0x27, 0x75, 0xD2, 0xEC, 0xFA, - 0x03, 0x2C, 0xFB, 0xDB, 0xF5, 0x2F, 0xB3, 0x78, - 0x61, 0x60, 0x27, 0x90, 0x04, 0xE5, 0x7A, 0xE6, - 0xAF, 0x87, 0x4E, 0x73, 0x03, 0xCE, 0x53, 0x29, - 0x9C, 0xCC, 0x04, 0x1C, 0x7B, 0xC3, 0x08, 0xD8, - 0x2A, 0x56, 0x98, 0xF3, 0xA8, 0xD0, 0xC3, 0x82, - 0x71, 0xAE, 0x35, 0xF8, 0xE9, 0xDB, 0xFB, 0xB6, - 0x94, 0xB5, 0xC8, 0x03, 0xD8, 0x9F, 0x7A, 0xE4, - 0x35, 0xDE, 0x23, 0x6D, 0x52, 0x5F, 0x54, 0x75, - 0x9B, 0x65, 0xE3, 0x72, 0xFC, 0xD6, 0x8E, 0xF2, - 0x0F, 0xA7, 0x11, 0x1F, 0x9E, 0x4A, 0xFF, 0x73 + 0xAC, 0x6B, 0xDB, 0x41, 0x32, 0x4A, 0x9A, 0x9B, + 0xF1, 0x66, 0xDE, 0x5E, 0x13, 0x89, 0x58, 0x2F, + 0xAF, 0x72, 0xB6, 0x65, 0x19, 0x87, 0xEE, 0x07, + 0xFC, 0x31, 0x92, 0x94, 0x3D, 0xB5, 0x60, 0x50, + 0xA3, 0x73, 0x29, 0xCB, 0xB4, 0xA0, 0x99, 0xED, + 0x81, 0x93, 0xE0, 0x75, 0x77, 0x67, 0xA1, 0x3D, + 0xD5, 0x23, 0x12, 0xAB, 0x4B, 0x03, 0x31, 0x0D, + 0xCD, 0x7F, 0x48, 0xA9, 0xDA, 0x04, 0xFD, 0x50, + 0xE8, 0x08, 0x39, 0x69, 0xED, 0xB7, 0x67, 0xB0, + 0xCF, 0x60, 0x95, 0x17, 0x9A, 0x16, 0x3A, 0xB3, + 0x66, 0x1A, 0x05, 0xFB, 0xD5, 0xFA, 0xAA, 0xE8, + 0x29, 0x18, 0xA9, 0x96, 0x2F, 0x0B, 0x93, 0xB8, + 0x55, 0xF9, 0x79, 0x93, 0xEC, 0x97, 0x5E, 0xEA, + 0xA8, 0x0D, 0x74, 0x0A, 0xDB, 0xF4, 0xFF, 0x74, + 0x73, 0x59, 0xD0, 0x41, 0xD5, 0xC3, 0x3E, 0xA7, + 0x1D, 0x28, 0x1E, 0x44, 0x6B, 0x14, 0x77, 0x3B, + 0xCA, 0x97, 0xB4, 0x3A, 0x23, 0xFB, 0x80, 0x16, + 0x76, 0xBD, 0x20, 0x7A, 0x43, 0x6C, 0x64, 0x81, + 0xF1, 0xD2, 0xB9, 0x07, 0x87, 0x17, 0x46, 0x1A, + 0x5B, 0x9D, 0x32, 0xE6, 0x88, 0xF8, 0x77, 0x48, + 0x54, 0x45, 0x23, 0xB5, 0x24, 0xB0, 0xD5, 0x7D, + 0x5E, 0xA7, 0x7A, 0x27, 0x75, 0xD2, 0xEC, 0xFA, + 0x03, 0x2C, 0xFB, 0xDB, 0xF5, 0x2F, 0xB3, 0x78, + 0x61, 0x60, 0x27, 0x90, 0x04, 0xE5, 0x7A, 0xE6, + 0xAF, 0x87, 0x4E, 0x73, 0x03, 0xCE, 0x53, 0x29, + 0x9C, 0xCC, 0x04, 0x1C, 0x7B, 0xC3, 0x08, 0xD8, + 0x2A, 0x56, 0x98, 0xF3, 0xA8, 0xD0, 0xC3, 0x82, + 0x71, 0xAE, 0x35, 0xF8, 0xE9, 0xDB, 0xFB, 0xB6, + 0x94, 0xB5, 0xC8, 0x03, 0xD8, 0x9F, 0x7A, 0xE4, + 0x35, 0xDE, 0x23, 0x6D, 0x52, 0x5F, 0x54, 0x75, + 0x9B, 0x65, 0xE3, 0x72, 0xFC, 0xD6, 0x8E, 0xF2, + 0x0F, 0xA7, 0x11, 0x1F, 0x9E, 0x4A, 0xFF, 0x73 }; #endif @@ -184,9 +184,9 @@ static void eap_server_timeout(void *arg); */ static const char * eap_state_name(enum eap_state_code esc) { - static const char *state_names[] = { EAP_STATES }; + static const char *state_names[] = { EAP_STATES }; - return (state_names[(int)esc]); + return (state_names[(int)esc]); } /* @@ -195,9 +195,9 @@ static const char * eap_state_name(enum eap_state_code esc) */ static void eap_init(ppp_pcb *pcb) { - BZERO(&pcb->eap, sizeof(eap_state)); + BZERO(&pcb->eap, sizeof(eap_state)); #if PPP_SERVER - pcb->eap.es_server.ea_id = magic(); + pcb->eap.es_server.ea_id = magic(); #endif /* PPP_SERVER */ } @@ -206,14 +206,14 @@ static void eap_init(ppp_pcb *pcb) { * Request messages. */ static void eap_client_timeout(void *arg) { - ppp_pcb *pcb = (ppp_pcb*)arg; + ppp_pcb *pcb = (ppp_pcb*)arg; - if (!eap_client_active(pcb)) - return; + if (!eap_client_active(pcb)) + return; - ppp_error("EAP: timeout waiting for Request from peer"); - auth_withpeer_fail(pcb, PPP_EAP); - pcb->eap.es_client.ea_state = eapBadAuth; + ppp_error("EAP: timeout waiting for Request from peer"); + auth_withpeer_fail(pcb, PPP_EAP); + pcb->eap.es_client.ea_state = eapBadAuth; } /* @@ -224,22 +224,22 @@ static void eap_client_timeout(void *arg) { */ void eap_authwithpeer(ppp_pcb *pcb, const char *localname) { - if(NULL == localname) - return; + if(NULL == localname) + return; - /* Save the peer name we're given */ - pcb->eap.es_client.ea_name = localname; - pcb->eap.es_client.ea_namelen = strlen(localname); + /* Save the peer name we're given */ + pcb->eap.es_client.ea_name = localname; + pcb->eap.es_client.ea_namelen = strlen(localname); - pcb->eap.es_client.ea_state = eapListen; + pcb->eap.es_client.ea_state = eapListen; - /* - * Start a timer so that if the other end just goes - * silent, we don't sit here waiting forever. - */ - if (pcb->settings.eap_req_time > 0) - TIMEOUT(eap_client_timeout, pcb, - pcb->settings.eap_req_time); + /* + * Start a timer so that if the other end just goes + * silent, we don't sit here waiting forever. + */ + if (pcb->settings.eap_req_time > 0) + TIMEOUT(eap_client_timeout, pcb, + pcb->settings.eap_req_time); } #if PPP_SERVER @@ -248,30 +248,30 @@ void eap_authwithpeer(ppp_pcb *pcb, const char *localname) { * (Server operation) */ static void eap_send_failure(ppp_pcb *pcb) { - struct pbuf *p; - u_char *outp; + struct pbuf *p; + u_char *outp; - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + EAP_HEADERLEN), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + EAP_HEADERLEN), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = (u_char*)p->payload; + outp = (u_char*)p->payload; - MAKEHEADER(outp, PPP_EAP); + MAKEHEADER(outp, PPP_EAP); - PUTCHAR(EAP_FAILURE, outp); - pcb->eap.es_server.ea_id++; - PUTCHAR(pcb->eap.es_server.ea_id, outp); - PUTSHORT(EAP_HEADERLEN, outp); + PUTCHAR(EAP_FAILURE, outp); + pcb->eap.es_server.ea_id++; + PUTCHAR(pcb->eap.es_server.ea_id, outp); + PUTSHORT(EAP_HEADERLEN, outp); - ppp_write(pcb, p); + ppp_write(pcb, p); - pcb->eap.es_server.ea_state = eapBadAuth; - auth_peer_fail(pcb, PPP_EAP); + pcb->eap.es_server.ea_state = eapBadAuth; + auth_peer_fail(pcb, PPP_EAP); } /* @@ -279,30 +279,30 @@ static void eap_send_failure(ppp_pcb *pcb) { * (Server operation) */ static void eap_send_success(ppp_pcb *pcb) { - struct pbuf *p; - u_char *outp; + struct pbuf *p; + u_char *outp; - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + EAP_HEADERLEN), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + EAP_HEADERLEN), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = (u_char*)p->payload; - - MAKEHEADER(outp, PPP_EAP); + outp = (u_char*)p->payload; - PUTCHAR(EAP_SUCCESS, outp); - pcb->eap.es_server.ea_id++; - PUTCHAR(pcb->eap.es_server.ea_id, outp); - PUTSHORT(EAP_HEADERLEN, outp); + MAKEHEADER(outp, PPP_EAP); - ppp_write(pcb, p); + PUTCHAR(EAP_SUCCESS, outp); + pcb->eap.es_server.ea_id++; + PUTCHAR(pcb->eap.es_server.ea_id, outp); + PUTSHORT(EAP_HEADERLEN, outp); - auth_peer_success(pcb, PPP_EAP, 0, - pcb->eap.es_server.ea_peer, pcb->eap.es_server.ea_peerlen); + ppp_write(pcb, p); + + auth_peer_success(pcb, PPP_EAP, 0, + pcb->eap.es_server.ea_peer, pcb->eap.es_server.ea_peerlen); } #endif /* PPP_SERVER */ @@ -314,31 +314,31 @@ static void eap_send_success(ppp_pcb *pcb) { static bool pncrypt_setkey(int timeoffs) { - struct tm *tp; - char tbuf[9]; - SHA1_CTX ctxt; - u_char dig[SHA_DIGESTSIZE]; - time_t reftime; + struct tm *tp; + char tbuf[9]; + SHA1_CTX ctxt; + u_char dig[SHA_DIGESTSIZE]; + time_t reftime; - if (pn_secret == NULL) - return (0); - reftime = time(NULL) + timeoffs; - tp = localtime(&reftime); - SHA1Init(&ctxt); - SHA1Update(&ctxt, pn_secret, strlen(pn_secret)); - strftime(tbuf, sizeof (tbuf), "%Y%m%d", tp); - SHA1Update(&ctxt, tbuf, strlen(tbuf)); - SHA1Final(dig, &ctxt); - /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ - return (DesSetkey(dig)); + if (pn_secret == NULL) + return (0); + reftime = time(NULL) + timeoffs; + tp = localtime(&reftime); + SHA1Init(&ctxt); + SHA1Update(&ctxt, pn_secret, strlen(pn_secret)); + strftime(tbuf, sizeof (tbuf), "%Y%m%d", tp); + SHA1Update(&ctxt, tbuf, strlen(tbuf)); + SHA1Final(dig, &ctxt); + /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ + return (DesSetkey(dig)); } static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; struct b64state { - u32_t bs_bits; - int bs_offs; + u32_t bs_bits; + int bs_offs; }; static int @@ -348,23 +348,23 @@ u_char *inp; int inlen; u_char *outp; { - int outlen = 0; + int outlen = 0; - while (inlen > 0) { - bs->bs_bits = (bs->bs_bits << 8) | *inp++; - inlen--; - bs->bs_offs += 8; - if (bs->bs_offs >= 24) { - *outp++ = base64[(bs->bs_bits >> 18) & 0x3F]; - *outp++ = base64[(bs->bs_bits >> 12) & 0x3F]; - *outp++ = base64[(bs->bs_bits >> 6) & 0x3F]; - *outp++ = base64[bs->bs_bits & 0x3F]; - outlen += 4; - bs->bs_offs = 0; - bs->bs_bits = 0; - } - } - return (outlen); + while (inlen > 0) { + bs->bs_bits = (bs->bs_bits << 8) | *inp++; + inlen--; + bs->bs_offs += 8; + if (bs->bs_offs >= 24) { + *outp++ = base64[(bs->bs_bits >> 18) & 0x3F]; + *outp++ = base64[(bs->bs_bits >> 12) & 0x3F]; + *outp++ = base64[(bs->bs_bits >> 6) & 0x3F]; + *outp++ = base64[bs->bs_bits & 0x3F]; + outlen += 4; + bs->bs_offs = 0; + bs->bs_bits = 0; + } + } + return (outlen); } static int @@ -372,21 +372,21 @@ b64flush(bs, outp) struct b64state *bs; u_char *outp; { - int outlen = 0; + int outlen = 0; - if (bs->bs_offs == 8) { - *outp++ = base64[(bs->bs_bits >> 2) & 0x3F]; - *outp++ = base64[(bs->bs_bits << 4) & 0x3F]; - outlen = 2; - } else if (bs->bs_offs == 16) { - *outp++ = base64[(bs->bs_bits >> 10) & 0x3F]; - *outp++ = base64[(bs->bs_bits >> 4) & 0x3F]; - *outp++ = base64[(bs->bs_bits << 2) & 0x3F]; - outlen = 3; - } - bs->bs_offs = 0; - bs->bs_bits = 0; - return (outlen); + if (bs->bs_offs == 8) { + *outp++ = base64[(bs->bs_bits >> 2) & 0x3F]; + *outp++ = base64[(bs->bs_bits << 4) & 0x3F]; + outlen = 2; + } else if (bs->bs_offs == 16) { + *outp++ = base64[(bs->bs_bits >> 10) & 0x3F]; + *outp++ = base64[(bs->bs_bits >> 4) & 0x3F]; + *outp++ = base64[(bs->bs_bits << 2) & 0x3F]; + outlen = 3; + } + bs->bs_offs = 0; + bs->bs_bits = 0; + return (outlen); } static int @@ -396,22 +396,22 @@ u_char *inp; int inlen; u_char *outp; { - int outlen = 0; - char *cp; + int outlen = 0; + char *cp; - while (inlen > 0) { - if ((cp = strchr(base64, *inp++)) == NULL) - break; - bs->bs_bits = (bs->bs_bits << 6) | (cp - base64); - inlen--; - bs->bs_offs += 6; - if (bs->bs_offs >= 8) { - *outp++ = bs->bs_bits >> (bs->bs_offs - 8); - outlen++; - bs->bs_offs -= 8; - } - } - return (outlen); + while (inlen > 0) { + if ((cp = strchr(base64, *inp++)) == NULL) + break; + bs->bs_bits = (bs->bs_bits << 6) | (cp - base64); + inlen--; + bs->bs_offs += 6; + if (bs->bs_offs >= 8) { + *outp++ = bs->bs_bits >> (bs->bs_offs - 8); + outlen++; + bs->bs_offs -= 8; + } + } + return (outlen); } #endif /* USE_SRP */ @@ -424,211 +424,211 @@ u_char *outp; */ static void eap_figure_next_state(ppp_pcb *pcb, int status) { #ifdef USE_SRP - unsigned char secbuf[MAXSECRETLEN], clear[8], *sp, *dp; - struct t_pw tpw; - struct t_confent *tce, mytce; - char *cp, *cp2; - struct t_server *ts; - int id, i, plen, toffs; - u_char vals[2]; - struct b64state bs; + unsigned char secbuf[MAXSECRETLEN], clear[8], *sp, *dp; + struct t_pw tpw; + struct t_confent *tce, mytce; + char *cp, *cp2; + struct t_server *ts; + int id, i, plen, toffs; + u_char vals[2]; + struct b64state bs; #endif /* USE_SRP */ - pcb->settings.eap_timeout_time = pcb->eap.es_savedtime; - switch (pcb->eap.es_server.ea_state) { - case eapBadAuth: - return; + pcb->settings.eap_timeout_time = pcb->eap.es_savedtime; + switch (pcb->eap.es_server.ea_state) { + case eapBadAuth: + return; - case eapIdentify: + case eapIdentify: #ifdef USE_SRP - /* Discard any previous session. */ - ts = (struct t_server *)pcb->eap.es_server.ea_session; - if (ts != NULL) { - t_serverclose(ts); - pcb->eap.es_server.ea_session = NULL; - pcb->eap.es_server.ea_skey = NULL; - } + /* Discard any previous session. */ + ts = (struct t_server *)pcb->eap.es_server.ea_session; + if (ts != NULL) { + t_serverclose(ts); + pcb->eap.es_server.ea_session = NULL; + pcb->eap.es_server.ea_skey = NULL; + } #endif /* USE_SRP */ - if (status != 0) { - pcb->eap.es_server.ea_state = eapBadAuth; - break; - } + if (status != 0) { + pcb->eap.es_server.ea_state = eapBadAuth; + break; + } #ifdef USE_SRP - /* If we've got a pseudonym, try to decode to real name. */ - if (pcb->eap.es_server.ea_peerlen > SRP_PSEUDO_LEN && - strncmp(pcb->eap.es_server.ea_peer, SRP_PSEUDO_ID, - SRP_PSEUDO_LEN) == 0 && - (pcb->eap.es_server.ea_peerlen - SRP_PSEUDO_LEN) * 3 / 4 < - sizeof (secbuf)) { - BZERO(&bs, sizeof (bs)); - plen = b64dec(&bs, - pcb->eap.es_server.ea_peer + SRP_PSEUDO_LEN, - pcb->eap.es_server.ea_peerlen - SRP_PSEUDO_LEN, - secbuf); - toffs = 0; - for (i = 0; i < 5; i++) { - pncrypt_setkey(toffs); - toffs -= 86400; - /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ - if (!DesDecrypt(secbuf, clear)) { - ppp_dbglog("no DES here; cannot decode " - "pseudonym"); - return; - } - id = *(unsigned char *)clear; - if (id + 1 <= plen && id + 9 > plen) - break; - } - if (plen % 8 == 0 && i < 5) { - /* - * Note that this is always shorter than the - * original stored string, so there's no need - * to realloc. - */ - if ((i = plen = *(unsigned char *)clear) > 7) - i = 7; - pcb->eap.es_server.ea_peerlen = plen; - dp = (unsigned char *)pcb->eap.es_server.ea_peer; - MEMCPY(dp, clear + 1, i); - plen -= i; - dp += i; - sp = secbuf + 8; - while (plen > 0) { - /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ - (void) DesDecrypt(sp, dp); - sp += 8; - dp += 8; - plen -= 8; - } - pcb->eap.es_server.ea_peer[ - pcb->eap.es_server.ea_peerlen] = '\0'; - ppp_dbglog("decoded pseudonym to \"%.*q\"", - pcb->eap.es_server.ea_peerlen, - pcb->eap.es_server.ea_peer); - } else { - ppp_dbglog("failed to decode real name"); - /* Stay in eapIdentfy state; requery */ - break; - } - } - /* Look up user in secrets database. */ - if (get_srp_secret(pcb->eap.es_unit, pcb->eap.es_server.ea_peer, - pcb->eap.es_server.ea_name, (char *)secbuf, 1) != 0) { - /* Set up default in case SRP entry is bad */ - pcb->eap.es_server.ea_state = eapMD5Chall; - /* Get t_confent based on index in srp-secrets */ - id = strtol((char *)secbuf, &cp, 10); - if (*cp++ != ':' || id < 0) - break; - if (id == 0) { - mytce.index = 0; - mytce.modulus.data = (u_char *)wkmodulus; - mytce.modulus.len = sizeof (wkmodulus); - mytce.generator.data = (u_char *)"\002"; - mytce.generator.len = 1; - tce = &mytce; - } else if ((tce = gettcid(id)) != NULL) { - /* - * Client will have to verify this modulus/ - * generator combination, and that will take - * a while. Lengthen the timeout here. - */ - if (pcb->settings.eap_timeout_time > 0 && - pcb->settings.eap_timeout_time < 30) - pcb->settings.eap_timeout_time = 30; - } else { - break; - } - if ((cp2 = strchr(cp, ':')) == NULL) - break; - *cp2++ = '\0'; - tpw.pebuf.name = pcb->eap.es_server.ea_peer; - tpw.pebuf.password.len = t_fromb64((char *)tpw.pwbuf, - cp); - tpw.pebuf.password.data = tpw.pwbuf; - tpw.pebuf.salt.len = t_fromb64((char *)tpw.saltbuf, - cp2); - tpw.pebuf.salt.data = tpw.saltbuf; - if ((ts = t_serveropenraw(&tpw.pebuf, tce)) == NULL) - break; - pcb->eap.es_server.ea_session = (void *)ts; - pcb->eap.es_server.ea_state = eapSRP1; - vals[0] = pcb->eap.es_server.ea_id + 1; - vals[1] = EAPT_SRP; - t_serveraddexdata(ts, vals, 2); - /* Generate B; must call before t_servergetkey() */ - t_servergenexp(ts); - break; - } + /* If we've got a pseudonym, try to decode to real name. */ + if (pcb->eap.es_server.ea_peerlen > SRP_PSEUDO_LEN && + strncmp(pcb->eap.es_server.ea_peer, SRP_PSEUDO_ID, + SRP_PSEUDO_LEN) == 0 && + (pcb->eap.es_server.ea_peerlen - SRP_PSEUDO_LEN) * 3 / 4 < + sizeof (secbuf)) { + BZERO(&bs, sizeof (bs)); + plen = b64dec(&bs, + pcb->eap.es_server.ea_peer + SRP_PSEUDO_LEN, + pcb->eap.es_server.ea_peerlen - SRP_PSEUDO_LEN, + secbuf); + toffs = 0; + for (i = 0; i < 5; i++) { + pncrypt_setkey(toffs); + toffs -= 86400; + /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ + if (!DesDecrypt(secbuf, clear)) { + ppp_dbglog("no DES here; cannot decode " + "pseudonym"); + return; + } + id = *(unsigned char *)clear; + if (id + 1 <= plen && id + 9 > plen) + break; + } + if (plen % 8 == 0 && i < 5) { + /* + * Note that this is always shorter than the + * original stored string, so there's no need + * to realloc. + */ + if ((i = plen = *(unsigned char *)clear) > 7) + i = 7; + pcb->eap.es_server.ea_peerlen = plen; + dp = (unsigned char *)pcb->eap.es_server.ea_peer; + MEMCPY(dp, clear + 1, i); + plen -= i; + dp += i; + sp = secbuf + 8; + while (plen > 0) { + /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ + (void) DesDecrypt(sp, dp); + sp += 8; + dp += 8; + plen -= 8; + } + pcb->eap.es_server.ea_peer[ + pcb->eap.es_server.ea_peerlen] = '\0'; + ppp_dbglog("decoded pseudonym to \"%.*q\"", + pcb->eap.es_server.ea_peerlen, + pcb->eap.es_server.ea_peer); + } else { + ppp_dbglog("failed to decode real name"); + /* Stay in eapIdentfy state; requery */ + break; + } + } + /* Look up user in secrets database. */ + if (get_srp_secret(pcb->eap.es_unit, pcb->eap.es_server.ea_peer, + pcb->eap.es_server.ea_name, (char *)secbuf, 1) != 0) { + /* Set up default in case SRP entry is bad */ + pcb->eap.es_server.ea_state = eapMD5Chall; + /* Get t_confent based on index in srp-secrets */ + id = strtol((char *)secbuf, &cp, 10); + if (*cp++ != ':' || id < 0) + break; + if (id == 0) { + mytce.index = 0; + mytce.modulus.data = (u_char *)wkmodulus; + mytce.modulus.len = sizeof (wkmodulus); + mytce.generator.data = (u_char *)"\002"; + mytce.generator.len = 1; + tce = &mytce; + } else if ((tce = gettcid(id)) != NULL) { + /* + * Client will have to verify this modulus/ + * generator combination, and that will take + * a while. Lengthen the timeout here. + */ + if (pcb->settings.eap_timeout_time > 0 && + pcb->settings.eap_timeout_time < 30) + pcb->settings.eap_timeout_time = 30; + } else { + break; + } + if ((cp2 = strchr(cp, ':')) == NULL) + break; + *cp2++ = '\0'; + tpw.pebuf.name = pcb->eap.es_server.ea_peer; + tpw.pebuf.password.len = t_fromb64((char *)tpw.pwbuf, + cp); + tpw.pebuf.password.data = tpw.pwbuf; + tpw.pebuf.salt.len = t_fromb64((char *)tpw.saltbuf, + cp2); + tpw.pebuf.salt.data = tpw.saltbuf; + if ((ts = t_serveropenraw(&tpw.pebuf, tce)) == NULL) + break; + pcb->eap.es_server.ea_session = (void *)ts; + pcb->eap.es_server.ea_state = eapSRP1; + vals[0] = pcb->eap.es_server.ea_id + 1; + vals[1] = EAPT_SRP; + t_serveraddexdata(ts, vals, 2); + /* Generate B; must call before t_servergetkey() */ + t_servergenexp(ts); + break; + } #endif /* USE_SRP */ - pcb->eap.es_server.ea_state = eapMD5Chall; - break; + pcb->eap.es_server.ea_state = eapMD5Chall; + break; - case eapSRP1: + case eapSRP1: #ifdef USE_SRP - ts = (struct t_server *)pcb->eap.es_server.ea_session; - if (ts != NULL && status != 0) { - t_serverclose(ts); - pcb->eap.es_server.ea_session = NULL; - pcb->eap.es_server.ea_skey = NULL; - } + ts = (struct t_server *)pcb->eap.es_server.ea_session; + if (ts != NULL && status != 0) { + t_serverclose(ts); + pcb->eap.es_server.ea_session = NULL; + pcb->eap.es_server.ea_skey = NULL; + } #endif /* USE_SRP */ - if (status == 1) { - pcb->eap.es_server.ea_state = eapMD5Chall; - } else if (status != 0 || pcb->eap.es_server.ea_session == NULL) { - pcb->eap.es_server.ea_state = eapBadAuth; - } else { - pcb->eap.es_server.ea_state = eapSRP2; - } - break; + if (status == 1) { + pcb->eap.es_server.ea_state = eapMD5Chall; + } else if (status != 0 || pcb->eap.es_server.ea_session == NULL) { + pcb->eap.es_server.ea_state = eapBadAuth; + } else { + pcb->eap.es_server.ea_state = eapSRP2; + } + break; - case eapSRP2: + case eapSRP2: #ifdef USE_SRP - ts = (struct t_server *)pcb->eap.es_server.ea_session; - if (ts != NULL && status != 0) { - t_serverclose(ts); - pcb->eap.es_server.ea_session = NULL; - pcb->eap.es_server.ea_skey = NULL; - } + ts = (struct t_server *)pcb->eap.es_server.ea_session; + if (ts != NULL && status != 0) { + t_serverclose(ts); + pcb->eap.es_server.ea_session = NULL; + pcb->eap.es_server.ea_skey = NULL; + } #endif /* USE_SRP */ - if (status != 0 || pcb->eap.es_server.ea_session == NULL) { - pcb->eap.es_server.ea_state = eapBadAuth; - } else { - pcb->eap.es_server.ea_state = eapSRP3; - } - break; + if (status != 0 || pcb->eap.es_server.ea_session == NULL) { + pcb->eap.es_server.ea_state = eapBadAuth; + } else { + pcb->eap.es_server.ea_state = eapSRP3; + } + break; - case eapSRP3: - case eapSRP4: + case eapSRP3: + case eapSRP4: #ifdef USE_SRP - ts = (struct t_server *)pcb->eap.es_server.ea_session; - if (ts != NULL && status != 0) { - t_serverclose(ts); - pcb->eap.es_server.ea_session = NULL; - pcb->eap.es_server.ea_skey = NULL; - } + ts = (struct t_server *)pcb->eap.es_server.ea_session; + if (ts != NULL && status != 0) { + t_serverclose(ts); + pcb->eap.es_server.ea_session = NULL; + pcb->eap.es_server.ea_skey = NULL; + } #endif /* USE_SRP */ - if (status != 0 || pcb->eap.es_server.ea_session == NULL) { - pcb->eap.es_server.ea_state = eapBadAuth; - } else { - pcb->eap.es_server.ea_state = eapOpen; - } - break; + if (status != 0 || pcb->eap.es_server.ea_session == NULL) { + pcb->eap.es_server.ea_state = eapBadAuth; + } else { + pcb->eap.es_server.ea_state = eapOpen; + } + break; - case eapMD5Chall: - if (status != 0) { - pcb->eap.es_server.ea_state = eapBadAuth; - } else { - pcb->eap.es_server.ea_state = eapOpen; - } - break; + case eapMD5Chall: + if (status != 0) { + pcb->eap.es_server.ea_state = eapBadAuth; + } else { + pcb->eap.es_server.ea_state = eapOpen; + } + break; - default: - pcb->eap.es_server.ea_state = eapBadAuth; - break; - } - if (pcb->eap.es_server.ea_state == eapBadAuth) - eap_send_failure(pcb); + default: + pcb->eap.es_server.ea_state = eapBadAuth; + break; + } + if (pcb->eap.es_server.ea_state == eapBadAuth) + eap_send_failure(pcb); } /* @@ -636,235 +636,235 @@ static void eap_figure_next_state(ppp_pcb *pcb, int status) { * type depends on current state. (Server operation) */ static void eap_send_request(ppp_pcb *pcb) { - struct pbuf *p; - u_char *outp; - u_char *lenloc; - int outlen; - int len; - const char *str; + struct pbuf *p; + u_char *outp; + u_char *lenloc; + int outlen; + int len; + const char *str; #ifdef USE_SRP - struct t_server *ts; - u_char clear[8], cipher[8], dig[SHA_DIGESTSIZE], *optr, *cp; - int i, j; - struct b64state b64; - SHA1_CTX ctxt; + struct t_server *ts; + u_char clear[8], cipher[8], dig[SHA_DIGESTSIZE], *optr, *cp; + int i, j; + struct b64state b64; + SHA1_CTX ctxt; #endif /* USE_SRP */ - /* Handle both initial auth and restart */ - if (pcb->eap.es_server.ea_state < eapIdentify && - pcb->eap.es_server.ea_state != eapInitial) { - pcb->eap.es_server.ea_state = eapIdentify; + /* Handle both initial auth and restart */ + if (pcb->eap.es_server.ea_state < eapIdentify && + pcb->eap.es_server.ea_state != eapInitial) { + pcb->eap.es_server.ea_state = eapIdentify; #if PPP_REMOTENAME - if (pcb->settings.explicit_remote && pcb->remote_name) { - /* - * If we already know the peer's - * unauthenticated name, then there's no - * reason to ask. Go to next state instead. - */ - int len = (int)strlen(pcb->remote_name); - if (len > MAXNAMELEN) { - len = MAXNAMELEN; - } - MEMCPY(pcb->eap.es_server.ea_peer, pcb->remote_name, len); - pcb->eap.es_server.ea_peer[len] = '\0'; - pcb->eap.es_server.ea_peerlen = len; - eap_figure_next_state(pcb, 0); - } + if (pcb->settings.explicit_remote && pcb->remote_name) { + /* + * If we already know the peer's + * unauthenticated name, then there's no + * reason to ask. Go to next state instead. + */ + int len = (int)strlen(pcb->remote_name); + if (len > MAXNAMELEN) { + len = MAXNAMELEN; + } + MEMCPY(pcb->eap.es_server.ea_peer, pcb->remote_name, len); + pcb->eap.es_server.ea_peer[len] = '\0'; + pcb->eap.es_server.ea_peerlen = len; + eap_figure_next_state(pcb, 0); + } #endif /* PPP_REMOTENAME */ - } + } - if (pcb->settings.eap_max_transmits > 0 && - pcb->eap.es_server.ea_requests >= pcb->settings.eap_max_transmits) { - if (pcb->eap.es_server.ea_responses > 0) - ppp_error("EAP: too many Requests sent"); - else - ppp_error("EAP: no response to Requests"); - eap_send_failure(pcb); - return; - } + if (pcb->settings.eap_max_transmits > 0 && + pcb->eap.es_server.ea_requests >= pcb->settings.eap_max_transmits) { + if (pcb->eap.es_server.ea_responses > 0) + ppp_error("EAP: too many Requests sent"); + else + ppp_error("EAP: no response to Requests"); + eap_send_failure(pcb); + return; + } - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_CTRL_PBUF_MAX_SIZE), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_CTRL_PBUF_MAX_SIZE), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = (u_char*)p->payload; - - MAKEHEADER(outp, PPP_EAP); + outp = (u_char*)p->payload; - PUTCHAR(EAP_REQUEST, outp); - PUTCHAR(pcb->eap.es_server.ea_id, outp); - lenloc = outp; - INCPTR(2, outp); + MAKEHEADER(outp, PPP_EAP); - switch (pcb->eap.es_server.ea_state) { - case eapIdentify: - PUTCHAR(EAPT_IDENTITY, outp); - str = "Name"; - len = strlen(str); - MEMCPY(outp, str, len); - INCPTR(len, outp); - break; + PUTCHAR(EAP_REQUEST, outp); + PUTCHAR(pcb->eap.es_server.ea_id, outp); + lenloc = outp; + INCPTR(2, outp); - case eapMD5Chall: - PUTCHAR(EAPT_MD5CHAP, outp); - /* - * pick a random challenge length between - * EAP_MIN_CHALLENGE_LENGTH and EAP_MAX_CHALLENGE_LENGTH - */ - pcb->eap.es_challen = EAP_MIN_CHALLENGE_LENGTH + - magic_pow(EAP_MIN_MAX_POWER_OF_TWO_CHALLENGE_LENGTH); - PUTCHAR(pcb->eap.es_challen, outp); - magic_random_bytes(pcb->eap.es_challenge, pcb->eap.es_challen); - MEMCPY(outp, pcb->eap.es_challenge, pcb->eap.es_challen); - INCPTR(pcb->eap.es_challen, outp); - MEMCPY(outp, pcb->eap.es_server.ea_name, pcb->eap.es_server.ea_namelen); - INCPTR(pcb->eap.es_server.ea_namelen, outp); - break; + switch (pcb->eap.es_server.ea_state) { + case eapIdentify: + PUTCHAR(EAPT_IDENTITY, outp); + str = "Name"; + len = strlen(str); + MEMCPY(outp, str, len); + INCPTR(len, outp); + break; + + case eapMD5Chall: + PUTCHAR(EAPT_MD5CHAP, outp); + /* + * pick a random challenge length between + * EAP_MIN_CHALLENGE_LENGTH and EAP_MAX_CHALLENGE_LENGTH + */ + pcb->eap.es_challen = EAP_MIN_CHALLENGE_LENGTH + + magic_pow(EAP_MIN_MAX_POWER_OF_TWO_CHALLENGE_LENGTH); + PUTCHAR(pcb->eap.es_challen, outp); + magic_random_bytes(pcb->eap.es_challenge, pcb->eap.es_challen); + MEMCPY(outp, pcb->eap.es_challenge, pcb->eap.es_challen); + INCPTR(pcb->eap.es_challen, outp); + MEMCPY(outp, pcb->eap.es_server.ea_name, pcb->eap.es_server.ea_namelen); + INCPTR(pcb->eap.es_server.ea_namelen, outp); + break; #ifdef USE_SRP - case eapSRP1: - PUTCHAR(EAPT_SRP, outp); - PUTCHAR(EAPSRP_CHALLENGE, outp); + case eapSRP1: + PUTCHAR(EAPT_SRP, outp); + PUTCHAR(EAPSRP_CHALLENGE, outp); - PUTCHAR(pcb->eap.es_server.ea_namelen, outp); - MEMCPY(outp, pcb->eap.es_server.ea_name, pcb->eap.es_server.ea_namelen); - INCPTR(pcb->eap.es_server.ea_namelen, outp); + PUTCHAR(pcb->eap.es_server.ea_namelen, outp); + MEMCPY(outp, pcb->eap.es_server.ea_name, pcb->eap.es_server.ea_namelen); + INCPTR(pcb->eap.es_server.ea_namelen, outp); - ts = (struct t_server *)pcb->eap.es_server.ea_session; - assert(ts != NULL); - PUTCHAR(ts->s.len, outp); - MEMCPY(outp, ts->s.data, ts->s.len); - INCPTR(ts->s.len, outp); + ts = (struct t_server *)pcb->eap.es_server.ea_session; + assert(ts != NULL); + PUTCHAR(ts->s.len, outp); + MEMCPY(outp, ts->s.data, ts->s.len); + INCPTR(ts->s.len, outp); - if (ts->g.len == 1 && ts->g.data[0] == 2) { - PUTCHAR(0, outp); - } else { - PUTCHAR(ts->g.len, outp); - MEMCPY(outp, ts->g.data, ts->g.len); - INCPTR(ts->g.len, outp); - } + if (ts->g.len == 1 && ts->g.data[0] == 2) { + PUTCHAR(0, outp); + } else { + PUTCHAR(ts->g.len, outp); + MEMCPY(outp, ts->g.data, ts->g.len); + INCPTR(ts->g.len, outp); + } - if (ts->n.len != sizeof (wkmodulus) || - BCMP(ts->n.data, wkmodulus, sizeof (wkmodulus)) != 0) { - MEMCPY(outp, ts->n.data, ts->n.len); - INCPTR(ts->n.len, outp); - } - break; + if (ts->n.len != sizeof (wkmodulus) || + BCMP(ts->n.data, wkmodulus, sizeof (wkmodulus)) != 0) { + MEMCPY(outp, ts->n.data, ts->n.len); + INCPTR(ts->n.len, outp); + } + break; - case eapSRP2: - PUTCHAR(EAPT_SRP, outp); - PUTCHAR(EAPSRP_SKEY, outp); + case eapSRP2: + PUTCHAR(EAPT_SRP, outp); + PUTCHAR(EAPSRP_SKEY, outp); - ts = (struct t_server *)pcb->eap.es_server.ea_session; - assert(ts != NULL); - MEMCPY(outp, ts->B.data, ts->B.len); - INCPTR(ts->B.len, outp); - break; + ts = (struct t_server *)pcb->eap.es_server.ea_session; + assert(ts != NULL); + MEMCPY(outp, ts->B.data, ts->B.len); + INCPTR(ts->B.len, outp); + break; - case eapSRP3: - PUTCHAR(EAPT_SRP, outp); - PUTCHAR(EAPSRP_SVALIDATOR, outp); - PUTLONG(SRPVAL_EBIT, outp); - ts = (struct t_server *)pcb->eap.es_server.ea_session; - assert(ts != NULL); - MEMCPY(outp, t_serverresponse(ts), SHA_DIGESTSIZE); - INCPTR(SHA_DIGESTSIZE, outp); + case eapSRP3: + PUTCHAR(EAPT_SRP, outp); + PUTCHAR(EAPSRP_SVALIDATOR, outp); + PUTLONG(SRPVAL_EBIT, outp); + ts = (struct t_server *)pcb->eap.es_server.ea_session; + assert(ts != NULL); + MEMCPY(outp, t_serverresponse(ts), SHA_DIGESTSIZE); + INCPTR(SHA_DIGESTSIZE, outp); - if (pncrypt_setkey(0)) { - /* Generate pseudonym */ - optr = outp; - cp = (unsigned char *)pcb->eap.es_server.ea_peer; - if ((j = i = pcb->eap.es_server.ea_peerlen) > 7) - j = 7; - clear[0] = i; - MEMCPY(clear + 1, cp, j); - i -= j; - cp += j; - /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ - if (!DesEncrypt(clear, cipher)) { - ppp_dbglog("no DES here; not generating pseudonym"); - break; - } - BZERO(&b64, sizeof (b64)); - outp++; /* space for pseudonym length */ - outp += b64enc(&b64, cipher, 8, outp); - while (i >= 8) { - /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ - (void) DesEncrypt(cp, cipher); - outp += b64enc(&b64, cipher, 8, outp); - cp += 8; - i -= 8; - } - if (i > 0) { - MEMCPY(clear, cp, i); - cp += i; - magic_random_bytes(cp, 8-i); - /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ - (void) DesEncrypt(clear, cipher); - outp += b64enc(&b64, cipher, 8, outp); - } - outp += b64flush(&b64, outp); + if (pncrypt_setkey(0)) { + /* Generate pseudonym */ + optr = outp; + cp = (unsigned char *)pcb->eap.es_server.ea_peer; + if ((j = i = pcb->eap.es_server.ea_peerlen) > 7) + j = 7; + clear[0] = i; + MEMCPY(clear + 1, cp, j); + i -= j; + cp += j; + /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ + if (!DesEncrypt(clear, cipher)) { + ppp_dbglog("no DES here; not generating pseudonym"); + break; + } + BZERO(&b64, sizeof (b64)); + outp++; /* space for pseudonym length */ + outp += b64enc(&b64, cipher, 8, outp); + while (i >= 8) { + /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ + (void) DesEncrypt(cp, cipher); + outp += b64enc(&b64, cipher, 8, outp); + cp += 8; + i -= 8; + } + if (i > 0) { + MEMCPY(clear, cp, i); + cp += i; + magic_random_bytes(cp, 8-i); + /* FIXME: if we want to do SRP, we need to find a way to pass the PolarSSL des_context instead of using static memory */ + (void) DesEncrypt(clear, cipher); + outp += b64enc(&b64, cipher, 8, outp); + } + outp += b64flush(&b64, outp); - /* Set length and pad out to next 20 octet boundary */ - i = outp - optr - 1; - *optr = i; - i %= SHA_DIGESTSIZE; - if (i != 0) { - magic_random_bytes(outp, SHA_DIGESTSIZE-i); - INCPTR(SHA_DIGESTSIZE-i, outp); - } + /* Set length and pad out to next 20 octet boundary */ + i = outp - optr - 1; + *optr = i; + i %= SHA_DIGESTSIZE; + if (i != 0) { + magic_random_bytes(outp, SHA_DIGESTSIZE-i); + INCPTR(SHA_DIGESTSIZE-i, outp); + } - /* Obscure the pseudonym with SHA1 hash */ - SHA1Init(&ctxt); - SHA1Update(&ctxt, &pcb->eap.es_server.ea_id, 1); - SHA1Update(&ctxt, pcb->eap.es_server.ea_skey, - SESSION_KEY_LEN); - SHA1Update(&ctxt, pcb->eap.es_server.ea_peer, - pcb->eap.es_server.ea_peerlen); - while (optr < outp) { - SHA1Final(dig, &ctxt); - cp = dig; - while (cp < dig + SHA_DIGESTSIZE) - *optr++ ^= *cp++; - SHA1Init(&ctxt); - SHA1Update(&ctxt, &pcb->eap.es_server.ea_id, 1); - SHA1Update(&ctxt, pcb->eap.es_server.ea_skey, - SESSION_KEY_LEN); - SHA1Update(&ctxt, optr - SHA_DIGESTSIZE, - SHA_DIGESTSIZE); - } - } - break; + /* Obscure the pseudonym with SHA1 hash */ + SHA1Init(&ctxt); + SHA1Update(&ctxt, &pcb->eap.es_server.ea_id, 1); + SHA1Update(&ctxt, pcb->eap.es_server.ea_skey, + SESSION_KEY_LEN); + SHA1Update(&ctxt, pcb->eap.es_server.ea_peer, + pcb->eap.es_server.ea_peerlen); + while (optr < outp) { + SHA1Final(dig, &ctxt); + cp = dig; + while (cp < dig + SHA_DIGESTSIZE) + *optr++ ^= *cp++; + SHA1Init(&ctxt); + SHA1Update(&ctxt, &pcb->eap.es_server.ea_id, 1); + SHA1Update(&ctxt, pcb->eap.es_server.ea_skey, + SESSION_KEY_LEN); + SHA1Update(&ctxt, optr - SHA_DIGESTSIZE, + SHA_DIGESTSIZE); + } + } + break; - case eapSRP4: - PUTCHAR(EAPT_SRP, outp); - PUTCHAR(EAPSRP_LWRECHALLENGE, outp); - pcb->eap.es_challen = EAP_MIN_CHALLENGE_LENGTH + - magic_pow(EAP_MIN_MAX_POWER_OF_TWO_CHALLENGE_LENGTH); - magic_random_bytes(pcb->eap.es_challenge, pcb->eap.es_challen); - MEMCPY(outp, pcb->eap.es_challenge, pcb->eap.es_challen); - INCPTR(pcb->eap.es_challen, outp); - break; + case eapSRP4: + PUTCHAR(EAPT_SRP, outp); + PUTCHAR(EAPSRP_LWRECHALLENGE, outp); + pcb->eap.es_challen = EAP_MIN_CHALLENGE_LENGTH + + magic_pow(EAP_MIN_MAX_POWER_OF_TWO_CHALLENGE_LENGTH); + magic_random_bytes(pcb->eap.es_challenge, pcb->eap.es_challen); + MEMCPY(outp, pcb->eap.es_challenge, pcb->eap.es_challen); + INCPTR(pcb->eap.es_challen, outp); + break; #endif /* USE_SRP */ - default: - return; - } + default: + return; + } - outlen = (outp - (unsigned char*)p->payload) - PPP_HDRLEN; - PUTSHORT(outlen, lenloc); + outlen = (outp - (unsigned char*)p->payload) - PPP_HDRLEN; + PUTSHORT(outlen, lenloc); - pbuf_realloc(p, outlen + PPP_HDRLEN); - ppp_write(pcb, p); + pbuf_realloc(p, outlen + PPP_HDRLEN); + ppp_write(pcb, p); - pcb->eap.es_server.ea_requests++; + pcb->eap.es_server.ea_requests++; - if (pcb->settings.eap_timeout_time > 0) - TIMEOUT(eap_server_timeout, pcb, pcb->settings.eap_timeout_time); + if (pcb->settings.eap_timeout_time > 0) + TIMEOUT(eap_server_timeout, pcb, pcb->settings.eap_timeout_time); } /* @@ -875,23 +875,23 @@ static void eap_send_request(ppp_pcb *pcb) { */ void eap_authpeer(ppp_pcb *pcb, const char *localname) { - /* Save the name we're given. */ - pcb->eap.es_server.ea_name = localname; - pcb->eap.es_server.ea_namelen = strlen(localname); + /* Save the name we're given. */ + pcb->eap.es_server.ea_name = localname; + pcb->eap.es_server.ea_namelen = strlen(localname); - pcb->eap.es_savedtime = pcb->settings.eap_timeout_time; + pcb->eap.es_savedtime = pcb->settings.eap_timeout_time; - /* Lower layer up yet? */ - if (pcb->eap.es_server.ea_state == eapInitial || - pcb->eap.es_server.ea_state == eapPending) { - pcb->eap.es_server.ea_state = eapPending; - return; - } + /* Lower layer up yet? */ + if (pcb->eap.es_server.ea_state == eapInitial || + pcb->eap.es_server.ea_state == eapPending) { + pcb->eap.es_server.ea_state = eapPending; + return; + } - pcb->eap.es_server.ea_state = eapPending; + pcb->eap.es_server.ea_state = eapPending; - /* ID number not updated here intentionally; hashed into M1 */ - eap_send_request(pcb); + /* ID number not updated here intentionally; hashed into M1 */ + eap_send_request(pcb); } /* @@ -899,13 +899,13 @@ void eap_authpeer(ppp_pcb *pcb, const char *localname) { * expired. */ static void eap_server_timeout(void *arg) { - ppp_pcb *pcb = (ppp_pcb*)arg; + ppp_pcb *pcb = (ppp_pcb*)arg; - if (!eap_server_active(pcb)) - return; + if (!eap_server_active(pcb)) + return; - /* EAP ID number must not change on timeout. */ - eap_send_request(pcb); + /* EAP ID number must not change on timeout. */ + eap_send_request(pcb); } /* @@ -914,30 +914,30 @@ static void eap_server_timeout(void *arg) { * will restart the timer. If it fails, then the link is dropped. */ static void eap_rechallenge(void *arg) { - ppp_pcb *pcb = (ppp_pcb*)arg; + ppp_pcb *pcb = (ppp_pcb*)arg; - if (pcb->eap.es_server.ea_state != eapOpen && - pcb->eap.es_server.ea_state != eapSRP4) - return; + if (pcb->eap.es_server.ea_state != eapOpen && + pcb->eap.es_server.ea_state != eapSRP4) + return; - pcb->eap.es_server.ea_requests = 0; - pcb->eap.es_server.ea_state = eapIdentify; - eap_figure_next_state(pcb, 0); - pcb->eap.es_server.ea_id++; - eap_send_request(pcb); + pcb->eap.es_server.ea_requests = 0; + pcb->eap.es_server.ea_state = eapIdentify; + eap_figure_next_state(pcb, 0); + pcb->eap.es_server.ea_id++; + eap_send_request(pcb); } static void srp_lwrechallenge(void *arg) { - ppp_pcb *pcb = (ppp_pcb*)arg; + ppp_pcb *pcb = (ppp_pcb*)arg; - if (pcb->eap.es_server.ea_state != eapOpen || - pcb->eap.es_server.ea_type != EAPT_SRP) - return; + if (pcb->eap.es_server.ea_state != eapOpen || + pcb->eap.es_server.ea_type != EAPT_SRP) + return; - pcb->eap.es_server.ea_requests = 0; - pcb->eap.es_server.ea_state = eapSRP4; - pcb->eap.es_server.ea_id++; - eap_send_request(pcb); + pcb->eap.es_server.ea_requests = 0; + pcb->eap.es_server.ea_state = eapSRP4; + pcb->eap.es_server.ea_id++; + eap_send_request(pcb); } #endif /* PPP_SERVER */ @@ -950,9 +950,9 @@ static void srp_lwrechallenge(void *arg) { * thing. */ static void eap_lowerup(ppp_pcb *pcb) { - pcb->eap.es_client.ea_state = eapClosed; + pcb->eap.es_client.ea_state = eapClosed; #if PPP_SERVER - pcb->eap.es_server.ea_state = eapClosed; + pcb->eap.es_server.ea_state = eapClosed; #endif /* PPP_SERVER */ } @@ -963,28 +963,28 @@ static void eap_lowerup(ppp_pcb *pcb) { */ static void eap_lowerdown(ppp_pcb *pcb) { - if (eap_client_active(pcb) && pcb->settings.eap_req_time > 0) { - UNTIMEOUT(eap_client_timeout, pcb); - } + if (eap_client_active(pcb) && pcb->settings.eap_req_time > 0) { + UNTIMEOUT(eap_client_timeout, pcb); + } #if PPP_SERVER - if (eap_server_active(pcb)) { - if (pcb->settings.eap_timeout_time > 0) { - UNTIMEOUT(eap_server_timeout, pcb); - } - } else { - if ((pcb->eap.es_server.ea_state == eapOpen || - pcb->eap.es_server.ea_state == eapSRP4) && - pcb->eap.es_rechallenge > 0) { - UNTIMEOUT(eap_rechallenge, (void *)pcb); - } - if (pcb->eap.es_server.ea_state == eapOpen && - pcb->eap.es_lwrechallenge > 0) { - UNTIMEOUT(srp_lwrechallenge, (void *)pcb); - } - } + if (eap_server_active(pcb)) { + if (pcb->settings.eap_timeout_time > 0) { + UNTIMEOUT(eap_server_timeout, pcb); + } + } else { + if ((pcb->eap.es_server.ea_state == eapOpen || + pcb->eap.es_server.ea_state == eapSRP4) && + pcb->eap.es_rechallenge > 0) { + UNTIMEOUT(eap_rechallenge, (void *)pcb); + } + if (pcb->eap.es_server.ea_state == eapOpen && + pcb->eap.es_lwrechallenge > 0) { + UNTIMEOUT(srp_lwrechallenge, (void *)pcb); + } + } - pcb->eap.es_client.ea_state = pcb->eap.es_server.ea_state = eapInitial; - pcb->eap.es_client.ea_requests = pcb->eap.es_server.ea_requests = 0; + pcb->eap.es_client.ea_state = pcb->eap.es_server.ea_state = eapInitial; + pcb->eap.es_client.ea_requests = pcb->eap.es_server.ea_requests = 0; #endif /* PPP_SERVER */ } @@ -996,87 +996,87 @@ static void eap_lowerdown(ppp_pcb *pcb) { */ static void eap_protrej(ppp_pcb *pcb) { - if (eap_client_active(pcb)) { - ppp_error("EAP authentication failed due to Protocol-Reject"); - auth_withpeer_fail(pcb, PPP_EAP); - } + if (eap_client_active(pcb)) { + ppp_error("EAP authentication failed due to Protocol-Reject"); + auth_withpeer_fail(pcb, PPP_EAP); + } #if PPP_SERVER - if (eap_server_active(pcb)) { - ppp_error("EAP authentication of peer failed on Protocol-Reject"); - auth_peer_fail(pcb, PPP_EAP); - } + if (eap_server_active(pcb)) { + ppp_error("EAP authentication of peer failed on Protocol-Reject"); + auth_peer_fail(pcb, PPP_EAP); + } #endif /* PPP_SERVER */ - eap_lowerdown(pcb); + eap_lowerdown(pcb); } /* * Format and send a regular EAP Response message. */ static void eap_send_response(ppp_pcb *pcb, u_char id, u_char typenum, const u_char *str, int lenstr) { - struct pbuf *p; - u_char *outp; - int msglen; + struct pbuf *p; + u_char *outp; + int msglen; - msglen = EAP_HEADERLEN + sizeof (u_char) + lenstr; - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + msglen = EAP_HEADERLEN + sizeof (u_char) + lenstr; + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = (u_char*)p->payload; + outp = (u_char*)p->payload; - MAKEHEADER(outp, PPP_EAP); + MAKEHEADER(outp, PPP_EAP); - PUTCHAR(EAP_RESPONSE, outp); - PUTCHAR(id, outp); - pcb->eap.es_client.ea_id = id; - PUTSHORT(msglen, outp); - PUTCHAR(typenum, outp); - if (lenstr > 0) { - MEMCPY(outp, str, lenstr); - } + PUTCHAR(EAP_RESPONSE, outp); + PUTCHAR(id, outp); + pcb->eap.es_client.ea_id = id; + PUTSHORT(msglen, outp); + PUTCHAR(typenum, outp); + if (lenstr > 0) { + MEMCPY(outp, str, lenstr); + } - ppp_write(pcb, p); + ppp_write(pcb, p); } /* * Format and send an MD5-Challenge EAP Response message. */ static void eap_chap_response(ppp_pcb *pcb, u_char id, u_char *hash, const char *name, int namelen) { - struct pbuf *p; - u_char *outp; - int msglen; + struct pbuf *p; + u_char *outp; + int msglen; - msglen = EAP_HEADERLEN + 2 * sizeof (u_char) + MD5_SIGNATURE_SIZE + - namelen; - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + msglen = EAP_HEADERLEN + 2 * sizeof (u_char) + MD5_SIGNATURE_SIZE + + namelen; + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = (u_char*)p->payload; - - MAKEHEADER(outp, PPP_EAP); + outp = (u_char*)p->payload; - PUTCHAR(EAP_RESPONSE, outp); - PUTCHAR(id, outp); - pcb->eap.es_client.ea_id = id; - PUTSHORT(msglen, outp); - PUTCHAR(EAPT_MD5CHAP, outp); - PUTCHAR(MD5_SIGNATURE_SIZE, outp); - MEMCPY(outp, hash, MD5_SIGNATURE_SIZE); - INCPTR(MD5_SIGNATURE_SIZE, outp); - if (namelen > 0) { - MEMCPY(outp, name, namelen); - } + MAKEHEADER(outp, PPP_EAP); - ppp_write(pcb, p); + PUTCHAR(EAP_RESPONSE, outp); + PUTCHAR(id, outp); + pcb->eap.es_client.ea_id = id; + PUTSHORT(msglen, outp); + PUTCHAR(EAPT_MD5CHAP, outp); + PUTCHAR(MD5_SIGNATURE_SIZE, outp); + MEMCPY(outp, hash, MD5_SIGNATURE_SIZE); + INCPTR(MD5_SIGNATURE_SIZE, outp); + if (namelen > 0) { + MEMCPY(outp, name, namelen); + } + + ppp_write(pcb, p); } #ifdef USE_SRP @@ -1091,35 +1091,35 @@ u_char subtypenum; u_char *str; int lenstr; { - ppp_pcb *pcb = &ppp_pcb_list[pcb->eap.es_unit]; - struct pbuf *p; - u_char *outp; - int msglen; + ppp_pcb *pcb = &ppp_pcb_list[pcb->eap.es_unit]; + struct pbuf *p; + u_char *outp; + int msglen; - msglen = EAP_HEADERLEN + 2 * sizeof (u_char) + lenstr; - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + msglen = EAP_HEADERLEN + 2 * sizeof (u_char) + lenstr; + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = p->payload; + outp = p->payload; - MAKEHEADER(outp, PPP_EAP); + MAKEHEADER(outp, PPP_EAP); - PUTCHAR(EAP_RESPONSE, outp); - PUTCHAR(id, outp); - pcb->eap.es_client.ea_id = id; - PUTSHORT(msglen, outp); - PUTCHAR(EAPT_SRP, outp); - PUTCHAR(subtypenum, outp); - if (lenstr > 0) { - MEMCPY(outp, str, lenstr); - } + PUTCHAR(EAP_RESPONSE, outp); + PUTCHAR(id, outp); + pcb->eap.es_client.ea_id = id; + PUTSHORT(msglen, outp); + PUTCHAR(EAPT_SRP, outp); + PUTCHAR(subtypenum, outp); + if (lenstr > 0) { + MEMCPY(outp, str, lenstr); + } - ppp_write(pcb, p); + ppp_write(pcb, p); } /* @@ -1132,118 +1132,118 @@ u_char id; u32_t flags; u_char *str; { - ppp_pcb *pcb = &ppp_pcb_list[pcb->eap.es_unit]; - struct pbuf *p; - u_char *outp; - int msglen; + ppp_pcb *pcb = &ppp_pcb_list[pcb->eap.es_unit]; + struct pbuf *p; + u_char *outp; + int msglen; - msglen = EAP_HEADERLEN + 2 * sizeof (u_char) + sizeof (u32_t) + - SHA_DIGESTSIZE; - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + msglen = EAP_HEADERLEN + 2 * sizeof (u_char) + sizeof (u32_t) + + SHA_DIGESTSIZE; + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = p->payload; + outp = p->payload; - MAKEHEADER(outp, PPP_EAP); + MAKEHEADER(outp, PPP_EAP); - PUTCHAR(EAP_RESPONSE, outp); - PUTCHAR(id, outp); - pcb->eap.es_client.ea_id = id; - PUTSHORT(msglen, outp); - PUTCHAR(EAPT_SRP, outp); - PUTCHAR(EAPSRP_CVALIDATOR, outp); - PUTLONG(flags, outp); - MEMCPY(outp, str, SHA_DIGESTSIZE); + PUTCHAR(EAP_RESPONSE, outp); + PUTCHAR(id, outp); + pcb->eap.es_client.ea_id = id; + PUTSHORT(msglen, outp); + PUTCHAR(EAPT_SRP, outp); + PUTCHAR(EAPSRP_CVALIDATOR, outp); + PUTLONG(flags, outp); + MEMCPY(outp, str, SHA_DIGESTSIZE); - ppp_write(pcb, p); + ppp_write(pcb, p); } #endif /* USE_SRP */ static void eap_send_nak(ppp_pcb *pcb, u_char id, u_char type) { - struct pbuf *p; - u_char *outp; - int msglen; + struct pbuf *p; + u_char *outp; + int msglen; - msglen = EAP_HEADERLEN + 2 * sizeof (u_char); - p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); - if(NULL == p) - return; - if(p->tot_len != p->len) { - pbuf_free(p); - return; - } + msglen = EAP_HEADERLEN + 2 * sizeof (u_char); + p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN + msglen), PPP_CTRL_PBUF_TYPE); + if(NULL == p) + return; + if(p->tot_len != p->len) { + pbuf_free(p); + return; + } - outp = (u_char*)p->payload; + outp = (u_char*)p->payload; - MAKEHEADER(outp, PPP_EAP); + MAKEHEADER(outp, PPP_EAP); - PUTCHAR(EAP_RESPONSE, outp); - PUTCHAR(id, outp); - pcb->eap.es_client.ea_id = id; - PUTSHORT(msglen, outp); - PUTCHAR(EAPT_NAK, outp); - PUTCHAR(type, outp); + PUTCHAR(EAP_RESPONSE, outp); + PUTCHAR(id, outp); + pcb->eap.es_client.ea_id = id; + PUTSHORT(msglen, outp); + PUTCHAR(EAPT_NAK, outp); + PUTCHAR(type, outp); - ppp_write(pcb, p); + ppp_write(pcb, p); } #ifdef USE_SRP static char * name_of_pn_file() { - char *user, *path, *file; - struct passwd *pw; - size_t pl; - static bool pnlogged = 0; + char *user, *path, *file; + struct passwd *pw; + size_t pl; + static bool pnlogged = 0; - pw = getpwuid(getuid()); - if (pw == NULL || (user = pw->pw_dir) == NULL || user[0] == 0) { - errno = EINVAL; - return (NULL); - } - file = _PATH_PSEUDONYM; - pl = strlen(user) + strlen(file) + 2; - path = malloc(pl); - if (path == NULL) - return (NULL); - (void) slprintf(path, pl, "%s/%s", user, file); - if (!pnlogged) { - ppp_dbglog("pseudonym file: %s", path); - pnlogged = 1; - } - return (path); + pw = getpwuid(getuid()); + if (pw == NULL || (user = pw->pw_dir) == NULL || user[0] == 0) { + errno = EINVAL; + return (NULL); + } + file = _PATH_PSEUDONYM; + pl = strlen(user) + strlen(file) + 2; + path = malloc(pl); + if (path == NULL) + return (NULL); + (void) slprintf(path, pl, "%s/%s", user, file); + if (!pnlogged) { + ppp_dbglog("pseudonym file: %s", path); + pnlogged = 1; + } + return (path); } static int open_pn_file(modebits) mode_t modebits; { - char *path; - int fd, err; + char *path; + int fd, err; - if ((path = name_of_pn_file()) == NULL) - return (-1); - fd = open(path, modebits, S_IRUSR | S_IWUSR); - err = errno; - free(path); - errno = err; - return (fd); + if ((path = name_of_pn_file()) == NULL) + return (-1); + fd = open(path, modebits, S_IRUSR | S_IWUSR); + err = errno; + free(path); + errno = err; + return (fd); } static void remove_pn_file() { - char *path; + char *path; - if ((path = name_of_pn_file()) != NULL) { - (void) unlink(path); - (void) free(path); - } + if ((path = name_of_pn_file()) != NULL) { + (void) unlink(path); + (void) free(path); + } } static void @@ -1252,56 +1252,56 @@ eap_state *esp; u_char *inp; int len, id; { - u_char val; - u_char *datp, *digp; - SHA1_CTX ctxt; - u_char dig[SHA_DIGESTSIZE]; - int dsize, fd, olen = len; + u_char val; + u_char *datp, *digp; + SHA1_CTX ctxt; + u_char dig[SHA_DIGESTSIZE]; + int dsize, fd, olen = len; - /* - * Do the decoding by working backwards. This eliminates the need - * to save the decoded output in a separate buffer. - */ - val = id; - while (len > 0) { - if ((dsize = len % SHA_DIGESTSIZE) == 0) - dsize = SHA_DIGESTSIZE; - len -= dsize; - datp = inp + len; - SHA1Init(&ctxt); - SHA1Update(&ctxt, &val, 1); - SHA1Update(&ctxt, pcb->eap.es_client.ea_skey, SESSION_KEY_LEN); - if (len > 0) { - SHA1Update(&ctxt, datp, SHA_DIGESTSIZE); - } else { - SHA1Update(&ctxt, pcb->eap.es_client.ea_name, - pcb->eap.es_client.ea_namelen); - } - SHA1Final(dig, &ctxt); - for (digp = dig; digp < dig + SHA_DIGESTSIZE; digp++) - *datp++ ^= *digp; - } + /* + * Do the decoding by working backwards. This eliminates the need + * to save the decoded output in a separate buffer. + */ + val = id; + while (len > 0) { + if ((dsize = len % SHA_DIGESTSIZE) == 0) + dsize = SHA_DIGESTSIZE; + len -= dsize; + datp = inp + len; + SHA1Init(&ctxt); + SHA1Update(&ctxt, &val, 1); + SHA1Update(&ctxt, pcb->eap.es_client.ea_skey, SESSION_KEY_LEN); + if (len > 0) { + SHA1Update(&ctxt, datp, SHA_DIGESTSIZE); + } else { + SHA1Update(&ctxt, pcb->eap.es_client.ea_name, + pcb->eap.es_client.ea_namelen); + } + SHA1Final(dig, &ctxt); + for (digp = dig; digp < dig + SHA_DIGESTSIZE; digp++) + *datp++ ^= *digp; + } - /* Now check that the result is sane */ - if (olen <= 0 || *inp + 1 > olen) { - ppp_dbglog("EAP: decoded pseudonym is unusable <%.*B>", olen, inp); - return; - } + /* Now check that the result is sane */ + if (olen <= 0 || *inp + 1 > olen) { + ppp_dbglog("EAP: decoded pseudonym is unusable <%.*B>", olen, inp); + return; + } - /* Save it away */ - fd = open_pn_file(O_WRONLY | O_CREAT | O_TRUNC); - if (fd < 0) { - ppp_dbglog("EAP: error saving pseudonym: %m"); - return; - } - len = write(fd, inp + 1, *inp); - if (close(fd) != -1 && len == *inp) { - ppp_dbglog("EAP: saved pseudonym"); - pcb->eap.es_usedpseudo = 0; - } else { - ppp_dbglog("EAP: failed to save pseudonym"); - remove_pn_file(); - } + /* Save it away */ + fd = open_pn_file(O_WRONLY | O_CREAT | O_TRUNC); + if (fd < 0) { + ppp_dbglog("EAP: error saving pseudonym: %m"); + return; + } + len = write(fd, inp + 1, *inp); + if (close(fd) != -1 && len == *inp) { + ppp_dbglog("EAP: saved pseudonym"); + pcb->eap.es_usedpseudo = 0; + } else { + ppp_dbglog("EAP: failed to save pseudonym"); + remove_pn_file(); + } } #endif /* USE_SRP */ @@ -1309,418 +1309,418 @@ int len, id; * eap_request - Receive EAP Request message (client mode). */ static void eap_request(ppp_pcb *pcb, u_char *inp, int id, int len) { - u_char typenum; - u_char vallen; - int secret_len; - char secret[MAXSECRETLEN]; - char rhostname[MAXNAMELEN]; - lwip_md5_context mdContext; - u_char hash[MD5_SIGNATURE_SIZE]; + u_char typenum; + u_char vallen; + int secret_len; + char secret[MAXSECRETLEN]; + char rhostname[MAXNAMELEN]; + lwip_md5_context mdContext; + u_char hash[MD5_SIGNATURE_SIZE]; #ifdef USE_SRP - struct t_client *tc; - struct t_num sval, gval, Nval, *Ap, Bval; - u_char vals[2]; - SHA1_CTX ctxt; - u_char dig[SHA_DIGESTSIZE]; - int fd; + struct t_client *tc; + struct t_num sval, gval, Nval, *Ap, Bval; + u_char vals[2]; + SHA1_CTX ctxt; + u_char dig[SHA_DIGESTSIZE]; + int fd; #endif /* USE_SRP */ - /* - * Ignore requests if we're not open - */ - if (esp->es_client.ea_state <= eapClosed) - return; + /* + * Ignore requests if we're not open + */ + if (esp->es_client.ea_state <= eapClosed) + return; - /* - * Note: we update es_client.ea_id *only if* a Response - * message is being generated. Otherwise, we leave it the - * same for duplicate detection purposes. - */ + /* + * Note: we update es_client.ea_id *only if* a Response + * message is being generated. Otherwise, we leave it the + * same for duplicate detection purposes. + */ - pcb->eap.es_client.ea_requests++; - if (pcb->settings.eap_allow_req != 0 && - pcb->eap.es_client.ea_requests > pcb->settings.eap_allow_req) { - ppp_info("EAP: received too many Request messages"); - if (pcb->settings.eap_req_time > 0) { - UNTIMEOUT(eap_client_timeout, pcb); - } - auth_withpeer_fail(pcb, PPP_EAP); - return; - } + pcb->eap.es_client.ea_requests++; + if (pcb->settings.eap_allow_req != 0 && + pcb->eap.es_client.ea_requests > pcb->settings.eap_allow_req) { + ppp_info("EAP: received too many Request messages"); + if (pcb->settings.eap_req_time > 0) { + UNTIMEOUT(eap_client_timeout, pcb); + } + auth_withpeer_fail(pcb, PPP_EAP); + return; + } - if (len <= 0) { - ppp_error("EAP: empty Request message discarded"); - return; - } + if (len <= 0) { + ppp_error("EAP: empty Request message discarded"); + return; + } - GETCHAR(typenum, inp); - len--; + GETCHAR(typenum, inp); + len--; - switch (typenum) { - case EAPT_IDENTITY: - if (len > 0) - ppp_info("EAP: Identity prompt \"%.*q\"", len, inp); + switch (typenum) { + case EAPT_IDENTITY: + if (len > 0) + ppp_info("EAP: Identity prompt \"%.*q\"", len, inp); #ifdef USE_SRP - if (pcb->eap.es_usepseudo && - (pcb->eap.es_usedpseudo == 0 || - (pcb->eap.es_usedpseudo == 1 && - id == pcb->eap.es_client.ea_id))) { - pcb->eap.es_usedpseudo = 1; - /* Try to get a pseudonym */ - if ((fd = open_pn_file(O_RDONLY)) >= 0) { - strcpy(rhostname, SRP_PSEUDO_ID); - len = read(fd, rhostname + SRP_PSEUDO_LEN, - sizeof (rhostname) - SRP_PSEUDO_LEN); - /* XXX NAI unsupported */ - if (len > 0) { - eap_send_response(pcb, id, typenum, - rhostname, len + SRP_PSEUDO_LEN); - } - (void) close(fd); - if (len > 0) - break; - } - } - /* Stop using pseudonym now. */ - if (pcb->eap.es_usepseudo && pcb->eap.es_usedpseudo != 2) { - remove_pn_file(); - pcb->eap.es_usedpseudo = 2; - } + if (pcb->eap.es_usepseudo && + (pcb->eap.es_usedpseudo == 0 || + (pcb->eap.es_usedpseudo == 1 && + id == pcb->eap.es_client.ea_id))) { + pcb->eap.es_usedpseudo = 1; + /* Try to get a pseudonym */ + if ((fd = open_pn_file(O_RDONLY)) >= 0) { + strcpy(rhostname, SRP_PSEUDO_ID); + len = read(fd, rhostname + SRP_PSEUDO_LEN, + sizeof (rhostname) - SRP_PSEUDO_LEN); + /* XXX NAI unsupported */ + if (len > 0) { + eap_send_response(pcb, id, typenum, + rhostname, len + SRP_PSEUDO_LEN); + } + (void) close(fd); + if (len > 0) + break; + } + } + /* Stop using pseudonym now. */ + if (pcb->eap.es_usepseudo && pcb->eap.es_usedpseudo != 2) { + remove_pn_file(); + pcb->eap.es_usedpseudo = 2; + } #endif /* USE_SRP */ - eap_send_response(pcb, id, typenum, (const u_char*)pcb->eap.es_client.ea_name, - pcb->eap.es_client.ea_namelen); - break; + eap_send_response(pcb, id, typenum, (const u_char*)pcb->eap.es_client.ea_name, + pcb->eap.es_client.ea_namelen); + break; - case EAPT_NOTIFICATION: - if (len > 0) - ppp_info("EAP: Notification \"%.*q\"", len, inp); - eap_send_response(pcb, id, typenum, NULL, 0); - break; + case EAPT_NOTIFICATION: + if (len > 0) + ppp_info("EAP: Notification \"%.*q\"", len, inp); + eap_send_response(pcb, id, typenum, NULL, 0); + break; - case EAPT_NAK: - /* - * Avoid the temptation to send Response Nak in reply - * to Request Nak here. It can only lead to trouble. - */ - ppp_warn("EAP: unexpected Nak in Request; ignored"); - /* Return because we're waiting for something real. */ - return; + case EAPT_NAK: + /* + * Avoid the temptation to send Response Nak in reply + * to Request Nak here. It can only lead to trouble. + */ + ppp_warn("EAP: unexpected Nak in Request; ignored"); + /* Return because we're waiting for something real. */ + return; - case EAPT_MD5CHAP: - if (len < 1) { - ppp_error("EAP: received MD5-Challenge with no data"); - /* Bogus request; wait for something real. */ - return; - } - GETCHAR(vallen, inp); - len--; - if (vallen < 8 || vallen > len) { - ppp_error("EAP: MD5-Challenge with bad length %d (8..%d)", - vallen, len); - /* Try something better. */ - eap_send_nak(pcb, id, EAPT_SRP); - break; - } + case EAPT_MD5CHAP: + if (len < 1) { + ppp_error("EAP: received MD5-Challenge with no data"); + /* Bogus request; wait for something real. */ + return; + } + GETCHAR(vallen, inp); + len--; + if (vallen < 8 || vallen > len) { + ppp_error("EAP: MD5-Challenge with bad length %d (8..%d)", + vallen, len); + /* Try something better. */ + eap_send_nak(pcb, id, EAPT_SRP); + break; + } - /* Not so likely to happen. */ - if (len - vallen >= sizeof (rhostname)) { - ppp_dbglog("EAP: trimming really long peer name down"); - MEMCPY(rhostname, inp + vallen, sizeof (rhostname) - 1); - rhostname[sizeof (rhostname) - 1] = '\0'; - } else { - MEMCPY(rhostname, inp + vallen, len - vallen); - rhostname[len - vallen] = '\0'; - } + /* Not so likely to happen. */ + if (len - vallen >= sizeof (rhostname)) { + ppp_dbglog("EAP: trimming really long peer name down"); + MEMCPY(rhostname, inp + vallen, sizeof (rhostname) - 1); + rhostname[sizeof (rhostname) - 1] = '\0'; + } else { + MEMCPY(rhostname, inp + vallen, len - vallen); + rhostname[len - vallen] = '\0'; + } #if PPP_REMOTENAME - /* In case the remote doesn't give us his name. */ - if (pcb->settings.explicit_remote || - (pcb->settings.remote_name[0] != '\0' && vallen == len)) - strlcpy(rhostname, pcb->settings.remote_name, sizeof (rhostname)); + /* In case the remote doesn't give us his name. */ + if (pcb->settings.explicit_remote || + (pcb->settings.remote_name[0] != '\0' && vallen == len)) + strlcpy(rhostname, pcb->settings.remote_name, sizeof (rhostname)); #endif /* PPP_REMOTENAME */ - /* - * Get the secret for authenticating ourselves with - * the specified host. - */ - if (!get_secret(pcb, pcb->eap.es_client.ea_name, - rhostname, secret, &secret_len, 0)) { - ppp_dbglog("EAP: no MD5 secret for auth to %q", rhostname); - eap_send_nak(pcb, id, EAPT_SRP); - break; - } - lwip_md5_init(&mdContext); - lwip_md5_starts(&mdContext); - typenum = id; - lwip_md5_update(&mdContext, &typenum, 1); - lwip_md5_update(&mdContext, (u_char *)secret, secret_len); - BZERO(secret, sizeof (secret)); - lwip_md5_update(&mdContext, inp, vallen); - lwip_md5_finish(&mdContext, hash); - lwip_md5_free(&mdContext); - eap_chap_response(pcb, id, hash, pcb->eap.es_client.ea_name, - pcb->eap.es_client.ea_namelen); - break; + /* + * Get the secret for authenticating ourselves with + * the specified host. + */ + if (!get_secret(pcb, pcb->eap.es_client.ea_name, + rhostname, secret, &secret_len, 0)) { + ppp_dbglog("EAP: no MD5 secret for auth to %q", rhostname); + eap_send_nak(pcb, id, EAPT_SRP); + break; + } + lwip_md5_init(&mdContext); + lwip_md5_starts(&mdContext); + typenum = id; + lwip_md5_update(&mdContext, &typenum, 1); + lwip_md5_update(&mdContext, (u_char *)secret, secret_len); + BZERO(secret, sizeof (secret)); + lwip_md5_update(&mdContext, inp, vallen); + lwip_md5_finish(&mdContext, hash); + lwip_md5_free(&mdContext); + eap_chap_response(pcb, id, hash, pcb->eap.es_client.ea_name, + pcb->eap.es_client.ea_namelen); + break; #ifdef USE_SRP - case EAPT_SRP: - if (len < 1) { - ppp_error("EAP: received empty SRP Request"); - /* Bogus request; wait for something real. */ - return; - } + case EAPT_SRP: + if (len < 1) { + ppp_error("EAP: received empty SRP Request"); + /* Bogus request; wait for something real. */ + return; + } - /* Get subtype */ - GETCHAR(vallen, inp); - len--; - switch (vallen) { - case EAPSRP_CHALLENGE: - tc = NULL; - if (pcb->eap.es_client.ea_session != NULL) { - tc = (struct t_client *)pcb->eap.es_client. - ea_session; - /* - * If this is a new challenge, then start - * over with a new client session context. - * Otherwise, just resend last response. - */ - if (id != pcb->eap.es_client.ea_id) { - t_clientclose(tc); - pcb->eap.es_client.ea_session = NULL; - tc = NULL; - } - } - /* No session key just yet */ - pcb->eap.es_client.ea_skey = NULL; - if (tc == NULL) { - int rhostnamelen; + /* Get subtype */ + GETCHAR(vallen, inp); + len--; + switch (vallen) { + case EAPSRP_CHALLENGE: + tc = NULL; + if (pcb->eap.es_client.ea_session != NULL) { + tc = (struct t_client *)pcb->eap.es_client. + ea_session; + /* + * If this is a new challenge, then start + * over with a new client session context. + * Otherwise, just resend last response. + */ + if (id != pcb->eap.es_client.ea_id) { + t_clientclose(tc); + pcb->eap.es_client.ea_session = NULL; + tc = NULL; + } + } + /* No session key just yet */ + pcb->eap.es_client.ea_skey = NULL; + if (tc == NULL) { + int rhostnamelen; - GETCHAR(vallen, inp); - len--; - if (vallen >= len) { - ppp_error("EAP: badly-formed SRP Challenge" - " (name)"); - /* Ignore badly-formed messages */ - return; - } - MEMCPY(rhostname, inp, vallen); - rhostname[vallen] = '\0'; - INCPTR(vallen, inp); - len -= vallen; + GETCHAR(vallen, inp); + len--; + if (vallen >= len) { + ppp_error("EAP: badly-formed SRP Challenge" + " (name)"); + /* Ignore badly-formed messages */ + return; + } + MEMCPY(rhostname, inp, vallen); + rhostname[vallen] = '\0'; + INCPTR(vallen, inp); + len -= vallen; - /* - * In case the remote doesn't give us his name, - * use configured name. - */ - if (explicit_remote || - (remote_name[0] != '\0' && vallen == 0)) { - strlcpy(rhostname, remote_name, - sizeof (rhostname)); - } + /* + * In case the remote doesn't give us his name, + * use configured name. + */ + if (explicit_remote || + (remote_name[0] != '\0' && vallen == 0)) { + strlcpy(rhostname, remote_name, + sizeof (rhostname)); + } - rhostnamelen = (int)strlen(rhostname); - if (rhostnamelen > MAXNAMELEN) { - rhostnamelen = MAXNAMELEN; - } - MEMCPY(pcb->eap.es_client.ea_peer, rhostname, rhostnamelen); - pcb->eap.es_client.ea_peer[rhostnamelen] = '\0'; - pcb->eap.es_client.ea_peerlen = rhostnamelen; + rhostnamelen = (int)strlen(rhostname); + if (rhostnamelen > MAXNAMELEN) { + rhostnamelen = MAXNAMELEN; + } + MEMCPY(pcb->eap.es_client.ea_peer, rhostname, rhostnamelen); + pcb->eap.es_client.ea_peer[rhostnamelen] = '\0'; + pcb->eap.es_client.ea_peerlen = rhostnamelen; - GETCHAR(vallen, inp); - len--; - if (vallen >= len) { - ppp_error("EAP: badly-formed SRP Challenge" - " (s)"); - /* Ignore badly-formed messages */ - return; - } - sval.data = inp; - sval.len = vallen; - INCPTR(vallen, inp); - len -= vallen; + GETCHAR(vallen, inp); + len--; + if (vallen >= len) { + ppp_error("EAP: badly-formed SRP Challenge" + " (s)"); + /* Ignore badly-formed messages */ + return; + } + sval.data = inp; + sval.len = vallen; + INCPTR(vallen, inp); + len -= vallen; - GETCHAR(vallen, inp); - len--; - if (vallen > len) { - ppp_error("EAP: badly-formed SRP Challenge" - " (g)"); - /* Ignore badly-formed messages */ - return; - } - /* If no generator present, then use value 2 */ - if (vallen == 0) { - gval.data = (u_char *)"\002"; - gval.len = 1; - } else { - gval.data = inp; - gval.len = vallen; - } - INCPTR(vallen, inp); - len -= vallen; + GETCHAR(vallen, inp); + len--; + if (vallen > len) { + ppp_error("EAP: badly-formed SRP Challenge" + " (g)"); + /* Ignore badly-formed messages */ + return; + } + /* If no generator present, then use value 2 */ + if (vallen == 0) { + gval.data = (u_char *)"\002"; + gval.len = 1; + } else { + gval.data = inp; + gval.len = vallen; + } + INCPTR(vallen, inp); + len -= vallen; - /* - * If no modulus present, then use well-known - * value. - */ - if (len == 0) { - Nval.data = (u_char *)wkmodulus; - Nval.len = sizeof (wkmodulus); - } else { - Nval.data = inp; - Nval.len = len; - } - tc = t_clientopen(pcb->eap.es_client.ea_name, - &Nval, &gval, &sval); - if (tc == NULL) { - eap_send_nak(pcb, id, EAPT_MD5CHAP); - break; - } - pcb->eap.es_client.ea_session = (void *)tc; + /* + * If no modulus present, then use well-known + * value. + */ + if (len == 0) { + Nval.data = (u_char *)wkmodulus; + Nval.len = sizeof (wkmodulus); + } else { + Nval.data = inp; + Nval.len = len; + } + tc = t_clientopen(pcb->eap.es_client.ea_name, + &Nval, &gval, &sval); + if (tc == NULL) { + eap_send_nak(pcb, id, EAPT_MD5CHAP); + break; + } + pcb->eap.es_client.ea_session = (void *)tc; - /* Add Challenge ID & type to verifier */ - vals[0] = id; - vals[1] = EAPT_SRP; - t_clientaddexdata(tc, vals, 2); - } - Ap = t_clientgenexp(tc); - eap_srp_response(esp, id, EAPSRP_CKEY, Ap->data, - Ap->len); - break; + /* Add Challenge ID & type to verifier */ + vals[0] = id; + vals[1] = EAPT_SRP; + t_clientaddexdata(tc, vals, 2); + } + Ap = t_clientgenexp(tc); + eap_srp_response(esp, id, EAPSRP_CKEY, Ap->data, + Ap->len); + break; - case EAPSRP_SKEY: - tc = (struct t_client *)pcb->eap.es_client.ea_session; - if (tc == NULL) { - ppp_warn("EAP: peer sent Subtype 2 without 1"); - eap_send_nak(pcb, id, EAPT_MD5CHAP); - break; - } - if (pcb->eap.es_client.ea_skey != NULL) { - /* - * ID number should not change here. Warn - * if it does (but otherwise ignore). - */ - if (id != pcb->eap.es_client.ea_id) { - ppp_warn("EAP: ID changed from %d to %d " - "in SRP Subtype 2 rexmit", - pcb->eap.es_client.ea_id, id); - } - } else { - if (get_srp_secret(pcb->eap.es_unit, - pcb->eap.es_client.ea_name, - pcb->eap.es_client.ea_peer, secret, 0) == 0) { - /* - * Can't work with this peer because - * the secret is missing. Just give - * up. - */ - eap_send_nak(pcb, id, EAPT_MD5CHAP); - break; - } - Bval.data = inp; - Bval.len = len; - t_clientpasswd(tc, secret); - BZERO(secret, sizeof (secret)); - pcb->eap.es_client.ea_skey = - t_clientgetkey(tc, &Bval); - if (pcb->eap.es_client.ea_skey == NULL) { - /* Server is rogue; stop now */ - ppp_error("EAP: SRP server is rogue"); - goto client_failure; - } - } - eap_srpval_response(esp, id, SRPVAL_EBIT, - t_clientresponse(tc)); - break; + case EAPSRP_SKEY: + tc = (struct t_client *)pcb->eap.es_client.ea_session; + if (tc == NULL) { + ppp_warn("EAP: peer sent Subtype 2 without 1"); + eap_send_nak(pcb, id, EAPT_MD5CHAP); + break; + } + if (pcb->eap.es_client.ea_skey != NULL) { + /* + * ID number should not change here. Warn + * if it does (but otherwise ignore). + */ + if (id != pcb->eap.es_client.ea_id) { + ppp_warn("EAP: ID changed from %d to %d " + "in SRP Subtype 2 rexmit", + pcb->eap.es_client.ea_id, id); + } + } else { + if (get_srp_secret(pcb->eap.es_unit, + pcb->eap.es_client.ea_name, + pcb->eap.es_client.ea_peer, secret, 0) == 0) { + /* + * Can't work with this peer because + * the secret is missing. Just give + * up. + */ + eap_send_nak(pcb, id, EAPT_MD5CHAP); + break; + } + Bval.data = inp; + Bval.len = len; + t_clientpasswd(tc, secret); + BZERO(secret, sizeof (secret)); + pcb->eap.es_client.ea_skey = + t_clientgetkey(tc, &Bval); + if (pcb->eap.es_client.ea_skey == NULL) { + /* Server is rogue; stop now */ + ppp_error("EAP: SRP server is rogue"); + goto client_failure; + } + } + eap_srpval_response(esp, id, SRPVAL_EBIT, + t_clientresponse(tc)); + break; - case EAPSRP_SVALIDATOR: - tc = (struct t_client *)pcb->eap.es_client.ea_session; - if (tc == NULL || pcb->eap.es_client.ea_skey == NULL) { - ppp_warn("EAP: peer sent Subtype 3 without 1/2"); - eap_send_nak(pcb, id, EAPT_MD5CHAP); - break; - } - /* - * If we're already open, then this ought to be a - * duplicate. Otherwise, check that the server is - * who we think it is. - */ - if (pcb->eap.es_client.ea_state == eapOpen) { - if (id != pcb->eap.es_client.ea_id) { - ppp_warn("EAP: ID changed from %d to %d " - "in SRP Subtype 3 rexmit", - pcb->eap.es_client.ea_id, id); - } - } else { - len -= sizeof (u32_t) + SHA_DIGESTSIZE; - if (len < 0 || t_clientverify(tc, inp + - sizeof (u32_t)) != 0) { - ppp_error("EAP: SRP server verification " - "failed"); - goto client_failure; - } - GETLONG(pcb->eap.es_client.ea_keyflags, inp); - /* Save pseudonym if user wants it. */ - if (len > 0 && pcb->eap.es_usepseudo) { - INCPTR(SHA_DIGESTSIZE, inp); - write_pseudonym(esp, inp, len, id); - } - } - /* - * We've verified our peer. We're now mostly done, - * except for waiting on the regular EAP Success - * message. - */ - eap_srp_response(esp, id, EAPSRP_ACK, NULL, 0); - break; + case EAPSRP_SVALIDATOR: + tc = (struct t_client *)pcb->eap.es_client.ea_session; + if (tc == NULL || pcb->eap.es_client.ea_skey == NULL) { + ppp_warn("EAP: peer sent Subtype 3 without 1/2"); + eap_send_nak(pcb, id, EAPT_MD5CHAP); + break; + } + /* + * If we're already open, then this ought to be a + * duplicate. Otherwise, check that the server is + * who we think it is. + */ + if (pcb->eap.es_client.ea_state == eapOpen) { + if (id != pcb->eap.es_client.ea_id) { + ppp_warn("EAP: ID changed from %d to %d " + "in SRP Subtype 3 rexmit", + pcb->eap.es_client.ea_id, id); + } + } else { + len -= sizeof (u32_t) + SHA_DIGESTSIZE; + if (len < 0 || t_clientverify(tc, inp + + sizeof (u32_t)) != 0) { + ppp_error("EAP: SRP server verification " + "failed"); + goto client_failure; + } + GETLONG(pcb->eap.es_client.ea_keyflags, inp); + /* Save pseudonym if user wants it. */ + if (len > 0 && pcb->eap.es_usepseudo) { + INCPTR(SHA_DIGESTSIZE, inp); + write_pseudonym(esp, inp, len, id); + } + } + /* + * We've verified our peer. We're now mostly done, + * except for waiting on the regular EAP Success + * message. + */ + eap_srp_response(esp, id, EAPSRP_ACK, NULL, 0); + break; - case EAPSRP_LWRECHALLENGE: - if (len < 4) { - ppp_warn("EAP: malformed Lightweight rechallenge"); - return; - } - SHA1Init(&ctxt); - vals[0] = id; - SHA1Update(&ctxt, vals, 1); - SHA1Update(&ctxt, pcb->eap.es_client.ea_skey, - SESSION_KEY_LEN); - SHA1Update(&ctxt, inp, len); - SHA1Update(&ctxt, pcb->eap.es_client.ea_name, - pcb->eap.es_client.ea_namelen); - SHA1Final(dig, &ctxt); - eap_srp_response(esp, id, EAPSRP_LWRECHALLENGE, dig, - SHA_DIGESTSIZE); - break; + case EAPSRP_LWRECHALLENGE: + if (len < 4) { + ppp_warn("EAP: malformed Lightweight rechallenge"); + return; + } + SHA1Init(&ctxt); + vals[0] = id; + SHA1Update(&ctxt, vals, 1); + SHA1Update(&ctxt, pcb->eap.es_client.ea_skey, + SESSION_KEY_LEN); + SHA1Update(&ctxt, inp, len); + SHA1Update(&ctxt, pcb->eap.es_client.ea_name, + pcb->eap.es_client.ea_namelen); + SHA1Final(dig, &ctxt); + eap_srp_response(esp, id, EAPSRP_LWRECHALLENGE, dig, + SHA_DIGESTSIZE); + break; - default: - ppp_error("EAP: unknown SRP Subtype %d", vallen); - eap_send_nak(pcb, id, EAPT_MD5CHAP); - break; - } - break; + default: + ppp_error("EAP: unknown SRP Subtype %d", vallen); + eap_send_nak(pcb, id, EAPT_MD5CHAP); + break; + } + break; #endif /* USE_SRP */ - default: - ppp_info("EAP: unknown authentication type %d; Naking", typenum); - eap_send_nak(pcb, id, EAPT_SRP); - break; - } + default: + ppp_info("EAP: unknown authentication type %d; Naking", typenum); + eap_send_nak(pcb, id, EAPT_SRP); + break; + } - if (pcb->settings.eap_req_time > 0) { - UNTIMEOUT(eap_client_timeout, pcb); - TIMEOUT(eap_client_timeout, pcb, - pcb->settings.eap_req_time); - } - return; + if (pcb->settings.eap_req_time > 0) { + UNTIMEOUT(eap_client_timeout, pcb); + TIMEOUT(eap_client_timeout, pcb, + pcb->settings.eap_req_time); + } + return; #ifdef USE_SRP client_failure: - pcb->eap.es_client.ea_state = eapBadAuth; - if (pcb->settings.eap_req_time > 0) { - UNTIMEOUT(eap_client_timeout, (void *)esp); - } - pcb->eap.es_client.ea_session = NULL; - t_clientclose(tc); - auth_withpeer_fail(pcb, PPP_EAP); + pcb->eap.es_client.ea_state = eapBadAuth; + if (pcb->settings.eap_req_time > 0) { + UNTIMEOUT(eap_client_timeout, (void *)esp); + } + pcb->eap.es_client.ea_session = NULL; + t_clientclose(tc); + auth_withpeer_fail(pcb, PPP_EAP); #endif /* USE_SRP */ } @@ -1729,297 +1729,297 @@ client_failure: * eap_response - Receive EAP Response message (server mode). */ static void eap_response(ppp_pcb *pcb, u_char *inp, int id, int len) { - u_char typenum; - u_char vallen; - int secret_len; - char secret[MAXSECRETLEN]; - char rhostname[MAXNAMELEN]; - lwip_md5_context mdContext; - u_char hash[MD5_SIGNATURE_SIZE]; + u_char typenum; + u_char vallen; + int secret_len; + char secret[MAXSECRETLEN]; + char rhostname[MAXNAMELEN]; + lwip_md5_context mdContext; + u_char hash[MD5_SIGNATURE_SIZE]; #ifdef USE_SRP - struct t_server *ts; - struct t_num A; - SHA1_CTX ctxt; - u_char dig[SHA_DIGESTSIZE]; + struct t_server *ts; + struct t_num A; + SHA1_CTX ctxt; + u_char dig[SHA_DIGESTSIZE]; #endif /* USE_SRP */ - /* - * Ignore responses if we're not open - */ - if (esp->es_server.ea_state <= eapClosed) - return; + /* + * Ignore responses if we're not open + */ + if (esp->es_server.ea_state <= eapClosed) + return; - if (pcb->eap.es_server.ea_id != id) { - ppp_dbglog("EAP: discarding Response %d; expected ID %d", id, - pcb->eap.es_server.ea_id); - return; - } + if (pcb->eap.es_server.ea_id != id) { + ppp_dbglog("EAP: discarding Response %d; expected ID %d", id, + pcb->eap.es_server.ea_id); + return; + } - pcb->eap.es_server.ea_responses++; + pcb->eap.es_server.ea_responses++; - if (len <= 0) { - ppp_error("EAP: empty Response message discarded"); - return; - } + if (len <= 0) { + ppp_error("EAP: empty Response message discarded"); + return; + } - GETCHAR(typenum, inp); - len--; + GETCHAR(typenum, inp); + len--; - switch (typenum) { - case EAPT_IDENTITY: - if (pcb->eap.es_server.ea_state != eapIdentify) { - ppp_dbglog("EAP discarding unwanted Identify \"%.q\"", len, - inp); - break; - } - ppp_info("EAP: unauthenticated peer name \"%.*q\"", len, inp); - if (len > MAXNAMELEN) { - len = MAXNAMELEN; - } - MEMCPY(pcb->eap.es_server.ea_peer, inp, len); - pcb->eap.es_server.ea_peer[len] = '\0'; - pcb->eap.es_server.ea_peerlen = len; - eap_figure_next_state(pcb, 0); - break; + switch (typenum) { + case EAPT_IDENTITY: + if (pcb->eap.es_server.ea_state != eapIdentify) { + ppp_dbglog("EAP discarding unwanted Identify \"%.q\"", len, + inp); + break; + } + ppp_info("EAP: unauthenticated peer name \"%.*q\"", len, inp); + if (len > MAXNAMELEN) { + len = MAXNAMELEN; + } + MEMCPY(pcb->eap.es_server.ea_peer, inp, len); + pcb->eap.es_server.ea_peer[len] = '\0'; + pcb->eap.es_server.ea_peerlen = len; + eap_figure_next_state(pcb, 0); + break; - case EAPT_NOTIFICATION: - ppp_dbglog("EAP unexpected Notification; response discarded"); - break; + case EAPT_NOTIFICATION: + ppp_dbglog("EAP unexpected Notification; response discarded"); + break; - case EAPT_NAK: - if (len < 1) { - ppp_info("EAP: Nak Response with no suggested protocol"); - eap_figure_next_state(pcb, 1); - break; - } + case EAPT_NAK: + if (len < 1) { + ppp_info("EAP: Nak Response with no suggested protocol"); + eap_figure_next_state(pcb, 1); + break; + } - GETCHAR(vallen, inp); - len--; + GETCHAR(vallen, inp); + len--; - if ( + if ( #if PPP_REMOTENAME - !pcb->explicit_remote && + !pcb->explicit_remote && #endif /* PPP_REMOTENAME */ - pcb->eap.es_server.ea_state == eapIdentify){ - /* Peer cannot Nak Identify Request */ - eap_figure_next_state(pcb, 1); - break; - } + pcb->eap.es_server.ea_state == eapIdentify){ + /* Peer cannot Nak Identify Request */ + eap_figure_next_state(pcb, 1); + break; + } - switch (vallen) { - case EAPT_SRP: - /* Run through SRP validator selection again. */ - pcb->eap.es_server.ea_state = eapIdentify; - eap_figure_next_state(pcb, 0); - break; + switch (vallen) { + case EAPT_SRP: + /* Run through SRP validator selection again. */ + pcb->eap.es_server.ea_state = eapIdentify; + eap_figure_next_state(pcb, 0); + break; - case EAPT_MD5CHAP: - pcb->eap.es_server.ea_state = eapMD5Chall; - break; + case EAPT_MD5CHAP: + pcb->eap.es_server.ea_state = eapMD5Chall; + break; - default: - ppp_dbglog("EAP: peer requesting unknown Type %d", vallen); - switch (pcb->eap.es_server.ea_state) { - case eapSRP1: - case eapSRP2: - case eapSRP3: - pcb->eap.es_server.ea_state = eapMD5Chall; - break; - case eapMD5Chall: - case eapSRP4: - pcb->eap.es_server.ea_state = eapIdentify; - eap_figure_next_state(pcb, 0); - break; - default: - break; - } - break; - } - break; + default: + ppp_dbglog("EAP: peer requesting unknown Type %d", vallen); + switch (pcb->eap.es_server.ea_state) { + case eapSRP1: + case eapSRP2: + case eapSRP3: + pcb->eap.es_server.ea_state = eapMD5Chall; + break; + case eapMD5Chall: + case eapSRP4: + pcb->eap.es_server.ea_state = eapIdentify; + eap_figure_next_state(pcb, 0); + break; + default: + break; + } + break; + } + break; - case EAPT_MD5CHAP: - if (pcb->eap.es_server.ea_state != eapMD5Chall) { - ppp_error("EAP: unexpected MD5-Response"); - eap_figure_next_state(pcb, 1); - break; - } - if (len < 1) { - ppp_error("EAP: received MD5-Response with no data"); - eap_figure_next_state(pcb, 1); - break; - } - GETCHAR(vallen, inp); - len--; - if (vallen != 16 || vallen > len) { - ppp_error("EAP: MD5-Response with bad length %d", vallen); - eap_figure_next_state(pcb, 1); - break; - } + case EAPT_MD5CHAP: + if (pcb->eap.es_server.ea_state != eapMD5Chall) { + ppp_error("EAP: unexpected MD5-Response"); + eap_figure_next_state(pcb, 1); + break; + } + if (len < 1) { + ppp_error("EAP: received MD5-Response with no data"); + eap_figure_next_state(pcb, 1); + break; + } + GETCHAR(vallen, inp); + len--; + if (vallen != 16 || vallen > len) { + ppp_error("EAP: MD5-Response with bad length %d", vallen); + eap_figure_next_state(pcb, 1); + break; + } - /* Not so likely to happen. */ - if (len - vallen >= sizeof (rhostname)) { - ppp_dbglog("EAP: trimming really long peer name down"); - MEMCPY(rhostname, inp + vallen, sizeof (rhostname) - 1); - rhostname[sizeof (rhostname) - 1] = '\0'; - } else { - MEMCPY(rhostname, inp + vallen, len - vallen); - rhostname[len - vallen] = '\0'; - } + /* Not so likely to happen. */ + if (len - vallen >= sizeof (rhostname)) { + ppp_dbglog("EAP: trimming really long peer name down"); + MEMCPY(rhostname, inp + vallen, sizeof (rhostname) - 1); + rhostname[sizeof (rhostname) - 1] = '\0'; + } else { + MEMCPY(rhostname, inp + vallen, len - vallen); + rhostname[len - vallen] = '\0'; + } #if PPP_REMOTENAME - /* In case the remote doesn't give us his name. */ - if (explicit_remote || - (remote_name[0] != '\0' && vallen == len)) - strlcpy(rhostname, remote_name, sizeof (rhostname)); + /* In case the remote doesn't give us his name. */ + if (explicit_remote || + (remote_name[0] != '\0' && vallen == len)) + strlcpy(rhostname, remote_name, sizeof (rhostname)); #endif /* PPP_REMOTENAME */ - /* - * Get the secret for authenticating the specified - * host. - */ - if (!get_secret(pcb, rhostname, - pcb->eap.es_server.ea_name, secret, &secret_len, 1)) { - ppp_dbglog("EAP: no MD5 secret for auth of %q", rhostname); - eap_send_failure(pcb); - break; - } - lwip_md5_init(&mdContext); - lwip_md5_starts(&mdContext); - lwip_md5_update(&mdContext, &pcb->eap.es_server.ea_id, 1); - lwip_md5_update(&mdContext, (u_char *)secret, secret_len); - BZERO(secret, sizeof (secret)); - lwip_md5_update(&mdContext, pcb->eap.es_challenge, pcb->eap.es_challen); - lwip_md5_finish(&mdContext, hash); - lwip_md5_free(&mdContext); - if (BCMP(hash, inp, MD5_SIGNATURE_SIZE) != 0) { - eap_send_failure(pcb); - break; - } - pcb->eap.es_server.ea_type = EAPT_MD5CHAP; - eap_send_success(pcb); - eap_figure_next_state(pcb, 0); - if (pcb->eap.es_rechallenge != 0) - TIMEOUT(eap_rechallenge, pcb, pcb->eap.es_rechallenge); - break; + /* + * Get the secret for authenticating the specified + * host. + */ + if (!get_secret(pcb, rhostname, + pcb->eap.es_server.ea_name, secret, &secret_len, 1)) { + ppp_dbglog("EAP: no MD5 secret for auth of %q", rhostname); + eap_send_failure(pcb); + break; + } + lwip_md5_init(&mdContext); + lwip_md5_starts(&mdContext); + lwip_md5_update(&mdContext, &pcb->eap.es_server.ea_id, 1); + lwip_md5_update(&mdContext, (u_char *)secret, secret_len); + BZERO(secret, sizeof (secret)); + lwip_md5_update(&mdContext, pcb->eap.es_challenge, pcb->eap.es_challen); + lwip_md5_finish(&mdContext, hash); + lwip_md5_free(&mdContext); + if (BCMP(hash, inp, MD5_SIGNATURE_SIZE) != 0) { + eap_send_failure(pcb); + break; + } + pcb->eap.es_server.ea_type = EAPT_MD5CHAP; + eap_send_success(pcb); + eap_figure_next_state(pcb, 0); + if (pcb->eap.es_rechallenge != 0) + TIMEOUT(eap_rechallenge, pcb, pcb->eap.es_rechallenge); + break; #ifdef USE_SRP - case EAPT_SRP: - if (len < 1) { - ppp_error("EAP: empty SRP Response"); - eap_figure_next_state(pcb, 1); - break; - } - GETCHAR(typenum, inp); - len--; - switch (typenum) { - case EAPSRP_CKEY: - if (pcb->eap.es_server.ea_state != eapSRP1) { - ppp_error("EAP: unexpected SRP Subtype 1 Response"); - eap_figure_next_state(pcb, 1); - break; - } - A.data = inp; - A.len = len; - ts = (struct t_server *)pcb->eap.es_server.ea_session; - assert(ts != NULL); - pcb->eap.es_server.ea_skey = t_servergetkey(ts, &A); - if (pcb->eap.es_server.ea_skey == NULL) { - /* Client's A value is bogus; terminate now */ - ppp_error("EAP: bogus A value from client"); - eap_send_failure(pcb); - } else { - eap_figure_next_state(pcb, 0); - } - break; + case EAPT_SRP: + if (len < 1) { + ppp_error("EAP: empty SRP Response"); + eap_figure_next_state(pcb, 1); + break; + } + GETCHAR(typenum, inp); + len--; + switch (typenum) { + case EAPSRP_CKEY: + if (pcb->eap.es_server.ea_state != eapSRP1) { + ppp_error("EAP: unexpected SRP Subtype 1 Response"); + eap_figure_next_state(pcb, 1); + break; + } + A.data = inp; + A.len = len; + ts = (struct t_server *)pcb->eap.es_server.ea_session; + assert(ts != NULL); + pcb->eap.es_server.ea_skey = t_servergetkey(ts, &A); + if (pcb->eap.es_server.ea_skey == NULL) { + /* Client's A value is bogus; terminate now */ + ppp_error("EAP: bogus A value from client"); + eap_send_failure(pcb); + } else { + eap_figure_next_state(pcb, 0); + } + break; - case EAPSRP_CVALIDATOR: - if (pcb->eap.es_server.ea_state != eapSRP2) { - ppp_error("EAP: unexpected SRP Subtype 2 Response"); - eap_figure_next_state(pcb, 1); - break; - } - if (len < sizeof (u32_t) + SHA_DIGESTSIZE) { - ppp_error("EAP: M1 length %d < %d", len, - sizeof (u32_t) + SHA_DIGESTSIZE); - eap_figure_next_state(pcb, 1); - break; - } - GETLONG(pcb->eap.es_server.ea_keyflags, inp); - ts = (struct t_server *)pcb->eap.es_server.ea_session; - assert(ts != NULL); - if (t_serververify(ts, inp)) { - ppp_info("EAP: unable to validate client identity"); - eap_send_failure(pcb); - break; - } - eap_figure_next_state(pcb, 0); - break; + case EAPSRP_CVALIDATOR: + if (pcb->eap.es_server.ea_state != eapSRP2) { + ppp_error("EAP: unexpected SRP Subtype 2 Response"); + eap_figure_next_state(pcb, 1); + break; + } + if (len < sizeof (u32_t) + SHA_DIGESTSIZE) { + ppp_error("EAP: M1 length %d < %d", len, + sizeof (u32_t) + SHA_DIGESTSIZE); + eap_figure_next_state(pcb, 1); + break; + } + GETLONG(pcb->eap.es_server.ea_keyflags, inp); + ts = (struct t_server *)pcb->eap.es_server.ea_session; + assert(ts != NULL); + if (t_serververify(ts, inp)) { + ppp_info("EAP: unable to validate client identity"); + eap_send_failure(pcb); + break; + } + eap_figure_next_state(pcb, 0); + break; - case EAPSRP_ACK: - if (pcb->eap.es_server.ea_state != eapSRP3) { - ppp_error("EAP: unexpected SRP Subtype 3 Response"); - eap_send_failure(esp); - break; - } - pcb->eap.es_server.ea_type = EAPT_SRP; - eap_send_success(pcb, esp); - eap_figure_next_state(pcb, 0); - if (pcb->eap.es_rechallenge != 0) - TIMEOUT(eap_rechallenge, pcb, - pcb->eap.es_rechallenge); - if (pcb->eap.es_lwrechallenge != 0) - TIMEOUT(srp_lwrechallenge, pcb, - pcb->eap.es_lwrechallenge); - break; + case EAPSRP_ACK: + if (pcb->eap.es_server.ea_state != eapSRP3) { + ppp_error("EAP: unexpected SRP Subtype 3 Response"); + eap_send_failure(esp); + break; + } + pcb->eap.es_server.ea_type = EAPT_SRP; + eap_send_success(pcb, esp); + eap_figure_next_state(pcb, 0); + if (pcb->eap.es_rechallenge != 0) + TIMEOUT(eap_rechallenge, pcb, + pcb->eap.es_rechallenge); + if (pcb->eap.es_lwrechallenge != 0) + TIMEOUT(srp_lwrechallenge, pcb, + pcb->eap.es_lwrechallenge); + break; - case EAPSRP_LWRECHALLENGE: - if (pcb->eap.es_server.ea_state != eapSRP4) { - ppp_info("EAP: unexpected SRP Subtype 4 Response"); - return; - } - if (len != SHA_DIGESTSIZE) { - ppp_error("EAP: bad Lightweight rechallenge " - "response"); - return; - } - SHA1Init(&ctxt); - vallen = id; - SHA1Update(&ctxt, &vallen, 1); - SHA1Update(&ctxt, pcb->eap.es_server.ea_skey, - SESSION_KEY_LEN); - SHA1Update(&ctxt, pcb->eap.es_challenge, pcb->eap.es_challen); - SHA1Update(&ctxt, pcb->eap.es_server.ea_peer, - pcb->eap.es_server.ea_peerlen); - SHA1Final(dig, &ctxt); - if (BCMP(dig, inp, SHA_DIGESTSIZE) != 0) { - ppp_error("EAP: failed Lightweight rechallenge"); - eap_send_failure(pcb); - break; - } - pcb->eap.es_server.ea_state = eapOpen; - if (pcb->eap.es_lwrechallenge != 0) - TIMEOUT(srp_lwrechallenge, esp, - pcb->eap.es_lwrechallenge); - break; - } - break; + case EAPSRP_LWRECHALLENGE: + if (pcb->eap.es_server.ea_state != eapSRP4) { + ppp_info("EAP: unexpected SRP Subtype 4 Response"); + return; + } + if (len != SHA_DIGESTSIZE) { + ppp_error("EAP: bad Lightweight rechallenge " + "response"); + return; + } + SHA1Init(&ctxt); + vallen = id; + SHA1Update(&ctxt, &vallen, 1); + SHA1Update(&ctxt, pcb->eap.es_server.ea_skey, + SESSION_KEY_LEN); + SHA1Update(&ctxt, pcb->eap.es_challenge, pcb->eap.es_challen); + SHA1Update(&ctxt, pcb->eap.es_server.ea_peer, + pcb->eap.es_server.ea_peerlen); + SHA1Final(dig, &ctxt); + if (BCMP(dig, inp, SHA_DIGESTSIZE) != 0) { + ppp_error("EAP: failed Lightweight rechallenge"); + eap_send_failure(pcb); + break; + } + pcb->eap.es_server.ea_state = eapOpen; + if (pcb->eap.es_lwrechallenge != 0) + TIMEOUT(srp_lwrechallenge, esp, + pcb->eap.es_lwrechallenge); + break; + } + break; #endif /* USE_SRP */ - default: - /* This can't happen. */ - ppp_error("EAP: unknown Response type %d; ignored", typenum); - return; - } + default: + /* This can't happen. */ + ppp_error("EAP: unknown Response type %d; ignored", typenum); + return; + } - if (pcb->settings.eap_timeout_time > 0) { - UNTIMEOUT(eap_server_timeout, pcb); - } + if (pcb->settings.eap_timeout_time > 0) { + UNTIMEOUT(eap_server_timeout, pcb); + } - if (pcb->eap.es_server.ea_state != eapBadAuth && - pcb->eap.es_server.ea_state != eapOpen) { - pcb->eap.es_server.ea_id++; - eap_send_request(pcb); - } + if (pcb->eap.es_server.ea_state != eapBadAuth && + pcb->eap.es_server.ea_state != eapOpen) { + pcb->eap.es_server.ea_id++; + eap_send_request(pcb); + } } #endif /* PPP_SERVER */ @@ -2027,111 +2027,111 @@ static void eap_response(ppp_pcb *pcb, u_char *inp, int id, int len) { * eap_success - Receive EAP Success message (client mode). */ static void eap_success(ppp_pcb *pcb, u_char *inp, int id, int len) { - LWIP_UNUSED_ARG(id); + LWIP_UNUSED_ARG(id); - if (pcb->eap.es_client.ea_state != eapOpen && !eap_client_active(pcb)) { - ppp_dbglog("EAP unexpected success message in state %s (%d)", - eap_state_name(pcb->eap.es_client.ea_state), - pcb->eap.es_client.ea_state); - return; - } + if (pcb->eap.es_client.ea_state != eapOpen && !eap_client_active(pcb)) { + ppp_dbglog("EAP unexpected success message in state %s (%d)", + eap_state_name(pcb->eap.es_client.ea_state), + pcb->eap.es_client.ea_state); + return; + } - if (pcb->settings.eap_req_time > 0) { - UNTIMEOUT(eap_client_timeout, pcb); - } + if (pcb->settings.eap_req_time > 0) { + UNTIMEOUT(eap_client_timeout, pcb); + } - if (len > 0) { - /* This is odd. The spec doesn't allow for this. */ - PRINTMSG(inp, len); - } + if (len > 0) { + /* This is odd. The spec doesn't allow for this. */ + PRINTMSG(inp, len); + } - pcb->eap.es_client.ea_state = eapOpen; - auth_withpeer_success(pcb, PPP_EAP, 0); + pcb->eap.es_client.ea_state = eapOpen; + auth_withpeer_success(pcb, PPP_EAP, 0); } /* * eap_failure - Receive EAP Failure message (client mode). */ static void eap_failure(ppp_pcb *pcb, u_char *inp, int id, int len) { - LWIP_UNUSED_ARG(id); + LWIP_UNUSED_ARG(id); - /* - * Ignore responses if we're not open - */ - if (esp->es_client.ea_state <= eapClosed) - return; + /* + * Ignore responses if we're not open + */ + if (esp->es_client.ea_state <= eapClosed) + return; - if (!eap_client_active(pcb)) { - ppp_dbglog("EAP unexpected failure message in state %s (%d)", - eap_state_name(pcb->eap.es_client.ea_state), - pcb->eap.es_client.ea_state); - } + if (!eap_client_active(pcb)) { + ppp_dbglog("EAP unexpected failure message in state %s (%d)", + eap_state_name(pcb->eap.es_client.ea_state), + pcb->eap.es_client.ea_state); + } - if (pcb->settings.eap_req_time > 0) { - UNTIMEOUT(eap_client_timeout, pcb); - } + if (pcb->settings.eap_req_time > 0) { + UNTIMEOUT(eap_client_timeout, pcb); + } - if (len > 0) { - /* This is odd. The spec doesn't allow for this. */ - PRINTMSG(inp, len); - } + if (len > 0) { + /* This is odd. The spec doesn't allow for this. */ + PRINTMSG(inp, len); + } - pcb->eap.es_client.ea_state = eapBadAuth; + pcb->eap.es_client.ea_state = eapBadAuth; - ppp_error("EAP: peer reports authentication failure"); - auth_withpeer_fail(pcb, PPP_EAP); + ppp_error("EAP: peer reports authentication failure"); + auth_withpeer_fail(pcb, PPP_EAP); } /* * eap_input - Handle received EAP message. */ static void eap_input(ppp_pcb *pcb, u_char *inp, int inlen) { - u_char code, id; - int len; + u_char code, id; + int len; - /* - * Parse header (code, id and length). If packet too short, - * drop it. - */ - if (inlen < EAP_HEADERLEN) { - ppp_error("EAP: packet too short: %d < %d", inlen, EAP_HEADERLEN); - return; - } - GETCHAR(code, inp); - GETCHAR(id, inp); - GETSHORT(len, inp); - if (len < EAP_HEADERLEN || len > inlen) { - ppp_error("EAP: packet has illegal length field %d (%d..%d)", len, - EAP_HEADERLEN, inlen); - return; - } - len -= EAP_HEADERLEN; + /* + * Parse header (code, id and length). If packet too short, + * drop it. + */ + if (inlen < EAP_HEADERLEN) { + ppp_error("EAP: packet too short: %d < %d", inlen, EAP_HEADERLEN); + return; + } + GETCHAR(code, inp); + GETCHAR(id, inp); + GETSHORT(len, inp); + if (len < EAP_HEADERLEN || len > inlen) { + ppp_error("EAP: packet has illegal length field %d (%d..%d)", len, + EAP_HEADERLEN, inlen); + return; + } + len -= EAP_HEADERLEN; - /* Dispatch based on message code */ - switch (code) { - case EAP_REQUEST: - eap_request(pcb, inp, id, len); - break; + /* Dispatch based on message code */ + switch (code) { + case EAP_REQUEST: + eap_request(pcb, inp, id, len); + break; #if PPP_SERVER - case EAP_RESPONSE: - eap_response(pcb, inp, id, len); - break; + case EAP_RESPONSE: + eap_response(pcb, inp, id, len); + break; #endif /* PPP_SERVER */ - case EAP_SUCCESS: - eap_success(pcb, inp, id, len); - break; + case EAP_SUCCESS: + eap_success(pcb, inp, id, len); + break; - case EAP_FAILURE: - eap_failure(pcb, inp, id, len); - break; + case EAP_FAILURE: + eap_failure(pcb, inp, id, len); + break; - default: /* XXX Need code reject */ - /* Note: it's not legal to send EAP Nak here. */ - ppp_warn("EAP: unknown code %d received", code); - break; - } + default: /* XXX Need code reject */ + /* Note: it's not legal to send EAP Nak here. */ + ppp_warn("EAP: unknown code %d received", code); + break; + } } #if PRINTPKT_SUPPORT @@ -2139,302 +2139,302 @@ static void eap_input(ppp_pcb *pcb, u_char *inp, int inlen) { * eap_printpkt - print the contents of an EAP packet. */ static const char* const eap_codenames[] = { - "Request", "Response", "Success", "Failure" + "Request", "Response", "Success", "Failure" }; static const char* const eap_typenames[] = { - "Identity", "Notification", "Nak", "MD5-Challenge", - "OTP", "Generic-Token", NULL, NULL, - "RSA", "DSS", "KEA", "KEA-Validate", - "TLS", "Defender", "Windows 2000", "Arcot", - "Cisco", "Nokia", "SRP" + "Identity", "Notification", "Nak", "MD5-Challenge", + "OTP", "Generic-Token", NULL, NULL, + "RSA", "DSS", "KEA", "KEA-Validate", + "TLS", "Defender", "Windows 2000", "Arcot", + "Cisco", "Nokia", "SRP" }; static int eap_printpkt(const u_char *inp, int inlen, void (*printer) (void *, const char *, ...), void *arg) { - int code, id, len, rtype, vallen; - const u_char *pstart; - u32_t uval; + int code, id, len, rtype, vallen; + const u_char *pstart; + u32_t uval; - if (inlen < EAP_HEADERLEN) - return (0); - pstart = inp; - GETCHAR(code, inp); - GETCHAR(id, inp); - GETSHORT(len, inp); - if (len < EAP_HEADERLEN || len > inlen) - return (0); + if (inlen < EAP_HEADERLEN) + return (0); + pstart = inp; + GETCHAR(code, inp); + GETCHAR(id, inp); + GETSHORT(len, inp); + if (len < EAP_HEADERLEN || len > inlen) + return (0); - if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(eap_codenames)) - printer(arg, " %s", eap_codenames[code-1]); - else - printer(arg, " code=0x%x", code); - printer(arg, " id=0x%x", id); - len -= EAP_HEADERLEN; - switch (code) { - case EAP_REQUEST: - if (len < 1) { - printer(arg, " "); - break; - } - GETCHAR(rtype, inp); - len--; - if (rtype >= 1 && rtype <= (int)LWIP_ARRAYSIZE(eap_typenames)) - printer(arg, " %s", eap_typenames[rtype-1]); - else - printer(arg, " type=0x%x", rtype); - switch (rtype) { - case EAPT_IDENTITY: - case EAPT_NOTIFICATION: - if (len > 0) { - printer(arg, " "); - INCPTR(len, inp); - len = 0; - } else { - printer(arg, " "); - } - break; + if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(eap_codenames)) + printer(arg, " %s", eap_codenames[code-1]); + else + printer(arg, " code=0x%x", code); + printer(arg, " id=0x%x", id); + len -= EAP_HEADERLEN; + switch (code) { + case EAP_REQUEST: + if (len < 1) { + printer(arg, " "); + break; + } + GETCHAR(rtype, inp); + len--; + if (rtype >= 1 && rtype <= (int)LWIP_ARRAYSIZE(eap_typenames)) + printer(arg, " %s", eap_typenames[rtype-1]); + else + printer(arg, " type=0x%x", rtype); + switch (rtype) { + case EAPT_IDENTITY: + case EAPT_NOTIFICATION: + if (len > 0) { + printer(arg, " "); + INCPTR(len, inp); + len = 0; + } else { + printer(arg, " "); + } + break; - case EAPT_MD5CHAP: - if (len <= 0) - break; - GETCHAR(vallen, inp); - len--; - if (vallen > len) - goto truncated; - printer(arg, " ", vallen, inp); - INCPTR(vallen, inp); - len -= vallen; - if (len > 0) { - printer(arg, " "); - INCPTR(len, inp); - len = 0; - } else { - printer(arg, " "); - } - break; + case EAPT_MD5CHAP: + if (len <= 0) + break; + GETCHAR(vallen, inp); + len--; + if (vallen > len) + goto truncated; + printer(arg, " ", vallen, inp); + INCPTR(vallen, inp); + len -= vallen; + if (len > 0) { + printer(arg, " "); + INCPTR(len, inp); + len = 0; + } else { + printer(arg, " "); + } + break; - case EAPT_SRP: - if (len < 3) - goto truncated; - GETCHAR(vallen, inp); - len--; - printer(arg, "-%d", vallen); - switch (vallen) { - case EAPSRP_CHALLENGE: - GETCHAR(vallen, inp); - len--; - if (vallen >= len) - goto truncated; - if (vallen > 0) { - printer(arg, " "); - } else { - printer(arg, " "); - } - INCPTR(vallen, inp); - len -= vallen; - GETCHAR(vallen, inp); - len--; - if (vallen >= len) - goto truncated; - printer(arg, " ", vallen, inp); - INCPTR(vallen, inp); - len -= vallen; - GETCHAR(vallen, inp); - len--; - if (vallen > len) - goto truncated; - if (vallen == 0) { - printer(arg, " "); - } else { - printer(arg, " ", vallen, inp); - } - INCPTR(vallen, inp); - len -= vallen; - if (len == 0) { - printer(arg, " "); - } else { - printer(arg, " ", len, inp); - INCPTR(len, inp); - len = 0; - } - break; + case EAPT_SRP: + if (len < 3) + goto truncated; + GETCHAR(vallen, inp); + len--; + printer(arg, "-%d", vallen); + switch (vallen) { + case EAPSRP_CHALLENGE: + GETCHAR(vallen, inp); + len--; + if (vallen >= len) + goto truncated; + if (vallen > 0) { + printer(arg, " "); + } else { + printer(arg, " "); + } + INCPTR(vallen, inp); + len -= vallen; + GETCHAR(vallen, inp); + len--; + if (vallen >= len) + goto truncated; + printer(arg, " ", vallen, inp); + INCPTR(vallen, inp); + len -= vallen; + GETCHAR(vallen, inp); + len--; + if (vallen > len) + goto truncated; + if (vallen == 0) { + printer(arg, " "); + } else { + printer(arg, " ", vallen, inp); + } + INCPTR(vallen, inp); + len -= vallen; + if (len == 0) { + printer(arg, " "); + } else { + printer(arg, " ", len, inp); + INCPTR(len, inp); + len = 0; + } + break; - case EAPSRP_SKEY: - printer(arg, " ", len, inp); - INCPTR(len, inp); - len = 0; - break; + case EAPSRP_SKEY: + printer(arg, " ", len, inp); + INCPTR(len, inp); + len = 0; + break; - case EAPSRP_SVALIDATOR: - if (len < (int)sizeof (u32_t)) - break; - GETLONG(uval, inp); - len -= sizeof (u32_t); - if (uval & SRPVAL_EBIT) { - printer(arg, " E"); - uval &= ~SRPVAL_EBIT; - } - if (uval != 0) { - printer(arg, " f<%X>", uval); - } - if ((vallen = len) > SHA_DIGESTSIZE) - vallen = SHA_DIGESTSIZE; - printer(arg, " ", len, inp, - len < SHA_DIGESTSIZE ? "?" : ""); - INCPTR(vallen, inp); - len -= vallen; - if (len > 0) { - printer(arg, " ", len, inp); - INCPTR(len, inp); - len = 0; - } - break; + case EAPSRP_SVALIDATOR: + if (len < (int)sizeof (u32_t)) + break; + GETLONG(uval, inp); + len -= sizeof (u32_t); + if (uval & SRPVAL_EBIT) { + printer(arg, " E"); + uval &= ~SRPVAL_EBIT; + } + if (uval != 0) { + printer(arg, " f<%X>", uval); + } + if ((vallen = len) > SHA_DIGESTSIZE) + vallen = SHA_DIGESTSIZE; + printer(arg, " ", len, inp, + len < SHA_DIGESTSIZE ? "?" : ""); + INCPTR(vallen, inp); + len -= vallen; + if (len > 0) { + printer(arg, " ", len, inp); + INCPTR(len, inp); + len = 0; + } + break; - case EAPSRP_LWRECHALLENGE: - printer(arg, " ", len, inp); - INCPTR(len, inp); - len = 0; - break; - default: - break; - } - break; - default: - break; - } - break; + case EAPSRP_LWRECHALLENGE: + printer(arg, " ", len, inp); + INCPTR(len, inp); + len = 0; + break; + default: + break; + } + break; + default: + break; + } + break; - case EAP_RESPONSE: - if (len < 1) - break; - GETCHAR(rtype, inp); - len--; - if (rtype >= 1 && rtype <= (int)LWIP_ARRAYSIZE(eap_typenames)) - printer(arg, " %s", eap_typenames[rtype-1]); - else - printer(arg, " type=0x%x", rtype); - switch (rtype) { - case EAPT_IDENTITY: - if (len > 0) { - printer(arg, " "); - INCPTR(len, inp); - len = 0; - } - break; + case EAP_RESPONSE: + if (len < 1) + break; + GETCHAR(rtype, inp); + len--; + if (rtype >= 1 && rtype <= (int)LWIP_ARRAYSIZE(eap_typenames)) + printer(arg, " %s", eap_typenames[rtype-1]); + else + printer(arg, " type=0x%x", rtype); + switch (rtype) { + case EAPT_IDENTITY: + if (len > 0) { + printer(arg, " "); + INCPTR(len, inp); + len = 0; + } + break; - case EAPT_NAK: - if (len <= 0) { - printer(arg, " "); - break; - } - GETCHAR(rtype, inp); - len--; - printer(arg, " = 1 && rtype < (int)LWIP_ARRAYSIZE(eap_typenames)) - printer(arg, " (%s)", eap_typenames[rtype-1]); - printer(arg, ">"); - break; + case EAPT_NAK: + if (len <= 0) { + printer(arg, " "); + break; + } + GETCHAR(rtype, inp); + len--; + printer(arg, " = 1 && rtype < (int)LWIP_ARRAYSIZE(eap_typenames)) + printer(arg, " (%s)", eap_typenames[rtype-1]); + printer(arg, ">"); + break; - case EAPT_MD5CHAP: - if (len <= 0) { - printer(arg, " "); - break; - } - GETCHAR(vallen, inp); - len--; - if (vallen > len) - goto truncated; - printer(arg, " ", vallen, inp); - INCPTR(vallen, inp); - len -= vallen; - if (len > 0) { - printer(arg, " "); - INCPTR(len, inp); - len = 0; - } else { - printer(arg, " "); - } - break; + case EAPT_MD5CHAP: + if (len <= 0) { + printer(arg, " "); + break; + } + GETCHAR(vallen, inp); + len--; + if (vallen > len) + goto truncated; + printer(arg, " ", vallen, inp); + INCPTR(vallen, inp); + len -= vallen; + if (len > 0) { + printer(arg, " "); + INCPTR(len, inp); + len = 0; + } else { + printer(arg, " "); + } + break; - case EAPT_SRP: - if (len < 1) - goto truncated; - GETCHAR(vallen, inp); - len--; - printer(arg, "-%d", vallen); - switch (vallen) { - case EAPSRP_CKEY: - printer(arg, " ", len, inp); - INCPTR(len, inp); - len = 0; - break; + case EAPT_SRP: + if (len < 1) + goto truncated; + GETCHAR(vallen, inp); + len--; + printer(arg, "-%d", vallen); + switch (vallen) { + case EAPSRP_CKEY: + printer(arg, " ", len, inp); + INCPTR(len, inp); + len = 0; + break; - case EAPSRP_CVALIDATOR: - if (len < (int)sizeof (u32_t)) - break; - GETLONG(uval, inp); - len -= sizeof (u32_t); - if (uval & SRPVAL_EBIT) { - printer(arg, " E"); - uval &= ~SRPVAL_EBIT; - } - if (uval != 0) { - printer(arg, " f<%X>", uval); - } - printer(arg, " ", len, inp, - len == SHA_DIGESTSIZE ? "" : "?"); - INCPTR(len, inp); - len = 0; - break; + case EAPSRP_CVALIDATOR: + if (len < (int)sizeof (u32_t)) + break; + GETLONG(uval, inp); + len -= sizeof (u32_t); + if (uval & SRPVAL_EBIT) { + printer(arg, " E"); + uval &= ~SRPVAL_EBIT; + } + if (uval != 0) { + printer(arg, " f<%X>", uval); + } + printer(arg, " ", len, inp, + len == SHA_DIGESTSIZE ? "" : "?"); + INCPTR(len, inp); + len = 0; + break; - case EAPSRP_ACK: - break; + case EAPSRP_ACK: + break; - case EAPSRP_LWRECHALLENGE: - printer(arg, " ", len, inp, - len == SHA_DIGESTSIZE ? "" : "?"); - if ((vallen = len) > SHA_DIGESTSIZE) - vallen = SHA_DIGESTSIZE; - INCPTR(vallen, inp); - len -= vallen; - break; - default: - break; - } - break; - default: - break; - } - break; + case EAPSRP_LWRECHALLENGE: + printer(arg, " ", len, inp, + len == SHA_DIGESTSIZE ? "" : "?"); + if ((vallen = len) > SHA_DIGESTSIZE) + vallen = SHA_DIGESTSIZE; + INCPTR(vallen, inp); + len -= vallen; + break; + default: + break; + } + break; + default: + break; + } + break; - case EAP_SUCCESS: /* No payload expected for these! */ - case EAP_FAILURE: - default: - break; + case EAP_SUCCESS: /* No payload expected for these! */ + case EAP_FAILURE: + default: + break; - truncated: - printer(arg, " "); - break; - } + truncated: + printer(arg, " "); + break; + } - if (len > 8) - printer(arg, "%8B...", inp); - else if (len > 0) - printer(arg, "%.*B", len, inp); - INCPTR(len, inp); + if (len > 8) + printer(arg, "%8B...", inp); + else if (len > 0) + printer(arg, "%.*B", len, inp); + INCPTR(len, inp); - return (inp - pstart); + return (inp - pstart); } #endif /* PRINTPKT_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/ecp.c b/components/network/lwip/src/netif/ppp/ecp.c index 4d84f609..5b3b3315 100644 --- a/components/network/lwip/src/netif/ppp/ecp.c +++ b/components/network/lwip/src/netif/ppp/ecp.c @@ -92,8 +92,8 @@ static void ecp_protrej (int unit); */ #if PRINTPKT_SUPPORT static int ecp_printpkt (const u_char *pkt, int len, - void (*printer) (void *, char *, ...), - void *arg); + void (*printer) (void *, char *, ...), + void *arg); #endif /* PRINTPKT_SUPPORT */ /* static void ecp_datainput (int unit, u_char *pkt, int len); @@ -129,10 +129,10 @@ const struct protent ecp_protent = { }; fsm ecp_fsm[NUM_PPP]; -ecp_options ecp_wantoptions[NUM_PPP]; /* what to request the peer to use */ -ecp_options ecp_gotoptions[NUM_PPP]; /* what the peer agreed to do */ -ecp_options ecp_allowoptions[NUM_PPP]; /* what we'll agree to do */ -ecp_options ecp_hisoptions[NUM_PPP]; /* what we agreed to do */ +ecp_options ecp_wantoptions[NUM_PPP]; /* what to request the peer to use */ +ecp_options ecp_gotoptions[NUM_PPP]; /* what the peer agreed to do */ +ecp_options ecp_allowoptions[NUM_PPP]; /* what we'll agree to do */ +ecp_options ecp_hisoptions[NUM_PPP]; /* what we agreed to do */ static const fsm_callbacks ecp_callbacks = { NULL, /* ecp_resetci, */ diff --git a/components/network/lwip/src/netif/ppp/eui64.c b/components/network/lwip/src/netif/ppp/eui64.c index 01493bc1..9e25fc4c 100644 --- a/components/network/lwip/src/netif/ppp/eui64.c +++ b/components/network/lwip/src/netif/ppp/eui64.c @@ -48,8 +48,8 @@ char *eui64_ntoa(eui64_t e) { static char buf[20]; sprintf(buf, "%02x%02x:%02x%02x:%02x%02x:%02x%02x", - e.e8[0], e.e8[1], e.e8[2], e.e8[3], - e.e8[4], e.e8[5], e.e8[6], e.e8[7]); + e.e8[0], e.e8[1], e.e8[2], e.e8[3], + e.e8[4], e.e8[5], e.e8[6], e.e8[7]); return buf; } diff --git a/components/network/lwip/src/netif/ppp/fsm.c b/components/network/lwip/src/netif/ppp/fsm.c index b1f08aff..9df98b1e 100644 --- a/components/network/lwip/src/netif/ppp/fsm.c +++ b/components/network/lwip/src/netif/ppp/fsm.c @@ -68,7 +68,7 @@ static void fsm_rtermack(fsm *f); static void fsm_rcoderej(fsm *f, u_char *inp, int len); static void fsm_sconfreq(fsm *f, int retransmit); -#define PROTO_NAME(f) ((f)->callbacks->proto_name) +#define PROTO_NAME(f) ((f)->callbacks->proto_name) /* * fsm_init - Initialize fsm. @@ -79,7 +79,7 @@ void fsm_init(fsm *f) { ppp_pcb *pcb = f->pcb; f->state = PPP_FSM_INITIAL; f->flags = 0; - f->id = 0; /* XXX Start with random id? */ + f->id = 0; /* XXX Start with random id? */ f->maxnakloops = pcb->settings.fsm_max_nak_loops; f->term_reason_len = 0; } @@ -91,22 +91,22 @@ void fsm_init(fsm *f) { void fsm_lowerup(fsm *f) { switch( f->state ){ case PPP_FSM_INITIAL: - f->state = PPP_FSM_CLOSED; - break; + f->state = PPP_FSM_CLOSED; + break; case PPP_FSM_STARTING: - if( f->flags & OPT_SILENT ) - f->state = PPP_FSM_STOPPED; - else { - /* Send an initial configure-request */ - fsm_sconfreq(f, 0); - f->state = PPP_FSM_REQSENT; - } - break; + if( f->flags & OPT_SILENT ) + f->state = PPP_FSM_STOPPED; + else { + /* Send an initial configure-request */ + fsm_sconfreq(f, 0); + f->state = PPP_FSM_REQSENT; + } + break; default: - FSMDEBUG(("%s: Up event in state %d!", PROTO_NAME(f), f->state)); - /* no break */ + FSMDEBUG(("%s: Up event in state %d!", PROTO_NAME(f), f->state)); + /* no break */ } } @@ -119,37 +119,37 @@ void fsm_lowerup(fsm *f) { void fsm_lowerdown(fsm *f) { switch( f->state ){ case PPP_FSM_CLOSED: - f->state = PPP_FSM_INITIAL; - break; + f->state = PPP_FSM_INITIAL; + break; case PPP_FSM_STOPPED: - f->state = PPP_FSM_STARTING; - if( f->callbacks->starting ) - (*f->callbacks->starting)(f); - break; + f->state = PPP_FSM_STARTING; + if( f->callbacks->starting ) + (*f->callbacks->starting)(f); + break; case PPP_FSM_CLOSING: - f->state = PPP_FSM_INITIAL; - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - break; + f->state = PPP_FSM_INITIAL; + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + break; case PPP_FSM_STOPPING: case PPP_FSM_REQSENT: case PPP_FSM_ACKRCVD: case PPP_FSM_ACKSENT: - f->state = PPP_FSM_STARTING; - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - break; + f->state = PPP_FSM_STARTING; + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + break; case PPP_FSM_OPENED: - if( f->callbacks->down ) - (*f->callbacks->down)(f); - f->state = PPP_FSM_STARTING; - break; + if( f->callbacks->down ) + (*f->callbacks->down)(f); + f->state = PPP_FSM_STARTING; + break; default: - FSMDEBUG(("%s: Down event in state %d!", PROTO_NAME(f), f->state)); - /* no break */ + FSMDEBUG(("%s: Down event in state %d!", PROTO_NAME(f), f->state)); + /* no break */ } } @@ -160,34 +160,34 @@ void fsm_lowerdown(fsm *f) { void fsm_open(fsm *f) { switch( f->state ){ case PPP_FSM_INITIAL: - f->state = PPP_FSM_STARTING; - if( f->callbacks->starting ) - (*f->callbacks->starting)(f); - break; + f->state = PPP_FSM_STARTING; + if( f->callbacks->starting ) + (*f->callbacks->starting)(f); + break; case PPP_FSM_CLOSED: - if( f->flags & OPT_SILENT ) - f->state = PPP_FSM_STOPPED; - else { - /* Send an initial configure-request */ - fsm_sconfreq(f, 0); - f->state = PPP_FSM_REQSENT; - } - break; + if( f->flags & OPT_SILENT ) + f->state = PPP_FSM_STOPPED; + else { + /* Send an initial configure-request */ + fsm_sconfreq(f, 0); + f->state = PPP_FSM_REQSENT; + } + break; case PPP_FSM_CLOSING: - f->state = PPP_FSM_STOPPING; - /* fall through */ - /* no break */ + f->state = PPP_FSM_STOPPING; + /* fall through */ + /* no break */ case PPP_FSM_STOPPED: case PPP_FSM_OPENED: - if( f->flags & OPT_RESTART ){ - fsm_lowerdown(f); - fsm_lowerup(f); - } - break; + if( f->flags & OPT_RESTART ){ + fsm_lowerdown(f); + fsm_lowerup(f); + } + break; default: - break; + break; } } @@ -201,25 +201,25 @@ static void terminate_layer(fsm *f, int nextstate) { ppp_pcb *pcb = f->pcb; if( f->state != PPP_FSM_OPENED ) - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ else if( f->callbacks->down ) - (*f->callbacks->down)(f); /* Inform upper layers we're down */ + (*f->callbacks->down)(f); /* Inform upper layers we're down */ /* Init restart counter and send Terminate-Request */ f->retransmits = pcb->settings.fsm_max_term_transmits; fsm_sdata(f, TERMREQ, f->reqid = ++f->id, - (const u_char *) f->term_reason, f->term_reason_len); + (const u_char *) f->term_reason, f->term_reason_len); if (f->retransmits == 0) { - /* - * User asked for no terminate requests at all; just close it. - * We've already fired off one Terminate-Request just to be nice - * to the peer, but we're not going to wait for a reply. - */ - f->state = nextstate == PPP_FSM_CLOSING ? PPP_FSM_CLOSED : PPP_FSM_STOPPED; - if( f->callbacks->finished ) - (*f->callbacks->finished)(f); - return; + /* + * User asked for no terminate requests at all; just close it. + * We've already fired off one Terminate-Request just to be nice + * to the peer, but we're not going to wait for a reply. + */ + f->state = nextstate == PPP_FSM_CLOSING ? PPP_FSM_CLOSED : PPP_FSM_STOPPED; + if( f->callbacks->finished ) + (*f->callbacks->finished)(f); + return; } TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time); @@ -239,23 +239,23 @@ void fsm_close(fsm *f, const char *reason) { f->term_reason_len = (reason == NULL? 0: (u8_t)LWIP_MIN(strlen(reason), 0xFF) ); switch( f->state ){ case PPP_FSM_STARTING: - f->state = PPP_FSM_INITIAL; - break; + f->state = PPP_FSM_INITIAL; + break; case PPP_FSM_STOPPED: - f->state = PPP_FSM_CLOSED; - break; + f->state = PPP_FSM_CLOSED; + break; case PPP_FSM_STOPPING: - f->state = PPP_FSM_CLOSING; - break; + f->state = PPP_FSM_CLOSING; + break; case PPP_FSM_REQSENT: case PPP_FSM_ACKRCVD: case PPP_FSM_ACKSENT: case PPP_FSM_OPENED: - terminate_layer(f, PPP_FSM_CLOSING); - break; + terminate_layer(f, PPP_FSM_CLOSING); + break; default: - break; + break; } } @@ -270,44 +270,44 @@ static void fsm_timeout(void *arg) { switch (f->state) { case PPP_FSM_CLOSING: case PPP_FSM_STOPPING: - if( f->retransmits <= 0 ){ - /* - * We've waited for an ack long enough. Peer probably heard us. - */ - f->state = (f->state == PPP_FSM_CLOSING)? PPP_FSM_CLOSED: PPP_FSM_STOPPED; - if( f->callbacks->finished ) - (*f->callbacks->finished)(f); - } else { - /* Send Terminate-Request */ - fsm_sdata(f, TERMREQ, f->reqid = ++f->id, - (const u_char *) f->term_reason, f->term_reason_len); - TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time); - --f->retransmits; - } - break; + if( f->retransmits <= 0 ){ + /* + * We've waited for an ack long enough. Peer probably heard us. + */ + f->state = (f->state == PPP_FSM_CLOSING)? PPP_FSM_CLOSED: PPP_FSM_STOPPED; + if( f->callbacks->finished ) + (*f->callbacks->finished)(f); + } else { + /* Send Terminate-Request */ + fsm_sdata(f, TERMREQ, f->reqid = ++f->id, + (const u_char *) f->term_reason, f->term_reason_len); + TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time); + --f->retransmits; + } + break; case PPP_FSM_REQSENT: case PPP_FSM_ACKRCVD: case PPP_FSM_ACKSENT: - if (f->retransmits <= 0) { - ppp_warn("%s: timeout sending Config-Requests", PROTO_NAME(f)); - f->state = PPP_FSM_STOPPED; - if( (f->flags & OPT_PASSIVE) == 0 && f->callbacks->finished ) - (*f->callbacks->finished)(f); + if (f->retransmits <= 0) { + ppp_warn("%s: timeout sending Config-Requests", PROTO_NAME(f)); + f->state = PPP_FSM_STOPPED; + if( (f->flags & OPT_PASSIVE) == 0 && f->callbacks->finished ) + (*f->callbacks->finished)(f); - } else { - /* Retransmit the configure-request */ - if (f->callbacks->retransmit) - (*f->callbacks->retransmit)(f); - fsm_sconfreq(f, 1); /* Re-send Configure-Request */ - if( f->state == PPP_FSM_ACKRCVD ) - f->state = PPP_FSM_REQSENT; - } - break; + } else { + /* Retransmit the configure-request */ + if (f->callbacks->retransmit) + (*f->callbacks->retransmit)(f); + fsm_sconfreq(f, 1); /* Re-send Configure-Request */ + if( f->state == PPP_FSM_ACKRCVD ) + f->state = PPP_FSM_REQSENT; + } + break; default: - FSMDEBUG(("%s: Timeout event in state %d!", PROTO_NAME(f), f->state)); - /* no break */ + FSMDEBUG(("%s: Timeout event in state %d!", PROTO_NAME(f), f->state)); + /* no break */ } } @@ -326,26 +326,26 @@ void fsm_input(fsm *f, u_char *inpacket, int l) { */ inp = inpacket; if (l < HEADERLEN) { - FSMDEBUG(("fsm_input(%x): Rcvd short header.", f->protocol)); - return; + FSMDEBUG(("fsm_input(%x): Rcvd short header.", f->protocol)); + return; } GETCHAR(code, inp); GETCHAR(id, inp); GETSHORT(len, inp); if (len < HEADERLEN) { - FSMDEBUG(("fsm_input(%x): Rcvd illegal length.", f->protocol)); - return; + FSMDEBUG(("fsm_input(%x): Rcvd illegal length.", f->protocol)); + return; } if (len > l) { - FSMDEBUG(("fsm_input(%x): Rcvd short packet.", f->protocol)); - return; + FSMDEBUG(("fsm_input(%x): Rcvd short packet.", f->protocol)); + return; } - len -= HEADERLEN; /* subtract header length */ + len -= HEADERLEN; /* subtract header length */ if( f->state == PPP_FSM_INITIAL || f->state == PPP_FSM_STARTING ){ - FSMDEBUG(("fsm_input(%x): Rcvd packet in state %d.", - f->protocol, f->state)); - return; + FSMDEBUG(("fsm_input(%x): Rcvd packet in state %d.", + f->protocol, f->state)); + return; } /* @@ -353,35 +353,35 @@ void fsm_input(fsm *f, u_char *inpacket, int l) { */ switch (code) { case CONFREQ: - fsm_rconfreq(f, id, inp, len); - break; - + fsm_rconfreq(f, id, inp, len); + break; + case CONFACK: - fsm_rconfack(f, id, inp, len); - break; - + fsm_rconfack(f, id, inp, len); + break; + case CONFNAK: case CONFREJ: - fsm_rconfnakrej(f, code, id, inp, len); - break; - + fsm_rconfnakrej(f, code, id, inp, len); + break; + case TERMREQ: - fsm_rtermreq(f, id, inp, len); - break; - + fsm_rtermreq(f, id, inp, len); + break; + case TERMACK: - fsm_rtermack(f); - break; - + fsm_rtermack(f); + break; + case CODEREJ: - fsm_rcoderej(f, inp, len); - break; - + fsm_rcoderej(f, inp, len); + break; + default: - if( !f->callbacks->extcode - || !(*f->callbacks->extcode)(f, code, id, inp, len) ) - fsm_sdata(f, CODEREJ, ++f->id, inpacket, len + HEADERLEN); - break; + if( !f->callbacks->extcode + || !(*f->callbacks->extcode)(f, code, id, inp, len) ) + fsm_sdata(f, CODEREJ, ++f->id, inpacket, len + HEADERLEN); + break; } } @@ -394,61 +394,61 @@ static void fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len) { switch( f->state ){ case PPP_FSM_CLOSED: - /* Go away, we're closed */ - fsm_sdata(f, TERMACK, id, NULL, 0); - return; + /* Go away, we're closed */ + fsm_sdata(f, TERMACK, id, NULL, 0); + return; case PPP_FSM_CLOSING: case PPP_FSM_STOPPING: - return; + return; case PPP_FSM_OPENED: - /* Go down and restart negotiation */ - if( f->callbacks->down ) - (*f->callbacks->down)(f); /* Inform upper layers */ - fsm_sconfreq(f, 0); /* Send initial Configure-Request */ - f->state = PPP_FSM_REQSENT; - break; + /* Go down and restart negotiation */ + if( f->callbacks->down ) + (*f->callbacks->down)(f); /* Inform upper layers */ + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + f->state = PPP_FSM_REQSENT; + break; case PPP_FSM_STOPPED: - /* Negotiation started by our peer */ - fsm_sconfreq(f, 0); /* Send initial Configure-Request */ - f->state = PPP_FSM_REQSENT; - break; + /* Negotiation started by our peer */ + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + f->state = PPP_FSM_REQSENT; + break; default: - break; + break; } /* * Pass the requested configuration options * to protocol-specific code for checking. */ - if (f->callbacks->reqci){ /* Check CI */ - reject_if_disagree = (f->nakloops >= f->maxnakloops); - code = (*f->callbacks->reqci)(f, inp, &len, reject_if_disagree); + if (f->callbacks->reqci){ /* Check CI */ + reject_if_disagree = (f->nakloops >= f->maxnakloops); + code = (*f->callbacks->reqci)(f, inp, &len, reject_if_disagree); } else if (len) - code = CONFREJ; /* Reject all CI */ + code = CONFREJ; /* Reject all CI */ else - code = CONFACK; + code = CONFACK; /* send the Ack, Nak or Rej to the peer */ fsm_sdata(f, code, id, inp, len); if (code == CONFACK) { - if (f->state == PPP_FSM_ACKRCVD) { - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - f->state = PPP_FSM_OPENED; - if (f->callbacks->up) - (*f->callbacks->up)(f); /* Inform upper layers */ - } else - f->state = PPP_FSM_ACKSENT; - f->nakloops = 0; + if (f->state == PPP_FSM_ACKRCVD) { + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + f->state = PPP_FSM_OPENED; + if (f->callbacks->up) + (*f->callbacks->up)(f); /* Inform upper layers */ + } else + f->state = PPP_FSM_ACKSENT; + f->nakloops = 0; } else { - /* we sent CONFACK or CONFREJ */ - if (f->state != PPP_FSM_ACKRCVD) - f->state = PPP_FSM_REQSENT; - if( code == CONFNAK ) - ++f->nakloops; + /* we sent CONFACK or CONFREJ */ + if (f->state != PPP_FSM_ACKRCVD) + f->state = PPP_FSM_REQSENT; + if( code == CONFNAK ) + ++f->nakloops; } } @@ -459,13 +459,13 @@ static void fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len) { static void fsm_rconfack(fsm *f, int id, u_char *inp, int len) { ppp_pcb *pcb = f->pcb; - if (id != f->reqid || f->seen_ack) /* Expected id? */ - return; /* Nope, toss... */ + if (id != f->reqid || f->seen_ack) /* Expected id? */ + return; /* Nope, toss... */ if( !(f->callbacks->ackci? (*f->callbacks->ackci)(f, inp, len): - (len == 0)) ){ - /* Ack is bad - ignore it */ - ppp_error("Received bad configure-ack: %P", inp, len); - return; + (len == 0)) ){ + /* Ack is bad - ignore it */ + ppp_error("Received bad configure-ack: %P", inp, len); + return; } f->seen_ack = 1; f->rnakloops = 0; @@ -473,38 +473,38 @@ static void fsm_rconfack(fsm *f, int id, u_char *inp, int len) { switch (f->state) { case PPP_FSM_CLOSED: case PPP_FSM_STOPPED: - fsm_sdata(f, TERMACK, id, NULL, 0); - break; + fsm_sdata(f, TERMACK, id, NULL, 0); + break; case PPP_FSM_REQSENT: - f->state = PPP_FSM_ACKRCVD; - f->retransmits = pcb->settings.fsm_max_conf_req_transmits; - break; + f->state = PPP_FSM_ACKRCVD; + f->retransmits = pcb->settings.fsm_max_conf_req_transmits; + break; case PPP_FSM_ACKRCVD: - /* Huh? an extra valid Ack? oh well... */ - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - fsm_sconfreq(f, 0); - f->state = PPP_FSM_REQSENT; - break; + /* Huh? an extra valid Ack? oh well... */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + fsm_sconfreq(f, 0); + f->state = PPP_FSM_REQSENT; + break; case PPP_FSM_ACKSENT: - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - f->state = PPP_FSM_OPENED; - f->retransmits = pcb->settings.fsm_max_conf_req_transmits; - if (f->callbacks->up) - (*f->callbacks->up)(f); /* Inform upper layers */ - break; + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + f->state = PPP_FSM_OPENED; + f->retransmits = pcb->settings.fsm_max_conf_req_transmits; + if (f->callbacks->up) + (*f->callbacks->up)(f); /* Inform upper layers */ + break; case PPP_FSM_OPENED: - /* Go down and restart negotiation */ - if (f->callbacks->down) - (*f->callbacks->down)(f); /* Inform upper layers */ - fsm_sconfreq(f, 0); /* Send initial Configure-Request */ - f->state = PPP_FSM_REQSENT; - break; + /* Go down and restart negotiation */ + if (f->callbacks->down) + (*f->callbacks->down)(f); /* Inform upper layers */ + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + f->state = PPP_FSM_REQSENT; + break; default: - break; + break; } } @@ -516,24 +516,24 @@ static void fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len) { int ret; int treat_as_reject; - if (id != f->reqid || f->seen_ack) /* Expected id? */ - return; /* Nope, toss... */ + if (id != f->reqid || f->seen_ack) /* Expected id? */ + return; /* Nope, toss... */ if (code == CONFNAK) { - ++f->rnakloops; - treat_as_reject = (f->rnakloops >= f->maxnakloops); - if (f->callbacks->nakci == NULL - || !(ret = f->callbacks->nakci(f, inp, len, treat_as_reject))) { - ppp_error("Received bad configure-nak: %P", inp, len); - return; - } + ++f->rnakloops; + treat_as_reject = (f->rnakloops >= f->maxnakloops); + if (f->callbacks->nakci == NULL + || !(ret = f->callbacks->nakci(f, inp, len, treat_as_reject))) { + ppp_error("Received bad configure-nak: %P", inp, len); + return; + } } else { - f->rnakloops = 0; - if (f->callbacks->rejci == NULL - || !(ret = f->callbacks->rejci(f, inp, len))) { - ppp_error("Received bad configure-rej: %P", inp, len); - return; - } + f->rnakloops = 0; + if (f->callbacks->rejci == NULL + || !(ret = f->callbacks->rejci(f, inp, len))) { + ppp_error("Received bad configure-rej: %P", inp, len); + return; + } } f->seen_ack = 1; @@ -541,35 +541,35 @@ static void fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len) { switch (f->state) { case PPP_FSM_CLOSED: case PPP_FSM_STOPPED: - fsm_sdata(f, TERMACK, id, NULL, 0); - break; + fsm_sdata(f, TERMACK, id, NULL, 0); + break; case PPP_FSM_REQSENT: case PPP_FSM_ACKSENT: - /* They didn't agree to what we wanted - try another request */ - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - if (ret < 0) - f->state = PPP_FSM_STOPPED; /* kludge for stopping CCP */ - else - fsm_sconfreq(f, 0); /* Send Configure-Request */ - break; + /* They didn't agree to what we wanted - try another request */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + if (ret < 0) + f->state = PPP_FSM_STOPPED; /* kludge for stopping CCP */ + else + fsm_sconfreq(f, 0); /* Send Configure-Request */ + break; case PPP_FSM_ACKRCVD: - /* Got a Nak/reject when we had already had an Ack?? oh well... */ - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - fsm_sconfreq(f, 0); - f->state = PPP_FSM_REQSENT; - break; + /* Got a Nak/reject when we had already had an Ack?? oh well... */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + fsm_sconfreq(f, 0); + f->state = PPP_FSM_REQSENT; + break; case PPP_FSM_OPENED: - /* Go down and restart negotiation */ - if (f->callbacks->down) - (*f->callbacks->down)(f); /* Inform upper layers */ - fsm_sconfreq(f, 0); /* Send initial Configure-Request */ - f->state = PPP_FSM_REQSENT; - break; + /* Go down and restart negotiation */ + if (f->callbacks->down) + (*f->callbacks->down)(f); /* Inform upper layers */ + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + f->state = PPP_FSM_REQSENT; + break; default: - break; + break; } } @@ -583,22 +583,22 @@ static void fsm_rtermreq(fsm *f, int id, u_char *p, int len) { switch (f->state) { case PPP_FSM_ACKRCVD: case PPP_FSM_ACKSENT: - f->state = PPP_FSM_REQSENT; /* Start over but keep trying */ - break; + f->state = PPP_FSM_REQSENT; /* Start over but keep trying */ + break; case PPP_FSM_OPENED: - if (len > 0) { - ppp_info("%s terminated by peer (%0.*v)", PROTO_NAME(f), len, p); - } else - ppp_info("%s terminated by peer", PROTO_NAME(f)); - f->retransmits = 0; - f->state = PPP_FSM_STOPPING; - if (f->callbacks->down) - (*f->callbacks->down)(f); /* Inform upper layers */ - TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time); - break; + if (len > 0) { + ppp_info("%s terminated by peer (%0.*v)", PROTO_NAME(f), len, p); + } else + ppp_info("%s terminated by peer", PROTO_NAME(f)); + f->retransmits = 0; + f->state = PPP_FSM_STOPPING; + if (f->callbacks->down) + (*f->callbacks->down)(f); /* Inform upper layers */ + TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time); + break; default: - break; + break; } fsm_sdata(f, TERMACK, id, NULL, 0); @@ -611,30 +611,30 @@ static void fsm_rtermreq(fsm *f, int id, u_char *p, int len) { static void fsm_rtermack(fsm *f) { switch (f->state) { case PPP_FSM_CLOSING: - UNTIMEOUT(fsm_timeout, f); - f->state = PPP_FSM_CLOSED; - if( f->callbacks->finished ) - (*f->callbacks->finished)(f); - break; + UNTIMEOUT(fsm_timeout, f); + f->state = PPP_FSM_CLOSED; + if( f->callbacks->finished ) + (*f->callbacks->finished)(f); + break; case PPP_FSM_STOPPING: - UNTIMEOUT(fsm_timeout, f); - f->state = PPP_FSM_STOPPED; - if( f->callbacks->finished ) - (*f->callbacks->finished)(f); - break; + UNTIMEOUT(fsm_timeout, f); + f->state = PPP_FSM_STOPPED; + if( f->callbacks->finished ) + (*f->callbacks->finished)(f); + break; case PPP_FSM_ACKRCVD: - f->state = PPP_FSM_REQSENT; - break; + f->state = PPP_FSM_REQSENT; + break; case PPP_FSM_OPENED: - if (f->callbacks->down) - (*f->callbacks->down)(f); /* Inform upper layers */ - fsm_sconfreq(f, 0); - f->state = PPP_FSM_REQSENT; - break; + if (f->callbacks->down) + (*f->callbacks->down)(f); /* Inform upper layers */ + fsm_sconfreq(f, 0); + f->state = PPP_FSM_REQSENT; + break; default: - break; + break; } } @@ -646,15 +646,15 @@ static void fsm_rcoderej(fsm *f, u_char *inp, int len) { u_char code, id; if (len < HEADERLEN) { - FSMDEBUG(("fsm_rcoderej: Rcvd short Code-Reject packet!")); - return; + FSMDEBUG(("fsm_rcoderej: Rcvd short Code-Reject packet!")); + return; } GETCHAR(code, inp); GETCHAR(id, inp); ppp_warn("%s: Rcvd Code-Reject for code %d, id %d", PROTO_NAME(f), code, id); if( f->state == PPP_FSM_ACKRCVD ) - f->state = PPP_FSM_REQSENT; + f->state = PPP_FSM_REQSENT; } @@ -666,36 +666,36 @@ static void fsm_rcoderej(fsm *f, u_char *inp, int len) { void fsm_protreject(fsm *f) { switch( f->state ){ case PPP_FSM_CLOSING: - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - /* fall through */ - /* no break */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + /* fall through */ + /* no break */ case PPP_FSM_CLOSED: - f->state = PPP_FSM_CLOSED; - if( f->callbacks->finished ) - (*f->callbacks->finished)(f); - break; + f->state = PPP_FSM_CLOSED; + if( f->callbacks->finished ) + (*f->callbacks->finished)(f); + break; case PPP_FSM_STOPPING: case PPP_FSM_REQSENT: case PPP_FSM_ACKRCVD: case PPP_FSM_ACKSENT: - UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ - /* fall through */ - /* no break */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + /* fall through */ + /* no break */ case PPP_FSM_STOPPED: - f->state = PPP_FSM_STOPPED; - if( f->callbacks->finished ) - (*f->callbacks->finished)(f); - break; + f->state = PPP_FSM_STOPPED; + if( f->callbacks->finished ) + (*f->callbacks->finished)(f); + break; case PPP_FSM_OPENED: - terminate_layer(f, PPP_FSM_STOPPING); - break; + terminate_layer(f, PPP_FSM_STOPPING); + break; default: - FSMDEBUG(("%s: Protocol-reject event in state %d!", - PROTO_NAME(f), f->state)); - /* no break */ + FSMDEBUG(("%s: Protocol-reject event in state %d!", + PROTO_NAME(f), f->state)); + /* no break */ } } @@ -710,17 +710,17 @@ static void fsm_sconfreq(fsm *f, int retransmit) { int cilen; if( f->state != PPP_FSM_REQSENT && f->state != PPP_FSM_ACKRCVD && f->state != PPP_FSM_ACKSENT ){ - /* Not currently negotiating - reset options */ - if( f->callbacks->resetci ) - (*f->callbacks->resetci)(f); - f->nakloops = 0; - f->rnakloops = 0; + /* Not currently negotiating - reset options */ + if( f->callbacks->resetci ) + (*f->callbacks->resetci)(f); + f->nakloops = 0; + f->rnakloops = 0; } if( !retransmit ){ - /* New request - reset retransmission counter, use new ID */ - f->retransmits = pcb->settings.fsm_max_conf_req_transmits; - f->reqid = ++f->id; + /* New request - reset retransmission counter, use new ID */ + f->retransmits = pcb->settings.fsm_max_conf_req_transmits; + f->reqid = ++f->id; } f->seen_ack = 0; @@ -729,11 +729,11 @@ static void fsm_sconfreq(fsm *f, int retransmit) { * Make up the request packet */ if( f->callbacks->cilen && f->callbacks->addci ){ - cilen = (*f->callbacks->cilen)(f); - if( cilen > pcb->peer_mru - HEADERLEN ) - cilen = pcb->peer_mru - HEADERLEN; + cilen = (*f->callbacks->cilen)(f); + if( cilen > pcb->peer_mru - HEADERLEN ) + cilen = pcb->peer_mru - HEADERLEN; } else - cilen = 0; + cilen = 0; p = pbuf_alloc(PBUF_RAW, (u16_t)(cilen + HEADERLEN + PPP_HDRLEN), PPP_CTRL_PBUF_TYPE); if(NULL == p) @@ -750,8 +750,8 @@ static void fsm_sconfreq(fsm *f, int retransmit) { PUTCHAR(f->reqid, outp); PUTSHORT(cilen + HEADERLEN, outp); if (cilen != 0) { - (*f->callbacks->addci)(f, outp, &cilen); - LWIP_ASSERT("cilen == p->len - HEADERLEN - PPP_HDRLEN", cilen == p->len - HEADERLEN - PPP_HDRLEN); + (*f->callbacks->addci)(f, outp, &cilen); + LWIP_ASSERT("cilen == p->len - HEADERLEN - PPP_HDRLEN", cilen == p->len - HEADERLEN - PPP_HDRLEN); } ppp_write(pcb, p); @@ -775,7 +775,7 @@ void fsm_sdata(fsm *f, u_char code, u_char id, const u_char *data, int datalen) /* Adjust length to be smaller than MTU */ if (datalen > pcb->peer_mru - HEADERLEN) - datalen = pcb->peer_mru - HEADERLEN; + datalen = pcb->peer_mru - HEADERLEN; outlen = datalen + HEADERLEN; p = pbuf_alloc(PBUF_RAW, (u16_t)(outlen + PPP_HDRLEN), PPP_CTRL_PBUF_TYPE); @@ -788,7 +788,7 @@ void fsm_sdata(fsm *f, u_char code, u_char id, const u_char *data, int datalen) outp = (u_char*)p->payload; if (datalen) /* && data != outp + PPP_HDRLEN + HEADERLEN) -- was only for fsm_sconfreq() */ - MEMCPY(outp + PPP_HDRLEN + HEADERLEN, data, datalen); + MEMCPY(outp + PPP_HDRLEN + HEADERLEN, data, datalen); MAKEHEADER(outp, f->protocol); PUTCHAR(code, outp); PUTCHAR(id, outp); diff --git a/components/network/lwip/src/netif/ppp/ipcp.c b/components/network/lwip/src/netif/ppp/ipcp.c index b7c766eb..feb1f4be 100644 --- a/components/network/lwip/src/netif/ppp/ipcp.c +++ b/components/network/lwip/src/netif/ppp/ipcp.c @@ -66,15 +66,15 @@ #if 0 /* UNUSED */ /* global vars */ -u32_t netmask = 0; /* IP netmask to set on interface */ +u32_t netmask = 0; /* IP netmask to set on interface */ #endif /* UNUSED */ #if 0 /* UNUSED */ -bool disable_defaultip = 0; /* Don't use hostname for default IP adrs */ +bool disable_defaultip = 0; /* Don't use hostname for default IP adrs */ #endif /* UNUSED */ #if 0 /* moved to ppp_settings */ -bool noremoteip = 0; /* Let him have no IP address */ +bool noremoteip = 0; /* Let him have no IP address */ #endif /* moved to ppp_setting */ #if 0 /* UNUSED */ @@ -96,47 +96,47 @@ struct notifier *ip_down_notifier = NULL; /* local vars */ #if 0 /* moved to ppp_pcb */ -static int default_route_set[NUM_PPP]; /* Have set up a default route */ -static int proxy_arp_set[NUM_PPP]; /* Have created proxy arp entry */ -static int ipcp_is_up; /* have called np_up() */ -static int ipcp_is_open; /* haven't called np_finished() */ -static bool ask_for_local; /* request our address from peer */ +static int default_route_set[NUM_PPP]; /* Have set up a default route */ +static int proxy_arp_set[NUM_PPP]; /* Have created proxy arp entry */ +static int ipcp_is_up; /* have called np_up() */ +static int ipcp_is_open; /* haven't called np_finished() */ +static bool ask_for_local; /* request our address from peer */ #endif /* moved to ppp_pcb */ #if 0 /* UNUSED */ -static char vj_value[8]; /* string form of vj option value */ -static char netmask_str[20]; /* string form of netmask value */ +static char vj_value[8]; /* string form of vj option value */ +static char netmask_str[20]; /* string form of netmask value */ #endif /* UNUSED */ /* * Callbacks for fsm code. (CI = Configuration Information) */ -static void ipcp_resetci(fsm *f); /* Reset our CI */ -static int ipcp_cilen(fsm *f); /* Return length of our CI */ +static void ipcp_resetci(fsm *f); /* Reset our CI */ +static int ipcp_cilen(fsm *f); /* Return length of our CI */ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp); /* Add our CI */ -static int ipcp_ackci(fsm *f, u_char *p, int len); /* Peer ack'd our CI */ +static int ipcp_ackci(fsm *f, u_char *p, int len); /* Peer ack'd our CI */ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject);/* Peer nak'd our CI */ -static int ipcp_rejci(fsm *f, u_char *p, int len); /* Peer rej'd our CI */ +static int ipcp_rejci(fsm *f, u_char *p, int len); /* Peer rej'd our CI */ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree); /* Rcv CI */ -static void ipcp_up(fsm *f); /* We're UP */ -static void ipcp_down(fsm *f); /* We're DOWN */ -static void ipcp_finished(fsm *f); /* Don't need lower layer */ +static void ipcp_up(fsm *f); /* We're UP */ +static void ipcp_down(fsm *f); /* We're DOWN */ +static void ipcp_finished(fsm *f); /* Don't need lower layer */ static const fsm_callbacks ipcp_callbacks = { /* IPCP callback routines */ - ipcp_resetci, /* Reset our Configuration Information */ - ipcp_cilen, /* Length of our Configuration Information */ - ipcp_addci, /* Add our Configuration Information */ - ipcp_ackci, /* ACK our Configuration Information */ - ipcp_nakci, /* NAK our Configuration Information */ - ipcp_rejci, /* Reject our Configuration Information */ - ipcp_reqci, /* Request peer's Configuration Information */ - ipcp_up, /* Called when fsm reaches OPENED state */ - ipcp_down, /* Called when fsm leaves OPENED state */ - NULL, /* Called when we want the lower layer up */ - ipcp_finished, /* Called when we want the lower layer down */ - NULL, /* Called when Protocol-Reject received */ - NULL, /* Retransmission is necessary */ - NULL, /* Called to handle protocol-specific codes */ - "IPCP" /* String name of protocol */ + ipcp_resetci, /* Reset our Configuration Information */ + ipcp_cilen, /* Length of our Configuration Information */ + ipcp_addci, /* Add our Configuration Information */ + ipcp_ackci, /* ACK our Configuration Information */ + ipcp_nakci, /* NAK our Configuration Information */ + ipcp_rejci, /* Reject our Configuration Information */ + ipcp_reqci, /* Request peer's Configuration Information */ + ipcp_up, /* Called when fsm reaches OPENED state */ + ipcp_down, /* Called when fsm leaves OPENED state */ + NULL, /* Called when we want the lower layer up */ + ipcp_finished, /* Called when we want the lower layer down */ + NULL, /* Called when Protocol-Reject received */ + NULL, /* Retransmission is necessary */ + NULL, /* Called to handle protocol-specific codes */ + "IPCP" /* String name of protocol */ }; /* @@ -209,13 +209,13 @@ static option_t ipcp_option_list[] = { &ipcp_wantoptions[0].default_route }, { "replacedefaultroute", o_bool, - &ipcp_wantoptions[0].replace_default_route, + &ipcp_wantoptions[0].replace_default_route, "Replace default route", 1 }, { "noreplacedefaultroute", o_bool, - &ipcp_allowoptions[0].replace_default_route, + &ipcp_allowoptions[0].replace_default_route, "Never replace default route", OPT_A2COPY, - &ipcp_wantoptions[0].replace_default_route }, + &ipcp_wantoptions[0].replace_default_route }, { "proxyarp", o_bool, &ipcp_wantoptions[0].proxy_arp, "Add proxy ARP entry", OPT_ENABLE|1, &ipcp_allowoptions[0].proxy_arp }, { "noproxyarp", o_bool, &ipcp_allowoptions[0].proxy_arp, @@ -265,7 +265,7 @@ static void ipcp_input(ppp_pcb *pcb, u_char *p, int len); static void ipcp_protrej(ppp_pcb *pcb); #if PRINTPKT_SUPPORT static int ipcp_printpkt(const u_char *p, int plen, - void (*printer) (void *, const char *, ...), void *arg); + void (*printer) (void *, const char *, ...), void *arg); #endif /* PRINTPKT_SUPPORT */ #if PPP_OPTIONS static void ip_check_options (void); @@ -312,15 +312,15 @@ static void ipcp_clear_addrs(ppp_pcb *pcb, u32_t ouraddr, u32_t hisaddr, u8_t re /* * Lengths of configuration options. */ -#define CILEN_VOID 2 -#define CILEN_COMPRESS 4 /* min length for compression protocol opt. */ -#define CILEN_VJ 6 /* length for RFC1332 Van-Jacobson opt. */ -#define CILEN_ADDR 6 /* new-style single address option */ -#define CILEN_ADDRS 10 /* old-style dual address option */ +#define CILEN_VOID 2 +#define CILEN_COMPRESS 4 /* min length for compression protocol opt. */ +#define CILEN_VJ 6 /* length for RFC1332 Van-Jacobson opt. */ +#define CILEN_ADDR 6 /* new-style single address option */ +#define CILEN_ADDRS 10 /* old-style dual address option */ -#define CODENAME(x) ((x) == CONFACK ? "ACK" : \ - (x) == CONFNAK ? "NAK" : "REJ") +#define CODENAME(x) ((x) == CONFACK ? "ACK" : \ + (x) == CONFNAK ? "NAK" : "REJ") #if 0 /* UNUSED, already defined by lwIP */ /* @@ -351,11 +351,11 @@ setvjslots(argv) int value; if (!int_option(*argv, &value)) - return 0; + return 0; if (value < 2 || value > 16) { - option_error("vj-max-slots value must be between 2 and 16"); - return 0; + option_error("vj-max-slots value must be between 2 and 16"); + return 0; } ipcp_wantoptions [0].maxslotindex = ipcp_allowoptions[0].maxslotindex = value - 1; @@ -375,21 +375,21 @@ setdnsaddr(argv) dns = inet_addr(*argv); if (dns == (u32_t) -1) { - if ((hp = gethostbyname(*argv)) == NULL) { - option_error("invalid address parameter '%s' for ms-dns option", - *argv); - return 0; - } - dns = *(u32_t *)hp->h_addr; + if ((hp = gethostbyname(*argv)) == NULL) { + option_error("invalid address parameter '%s' for ms-dns option", + *argv); + return 0; + } + dns = *(u32_t *)hp->h_addr; } /* We take the last 2 values given, the 2nd-last as the primary and the last as the secondary. If only one is given it becomes both primary and secondary. */ if (ipcp_allowoptions[0].dnsaddr[1] == 0) - ipcp_allowoptions[0].dnsaddr[0] = dns; + ipcp_allowoptions[0].dnsaddr[0] = dns; else - ipcp_allowoptions[0].dnsaddr[0] = ipcp_allowoptions[0].dnsaddr[1]; + ipcp_allowoptions[0].dnsaddr[0] = ipcp_allowoptions[0].dnsaddr[1]; /* always set the secondary address value. */ ipcp_allowoptions[0].dnsaddr[1] = dns; @@ -411,21 +411,21 @@ setwinsaddr(argv) wins = inet_addr(*argv); if (wins == (u32_t) -1) { - if ((hp = gethostbyname(*argv)) == NULL) { - option_error("invalid address parameter '%s' for ms-wins option", - *argv); - return 0; - } - wins = *(u32_t *)hp->h_addr; + if ((hp = gethostbyname(*argv)) == NULL) { + option_error("invalid address parameter '%s' for ms-wins option", + *argv); + return 0; + } + wins = *(u32_t *)hp->h_addr; } /* We take the last 2 values given, the 2nd-last as the primary and the last as the secondary. If only one is given it becomes both primary and secondary. */ if (ipcp_allowoptions[0].winsaddr[1] == 0) - ipcp_allowoptions[0].winsaddr[0] = wins; + ipcp_allowoptions[0].winsaddr[0] = wins; else - ipcp_allowoptions[0].winsaddr[0] = ipcp_allowoptions[0].winsaddr[1]; + ipcp_allowoptions[0].winsaddr[0] = ipcp_allowoptions[0].winsaddr[1]; /* always set the secondary address value. */ ipcp_allowoptions[0].winsaddr[1] = wins; @@ -455,52 +455,52 @@ setipaddr(arg, argv, doit) * IP address pair separated by ":". */ if ((colon = strchr(arg, ':')) == NULL) - return 0; + return 0; if (!doit) - return 1; - + return 1; + /* * If colon first character, then no local addr. */ if (colon != arg && option_priority >= prio_local) { - *colon = '\0'; - if ((local = inet_addr(arg)) == (u32_t) -1) { - if ((hp = gethostbyname(arg)) == NULL) { - option_error("unknown host: %s", arg); - return 0; - } - local = *(u32_t *)hp->h_addr; - } - if (bad_ip_adrs(local)) { - option_error("bad local IP address %s", ip_ntoa(local)); - return 0; - } - if (local != 0) - wo->ouraddr = local; - *colon = ':'; - prio_local = option_priority; + *colon = '\0'; + if ((local = inet_addr(arg)) == (u32_t) -1) { + if ((hp = gethostbyname(arg)) == NULL) { + option_error("unknown host: %s", arg); + return 0; + } + local = *(u32_t *)hp->h_addr; } - + if (bad_ip_adrs(local)) { + option_error("bad local IP address %s", ip_ntoa(local)); + return 0; + } + if (local != 0) + wo->ouraddr = local; + *colon = ':'; + prio_local = option_priority; + } + /* * If colon last character, then no remote addr. */ if (*++colon != '\0' && option_priority >= prio_remote) { - if ((remote = inet_addr(colon)) == (u32_t) -1) { - if ((hp = gethostbyname(colon)) == NULL) { - option_error("unknown host: %s", colon); - return 0; - } - remote = *(u32_t *)hp->h_addr; - if (remote_name[0] == 0) - strlcpy(remote_name, colon, sizeof(remote_name)); - } - if (bad_ip_adrs(remote)) { - option_error("bad remote IP address %s", ip_ntoa(remote)); - return 0; - } - if (remote != 0) - wo->hisaddr = remote; - prio_remote = option_priority; + if ((remote = inet_addr(colon)) == (u32_t) -1) { + if ((hp = gethostbyname(colon)) == NULL) { + option_error("unknown host: %s", colon); + return 0; + } + remote = *(u32_t *)hp->h_addr; + if (remote_name[0] == 0) + strlcpy(remote_name, colon, sizeof(remote_name)); + } + if (bad_ip_adrs(remote)) { + option_error("bad remote IP address %s", ip_ntoa(remote)); + return 0; + } + if (remote != 0) + wo->hisaddr = remote; + prio_remote = option_priority; } return 1; @@ -512,13 +512,13 @@ printipaddr(opt, printer, arg) void (*printer) (void *, char *, ...); void *arg; { - ipcp_options *wo = &ipcp_wantoptions[0]; + ipcp_options *wo = &ipcp_wantoptions[0]; - if (wo->ouraddr != 0) - printer(arg, "%I", wo->ouraddr); - printer(arg, ":"); - if (wo->hisaddr != 0) - printer(arg, "%I", wo->hisaddr); + if (wo->ouraddr != 0) + printer(arg, "%I", wo->ouraddr); + printer(arg, ":"); + if (wo->hisaddr != 0) + printer(arg, "%I", wo->hisaddr); } /* @@ -542,8 +542,8 @@ setnetmask(argv) mask = lwip_htonl(mask); if (n == 0 || p[n] != 0 || (netmask & ~mask) != 0) { - option_error("invalid netmask value '%s'", *argv); - return 0; + option_error("invalid netmask value '%s'", *argv); + return 0; } netmask = mask; @@ -563,23 +563,23 @@ parse_dotted_ip(p, vp) v = 0; for (n = 3;; --n) { - b = strtoul(p, &endp, 0); - if (endp == p) - return 0; - if (b > 255) { - if (n < 3) - return 0; - /* accept e.g. 0xffffff00 */ - *vp = b; - return endp - p0; - } - v |= b << (n * 8); - p = endp; - if (n == 0) - break; - if (*p != '.') - return 0; - ++p; + b = strtoul(p, &endp, 0); + if (endp == p) + return 0; + if (b > 255) { + if (n < 3) + return 0; + /* accept e.g. 0xffffff00 */ + *vp = b; + return endp - p0; + } + v |= b << (n * 8); + p = endp; + if (n == 0) + break; + if (*p != '.') + return 0; + ++p; } *vp = v; return p - p0; @@ -716,23 +716,23 @@ static void ipcp_resetci(fsm *f) { ipcp_options *ao = &pcb->ipcp_allowoptions; wo->req_addr = (wo->neg_addr || wo->old_addrs) && - (ao->neg_addr || ao->old_addrs); + (ao->neg_addr || ao->old_addrs); if (wo->ouraddr == 0) - wo->accept_local = 1; + wo->accept_local = 1; if (wo->hisaddr == 0) - wo->accept_remote = 1; + wo->accept_remote = 1; #if LWIP_DNS - wo->req_dns1 = wo->req_dns2 = pcb->settings.usepeerdns; /* Request DNS addresses from the peer */ + wo->req_dns1 = wo->req_dns2 = pcb->settings.usepeerdns; /* Request DNS addresses from the peer */ #endif /* LWIP_DNS */ *go = *wo; if (!pcb->ask_for_local) - go->ouraddr = 0; + go->ouraddr = 0; #if 0 /* UNUSED */ if (ip_choose_hook) { - ip_choose_hook(&wo->hisaddr); - if (wo->hisaddr) { - wo->accept_remote = 0; - } + ip_choose_hook(&wo->hisaddr); + if (wo->hisaddr) { + wo->accept_remote = 0; + } } #endif /* UNUSED */ BZERO(&pcb->ipcp_hisoptions, sizeof(ipcp_options)); @@ -751,16 +751,16 @@ static int ipcp_cilen(fsm *f) { #endif /* VJ_SUPPORT */ ipcp_options *ho = &pcb->ipcp_hisoptions; -#define LENCIADDRS(neg) (neg ? CILEN_ADDRS : 0) +#define LENCIADDRS(neg) (neg ? CILEN_ADDRS : 0) #if VJ_SUPPORT -#define LENCIVJ(neg, old) (neg ? (old? CILEN_COMPRESS : CILEN_VJ) : 0) +#define LENCIVJ(neg, old) (neg ? (old? CILEN_COMPRESS : CILEN_VJ) : 0) #endif /* VJ_SUPPORT */ -#define LENCIADDR(neg) (neg ? CILEN_ADDR : 0) +#define LENCIADDR(neg) (neg ? CILEN_ADDR : 0) #if LWIP_DNS -#define LENCIDNS(neg) LENCIADDR(neg) +#define LENCIDNS(neg) LENCIADDR(neg) #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ -#define LENCIWINS(neg) LENCIADDR(neg) +#define LENCIWINS(neg) LENCIADDR(neg) #endif /* UNUSED - WINS */ /* @@ -768,34 +768,34 @@ static int ipcp_cilen(fsm *f) { * forms because we have received old forms from the peer. */ if (go->neg_addr && go->old_addrs && !ho->neg_addr && ho->old_addrs) - go->neg_addr = 0; + go->neg_addr = 0; #if VJ_SUPPORT if (wo->neg_vj && !go->neg_vj && !go->old_vj) { - /* try an older style of VJ negotiation */ - /* use the old style only if the peer did */ - if (ho->neg_vj && ho->old_vj) { - go->neg_vj = 1; - go->old_vj = 1; - go->vj_protocol = ho->vj_protocol; - } + /* try an older style of VJ negotiation */ + /* use the old style only if the peer did */ + if (ho->neg_vj && ho->old_vj) { + go->neg_vj = 1; + go->old_vj = 1; + go->vj_protocol = ho->vj_protocol; + } } #endif /* VJ_SUPPORT */ return (LENCIADDRS(!go->neg_addr && go->old_addrs) + #if VJ_SUPPORT - LENCIVJ(go->neg_vj, go->old_vj) + + LENCIVJ(go->neg_vj, go->old_vj) + #endif /* VJ_SUPPORT */ - LENCIADDR(go->neg_addr) + + LENCIADDR(go->neg_addr) + #if LWIP_DNS - LENCIDNS(go->req_dns1) + - LENCIDNS(go->req_dns2) + + LENCIDNS(go->req_dns1) + + LENCIDNS(go->req_dns2) + #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ - LENCIWINS(go->winsaddr[0]) + - LENCIWINS(go->winsaddr[1]) + + LENCIWINS(go->winsaddr[0]) + + LENCIWINS(go->winsaddr[1]) + #endif /* UNUSED - WINS */ - 0); + 0); } @@ -810,86 +810,86 @@ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp) { #define ADDCIADDRS(opt, neg, val1, val2) \ if (neg) { \ - if (len >= CILEN_ADDRS) { \ - u32_t l; \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_ADDRS, ucp); \ - l = lwip_ntohl(val1); \ - PUTLONG(l, ucp); \ - l = lwip_ntohl(val2); \ - PUTLONG(l, ucp); \ - len -= CILEN_ADDRS; \ - } else \ - go->old_addrs = 0; \ + if (len >= CILEN_ADDRS) { \ + u32_t l; \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_ADDRS, ucp); \ + l = lwip_ntohl(val1); \ + PUTLONG(l, ucp); \ + l = lwip_ntohl(val2); \ + PUTLONG(l, ucp); \ + len -= CILEN_ADDRS; \ + } else \ + go->old_addrs = 0; \ } #if VJ_SUPPORT #define ADDCIVJ(opt, neg, val, old, maxslotindex, cflag) \ if (neg) { \ - int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \ - if (len >= vjlen) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(vjlen, ucp); \ - PUTSHORT(val, ucp); \ - if (!old) { \ - PUTCHAR(maxslotindex, ucp); \ - PUTCHAR(cflag, ucp); \ - } \ - len -= vjlen; \ - } else \ - neg = 0; \ + int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \ + if (len >= vjlen) { \ + PUTCHAR(opt, ucp); \ + PUTCHAR(vjlen, ucp); \ + PUTSHORT(val, ucp); \ + if (!old) { \ + PUTCHAR(maxslotindex, ucp); \ + PUTCHAR(cflag, ucp); \ + } \ + len -= vjlen; \ + } else \ + neg = 0; \ } #endif /* VJ_SUPPORT */ #define ADDCIADDR(opt, neg, val) \ if (neg) { \ - if (len >= CILEN_ADDR) { \ - u32_t l; \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_ADDR, ucp); \ - l = lwip_ntohl(val); \ - PUTLONG(l, ucp); \ - len -= CILEN_ADDR; \ - } else \ - neg = 0; \ + if (len >= CILEN_ADDR) { \ + u32_t l; \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_ADDR, ucp); \ + l = lwip_ntohl(val); \ + PUTLONG(l, ucp); \ + len -= CILEN_ADDR; \ + } else \ + neg = 0; \ } #if LWIP_DNS #define ADDCIDNS(opt, neg, addr) \ if (neg) { \ - if (len >= CILEN_ADDR) { \ - u32_t l; \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_ADDR, ucp); \ - l = lwip_ntohl(addr); \ - PUTLONG(l, ucp); \ - len -= CILEN_ADDR; \ - } else \ - neg = 0; \ + if (len >= CILEN_ADDR) { \ + u32_t l; \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_ADDR, ucp); \ + l = lwip_ntohl(addr); \ + PUTLONG(l, ucp); \ + len -= CILEN_ADDR; \ + } else \ + neg = 0; \ } #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ #define ADDCIWINS(opt, addr) \ if (addr) { \ - if (len >= CILEN_ADDR) { \ - u32_t l; \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_ADDR, ucp); \ - l = lwip_ntohl(addr); \ - PUTLONG(l, ucp); \ - len -= CILEN_ADDR; \ - } else \ - addr = 0; \ + if (len >= CILEN_ADDR) { \ + u32_t l; \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_ADDR, ucp); \ + l = lwip_ntohl(addr); \ + PUTLONG(l, ucp); \ + len -= CILEN_ADDR; \ + } else \ + addr = 0; \ } #endif /* UNUSED - WINS */ ADDCIADDRS(CI_ADDRS, !go->neg_addr && go->old_addrs, go->ouraddr, - go->hisaddr); + go->hisaddr); #if VJ_SUPPORT ADDCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj, - go->maxslotindex, go->cflag); + go->maxslotindex, go->cflag); #endif /* VJ_SUPPORT */ ADDCIADDR(CI_ADDR, go->neg_addr, go->ouraddr); @@ -905,7 +905,7 @@ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp) { ADDCIWINS(CI_MS_WINS2, go->winsaddr[1]); #endif /* UNUSED - WINS */ - + *lenp -= len; } @@ -915,8 +915,8 @@ static void ipcp_addci(fsm *f, u_char *ucp, int *lenp) { * Called by fsm_rconfack, Receive Configure ACK. * * Returns: - * 0 - Ack was bad. - * 1 - Ack was good. + * 0 - Ack was bad. + * 1 - Ack was good. */ static int ipcp_ackci(fsm *f, u_char *p, int len) { ppp_pcb *pcb = f->pcb; @@ -936,105 +936,105 @@ static int ipcp_ackci(fsm *f, u_char *p, int len) { #define ACKCIADDRS(opt, neg, val1, val2) \ if (neg) { \ - u32_t l; \ - if ((len -= CILEN_ADDRS) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_ADDRS || \ - citype != opt) \ - goto bad; \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - if (val1 != cilong) \ - goto bad; \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - if (val2 != cilong) \ - goto bad; \ + u32_t l; \ + if ((len -= CILEN_ADDRS) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_ADDRS || \ + citype != opt) \ + goto bad; \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + if (val1 != cilong) \ + goto bad; \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + if (val2 != cilong) \ + goto bad; \ } #if VJ_SUPPORT #define ACKCIVJ(opt, neg, val, old, maxslotindex, cflag) \ if (neg) { \ - int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \ - if ((len -= vjlen) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != vjlen || \ - citype != opt) \ - goto bad; \ - GETSHORT(cishort, p); \ - if (cishort != val) \ - goto bad; \ - if (!old) { \ - GETCHAR(cimaxslotindex, p); \ - if (cimaxslotindex != maxslotindex) \ - goto bad; \ - GETCHAR(cicflag, p); \ - if (cicflag != cflag) \ - goto bad; \ - } \ + int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \ + if ((len -= vjlen) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != vjlen || \ + citype != opt) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != val) \ + goto bad; \ + if (!old) { \ + GETCHAR(cimaxslotindex, p); \ + if (cimaxslotindex != maxslotindex) \ + goto bad; \ + GETCHAR(cicflag, p); \ + if (cicflag != cflag) \ + goto bad; \ + } \ } #endif /* VJ_SUPPORT */ #define ACKCIADDR(opt, neg, val) \ if (neg) { \ - u32_t l; \ - if ((len -= CILEN_ADDR) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_ADDR || \ - citype != opt) \ - goto bad; \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - if (val != cilong) \ - goto bad; \ + u32_t l; \ + if ((len -= CILEN_ADDR) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_ADDR || \ + citype != opt) \ + goto bad; \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + if (val != cilong) \ + goto bad; \ } #if LWIP_DNS #define ACKCIDNS(opt, neg, addr) \ if (neg) { \ - u32_t l; \ - if ((len -= CILEN_ADDR) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_ADDR || citype != opt) \ - goto bad; \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - if (addr != cilong) \ - goto bad; \ + u32_t l; \ + if ((len -= CILEN_ADDR) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_ADDR || citype != opt) \ + goto bad; \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + if (addr != cilong) \ + goto bad; \ } #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ #define ACKCIWINS(opt, addr) \ if (addr) { \ - u32_t l; \ - if ((len -= CILEN_ADDR) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_ADDR || citype != opt) \ - goto bad; \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - if (addr != cilong) \ - goto bad; \ + u32_t l; \ + if ((len -= CILEN_ADDR) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_ADDR || citype != opt) \ + goto bad; \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + if (addr != cilong) \ + goto bad; \ } #endif /* UNUSED - WINS */ ACKCIADDRS(CI_ADDRS, !go->neg_addr && go->old_addrs, go->ouraddr, - go->hisaddr); + go->hisaddr); #if VJ_SUPPORT ACKCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj, - go->maxslotindex, go->cflag); + go->maxslotindex, go->cflag); #endif /* VJ_SUPPORT */ ACKCIADDR(CI_ADDR, go->neg_addr, go->ouraddr); @@ -1055,7 +1055,7 @@ static int ipcp_ackci(fsm *f, u_char *p, int len) { * If there are any remaining CIs, then this packet is bad. */ if (len != 0) - goto bad; + goto bad; return (1); bad: @@ -1070,8 +1070,8 @@ bad: * Calback from fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject. * * Returns: - * 0 - Nak was bad. - * 1 - Nak was good. + * 0 - Nak was bad. + * 1 - Nak was good. */ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { ppp_pcb *pcb = f->pcb; @@ -1085,8 +1085,8 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { #if LWIP_DNS u32_t cidnsaddr; #endif /* LWIP_DNS */ - ipcp_options no; /* options we've seen Naks for */ - ipcp_options try_; /* options to request next time */ + ipcp_options no; /* options we've seen Naks for */ + ipcp_options try_; /* options to request next time */ BZERO(&no, sizeof(no)); try_ = *go; @@ -1098,58 +1098,58 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { */ #define NAKCIADDRS(opt, neg, code) \ if ((neg) && \ - (cilen = p[1]) == CILEN_ADDRS && \ - len >= cilen && \ - p[0] == opt) { \ - len -= cilen; \ - INCPTR(2, p); \ - GETLONG(l, p); \ - ciaddr1 = lwip_htonl(l); \ - GETLONG(l, p); \ - ciaddr2 = lwip_htonl(l); \ - no.old_addrs = 1; \ - code \ + (cilen = p[1]) == CILEN_ADDRS && \ + len >= cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + ciaddr1 = lwip_htonl(l); \ + GETLONG(l, p); \ + ciaddr2 = lwip_htonl(l); \ + no.old_addrs = 1; \ + code \ } #if VJ_SUPPORT #define NAKCIVJ(opt, neg, code) \ if (go->neg && \ - ((cilen = p[1]) == CILEN_COMPRESS || cilen == CILEN_VJ) && \ - len >= cilen && \ - p[0] == opt) { \ - len -= cilen; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - no.neg = 1; \ + ((cilen = p[1]) == CILEN_COMPRESS || cilen == CILEN_VJ) && \ + len >= cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + no.neg = 1; \ code \ } #endif /* VJ_SUPPORT */ #define NAKCIADDR(opt, neg, code) \ if (go->neg && \ - (cilen = p[1]) == CILEN_ADDR && \ - len >= cilen && \ - p[0] == opt) { \ - len -= cilen; \ - INCPTR(2, p); \ - GETLONG(l, p); \ - ciaddr1 = lwip_htonl(l); \ - no.neg = 1; \ - code \ + (cilen = p[1]) == CILEN_ADDR && \ + len >= cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + ciaddr1 = lwip_htonl(l); \ + no.neg = 1; \ + code \ } #if LWIP_DNS #define NAKCIDNS(opt, neg, code) \ if (go->neg && \ - ((cilen = p[1]) == CILEN_ADDR) && \ - len >= cilen && \ - p[0] == opt) { \ - len -= cilen; \ - INCPTR(2, p); \ - GETLONG(l, p); \ - cidnsaddr = lwip_htonl(l); \ - no.neg = 1; \ - code \ + ((cilen = p[1]) == CILEN_ADDR) && \ + len >= cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cidnsaddr = lwip_htonl(l); \ + no.neg = 1; \ + code \ } #endif /* LWIP_DNS */ @@ -1158,19 +1158,19 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * from our idea, only if the accept_{local,remote} flag is set. */ NAKCIADDRS(CI_ADDRS, !go->neg_addr && go->old_addrs, - if (treat_as_reject) { - try_.old_addrs = 0; - } else { - if (go->accept_local && ciaddr1) { - /* take his idea of our address */ - try_.ouraddr = ciaddr1; - } - if (go->accept_remote && ciaddr2) { - /* take his idea of his address */ - try_.hisaddr = ciaddr2; - } - } - ); + if (treat_as_reject) { + try_.old_addrs = 0; + } else { + if (go->accept_local && ciaddr1) { + /* take his idea of our address */ + try_.ouraddr = ciaddr1; + } + if (go->accept_remote && ciaddr2) { + /* take his idea of his address */ + try_.hisaddr = ciaddr2; + } + } + ); #if VJ_SUPPORT /* @@ -1180,57 +1180,57 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * the peer wants. */ NAKCIVJ(CI_COMPRESSTYPE, neg_vj, - if (treat_as_reject) { - try_.neg_vj = 0; - } else if (cilen == CILEN_VJ) { - GETCHAR(cimaxslotindex, p); - GETCHAR(cicflag, p); - if (cishort == IPCP_VJ_COMP) { - try_.old_vj = 0; - if (cimaxslotindex < go->maxslotindex) - try_.maxslotindex = cimaxslotindex; - if (!cicflag) - try_.cflag = 0; - } else { - try_.neg_vj = 0; - } - } else { - if (cishort == IPCP_VJ_COMP || cishort == IPCP_VJ_COMP_OLD) { - try_.old_vj = 1; - try_.vj_protocol = cishort; - } else { - try_.neg_vj = 0; - } - } - ); + if (treat_as_reject) { + try_.neg_vj = 0; + } else if (cilen == CILEN_VJ) { + GETCHAR(cimaxslotindex, p); + GETCHAR(cicflag, p); + if (cishort == IPCP_VJ_COMP) { + try_.old_vj = 0; + if (cimaxslotindex < go->maxslotindex) + try_.maxslotindex = cimaxslotindex; + if (!cicflag) + try_.cflag = 0; + } else { + try_.neg_vj = 0; + } + } else { + if (cishort == IPCP_VJ_COMP || cishort == IPCP_VJ_COMP_OLD) { + try_.old_vj = 1; + try_.vj_protocol = cishort; + } else { + try_.neg_vj = 0; + } + } + ); #endif /* VJ_SUPPORT */ NAKCIADDR(CI_ADDR, neg_addr, - if (treat_as_reject) { - try_.neg_addr = 0; - try_.old_addrs = 0; - } else if (go->accept_local && ciaddr1) { - /* take his idea of our address */ - try_.ouraddr = ciaddr1; - } - ); + if (treat_as_reject) { + try_.neg_addr = 0; + try_.old_addrs = 0; + } else if (go->accept_local && ciaddr1) { + /* take his idea of our address */ + try_.ouraddr = ciaddr1; + } + ); #if LWIP_DNS NAKCIDNS(CI_MS_DNS1, req_dns1, - if (treat_as_reject) { - try_.req_dns1 = 0; - } else { - try_.dnsaddr[0] = cidnsaddr; - } - ); + if (treat_as_reject) { + try_.req_dns1 = 0; + } else { + try_.dnsaddr[0] = cidnsaddr; + } + ); NAKCIDNS(CI_MS_DNS2, req_dns2, - if (treat_as_reject) { - try_.req_dns2 = 0; - } else { - try_.dnsaddr[1] = cidnsaddr; - } - ); + if (treat_as_reject) { + try_.req_dns2 = 0; + } else { + try_.dnsaddr[1] = cidnsaddr; + } + ); #endif /* #if LWIP_DNS */ /* @@ -1242,81 +1242,81 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * peers get huffy if we don't. */ while (len >= CILEN_VOID) { - GETCHAR(citype, p); - GETCHAR(cilen, p); - if ( cilen < CILEN_VOID || (len -= cilen) < 0 ) - goto bad; - next = p + cilen - 2; + GETCHAR(citype, p); + GETCHAR(cilen, p); + if ( cilen < CILEN_VOID || (len -= cilen) < 0 ) + goto bad; + next = p + cilen - 2; - switch (citype) { + switch (citype) { #if VJ_SUPPORT - case CI_COMPRESSTYPE: - if (go->neg_vj || no.neg_vj || - (cilen != CILEN_VJ && cilen != CILEN_COMPRESS)) - goto bad; - no.neg_vj = 1; - break; + case CI_COMPRESSTYPE: + if (go->neg_vj || no.neg_vj || + (cilen != CILEN_VJ && cilen != CILEN_COMPRESS)) + goto bad; + no.neg_vj = 1; + break; #endif /* VJ_SUPPORT */ - case CI_ADDRS: - if ((!go->neg_addr && go->old_addrs) || no.old_addrs - || cilen != CILEN_ADDRS) - goto bad; - try_.neg_addr = 0; - GETLONG(l, p); - ciaddr1 = lwip_htonl(l); - if (ciaddr1 && go->accept_local) - try_.ouraddr = ciaddr1; - GETLONG(l, p); - ciaddr2 = lwip_htonl(l); - if (ciaddr2 && go->accept_remote) - try_.hisaddr = ciaddr2; - no.old_addrs = 1; - break; - case CI_ADDR: - if (go->neg_addr || no.neg_addr || cilen != CILEN_ADDR) - goto bad; - try_.old_addrs = 0; - GETLONG(l, p); - ciaddr1 = lwip_htonl(l); - if (ciaddr1 && go->accept_local) - try_.ouraddr = ciaddr1; - if (try_.ouraddr != 0) - try_.neg_addr = 1; - no.neg_addr = 1; - break; + case CI_ADDRS: + if ((!go->neg_addr && go->old_addrs) || no.old_addrs + || cilen != CILEN_ADDRS) + goto bad; + try_.neg_addr = 0; + GETLONG(l, p); + ciaddr1 = lwip_htonl(l); + if (ciaddr1 && go->accept_local) + try_.ouraddr = ciaddr1; + GETLONG(l, p); + ciaddr2 = lwip_htonl(l); + if (ciaddr2 && go->accept_remote) + try_.hisaddr = ciaddr2; + no.old_addrs = 1; + break; + case CI_ADDR: + if (go->neg_addr || no.neg_addr || cilen != CILEN_ADDR) + goto bad; + try_.old_addrs = 0; + GETLONG(l, p); + ciaddr1 = lwip_htonl(l); + if (ciaddr1 && go->accept_local) + try_.ouraddr = ciaddr1; + if (try_.ouraddr != 0) + try_.neg_addr = 1; + no.neg_addr = 1; + break; #if LWIP_DNS - case CI_MS_DNS1: - if (go->req_dns1 || no.req_dns1 || cilen != CILEN_ADDR) - goto bad; - GETLONG(l, p); - try_.dnsaddr[0] = lwip_htonl(l); - try_.req_dns1 = 1; - no.req_dns1 = 1; - break; - case CI_MS_DNS2: - if (go->req_dns2 || no.req_dns2 || cilen != CILEN_ADDR) - goto bad; - GETLONG(l, p); - try_.dnsaddr[1] = lwip_htonl(l); - try_.req_dns2 = 1; - no.req_dns2 = 1; - break; + case CI_MS_DNS1: + if (go->req_dns1 || no.req_dns1 || cilen != CILEN_ADDR) + goto bad; + GETLONG(l, p); + try_.dnsaddr[0] = lwip_htonl(l); + try_.req_dns1 = 1; + no.req_dns1 = 1; + break; + case CI_MS_DNS2: + if (go->req_dns2 || no.req_dns2 || cilen != CILEN_ADDR) + goto bad; + GETLONG(l, p); + try_.dnsaddr[1] = lwip_htonl(l); + try_.req_dns2 = 1; + no.req_dns2 = 1; + break; #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ - case CI_MS_WINS1: - case CI_MS_WINS2: - if (cilen != CILEN_ADDR) - goto bad; - GETLONG(l, p); - ciaddr1 = lwip_htonl(l); - if (ciaddr1) - try_.winsaddr[citype == CI_MS_WINS2] = ciaddr1; - break; + case CI_MS_WINS1: + case CI_MS_WINS2: + if (cilen != CILEN_ADDR) + goto bad; + GETLONG(l, p); + ciaddr1 = lwip_htonl(l); + if (ciaddr1) + try_.winsaddr[citype == CI_MS_WINS2] = ciaddr1; + break; #endif /* UNUSED - WINS */ - default: - break; - } - p = next; + default: + break; + } + p = next; } /* @@ -1324,7 +1324,7 @@ static int ipcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * If there are any remaining options, we ignore them. */ if (f->state != PPP_FSM_OPENED) - *go = try_; + *go = try_; return 1; @@ -1347,7 +1347,7 @@ static int ipcp_rejci(fsm *f, u_char *p, int len) { u_short cishort; #endif /* VJ_SUPPORT */ u32_t cilong; - ipcp_options try_; /* options to request next time */ + ipcp_options try_; /* options to request next time */ try_ = *go; /* @@ -1357,107 +1357,107 @@ static int ipcp_rejci(fsm *f, u_char *p, int len) { */ #define REJCIADDRS(opt, neg, val1, val2) \ if ((neg) && \ - (cilen = p[1]) == CILEN_ADDRS && \ - len >= cilen && \ - p[0] == opt) { \ - u32_t l; \ - len -= cilen; \ - INCPTR(2, p); \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - /* Check rejected value. */ \ - if (cilong != val1) \ - goto bad; \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - /* Check rejected value. */ \ - if (cilong != val2) \ - goto bad; \ - try_.old_addrs = 0; \ + (cilen = p[1]) == CILEN_ADDRS && \ + len >= cilen && \ + p[0] == opt) { \ + u32_t l; \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + /* Check rejected value. */ \ + if (cilong != val1) \ + goto bad; \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + /* Check rejected value. */ \ + if (cilong != val2) \ + goto bad; \ + try_.old_addrs = 0; \ } #if VJ_SUPPORT #define REJCIVJ(opt, neg, val, old, maxslot, cflag) \ if (go->neg && \ - p[1] == (old? CILEN_COMPRESS : CILEN_VJ) && \ - len >= p[1] && \ - p[0] == opt) { \ - len -= p[1]; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - /* Check rejected value. */ \ - if (cishort != val) \ - goto bad; \ - if (!old) { \ - GETCHAR(cimaxslotindex, p); \ - if (cimaxslotindex != maxslot) \ - goto bad; \ - GETCHAR(ciflag, p); \ - if (ciflag != cflag) \ - goto bad; \ + p[1] == (old? CILEN_COMPRESS : CILEN_VJ) && \ + len >= p[1] && \ + p[0] == opt) { \ + len -= p[1]; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + /* Check rejected value. */ \ + if (cishort != val) \ + goto bad; \ + if (!old) { \ + GETCHAR(cimaxslotindex, p); \ + if (cimaxslotindex != maxslot) \ + goto bad; \ + GETCHAR(ciflag, p); \ + if (ciflag != cflag) \ + goto bad; \ } \ - try_.neg = 0; \ + try_.neg = 0; \ } #endif /* VJ_SUPPORT */ #define REJCIADDR(opt, neg, val) \ if (go->neg && \ - (cilen = p[1]) == CILEN_ADDR && \ - len >= cilen && \ - p[0] == opt) { \ - u32_t l; \ - len -= cilen; \ - INCPTR(2, p); \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - /* Check rejected value. */ \ - if (cilong != val) \ - goto bad; \ - try_.neg = 0; \ + (cilen = p[1]) == CILEN_ADDR && \ + len >= cilen && \ + p[0] == opt) { \ + u32_t l; \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + /* Check rejected value. */ \ + if (cilong != val) \ + goto bad; \ + try_.neg = 0; \ } #if LWIP_DNS #define REJCIDNS(opt, neg, dnsaddr) \ if (go->neg && \ - ((cilen = p[1]) == CILEN_ADDR) && \ - len >= cilen && \ - p[0] == opt) { \ - u32_t l; \ - len -= cilen; \ - INCPTR(2, p); \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - /* Check rejected value. */ \ - if (cilong != dnsaddr) \ - goto bad; \ - try_.neg = 0; \ + ((cilen = p[1]) == CILEN_ADDR) && \ + len >= cilen && \ + p[0] == opt) { \ + u32_t l; \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + /* Check rejected value. */ \ + if (cilong != dnsaddr) \ + goto bad; \ + try_.neg = 0; \ } #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ #define REJCIWINS(opt, addr) \ if (addr && \ - ((cilen = p[1]) == CILEN_ADDR) && \ - len >= cilen && \ - p[0] == opt) { \ - u32_t l; \ - len -= cilen; \ - INCPTR(2, p); \ - GETLONG(l, p); \ - cilong = lwip_htonl(l); \ - /* Check rejected value. */ \ - if (cilong != addr) \ - goto bad; \ - try_.winsaddr[opt == CI_MS_WINS2] = 0; \ + ((cilen = p[1]) == CILEN_ADDR) && \ + len >= cilen && \ + p[0] == opt) { \ + u32_t l; \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cilong = lwip_htonl(l); \ + /* Check rejected value. */ \ + if (cilong != addr) \ + goto bad; \ + try_.winsaddr[opt == CI_MS_WINS2] = 0; \ } #endif /* UNUSED - WINS */ REJCIADDRS(CI_ADDRS, !go->neg_addr && go->old_addrs, - go->ouraddr, go->hisaddr); + go->ouraddr, go->hisaddr); #if VJ_SUPPORT REJCIVJ(CI_COMPRESSTYPE, neg_vj, go->vj_protocol, go->old_vj, - go->maxslotindex, go->cflag); + go->maxslotindex, go->cflag); #endif /* VJ_SUPPORT */ REJCIADDR(CI_ADDR, neg_addr, go->ouraddr); @@ -1478,12 +1478,12 @@ static int ipcp_rejci(fsm *f, u_char *p, int len) { * If there are any remaining CIs, then this packet is bad. */ if (len != 0) - goto bad; + goto bad; /* * Now we can update state. */ if (f->state != PPP_FSM_OPENED) - *go = try_; + *go = try_; return 1; bad: @@ -1508,17 +1508,17 @@ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) { ipcp_options *wo = &pcb->ipcp_wantoptions; ipcp_options *ho = &pcb->ipcp_hisoptions; ipcp_options *ao = &pcb->ipcp_allowoptions; - u_char *cip, *next; /* Pointer to current and next CIs */ - u_short cilen, citype; /* Parsed len, type */ + u_char *cip, *next; /* Pointer to current and next CIs */ + u_short cilen, citype; /* Parsed len, type */ #if VJ_SUPPORT - u_short cishort; /* Parsed short value */ + u_short cishort; /* Parsed short value */ #endif /* VJ_SUPPORT */ u32_t tl, ciaddr1, ciaddr2;/* Parsed address values */ - int rc = CONFACK; /* Final packet return code */ - int orc; /* Individual option return code */ - u_char *p; /* Pointer to next char to parse */ - u_char *ucp = inp; /* Pointer to current output char */ - int l = *len; /* Length left */ + int rc = CONFACK; /* Final packet return code */ + int orc; /* Individual option return code */ + u_char *p; /* Pointer to next char to parse */ + u_char *ucp = inp; /* Pointer to current output char */ + int l = *len; /* Length left */ #if VJ_SUPPORT u_char maxslotindex, cflag; #endif /* VJ_SUPPORT */ @@ -1530,243 +1530,243 @@ static int ipcp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) { * Reset all his options. */ BZERO(ho, sizeof(*ho)); - + /* * Process all his options. */ next = inp; while (l) { - orc = CONFACK; /* Assume success */ - cip = p = next; /* Remember begining of CI */ - if (l < 2 || /* Not enough data for CI header or */ - p[1] < 2 || /* CI length too small or */ - p[1] > l) { /* CI length too big? */ - IPCPDEBUG(("ipcp_reqci: bad CI length!")); - orc = CONFREJ; /* Reject bad CI */ - cilen = l; /* Reject till end of packet */ - l = 0; /* Don't loop again */ - goto endswitch; - } - GETCHAR(citype, p); /* Parse CI type */ - GETCHAR(cilen, p); /* Parse CI length */ - l -= cilen; /* Adjust remaining length */ - next += cilen; /* Step to next CI */ + orc = CONFACK; /* Assume success */ + cip = p = next; /* Remember begining of CI */ + if (l < 2 || /* Not enough data for CI header or */ + p[1] < 2 || /* CI length too small or */ + p[1] > l) { /* CI length too big? */ + IPCPDEBUG(("ipcp_reqci: bad CI length!")); + orc = CONFREJ; /* Reject bad CI */ + cilen = l; /* Reject till end of packet */ + l = 0; /* Don't loop again */ + goto endswitch; + } + GETCHAR(citype, p); /* Parse CI type */ + GETCHAR(cilen, p); /* Parse CI length */ + l -= cilen; /* Adjust remaining length */ + next += cilen; /* Step to next CI */ - switch (citype) { /* Check CI type */ - case CI_ADDRS: - if (!ao->old_addrs || ho->neg_addr || - cilen != CILEN_ADDRS) { /* Check CI length */ - orc = CONFREJ; /* Reject CI */ - break; - } + switch (citype) { /* Check CI type */ + case CI_ADDRS: + if (!ao->old_addrs || ho->neg_addr || + cilen != CILEN_ADDRS) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } - /* - * If he has no address, or if we both have his address but - * disagree about it, then NAK it with our idea. - * In particular, if we don't know his address, but he does, - * then accept it. - */ - GETLONG(tl, p); /* Parse source address (his) */ - ciaddr1 = lwip_htonl(tl); - if (ciaddr1 != wo->hisaddr - && (ciaddr1 == 0 || !wo->accept_remote)) { - orc = CONFNAK; - if (!reject_if_disagree) { - DECPTR(sizeof(u32_t), p); - tl = lwip_ntohl(wo->hisaddr); - PUTLONG(tl, p); - } - } else if (ciaddr1 == 0 && wo->hisaddr == 0) { - /* - * If neither we nor he knows his address, reject the option. - */ - orc = CONFREJ; - wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */ - break; - } + /* + * If he has no address, or if we both have his address but + * disagree about it, then NAK it with our idea. + * In particular, if we don't know his address, but he does, + * then accept it. + */ + GETLONG(tl, p); /* Parse source address (his) */ + ciaddr1 = lwip_htonl(tl); + if (ciaddr1 != wo->hisaddr + && (ciaddr1 == 0 || !wo->accept_remote)) { + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(sizeof(u32_t), p); + tl = lwip_ntohl(wo->hisaddr); + PUTLONG(tl, p); + } + } else if (ciaddr1 == 0 && wo->hisaddr == 0) { + /* + * If neither we nor he knows his address, reject the option. + */ + orc = CONFREJ; + wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */ + break; + } - /* - * If he doesn't know our address, or if we both have our address - * but disagree about it, then NAK it with our idea. - */ - GETLONG(tl, p); /* Parse desination address (ours) */ - ciaddr2 = lwip_htonl(tl); - if (ciaddr2 != wo->ouraddr) { - if (ciaddr2 == 0 || !wo->accept_local) { - orc = CONFNAK; - if (!reject_if_disagree) { - DECPTR(sizeof(u32_t), p); - tl = lwip_ntohl(wo->ouraddr); - PUTLONG(tl, p); - } - } else { - wo->ouraddr = ciaddr2; /* accept peer's idea */ - } - } + /* + * If he doesn't know our address, or if we both have our address + * but disagree about it, then NAK it with our idea. + */ + GETLONG(tl, p); /* Parse desination address (ours) */ + ciaddr2 = lwip_htonl(tl); + if (ciaddr2 != wo->ouraddr) { + if (ciaddr2 == 0 || !wo->accept_local) { + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(sizeof(u32_t), p); + tl = lwip_ntohl(wo->ouraddr); + PUTLONG(tl, p); + } + } else { + wo->ouraddr = ciaddr2; /* accept peer's idea */ + } + } - ho->old_addrs = 1; - ho->hisaddr = ciaddr1; - ho->ouraddr = ciaddr2; - break; + ho->old_addrs = 1; + ho->hisaddr = ciaddr1; + ho->ouraddr = ciaddr2; + break; - case CI_ADDR: - if (!ao->neg_addr || ho->old_addrs || - cilen != CILEN_ADDR) { /* Check CI length */ - orc = CONFREJ; /* Reject CI */ - break; - } + case CI_ADDR: + if (!ao->neg_addr || ho->old_addrs || + cilen != CILEN_ADDR) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } - /* - * If he has no address, or if we both have his address but - * disagree about it, then NAK it with our idea. - * In particular, if we don't know his address, but he does, - * then accept it. - */ - GETLONG(tl, p); /* Parse source address (his) */ - ciaddr1 = lwip_htonl(tl); - if (ciaddr1 != wo->hisaddr - && (ciaddr1 == 0 || !wo->accept_remote)) { - orc = CONFNAK; - if (!reject_if_disagree) { - DECPTR(sizeof(u32_t), p); - tl = lwip_ntohl(wo->hisaddr); - PUTLONG(tl, p); - } - } else if (ciaddr1 == 0 && wo->hisaddr == 0) { - /* - * Don't ACK an address of 0.0.0.0 - reject it instead. - */ - orc = CONFREJ; - wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */ - break; - } - - ho->neg_addr = 1; - ho->hisaddr = ciaddr1; - break; + /* + * If he has no address, or if we both have his address but + * disagree about it, then NAK it with our idea. + * In particular, if we don't know his address, but he does, + * then accept it. + */ + GETLONG(tl, p); /* Parse source address (his) */ + ciaddr1 = lwip_htonl(tl); + if (ciaddr1 != wo->hisaddr + && (ciaddr1 == 0 || !wo->accept_remote)) { + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(sizeof(u32_t), p); + tl = lwip_ntohl(wo->hisaddr); + PUTLONG(tl, p); + } + } else if (ciaddr1 == 0 && wo->hisaddr == 0) { + /* + * Don't ACK an address of 0.0.0.0 - reject it instead. + */ + orc = CONFREJ; + wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */ + break; + } + + ho->neg_addr = 1; + ho->hisaddr = ciaddr1; + break; #if LWIP_DNS - case CI_MS_DNS1: - case CI_MS_DNS2: - /* Microsoft primary or secondary DNS request */ - d = citype == CI_MS_DNS2; + case CI_MS_DNS1: + case CI_MS_DNS2: + /* Microsoft primary or secondary DNS request */ + d = citype == CI_MS_DNS2; - /* If we do not have a DNS address then we cannot send it */ - if (ao->dnsaddr[d] == 0 || - cilen != CILEN_ADDR) { /* Check CI length */ - orc = CONFREJ; /* Reject CI */ - break; - } - GETLONG(tl, p); - if (lwip_htonl(tl) != ao->dnsaddr[d]) { + /* If we do not have a DNS address then we cannot send it */ + if (ao->dnsaddr[d] == 0 || + cilen != CILEN_ADDR) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } + GETLONG(tl, p); + if (lwip_htonl(tl) != ao->dnsaddr[d]) { DECPTR(sizeof(u32_t), p); - tl = lwip_ntohl(ao->dnsaddr[d]); - PUTLONG(tl, p); - orc = CONFNAK; + tl = lwip_ntohl(ao->dnsaddr[d]); + PUTLONG(tl, p); + orc = CONFNAK; } break; #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ - case CI_MS_WINS1: - case CI_MS_WINS2: - /* Microsoft primary or secondary WINS request */ - d = citype == CI_MS_WINS2; + case CI_MS_WINS1: + case CI_MS_WINS2: + /* Microsoft primary or secondary WINS request */ + d = citype == CI_MS_WINS2; - /* If we do not have a DNS address then we cannot send it */ - if (ao->winsaddr[d] == 0 || - cilen != CILEN_ADDR) { /* Check CI length */ - orc = CONFREJ; /* Reject CI */ - break; - } - GETLONG(tl, p); - if (lwip_htonl(tl) != ao->winsaddr[d]) { + /* If we do not have a DNS address then we cannot send it */ + if (ao->winsaddr[d] == 0 || + cilen != CILEN_ADDR) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } + GETLONG(tl, p); + if (lwip_htonl(tl) != ao->winsaddr[d]) { DECPTR(sizeof(u32_t), p); - tl = lwip_ntohl(ao->winsaddr[d]); - PUTLONG(tl, p); - orc = CONFNAK; + tl = lwip_ntohl(ao->winsaddr[d]); + PUTLONG(tl, p); + orc = CONFNAK; } break; #endif /* UNUSED - WINS */ #if VJ_SUPPORT - case CI_COMPRESSTYPE: - if (!ao->neg_vj || - (cilen != CILEN_VJ && cilen != CILEN_COMPRESS)) { - orc = CONFREJ; - break; - } - GETSHORT(cishort, p); + case CI_COMPRESSTYPE: + if (!ao->neg_vj || + (cilen != CILEN_VJ && cilen != CILEN_COMPRESS)) { + orc = CONFREJ; + break; + } + GETSHORT(cishort, p); - if (!(cishort == IPCP_VJ_COMP || - (cishort == IPCP_VJ_COMP_OLD && cilen == CILEN_COMPRESS))) { - orc = CONFREJ; - break; - } + if (!(cishort == IPCP_VJ_COMP || + (cishort == IPCP_VJ_COMP_OLD && cilen == CILEN_COMPRESS))) { + orc = CONFREJ; + break; + } - ho->neg_vj = 1; - ho->vj_protocol = cishort; - if (cilen == CILEN_VJ) { - GETCHAR(maxslotindex, p); - if (maxslotindex > ao->maxslotindex) { - orc = CONFNAK; - if (!reject_if_disagree){ - DECPTR(1, p); - PUTCHAR(ao->maxslotindex, p); - } - } - GETCHAR(cflag, p); - if (cflag && !ao->cflag) { - orc = CONFNAK; - if (!reject_if_disagree){ - DECPTR(1, p); - PUTCHAR(wo->cflag, p); - } - } - ho->maxslotindex = maxslotindex; - ho->cflag = cflag; - } else { - ho->old_vj = 1; - ho->maxslotindex = MAX_STATES - 1; - ho->cflag = 1; - } - break; + ho->neg_vj = 1; + ho->vj_protocol = cishort; + if (cilen == CILEN_VJ) { + GETCHAR(maxslotindex, p); + if (maxslotindex > ao->maxslotindex) { + orc = CONFNAK; + if (!reject_if_disagree){ + DECPTR(1, p); + PUTCHAR(ao->maxslotindex, p); + } + } + GETCHAR(cflag, p); + if (cflag && !ao->cflag) { + orc = CONFNAK; + if (!reject_if_disagree){ + DECPTR(1, p); + PUTCHAR(wo->cflag, p); + } + } + ho->maxslotindex = maxslotindex; + ho->cflag = cflag; + } else { + ho->old_vj = 1; + ho->maxslotindex = MAX_STATES - 1; + ho->cflag = 1; + } + break; #endif /* VJ_SUPPORT */ - default: - orc = CONFREJ; - break; - } + default: + orc = CONFREJ; + break; + } endswitch: - if (orc == CONFACK && /* Good CI */ - rc != CONFACK) /* but prior CI wasnt? */ - continue; /* Don't send this one */ + if (orc == CONFACK && /* Good CI */ + rc != CONFACK) /* but prior CI wasnt? */ + continue; /* Don't send this one */ - if (orc == CONFNAK) { /* Nak this CI? */ - if (reject_if_disagree) /* Getting fed up with sending NAKs? */ - orc = CONFREJ; /* Get tough if so */ - else { - if (rc == CONFREJ) /* Rejecting prior CI? */ - continue; /* Don't send this one */ - if (rc == CONFACK) { /* Ack'd all prior CIs? */ - rc = CONFNAK; /* Not anymore... */ - ucp = inp; /* Backup */ - } - } - } + if (orc == CONFNAK) { /* Nak this CI? */ + if (reject_if_disagree) /* Getting fed up with sending NAKs? */ + orc = CONFREJ; /* Get tough if so */ + else { + if (rc == CONFREJ) /* Rejecting prior CI? */ + continue; /* Don't send this one */ + if (rc == CONFACK) { /* Ack'd all prior CIs? */ + rc = CONFNAK; /* Not anymore... */ + ucp = inp; /* Backup */ + } + } + } - if (orc == CONFREJ && /* Reject this CI */ - rc != CONFREJ) { /* but no prior ones? */ - rc = CONFREJ; - ucp = inp; /* Backup */ - } + if (orc == CONFREJ && /* Reject this CI */ + rc != CONFREJ) { /* but no prior ones? */ + rc = CONFREJ; + ucp = inp; /* Backup */ + } - /* Need to move CI? */ - if (ucp != cip) - MEMCPY(ucp, cip, cilen); /* Move it */ + /* Need to move CI? */ + if (ucp != cip) + MEMCPY(ucp, cip, cilen); /* Move it */ - /* Update output pointer */ - INCPTR(cilen, ucp); + /* Update output pointer */ + INCPTR(cilen, ucp); } /* @@ -1777,21 +1777,21 @@ endswitch: * option safely. */ if (rc != CONFREJ && !ho->neg_addr && !ho->old_addrs && - wo->req_addr && !reject_if_disagree && !pcb->settings.noremoteip) { - if (rc == CONFACK) { - rc = CONFNAK; - ucp = inp; /* reset pointer */ - wo->req_addr = 0; /* don't ask again */ - } - PUTCHAR(CI_ADDR, ucp); - PUTCHAR(CILEN_ADDR, ucp); - tl = lwip_ntohl(wo->hisaddr); - PUTLONG(tl, ucp); + wo->req_addr && !reject_if_disagree && !pcb->settings.noremoteip) { + if (rc == CONFACK) { + rc = CONFNAK; + ucp = inp; /* reset pointer */ + wo->req_addr = 0; /* don't ask again */ + } + PUTCHAR(CI_ADDR, ucp); + PUTCHAR(CILEN_ADDR, ucp); + tl = lwip_ntohl(wo->hisaddr); + PUTLONG(tl, ucp); } - *len = ucp - inp; /* Compute output length */ + *len = ucp - inp; /* Compute output length */ IPCPDEBUG(("ipcp: returning Configure-%s", CODENAME(rc))); - return (rc); /* Return final code */ + return (rc); /* Return final code */ } @@ -1812,17 +1812,17 @@ ip_check_options() * If local IP address already given, don't bother. */ if (wo->ouraddr == 0 && !disable_defaultip) { - /* - * Look up our hostname (possibly with domain name appended) - * and take the first IP address as our local IP address. - * If there isn't an IP address for our hostname, too bad. - */ - wo->accept_local = 1; /* don't insist on this default value */ - if ((hp = gethostbyname(hostname)) != NULL) { - local = *(u32_t *)hp->h_addr; - if (local != 0 && !bad_ip_adrs(local)) - wo->ouraddr = local; - } + /* + * Look up our hostname (possibly with domain name appended) + * and take the first IP address as our local IP address. + * If there isn't an IP address for our hostname, too bad. + */ + wo->accept_local = 1; /* don't insist on this default value */ + if ((hp = gethostbyname(hostname)) != NULL) { + local = *(u32_t *)hp->h_addr; + if (local != 0 && !bad_ip_adrs(local)) + wo->ouraddr = local; + } } ask_for_local = wo->ouraddr != 0 || !disable_defaultip; } @@ -1841,37 +1841,37 @@ ip_demand_conf(u) ipcp_options *wo = &ipcp_wantoptions[u]; if (wo->hisaddr == 0 && !pcb->settings.noremoteip) { - /* make up an arbitrary address for the peer */ - wo->hisaddr = lwip_htonl(0x0a707070 + ifunit); - wo->accept_remote = 1; + /* make up an arbitrary address for the peer */ + wo->hisaddr = lwip_htonl(0x0a707070 + ifunit); + wo->accept_remote = 1; } if (wo->ouraddr == 0) { - /* make up an arbitrary address for us */ - wo->ouraddr = lwip_htonl(0x0a404040 + ifunit); - wo->accept_local = 1; - ask_for_local = 0; /* don't tell the peer this address */ + /* make up an arbitrary address for us */ + wo->ouraddr = lwip_htonl(0x0a404040 + ifunit); + wo->accept_local = 1; + ask_for_local = 0; /* don't tell the peer this address */ } if (!sifaddr(pcb, wo->ouraddr, wo->hisaddr, get_mask(wo->ouraddr))) - return 0; + return 0; if (!sifup(pcb)) - return 0; + return 0; if (!sifnpmode(pcb, PPP_IP, NPMODE_QUEUE)) - return 0; + return 0; #if 0 /* UNUSED */ if (wo->default_route) - if (sifdefaultroute(pcb, wo->ouraddr, wo->hisaddr, - wo->replace_default_route)) - default_route_set[u] = 1; + if (sifdefaultroute(pcb, wo->ouraddr, wo->hisaddr, + wo->replace_default_route)) + default_route_set[u] = 1; #endif /* UNUSED */ #if 0 /* UNUSED - PROXY ARP */ if (wo->proxy_arp) - if (sifproxyarp(pcb, wo->hisaddr)) - proxy_arp_set[u] = 1; + if (sifproxyarp(pcb, wo->hisaddr)) + proxy_arp_set[u] = 1; #endif /* UNUSED - PROXY ARP */ ppp_notice("local IP address %I", wo->ouraddr); if (wo->hisaddr) - ppp_notice("remote IP address %I", wo->hisaddr); + ppp_notice("remote IP address %I", wo->hisaddr); return 1; } @@ -1895,46 +1895,46 @@ static void ipcp_up(fsm *f) { * We must have a non-zero IP address for both ends of the link. */ if (!ho->neg_addr && !ho->old_addrs) - ho->hisaddr = wo->hisaddr; + ho->hisaddr = wo->hisaddr; if (!(go->neg_addr || go->old_addrs) && (wo->neg_addr || wo->old_addrs) - && wo->ouraddr != 0) { - ppp_error("Peer refused to agree to our IP address"); - ipcp_close(f->pcb, "Refused our IP address"); - return; + && wo->ouraddr != 0) { + ppp_error("Peer refused to agree to our IP address"); + ipcp_close(f->pcb, "Refused our IP address"); + return; } if (go->ouraddr == 0) { - ppp_error("Could not determine local IP address"); - ipcp_close(f->pcb, "Could not determine local IP address"); - return; + ppp_error("Could not determine local IP address"); + ipcp_close(f->pcb, "Could not determine local IP address"); + return; } if (ho->hisaddr == 0 && !pcb->settings.noremoteip) { - ho->hisaddr = lwip_htonl(0x0a404040); - ppp_warn("Could not determine remote IP address: defaulting to %I", - ho->hisaddr); + ho->hisaddr = lwip_htonl(0x0a404040); + ppp_warn("Could not determine remote IP address: defaulting to %I", + ho->hisaddr); } #if 0 /* UNUSED */ script_setenv("IPLOCAL", ip_ntoa(go->ouraddr), 0); if (ho->hisaddr != 0) - script_setenv("IPREMOTE", ip_ntoa(ho->hisaddr), 1); + script_setenv("IPREMOTE", ip_ntoa(ho->hisaddr), 1); #endif /* UNUSED */ #if LWIP_DNS if (!go->req_dns1) - go->dnsaddr[0] = 0; + go->dnsaddr[0] = 0; if (!go->req_dns2) - go->dnsaddr[1] = 0; + go->dnsaddr[1] = 0; #if 0 /* UNUSED */ if (go->dnsaddr[0]) - script_setenv("DNS1", ip_ntoa(go->dnsaddr[0]), 0); + script_setenv("DNS1", ip_ntoa(go->dnsaddr[0]), 0); if (go->dnsaddr[1]) - script_setenv("DNS2", ip_ntoa(go->dnsaddr[1]), 0); + script_setenv("DNS2", ip_ntoa(go->dnsaddr[1]), 0); #endif /* UNUSED */ if (pcb->settings.usepeerdns && (go->dnsaddr[0] || go->dnsaddr[1])) { - sdns(pcb, go->dnsaddr[0], go->dnsaddr[1]); + sdns(pcb, go->dnsaddr[0], go->dnsaddr[1]); #if 0 /* UNUSED */ - script_setenv("USEPEERDNS", "1", 0); - create_resolv(go->dnsaddr[0], go->dnsaddr[1]); + script_setenv("USEPEERDNS", "1", 0); + create_resolv(go->dnsaddr[0], go->dnsaddr[1]); #endif /* UNUSED */ } #endif /* LWIP_DNS */ @@ -1943,29 +1943,29 @@ static void ipcp_up(fsm *f) { * Check that the peer is allowed to use the IP address it wants. */ if (ho->hisaddr != 0) { - u32_t addr = lwip_ntohl(ho->hisaddr); - if ((addr >> IP_CLASSA_NSHIFT) == IP_LOOPBACKNET - || IP_MULTICAST(addr) || IP_BADCLASS(addr) - /* - * For now, consider that PPP in server mode with peer required - * to authenticate must provide the peer IP address, reject any - * IP address wanted by peer different than the one we wanted. - */ + u32_t addr = lwip_ntohl(ho->hisaddr); + if ((addr >> IP_CLASSA_NSHIFT) == IP_LOOPBACKNET + || IP_MULTICAST(addr) || IP_BADCLASS(addr) + /* + * For now, consider that PPP in server mode with peer required + * to authenticate must provide the peer IP address, reject any + * IP address wanted by peer different than the one we wanted. + */ #if PPP_SERVER && PPP_AUTH_SUPPORT - || (pcb->settings.auth_required && wo->hisaddr != ho->hisaddr) + || (pcb->settings.auth_required && wo->hisaddr != ho->hisaddr) #endif /* PPP_SERVER && PPP_AUTH_SUPPORT */ - ) { - ppp_error("Peer is not authorized to use remote address %I", ho->hisaddr); - ipcp_close(pcb, "Unauthorized remote IP address"); - return; - } + ) { + ppp_error("Peer is not authorized to use remote address %I", ho->hisaddr); + ipcp_close(pcb, "Unauthorized remote IP address"); + return; + } } #if 0 /* Unused */ /* Upstream checking code */ if (ho->hisaddr != 0 && !auth_ip_addr(f->unit, ho->hisaddr)) { - ppp_error("Peer is not authorized to use remote address %I", ho->hisaddr); - ipcp_close(f->unit, "Unauthorized remote IP address"); - return; + ppp_error("Peer is not authorized to use remote address %I", ho->hisaddr); + ipcp_close(f->unit, "Unauthorized remote IP address"); + return; } #endif /* Unused */ @@ -1981,114 +1981,114 @@ static void ipcp_up(fsm *f) { * interface to pass IP packets. */ if (demand) { - if (go->ouraddr != wo->ouraddr || ho->hisaddr != wo->hisaddr) { - ipcp_clear_addrs(f->unit, wo->ouraddr, wo->hisaddr, - wo->replace_default_route); - if (go->ouraddr != wo->ouraddr) { - ppp_warn("Local IP address changed to %I", go->ouraddr); - script_setenv("OLDIPLOCAL", ip_ntoa(wo->ouraddr), 0); - wo->ouraddr = go->ouraddr; - } else - script_unsetenv("OLDIPLOCAL"); - if (ho->hisaddr != wo->hisaddr && wo->hisaddr != 0) { - ppp_warn("Remote IP address changed to %I", ho->hisaddr); - script_setenv("OLDIPREMOTE", ip_ntoa(wo->hisaddr), 0); - wo->hisaddr = ho->hisaddr; - } else - script_unsetenv("OLDIPREMOTE"); + if (go->ouraddr != wo->ouraddr || ho->hisaddr != wo->hisaddr) { + ipcp_clear_addrs(f->unit, wo->ouraddr, wo->hisaddr, + wo->replace_default_route); + if (go->ouraddr != wo->ouraddr) { + ppp_warn("Local IP address changed to %I", go->ouraddr); + script_setenv("OLDIPLOCAL", ip_ntoa(wo->ouraddr), 0); + wo->ouraddr = go->ouraddr; + } else + script_unsetenv("OLDIPLOCAL"); + if (ho->hisaddr != wo->hisaddr && wo->hisaddr != 0) { + ppp_warn("Remote IP address changed to %I", ho->hisaddr); + script_setenv("OLDIPREMOTE", ip_ntoa(wo->hisaddr), 0); + wo->hisaddr = ho->hisaddr; + } else + script_unsetenv("OLDIPREMOTE"); - /* Set the interface to the new addresses */ - mask = get_mask(go->ouraddr); - if (!sifaddr(pcb, go->ouraddr, ho->hisaddr, mask)) { + /* Set the interface to the new addresses */ + mask = get_mask(go->ouraddr); + if (!sifaddr(pcb, go->ouraddr, ho->hisaddr, mask)) { #if PPP_DEBUG - ppp_warn("Interface configuration failed"); + ppp_warn("Interface configuration failed"); #endif /* PPP_DEBUG */ - ipcp_close(f->unit, "Interface configuration failed"); - return; - } + ipcp_close(f->unit, "Interface configuration failed"); + return; + } - /* assign a default route through the interface if required */ - if (ipcp_wantoptions[f->unit].default_route) - if (sifdefaultroute(pcb, go->ouraddr, ho->hisaddr, - wo->replace_default_route)) - default_route_set[f->unit] = 1; + /* assign a default route through the interface if required */ + if (ipcp_wantoptions[f->unit].default_route) + if (sifdefaultroute(pcb, go->ouraddr, ho->hisaddr, + wo->replace_default_route)) + default_route_set[f->unit] = 1; #if 0 /* UNUSED - PROXY ARP */ - /* Make a proxy ARP entry if requested. */ - if (ho->hisaddr != 0 && ipcp_wantoptions[f->unit].proxy_arp) - if (sifproxyarp(pcb, ho->hisaddr)) - proxy_arp_set[f->unit] = 1; + /* Make a proxy ARP entry if requested. */ + if (ho->hisaddr != 0 && ipcp_wantoptions[f->unit].proxy_arp) + if (sifproxyarp(pcb, ho->hisaddr)) + proxy_arp_set[f->unit] = 1; #endif /* UNUSED - PROXY ARP */ - } - demand_rexmit(PPP_IP,go->ouraddr); - sifnpmode(pcb, PPP_IP, NPMODE_PASS); + } + demand_rexmit(PPP_IP,go->ouraddr); + sifnpmode(pcb, PPP_IP, NPMODE_PASS); } else #endif /* DEMAND_SUPPORT */ { - /* - * Set IP addresses and (if specified) netmask. - */ - mask = get_mask(go->ouraddr); + /* + * Set IP addresses and (if specified) netmask. + */ + mask = get_mask(go->ouraddr); #if !(defined(SVR4) && (defined(SNI) || defined(__USLC__))) - if (!sifaddr(pcb, go->ouraddr, ho->hisaddr, mask)) { + if (!sifaddr(pcb, go->ouraddr, ho->hisaddr, mask)) { #if PPP_DEBUG - ppp_warn("Interface configuration failed"); + ppp_warn("Interface configuration failed"); #endif /* PPP_DEBUG */ - ipcp_close(f->pcb, "Interface configuration failed"); - return; - } + ipcp_close(f->pcb, "Interface configuration failed"); + return; + } #endif - /* bring the interface up for IP */ - if (!sifup(pcb)) { + /* bring the interface up for IP */ + if (!sifup(pcb)) { #if PPP_DEBUG - ppp_warn("Interface failed to come up"); + ppp_warn("Interface failed to come up"); #endif /* PPP_DEBUG */ - ipcp_close(f->pcb, "Interface configuration failed"); - return; - } + ipcp_close(f->pcb, "Interface configuration failed"); + return; + } #if (defined(SVR4) && (defined(SNI) || defined(__USLC__))) - if (!sifaddr(pcb, go->ouraddr, ho->hisaddr, mask)) { + if (!sifaddr(pcb, go->ouraddr, ho->hisaddr, mask)) { #if PPP_DEBUG - ppp_warn("Interface configuration failed"); + ppp_warn("Interface configuration failed"); #endif /* PPP_DEBUG */ - ipcp_close(f->unit, "Interface configuration failed"); - return; - } + ipcp_close(f->unit, "Interface configuration failed"); + return; + } #endif #if DEMAND_SUPPORT - sifnpmode(pcb, PPP_IP, NPMODE_PASS); + sifnpmode(pcb, PPP_IP, NPMODE_PASS); #endif /* DEMAND_SUPPORT */ #if 0 /* UNUSED */ - /* assign a default route through the interface if required */ - if (wo->default_route) - if (sifdefaultroute(pcb, go->ouraddr, ho->hisaddr, - wo->replace_default_route)) - pcb->default_route_set = 1; + /* assign a default route through the interface if required */ + if (wo->default_route) + if (sifdefaultroute(pcb, go->ouraddr, ho->hisaddr, + wo->replace_default_route)) + pcb->default_route_set = 1; #endif /* UNUSED */ #if 0 /* UNUSED - PROXY ARP */ - /* Make a proxy ARP entry if requested. */ - if (ho->hisaddr != 0 && wo->proxy_arp) - if (sifproxyarp(pcb, ho->hisaddr)) - pcb->proxy_arp_set = 1; + /* Make a proxy ARP entry if requested. */ + if (ho->hisaddr != 0 && wo->proxy_arp) + if (sifproxyarp(pcb, ho->hisaddr)) + pcb->proxy_arp_set = 1; #endif /* UNUSED - PROXY ARP */ - wo->ouraddr = go->ouraddr; + wo->ouraddr = go->ouraddr; - ppp_notice("local IP address %I", go->ouraddr); - if (ho->hisaddr != 0) - ppp_notice("remote IP address %I", ho->hisaddr); + ppp_notice("local IP address %I", go->ouraddr); + if (ho->hisaddr != 0) + ppp_notice("remote IP address %I", ho->hisaddr); #if LWIP_DNS - if (go->dnsaddr[0]) - ppp_notice("primary DNS address %I", go->dnsaddr[0]); - if (go->dnsaddr[1]) - ppp_notice("secondary DNS address %I", go->dnsaddr[1]); + if (go->dnsaddr[0]) + ppp_notice("primary DNS address %I", go->dnsaddr[0]); + if (go->dnsaddr[1]) + ppp_notice("secondary DNS address %I", go->dnsaddr[1]); #endif /* LWIP_DNS */ } @@ -2104,7 +2104,7 @@ static void ipcp_up(fsm *f) { #endif /* PPP_NOTIFY */ #if 0 /* UNUSED */ if (ip_up_hook) - ip_up_hook(); + ip_up_hook(); #endif /* UNUSED */ } @@ -2133,11 +2133,11 @@ static void ipcp_down(fsm *f) { #endif /* PPP_NOTIFY */ #if 0 /* UNUSED */ if (ip_down_hook) - ip_down_hook(); + ip_down_hook(); #endif /* UNUSED */ if (pcb->ipcp_is_up) { - pcb->ipcp_is_up = 0; - np_down(pcb, PPP_IP); + pcb->ipcp_is_up = 0; + np_down(pcb, PPP_IP); } #if VJ_SUPPORT sifvjcomp(pcb, 0, 0, 0); @@ -2145,8 +2145,8 @@ static void ipcp_down(fsm *f) { #if PPP_STATS_SUPPORT print_link_stats(); /* _after_ running the notifiers and ip_down_hook(), - * because print_link_stats() sets link_stats_valid - * to 0 (zero) */ + * because print_link_stats() sets link_stats_valid + * to 0 (zero) */ #endif /* PPP_STATS_SUPPORT */ #if DEMAND_SUPPORT @@ -2155,18 +2155,18 @@ static void ipcp_down(fsm *f) { * to queue up outgoing packets (for now). */ if (demand) { - sifnpmode(pcb, PPP_IP, NPMODE_QUEUE); + sifnpmode(pcb, PPP_IP, NPMODE_QUEUE); } else #endif /* DEMAND_SUPPORT */ { #if DEMAND_SUPPORT - sifnpmode(pcb, PPP_IP, NPMODE_DROP); + sifnpmode(pcb, PPP_IP, NPMODE_DROP); #endif /* DEMAND_SUPPORT */ - sifdown(pcb); - ipcp_clear_addrs(pcb, go->ouraddr, - ho->hisaddr, 0); + sifdown(pcb); + ipcp_clear_addrs(pcb, go->ouraddr, + ho->hisaddr, 0); #if LWIP_DNS - cdns(pcb, go->dnsaddr[0], go->dnsaddr[1]); + cdns(pcb, go->dnsaddr[0], go->dnsaddr[1]); #endif /* LWIP_DNS */ } } @@ -2181,8 +2181,8 @@ static void ipcp_clear_addrs(ppp_pcb *pcb, u32_t ouraddr, u32_t hisaddr, u8_t re #if 0 /* UNUSED - PROXY ARP */ if (pcb->proxy_arp_set) { - cifproxyarp(pcb, hisaddr); - pcb->proxy_arp_set = 0; + cifproxyarp(pcb, hisaddr); + pcb->proxy_arp_set = 0; } #endif /* UNUSED - PROXY ARP */ #if 0 /* UNUSED */ @@ -2195,8 +2195,8 @@ static void ipcp_clear_addrs(ppp_pcb *pcb, u32_t ouraddr, u32_t hisaddr, u8_t re * is one saved by an sifdefaultroute with replacedefaultroute. */ if (!replacedefaultroute && pcb->default_route_set) { - cifdefaultroute(pcb, ouraddr, hisaddr); - pcb->default_route_set = 0; + cifdefaultroute(pcb, ouraddr, hisaddr); + pcb->default_route_set = 0; } #endif /* UNUSED */ cifaddr(pcb, ouraddr, hisaddr); @@ -2207,11 +2207,11 @@ static void ipcp_clear_addrs(ppp_pcb *pcb, u32_t ouraddr, u32_t hisaddr, u8_t re * ipcp_finished - possibly shut down the lower layers. */ static void ipcp_finished(fsm *f) { - ppp_pcb *pcb = f->pcb; - if (pcb->ipcp_is_open) { - pcb->ipcp_is_open = 0; - np_finished(pcb, PPP_IP); - } + ppp_pcb *pcb = f->pcb; + if (pcb->ipcp_is_open) { + pcb->ipcp_is_open = 0; + np_finished(pcb, PPP_IP); + } } @@ -2237,7 +2237,7 @@ static const char* const ipcp_codenames[] = { }; static int ipcp_printpkt(const u_char *p, int plen, - void (*printer) (void *, const char *, ...), void *arg) { + void (*printer) (void *, const char *, ...), void *arg) { int code, id, len, olen; const u_char *pstart, *optend; #if VJ_SUPPORT @@ -2246,18 +2246,18 @@ static int ipcp_printpkt(const u_char *p, int plen, u32_t cilong; if (plen < HEADERLEN) - return 0; + return 0; pstart = p; GETCHAR(code, p); GETCHAR(id, p); GETSHORT(len, p); if (len < HEADERLEN || len > plen) - return 0; + return 0; if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(ipcp_codenames)) - printer(arg, " %s", ipcp_codenames[code-1]); + printer(arg, " %s", ipcp_codenames[code-1]); else - printer(arg, " code=0x%x", code); + printer(arg, " code=0x%x", code); printer(arg, " id=0x%x", id); len -= HEADERLEN; switch (code) { @@ -2265,98 +2265,98 @@ static int ipcp_printpkt(const u_char *p, int plen, case CONFACK: case CONFNAK: case CONFREJ: - /* print option list */ - while (len >= 2) { - GETCHAR(code, p); - GETCHAR(olen, p); - p -= 2; - if (olen < 2 || olen > len) { - break; - } - printer(arg, " <"); - len -= olen; - optend = p + olen; - switch (code) { - case CI_ADDRS: - if (olen == CILEN_ADDRS) { - p += 2; - GETLONG(cilong, p); - printer(arg, "addrs %I", lwip_htonl(cilong)); - GETLONG(cilong, p); - printer(arg, " %I", lwip_htonl(cilong)); - } - break; + /* print option list */ + while (len >= 2) { + GETCHAR(code, p); + GETCHAR(olen, p); + p -= 2; + if (olen < 2 || olen > len) { + break; + } + printer(arg, " <"); + len -= olen; + optend = p + olen; + switch (code) { + case CI_ADDRS: + if (olen == CILEN_ADDRS) { + p += 2; + GETLONG(cilong, p); + printer(arg, "addrs %I", lwip_htonl(cilong)); + GETLONG(cilong, p); + printer(arg, " %I", lwip_htonl(cilong)); + } + break; #if VJ_SUPPORT - case CI_COMPRESSTYPE: - if (olen >= CILEN_COMPRESS) { - p += 2; - GETSHORT(cishort, p); - printer(arg, "compress "); - switch (cishort) { - case IPCP_VJ_COMP: - printer(arg, "VJ"); - break; - case IPCP_VJ_COMP_OLD: - printer(arg, "old-VJ"); - break; - default: - printer(arg, "0x%x", cishort); - } - } - break; + case CI_COMPRESSTYPE: + if (olen >= CILEN_COMPRESS) { + p += 2; + GETSHORT(cishort, p); + printer(arg, "compress "); + switch (cishort) { + case IPCP_VJ_COMP: + printer(arg, "VJ"); + break; + case IPCP_VJ_COMP_OLD: + printer(arg, "old-VJ"); + break; + default: + printer(arg, "0x%x", cishort); + } + } + break; #endif /* VJ_SUPPORT */ - case CI_ADDR: - if (olen == CILEN_ADDR) { - p += 2; - GETLONG(cilong, p); - printer(arg, "addr %I", lwip_htonl(cilong)); - } - break; + case CI_ADDR: + if (olen == CILEN_ADDR) { + p += 2; + GETLONG(cilong, p); + printer(arg, "addr %I", lwip_htonl(cilong)); + } + break; #if LWIP_DNS - case CI_MS_DNS1: - case CI_MS_DNS2: - p += 2; - GETLONG(cilong, p); - printer(arg, "ms-dns%d %I", (code == CI_MS_DNS1? 1: 2), - htonl(cilong)); - break; + case CI_MS_DNS1: + case CI_MS_DNS2: + p += 2; + GETLONG(cilong, p); + printer(arg, "ms-dns%d %I", (code == CI_MS_DNS1? 1: 2), + htonl(cilong)); + break; #endif /* LWIP_DNS */ #if 0 /* UNUSED - WINS */ - case CI_MS_WINS1: - case CI_MS_WINS2: - p += 2; - GETLONG(cilong, p); - printer(arg, "ms-wins %I", lwip_htonl(cilong)); - break; + case CI_MS_WINS1: + case CI_MS_WINS2: + p += 2; + GETLONG(cilong, p); + printer(arg, "ms-wins %I", lwip_htonl(cilong)); + break; #endif /* UNUSED - WINS */ - default: - break; - } - while (p < optend) { - GETCHAR(code, p); - printer(arg, " %.2x", code); - } - printer(arg, ">"); - } - break; + default: + break; + } + while (p < optend) { + GETCHAR(code, p); + printer(arg, " %.2x", code); + } + printer(arg, ">"); + } + break; case TERMACK: case TERMREQ: - if (len > 0 && *p >= ' ' && *p < 0x7f) { - printer(arg, " "); - ppp_print_string(p, len, printer, arg); - p += len; - len = 0; - } - break; + if (len > 0 && *p >= ' ' && *p < 0x7f) { + printer(arg, " "); + ppp_print_string(p, len, printer, arg); + p += len; + len = 0; + } + break; default: - break; + break; } /* print the rest of the bytes in the packet */ for (; len > 0; --len) { - GETCHAR(code, p); - printer(arg, " %.2x", code); + GETCHAR(code, p); + printer(arg, " %.2x", code); } return p - pstart; @@ -2369,25 +2369,25 @@ static int ipcp_printpkt(const u_char *p, int plen, * We don't bring the link up for IP fragments or for TCP FIN packets * with no data. */ -#define IP_HDRLEN 20 /* bytes */ -#define IP_OFFMASK 0x1fff +#define IP_HDRLEN 20 /* bytes */ +#define IP_OFFMASK 0x1fff #ifndef IPPROTO_TCP -#define IPPROTO_TCP 6 +#define IPPROTO_TCP 6 #endif -#define TCP_HDRLEN 20 -#define TH_FIN 0x01 +#define TCP_HDRLEN 20 +#define TH_FIN 0x01 /* * We use these macros because the IP header may be at an odd address, * and some compilers might use word loads to get th_off or ip_hl. */ -#define net_short(x) (((x)[0] << 8) + (x)[1]) -#define get_iphl(x) (((unsigned char *)(x))[0] & 0xF) -#define get_ipoff(x) net_short((unsigned char *)(x) + 6) -#define get_ipproto(x) (((unsigned char *)(x))[9]) -#define get_tcpoff(x) (((unsigned char *)(x))[12] >> 4) -#define get_tcpflags(x) (((unsigned char *)(x))[13]) +#define net_short(x) (((x)[0] << 8) + (x)[1]) +#define get_iphl(x) (((unsigned char *)(x))[0] & 0xF) +#define get_ipoff(x) net_short((unsigned char *)(x) + 6) +#define get_ipproto(x) (((unsigned char *)(x))[9]) +#define get_tcpoff(x) (((unsigned char *)(x))[12] >> 4) +#define get_tcpflags(x) (((unsigned char *)(x))[13]) static int ip_active_pkt(pkt, len) @@ -2400,17 +2400,17 @@ ip_active_pkt(pkt, len) len -= PPP_HDRLEN; pkt += PPP_HDRLEN; if (len < IP_HDRLEN) - return 0; + return 0; if ((get_ipoff(pkt) & IP_OFFMASK) != 0) - return 0; + return 0; if (get_ipproto(pkt) != IPPROTO_TCP) - return 1; + return 1; hlen = get_iphl(pkt) * 4; if (len < hlen + TCP_HDRLEN) - return 0; + return 0; tcp = pkt + hlen; if ((get_tcpflags(tcp) & TH_FIN) != 0 && len == hlen + get_tcpoff(tcp) * 4) - return 0; + return 0; return 1; } #endif /* DEMAND_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/ipv6cp.c b/components/network/lwip/src/netif/ppp/ipv6cp.c index b8fc0c5a..eb699f49 100644 --- a/components/network/lwip/src/netif/ppp/ipv6cp.c +++ b/components/network/lwip/src/netif/ppp/ipv6cp.c @@ -73,7 +73,7 @@ between BULL S.A. and INRIA). This software is available with usual "research" terms - with the aim of retain credits of the software. + with the aim of retain credits of the software. Permission to use, copy, modify and distribute this software for any purpose and without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies, @@ -135,11 +135,11 @@ * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * - * $Id: ipv6cp.c,v 1.21 2005/08/25 23:59:34 paulus Exp $ + * $Id: ipv6cp.c,v 1.21 2005/08/25 23:59:34 paulus Exp $ */ /* - * @todo: + * @todo: * * Proxy Neighbour Discovery. * @@ -188,21 +188,21 @@ static void ipv6cp_down(fsm *f); /* We're DOWN */ static void ipv6cp_finished(fsm *f); /* Don't need lower layer */ static const fsm_callbacks ipv6cp_callbacks = { /* IPV6CP callback routines */ - ipv6cp_resetci, /* Reset our Configuration Information */ - ipv6cp_cilen, /* Length of our Configuration Information */ - ipv6cp_addci, /* Add our Configuration Information */ - ipv6cp_ackci, /* ACK our Configuration Information */ - ipv6cp_nakci, /* NAK our Configuration Information */ - ipv6cp_rejci, /* Reject our Configuration Information */ - ipv6cp_reqci, /* Request peer's Configuration Information */ - ipv6cp_up, /* Called when fsm reaches OPENED state */ - ipv6cp_down, /* Called when fsm leaves OPENED state */ - NULL, /* Called when we want the lower layer up */ - ipv6cp_finished, /* Called when we want the lower layer down */ - NULL, /* Called when Protocol-Reject received */ - NULL, /* Retransmission is necessary */ - NULL, /* Called to handle protocol-specific codes */ - "IPV6CP" /* String name of protocol */ + ipv6cp_resetci, /* Reset our Configuration Information */ + ipv6cp_cilen, /* Length of our Configuration Information */ + ipv6cp_addci, /* Add our Configuration Information */ + ipv6cp_ackci, /* ACK our Configuration Information */ + ipv6cp_nakci, /* NAK our Configuration Information */ + ipv6cp_rejci, /* Reject our Configuration Information */ + ipv6cp_reqci, /* Request peer's Configuration Information */ + ipv6cp_up, /* Called when fsm reaches OPENED state */ + ipv6cp_down, /* Called when fsm leaves OPENED state */ + NULL, /* Called when we want the lower layer up */ + ipv6cp_finished, /* Called when we want the lower layer down */ + NULL, /* Called when Protocol-Reject received */ + NULL, /* Retransmission is necessary */ + NULL, /* Called to handle protocol-specific codes */ + "IPV6CP" /* String name of protocol */ }; #if PPP_OPTIONS @@ -211,7 +211,7 @@ static const fsm_callbacks ipv6cp_callbacks = { /* IPV6CP callback routines */ */ static int setifaceid(char **arg)); static void printifaceid(option_t *, - void (*)(void *, char *, ...), void *)); + void (*)(void *, char *, ...), void *)); static option_t ipv6cp_option_list[] = { { "ipv6", o_special, (void *)setifaceid, @@ -265,7 +265,7 @@ static int ipv6_demand_conf(int u); #endif /* DEMAND_SUPPORT */ #if PRINTPKT_SUPPORT static int ipv6cp_printpkt(const u_char *p, int plen, - void (*printer)(void *, const char *, ...), void *arg); + void (*printer)(void *, const char *, ...), void *arg); #endif /* PRINTPKT_SUPPORT */ #if DEMAND_SUPPORT static int ipv6_active_pkt(u_char *pkt, int len); @@ -309,12 +309,12 @@ static void ipv6cp_script_done(void *)); /* * Lengths of configuration options. */ -#define CILEN_VOID 2 -#define CILEN_COMPRESS 4 /* length for RFC2023 compress opt. */ -#define CILEN_IFACEID 10 /* RFC2472, interface identifier */ +#define CILEN_VOID 2 +#define CILEN_COMPRESS 4 /* length for RFC2023 compress opt. */ +#define CILEN_IFACEID 10 /* RFC2472, interface identifier */ -#define CODENAME(x) ((x) == CONFACK ? "ACK" : \ - (x) == CONFNAK ? "NAK" : "REJ") +#define CODENAME(x) ((x) == CONFACK ? "ACK" : \ + (x) == CONFNAK ? "NAK" : "REJ") #if 0 /* UNUSED */ /* @@ -344,49 +344,49 @@ setifaceid(argv) static int prio_local, prio_remote; #define VALIDID(a) ( (((a).s6_addr32[0] == 0) && ((a).s6_addr32[1] == 0)) && \ - (((a).s6_addr32[2] != 0) || ((a).s6_addr32[3] != 0)) ) - + (((a).s6_addr32[2] != 0) || ((a).s6_addr32[3] != 0)) ) + arg = *argv; if ((comma = strchr(arg, ',')) == NULL) - comma = arg + strlen(arg); - - /* + comma = arg + strlen(arg); + + /* * If comma first character, then no local identifier */ if (comma != arg) { - c = *comma; - *comma = '\0'; + c = *comma; + *comma = '\0'; - if (inet_pton(AF_INET6, arg, &addr) == 0 || !VALIDID(addr)) { - option_error("Illegal interface identifier (local): %s", arg); - return 0; - } - - if (option_priority >= prio_local) { - eui64_copy(addr.s6_addr32[2], wo->ourid); - wo->opt_local = 1; - prio_local = option_priority; - } - *comma = c; + if (inet_pton(AF_INET6, arg, &addr) == 0 || !VALIDID(addr)) { + option_error("Illegal interface identifier (local): %s", arg); + return 0; } - + + if (option_priority >= prio_local) { + eui64_copy(addr.s6_addr32[2], wo->ourid); + wo->opt_local = 1; + prio_local = option_priority; + } + *comma = c; + } + /* * If comma last character, the no remote identifier */ if (*comma != 0 && *++comma != '\0') { - if (inet_pton(AF_INET6, comma, &addr) == 0 || !VALIDID(addr)) { - option_error("Illegal interface identifier (remote): %s", comma); - return 0; - } - if (option_priority >= prio_remote) { - eui64_copy(addr.s6_addr32[2], wo->hisid); - wo->opt_remote = 1; - prio_remote = option_priority; - } + if (inet_pton(AF_INET6, comma, &addr) == 0 || !VALIDID(addr)) { + option_error("Illegal interface identifier (remote): %s", comma); + return 0; + } + if (option_priority >= prio_remote) { + eui64_copy(addr.s6_addr32[2], wo->hisid); + wo->opt_remote = 1; + prio_remote = option_priority; + } } if (override_value("+ipv6", option_priority, option_source)) - ipv6cp_protent.enabled_flag = 1; + ipv6cp_protent.enabled_flag = 1; return 1; } @@ -396,13 +396,13 @@ printifaceid(opt, printer, arg) void (*printer)(void *, char *, ...)); void *arg; { - ipv6cp_options *wo = &ipv6cp_wantoptions[0]; + ipv6cp_options *wo = &ipv6cp_wantoptions[0]; - if (wo->opt_local) - printer(arg, "%s", llv6_ntoa(wo->ourid)); - printer(arg, ","); - if (wo->opt_remote) - printer(arg, "%s", llv6_ntoa(wo->hisid)); + if (wo->opt_local) + printer(arg, "%s", llv6_ntoa(wo->ourid)); + printer(arg, ","); + if (wo->opt_remote) + printer(arg, "%s", llv6_ntoa(wo->hisid)); } #endif /* PPP_OPTIONS */ @@ -513,14 +513,14 @@ static void ipv6cp_resetci(fsm *f) { ipv6cp_options *ao = &pcb->ipv6cp_allowoptions; wo->req_ifaceid = wo->neg_ifaceid && ao->neg_ifaceid; - + if (!wo->opt_local) { - wo->accept_local = 1; - eui64_magic_nz(wo->ourid); + wo->accept_local = 1; + eui64_magic_nz(wo->ourid); } - + *go = *wo; - eui64_zero(go->hisid); /* last proposed interface identifier */ + eui64_zero(go->hisid); /* last proposed interface identifier */ } @@ -532,15 +532,15 @@ static int ipv6cp_cilen(fsm *f) { ipv6cp_options *go = &pcb->ipv6cp_gotoptions; #ifdef IPV6CP_COMP -#define LENCIVJ(neg) (neg ? CILEN_COMPRESS : 0) +#define LENCIVJ(neg) (neg ? CILEN_COMPRESS : 0) #endif /* IPV6CP_COMP */ -#define LENCIIFACEID(neg) (neg ? CILEN_IFACEID : 0) +#define LENCIIFACEID(neg) (neg ? CILEN_IFACEID : 0) return (LENCIIFACEID(go->neg_ifaceid) + #ifdef IPV6CP_COMP - LENCIVJ(go->neg_vj) + + LENCIVJ(go->neg_vj) + #endif /* IPV6CP_COMP */ - 0); + 0); } @@ -555,27 +555,27 @@ static void ipv6cp_addci(fsm *f, u_char *ucp, int *lenp) { #ifdef IPV6CP_COMP #define ADDCIVJ(opt, neg, val) \ if (neg) { \ - int vjlen = CILEN_COMPRESS; \ - if (len >= vjlen) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(vjlen, ucp); \ - PUTSHORT(val, ucp); \ - len -= vjlen; \ - } else \ - neg = 0; \ + int vjlen = CILEN_COMPRESS; \ + if (len >= vjlen) { \ + PUTCHAR(opt, ucp); \ + PUTCHAR(vjlen, ucp); \ + PUTSHORT(val, ucp); \ + len -= vjlen; \ + } else \ + neg = 0; \ } #endif /* IPV6CP_COMP */ #define ADDCIIFACEID(opt, neg, val1) \ if (neg) { \ - int idlen = CILEN_IFACEID; \ - if (len >= idlen) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(idlen, ucp); \ - eui64_put(val1, ucp); \ - len -= idlen; \ - } else \ - neg = 0; \ + int idlen = CILEN_IFACEID; \ + if (len >= idlen) { \ + PUTCHAR(opt, ucp); \ + PUTCHAR(idlen, ucp); \ + eui64_put(val1, ucp); \ + len -= idlen; \ + } else \ + neg = 0; \ } ADDCIIFACEID(CI_IFACEID, go->neg_ifaceid, go->ourid); @@ -592,8 +592,8 @@ static void ipv6cp_addci(fsm *f, u_char *ucp, int *lenp) { * ipv6cp_ackci - Ack our CIs. * * Returns: - * 0 - Ack was bad. - * 1 - Ack was good. + * 0 - Ack was bad. + * 1 - Ack was good. */ static int ipv6cp_ackci(fsm *f, u_char *p, int len) { ppp_pcb *pcb = f->pcb; @@ -613,33 +613,33 @@ static int ipv6cp_ackci(fsm *f, u_char *p, int len) { #ifdef IPV6CP_COMP #define ACKCIVJ(opt, neg, val) \ if (neg) { \ - int vjlen = CILEN_COMPRESS; \ - if ((len -= vjlen) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != vjlen || \ - citype != opt) \ - goto bad; \ - GETSHORT(cishort, p); \ - if (cishort != val) \ - goto bad; \ + int vjlen = CILEN_COMPRESS; \ + if ((len -= vjlen) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != vjlen || \ + citype != opt) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != val) \ + goto bad; \ } #endif /* IPV6CP_COMP */ #define ACKCIIFACEID(opt, neg, val1) \ if (neg) { \ - int idlen = CILEN_IFACEID; \ - if ((len -= idlen) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != idlen || \ - citype != opt) \ - goto bad; \ - eui64_get(ifaceid, p); \ - if (! eui64_equals(val1, ifaceid)) \ - goto bad; \ + int idlen = CILEN_IFACEID; \ + if ((len -= idlen) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != idlen || \ + citype != opt) \ + goto bad; \ + eui64_get(ifaceid, p); \ + if (! eui64_equals(val1, ifaceid)) \ + goto bad; \ } ACKCIIFACEID(CI_IFACEID, go->neg_ifaceid, go->ourid); @@ -652,7 +652,7 @@ static int ipv6cp_ackci(fsm *f, u_char *p, int len) { * If there are any remaining CIs, then this packet is bad. */ if (len != 0) - goto bad; + goto bad; return (1); bad: @@ -666,8 +666,8 @@ bad: * or if IPV6CP is in the OPENED state. * * Returns: - * 0 - Nak was bad. - * 1 - Nak was good. + * 0 - Nak was bad. + * 1 - Nak was good. */ static int ipv6cp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { ppp_pcb *pcb = f->pcb; @@ -677,8 +677,8 @@ static int ipv6cp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { u_short cishort; #endif /* IPV6CP_COMP */ eui64_t ifaceid; - ipv6cp_options no; /* options we've seen Naks for */ - ipv6cp_options try_; /* options to request next time */ + ipv6cp_options no; /* options we've seen Naks for */ + ipv6cp_options try_; /* options to request next time */ BZERO(&no, sizeof(no)); try_ = *go; @@ -690,26 +690,26 @@ static int ipv6cp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { */ #define NAKCIIFACEID(opt, neg, code) \ if (go->neg && \ - len >= (cilen = CILEN_IFACEID) && \ - p[1] == cilen && \ - p[0] == opt) { \ - len -= cilen; \ - INCPTR(2, p); \ - eui64_get(ifaceid, p); \ - no.neg = 1; \ - code \ + len >= (cilen = CILEN_IFACEID) && \ + p[1] == cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + eui64_get(ifaceid, p); \ + no.neg = 1; \ + code \ } #ifdef IPV6CP_COMP #define NAKCIVJ(opt, neg, code) \ if (go->neg && \ - ((cilen = p[1]) == CILEN_COMPRESS) && \ - len >= cilen && \ - p[0] == opt) { \ - len -= cilen; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - no.neg = 1; \ + ((cilen = p[1]) == CILEN_COMPRESS) && \ + len >= cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + no.neg = 1; \ code \ } #endif /* IPV6CP_COMP */ @@ -719,27 +719,27 @@ static int ipv6cp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * from our idea, only if the accept_{local,remote} flag is set. */ NAKCIIFACEID(CI_IFACEID, neg_ifaceid, - if (treat_as_reject) { - try_.neg_ifaceid = 0; - } else if (go->accept_local) { - while (eui64_iszero(ifaceid) || - eui64_equals(ifaceid, go->hisid)) /* bad luck */ - eui64_magic(ifaceid); - try_.ourid = ifaceid; - IPV6CPDEBUG(("local LL address %s", llv6_ntoa(ifaceid))); - } - ); + if (treat_as_reject) { + try_.neg_ifaceid = 0; + } else if (go->accept_local) { + while (eui64_iszero(ifaceid) || + eui64_equals(ifaceid, go->hisid)) /* bad luck */ + eui64_magic(ifaceid); + try_.ourid = ifaceid; + IPV6CPDEBUG(("local LL address %s", llv6_ntoa(ifaceid))); + } + ); #ifdef IPV6CP_COMP NAKCIVJ(CI_COMPRESSTYPE, neg_vj, - { - if (cishort == IPV6CP_COMP && !treat_as_reject) { - try_.vj_protocol = cishort; - } else { - try_.neg_vj = 0; - } - } - ); + { + if (cishort == IPV6CP_COMP && !treat_as_reject) { + try_.vj_protocol = cishort; + } else { + try_.neg_vj = 0; + } + } + ); #endif /* IPV6CP_COMP */ /* @@ -749,49 +749,49 @@ static int ipv6cp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * If they want us to ask for compression, we refuse. */ while (len >= CILEN_VOID) { - GETCHAR(citype, p); - GETCHAR(cilen, p); - if ( cilen < CILEN_VOID || (len -= cilen) < 0 ) - goto bad; - next = p + cilen - 2; + GETCHAR(citype, p); + GETCHAR(cilen, p); + if ( cilen < CILEN_VOID || (len -= cilen) < 0 ) + goto bad; + next = p + cilen - 2; - switch (citype) { + switch (citype) { #ifdef IPV6CP_COMP - case CI_COMPRESSTYPE: - if (go->neg_vj || no.neg_vj || - (cilen != CILEN_COMPRESS)) - goto bad; - no.neg_vj = 1; - break; + case CI_COMPRESSTYPE: + if (go->neg_vj || no.neg_vj || + (cilen != CILEN_COMPRESS)) + goto bad; + no.neg_vj = 1; + break; #endif /* IPV6CP_COMP */ - case CI_IFACEID: - if (go->neg_ifaceid || no.neg_ifaceid || cilen != CILEN_IFACEID) - goto bad; - try_.neg_ifaceid = 1; - eui64_get(ifaceid, p); - if (go->accept_local) { - while (eui64_iszero(ifaceid) || - eui64_equals(ifaceid, go->hisid)) /* bad luck */ - eui64_magic(ifaceid); - try_.ourid = ifaceid; - } - no.neg_ifaceid = 1; - break; - default: - break; - } - p = next; + case CI_IFACEID: + if (go->neg_ifaceid || no.neg_ifaceid || cilen != CILEN_IFACEID) + goto bad; + try_.neg_ifaceid = 1; + eui64_get(ifaceid, p); + if (go->accept_local) { + while (eui64_iszero(ifaceid) || + eui64_equals(ifaceid, go->hisid)) /* bad luck */ + eui64_magic(ifaceid); + try_.ourid = ifaceid; + } + no.neg_ifaceid = 1; + break; + default: + break; + } + p = next; } /* If there is still anything left, this packet is bad. */ if (len != 0) - goto bad; + goto bad; /* * OK, the Nak is good. Now we can update state. */ if (f->state != PPP_FSM_OPENED) - *go = try_; + *go = try_; return 1; @@ -812,7 +812,7 @@ static int ipv6cp_rejci(fsm *f, u_char *p, int len) { u_short cishort; #endif /* IPV6CP_COMP */ eui64_t ifaceid; - ipv6cp_options try_; /* options to request next time */ + ipv6cp_options try_; /* options to request next time */ try_ = *go; /* @@ -822,31 +822,31 @@ static int ipv6cp_rejci(fsm *f, u_char *p, int len) { */ #define REJCIIFACEID(opt, neg, val1) \ if (go->neg && \ - len >= (cilen = CILEN_IFACEID) && \ - p[1] == cilen && \ - p[0] == opt) { \ - len -= cilen; \ - INCPTR(2, p); \ - eui64_get(ifaceid, p); \ - /* Check rejected value. */ \ - if (! eui64_equals(ifaceid, val1)) \ - goto bad; \ - try_.neg = 0; \ + len >= (cilen = CILEN_IFACEID) && \ + p[1] == cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + eui64_get(ifaceid, p); \ + /* Check rejected value. */ \ + if (! eui64_equals(ifaceid, val1)) \ + goto bad; \ + try_.neg = 0; \ } #ifdef IPV6CP_COMP #define REJCIVJ(opt, neg, val) \ if (go->neg && \ - p[1] == CILEN_COMPRESS && \ - len >= p[1] && \ - p[0] == opt) { \ - len -= p[1]; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - /* Check rejected value. */ \ - if (cishort != val) \ - goto bad; \ - try_.neg = 0; \ + p[1] == CILEN_COMPRESS && \ + len >= p[1] && \ + p[0] == opt) { \ + len -= p[1]; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + /* Check rejected value. */ \ + if (cishort != val) \ + goto bad; \ + try_.neg = 0; \ } #endif /* IPV6CP_COMP */ @@ -860,12 +860,12 @@ static int ipv6cp_rejci(fsm *f, u_char *p, int len) { * If there are any remaining CIs, then this packet is bad. */ if (len != 0) - goto bad; + goto bad; /* * Now we can update state. */ if (f->state != PPP_FSM_OPENED) - *go = try_; + *go = try_; return 1; bad: @@ -891,150 +891,150 @@ static int ipv6cp_reqci(fsm *f, u_char *inp, int *len, int reject_if_disagree) { ipv6cp_options *ho = &pcb->ipv6cp_hisoptions; ipv6cp_options *ao = &pcb->ipv6cp_allowoptions; ipv6cp_options *go = &pcb->ipv6cp_gotoptions; - u_char *cip, *next; /* Pointer to current and next CIs */ - u_short cilen, citype; /* Parsed len, type */ + u_char *cip, *next; /* Pointer to current and next CIs */ + u_short cilen, citype; /* Parsed len, type */ #ifdef IPV6CP_COMP - u_short cishort; /* Parsed short value */ + u_short cishort; /* Parsed short value */ #endif /* IPV6CP_COMP */ - eui64_t ifaceid; /* Parsed interface identifier */ - int rc = CONFACK; /* Final packet return code */ - int orc; /* Individual option return code */ - u_char *p; /* Pointer to next char to parse */ - u_char *ucp = inp; /* Pointer to current output char */ - int l = *len; /* Length left */ + eui64_t ifaceid; /* Parsed interface identifier */ + int rc = CONFACK; /* Final packet return code */ + int orc; /* Individual option return code */ + u_char *p; /* Pointer to next char to parse */ + u_char *ucp = inp; /* Pointer to current output char */ + int l = *len; /* Length left */ /* * Reset all his options. */ BZERO(ho, sizeof(*ho)); - + /* * Process all his options. */ next = inp; while (l) { - orc = CONFACK; /* Assume success */ - cip = p = next; /* Remember begining of CI */ - if (l < 2 || /* Not enough data for CI header or */ - p[1] < 2 || /* CI length too small or */ - p[1] > l) { /* CI length too big? */ - IPV6CPDEBUG(("ipv6cp_reqci: bad CI length!")); - orc = CONFREJ; /* Reject bad CI */ - cilen = l; /* Reject till end of packet */ - l = 0; /* Don't loop again */ - goto endswitch; - } - GETCHAR(citype, p); /* Parse CI type */ - GETCHAR(cilen, p); /* Parse CI length */ - l -= cilen; /* Adjust remaining length */ - next += cilen; /* Step to next CI */ + orc = CONFACK; /* Assume success */ + cip = p = next; /* Remember begining of CI */ + if (l < 2 || /* Not enough data for CI header or */ + p[1] < 2 || /* CI length too small or */ + p[1] > l) { /* CI length too big? */ + IPV6CPDEBUG(("ipv6cp_reqci: bad CI length!")); + orc = CONFREJ; /* Reject bad CI */ + cilen = l; /* Reject till end of packet */ + l = 0; /* Don't loop again */ + goto endswitch; + } + GETCHAR(citype, p); /* Parse CI type */ + GETCHAR(cilen, p); /* Parse CI length */ + l -= cilen; /* Adjust remaining length */ + next += cilen; /* Step to next CI */ - switch (citype) { /* Check CI type */ - case CI_IFACEID: - IPV6CPDEBUG(("ipv6cp: received interface identifier ")); + switch (citype) { /* Check CI type */ + case CI_IFACEID: + IPV6CPDEBUG(("ipv6cp: received interface identifier ")); - if (!ao->neg_ifaceid || - cilen != CILEN_IFACEID) { /* Check CI length */ - orc = CONFREJ; /* Reject CI */ - break; - } + if (!ao->neg_ifaceid || + cilen != CILEN_IFACEID) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } - /* - * If he has no interface identifier, or if we both have same - * identifier then NAK it with new idea. - * In particular, if we don't know his identifier, but he does, - * then accept it. - */ - eui64_get(ifaceid, p); - IPV6CPDEBUG(("(%s)", llv6_ntoa(ifaceid))); - if (eui64_iszero(ifaceid) && eui64_iszero(go->ourid)) { - orc = CONFREJ; /* Reject CI */ - break; - } - if (!eui64_iszero(wo->hisid) && - !eui64_equals(ifaceid, wo->hisid) && - eui64_iszero(go->hisid)) { - - orc = CONFNAK; - ifaceid = wo->hisid; - go->hisid = ifaceid; - DECPTR(sizeof(ifaceid), p); - eui64_put(ifaceid, p); - } else - if (eui64_iszero(ifaceid) || eui64_equals(ifaceid, go->ourid)) { - orc = CONFNAK; - if (eui64_iszero(go->hisid)) /* first time, try option */ - ifaceid = wo->hisid; - while (eui64_iszero(ifaceid) || - eui64_equals(ifaceid, go->ourid)) /* bad luck */ - eui64_magic(ifaceid); - go->hisid = ifaceid; - DECPTR(sizeof(ifaceid), p); - eui64_put(ifaceid, p); - } + /* + * If he has no interface identifier, or if we both have same + * identifier then NAK it with new idea. + * In particular, if we don't know his identifier, but he does, + * then accept it. + */ + eui64_get(ifaceid, p); + IPV6CPDEBUG(("(%s)", llv6_ntoa(ifaceid))); + if (eui64_iszero(ifaceid) && eui64_iszero(go->ourid)) { + orc = CONFREJ; /* Reject CI */ + break; + } + if (!eui64_iszero(wo->hisid) && + !eui64_equals(ifaceid, wo->hisid) && + eui64_iszero(go->hisid)) { - ho->neg_ifaceid = 1; - ho->hisid = ifaceid; - break; + orc = CONFNAK; + ifaceid = wo->hisid; + go->hisid = ifaceid; + DECPTR(sizeof(ifaceid), p); + eui64_put(ifaceid, p); + } else + if (eui64_iszero(ifaceid) || eui64_equals(ifaceid, go->ourid)) { + orc = CONFNAK; + if (eui64_iszero(go->hisid)) /* first time, try option */ + ifaceid = wo->hisid; + while (eui64_iszero(ifaceid) || + eui64_equals(ifaceid, go->ourid)) /* bad luck */ + eui64_magic(ifaceid); + go->hisid = ifaceid; + DECPTR(sizeof(ifaceid), p); + eui64_put(ifaceid, p); + } + + ho->neg_ifaceid = 1; + ho->hisid = ifaceid; + break; #ifdef IPV6CP_COMP - case CI_COMPRESSTYPE: - IPV6CPDEBUG(("ipv6cp: received COMPRESSTYPE ")); - if (!ao->neg_vj || - (cilen != CILEN_COMPRESS)) { - orc = CONFREJ; - break; - } - GETSHORT(cishort, p); - IPV6CPDEBUG(("(%d)", cishort)); + case CI_COMPRESSTYPE: + IPV6CPDEBUG(("ipv6cp: received COMPRESSTYPE ")); + if (!ao->neg_vj || + (cilen != CILEN_COMPRESS)) { + orc = CONFREJ; + break; + } + GETSHORT(cishort, p); + IPV6CPDEBUG(("(%d)", cishort)); - if (!(cishort == IPV6CP_COMP)) { - orc = CONFREJ; - break; - } + if (!(cishort == IPV6CP_COMP)) { + orc = CONFREJ; + break; + } - ho->neg_vj = 1; - ho->vj_protocol = cishort; - break; + ho->neg_vj = 1; + ho->vj_protocol = cishort; + break; #endif /* IPV6CP_COMP */ - default: - orc = CONFREJ; - break; - } + default: + orc = CONFREJ; + break; + } endswitch: - IPV6CPDEBUG((" (%s)\n", CODENAME(orc))); + IPV6CPDEBUG((" (%s)\n", CODENAME(orc))); - if (orc == CONFACK && /* Good CI */ - rc != CONFACK) /* but prior CI wasnt? */ - continue; /* Don't send this one */ + if (orc == CONFACK && /* Good CI */ + rc != CONFACK) /* but prior CI wasnt? */ + continue; /* Don't send this one */ - if (orc == CONFNAK) { /* Nak this CI? */ - if (reject_if_disagree) /* Getting fed up with sending NAKs? */ - orc = CONFREJ; /* Get tough if so */ - else { - if (rc == CONFREJ) /* Rejecting prior CI? */ - continue; /* Don't send this one */ - if (rc == CONFACK) { /* Ack'd all prior CIs? */ - rc = CONFNAK; /* Not anymore... */ - ucp = inp; /* Backup */ - } - } - } + if (orc == CONFNAK) { /* Nak this CI? */ + if (reject_if_disagree) /* Getting fed up with sending NAKs? */ + orc = CONFREJ; /* Get tough if so */ + else { + if (rc == CONFREJ) /* Rejecting prior CI? */ + continue; /* Don't send this one */ + if (rc == CONFACK) { /* Ack'd all prior CIs? */ + rc = CONFNAK; /* Not anymore... */ + ucp = inp; /* Backup */ + } + } + } - if (orc == CONFREJ && /* Reject this CI */ - rc != CONFREJ) { /* but no prior ones? */ - rc = CONFREJ; - ucp = inp; /* Backup */ - } + if (orc == CONFREJ && /* Reject this CI */ + rc != CONFREJ) { /* but no prior ones? */ + rc = CONFREJ; + ucp = inp; /* Backup */ + } - /* Need to move CI? */ - if (ucp != cip) - MEMCPY(ucp, cip, cilen); /* Move it */ + /* Need to move CI? */ + if (ucp != cip) + MEMCPY(ucp, cip, cilen); /* Move it */ - /* Update output pointer */ - INCPTR(cilen, ucp); + /* Update output pointer */ + INCPTR(cilen, ucp); } /* @@ -1045,20 +1045,20 @@ endswitch: * option safely. */ if (rc != CONFREJ && !ho->neg_ifaceid && - wo->req_ifaceid && !reject_if_disagree) { - if (rc == CONFACK) { - rc = CONFNAK; - ucp = inp; /* reset pointer */ - wo->req_ifaceid = 0; /* don't ask again */ - } - PUTCHAR(CI_IFACEID, ucp); - PUTCHAR(CILEN_IFACEID, ucp); - eui64_put(wo->hisid, ucp); + wo->req_ifaceid && !reject_if_disagree) { + if (rc == CONFACK) { + rc = CONFNAK; + ucp = inp; /* reset pointer */ + wo->req_ifaceid = 0; /* don't ask again */ + } + PUTCHAR(CI_IFACEID, ucp); + PUTCHAR(CILEN_IFACEID, ucp); + eui64_put(wo->hisid, ucp); } - *len = ucp - inp; /* Compute output length */ + *len = ucp - inp; /* Compute output length */ IPV6CPDEBUG(("ipv6cp: returning Configure-%s", CODENAME(rc))); - return (rc); /* Return final code */ + return (rc); /* Return final code */ } #if PPP_OPTIONS @@ -1070,7 +1070,7 @@ static void ipv6_check_options() { ipv6cp_options *wo = &ipv6cp_wantoptions[0]; if (!ipv6cp_protent.enabled_flag) - return; + return; /* * Persistent link-local id is only used when user has not explicitly @@ -1078,42 +1078,42 @@ static void ipv6_check_options() { */ if ((wo->use_persistent) && (!wo->opt_local) && (!wo->opt_remote)) { - /* - * On systems where there are no Ethernet interfaces used, there - * may be other ways to obtain a persistent id. Right now, it - * will fall back to using magic [see eui64_magic] below when - * an EUI-48 from MAC address can't be obtained. Other possibilities - * include obtaining EEPROM serial numbers, or some other unique - * yet persistent number. On Sparc platforms, this is possible, - * but too bad there's no standards yet for x86 machines. - */ - if (ether_to_eui64(&wo->ourid)) { - wo->opt_local = 1; - } + /* + * On systems where there are no Ethernet interfaces used, there + * may be other ways to obtain a persistent id. Right now, it + * will fall back to using magic [see eui64_magic] below when + * an EUI-48 from MAC address can't be obtained. Other possibilities + * include obtaining EEPROM serial numbers, or some other unique + * yet persistent number. On Sparc platforms, this is possible, + * but too bad there's no standards yet for x86 machines. + */ + if (ether_to_eui64(&wo->ourid)) { + wo->opt_local = 1; + } } - if (!wo->opt_local) { /* init interface identifier */ - if (wo->use_ip && eui64_iszero(wo->ourid)) { - eui64_setlo32(wo->ourid, lwip_ntohl(ipcp_wantoptions[0].ouraddr)); - if (!eui64_iszero(wo->ourid)) - wo->opt_local = 1; - } - - while (eui64_iszero(wo->ourid)) - eui64_magic(wo->ourid); + if (!wo->opt_local) { /* init interface identifier */ + if (wo->use_ip && eui64_iszero(wo->ourid)) { + eui64_setlo32(wo->ourid, lwip_ntohl(ipcp_wantoptions[0].ouraddr)); + if (!eui64_iszero(wo->ourid)) + wo->opt_local = 1; + } + + while (eui64_iszero(wo->ourid)) + eui64_magic(wo->ourid); } if (!wo->opt_remote) { - if (wo->use_ip && eui64_iszero(wo->hisid)) { - eui64_setlo32(wo->hisid, lwip_ntohl(ipcp_wantoptions[0].hisaddr)); - if (!eui64_iszero(wo->hisid)) - wo->opt_remote = 1; - } + if (wo->use_ip && eui64_iszero(wo->hisid)) { + eui64_setlo32(wo->hisid, lwip_ntohl(ipcp_wantoptions[0].hisaddr)); + if (!eui64_iszero(wo->hisid)) + wo->opt_remote = 1; + } } if (demand && (eui64_iszero(wo->ourid) || eui64_iszero(wo->hisid))) { - option_error("local/remote LL address required for demand-dialling\n"); - exit(1); + option_error("local/remote LL address required for demand-dialling\n"); + exit(1); } } #endif /* PPP_OPTIONS */ @@ -1127,13 +1127,13 @@ static int ipv6_demand_conf(int u) { ipv6cp_options *wo = &ipv6cp_wantoptions[u]; if (!sif6up(u)) - return 0; + return 0; if (!sif6addr(u, wo->ourid, wo->hisid)) - return 0; + return 0; if (!sifnpmode(u, PPP_IPV6, NPMODE_QUEUE)) - return 0; + return 0; ppp_notice("ipv6_demand_conf"); ppp_notice("local LL address %s", llv6_ntoa(wo->ourid)); @@ -1161,26 +1161,26 @@ static void ipv6cp_up(fsm *f) { * We must have a non-zero LL address for both ends of the link. */ if (!ho->neg_ifaceid) - ho->hisid = wo->hisid; + ho->hisid = wo->hisid; #if 0 /* UNUSED */ if(!no_ifaceid_neg) { #endif /* UNUSED */ - if (eui64_iszero(ho->hisid)) { - ppp_error("Could not determine remote LL address"); - ipv6cp_close(f->pcb, "Could not determine remote LL address"); - return; - } - if (eui64_iszero(go->ourid)) { - ppp_error("Could not determine local LL address"); - ipv6cp_close(f->pcb, "Could not determine local LL address"); - return; - } - if (eui64_equals(go->ourid, ho->hisid)) { - ppp_error("local and remote LL addresses are equal"); - ipv6cp_close(f->pcb, "local and remote LL addresses are equal"); - return; - } + if (eui64_iszero(ho->hisid)) { + ppp_error("Could not determine remote LL address"); + ipv6cp_close(f->pcb, "Could not determine remote LL address"); + return; + } + if (eui64_iszero(go->ourid)) { + ppp_error("Could not determine local LL address"); + ipv6cp_close(f->pcb, "Could not determine local LL address"); + return; + } + if (eui64_equals(go->ourid, ho->hisid)) { + ppp_error("local and remote LL addresses are equal"); + ipv6cp_close(f->pcb, "local and remote LL addresses are equal"); + return; + } #if 0 /* UNUSED */ } #endif /* UNUSED */ @@ -1201,52 +1201,52 @@ static void ipv6cp_up(fsm *f) { * interface to pass IPv6 packets. */ if (demand) { - if (! eui64_equals(go->ourid, wo->ourid) || - ! eui64_equals(ho->hisid, wo->hisid)) { - if (! eui64_equals(go->ourid, wo->ourid)) - warn("Local LL address changed to %s", - llv6_ntoa(go->ourid)); - if (! eui64_equals(ho->hisid, wo->hisid)) - warn("Remote LL address changed to %s", - llv6_ntoa(ho->hisid)); - ipv6cp_clear_addrs(f->pcb, go->ourid, ho->hisid); + if (! eui64_equals(go->ourid, wo->ourid) || + ! eui64_equals(ho->hisid, wo->hisid)) { + if (! eui64_equals(go->ourid, wo->ourid)) + warn("Local LL address changed to %s", + llv6_ntoa(go->ourid)); + if (! eui64_equals(ho->hisid, wo->hisid)) + warn("Remote LL address changed to %s", + llv6_ntoa(ho->hisid)); + ipv6cp_clear_addrs(f->pcb, go->ourid, ho->hisid); - /* Set the interface to the new addresses */ - if (!sif6addr(f->pcb, go->ourid, ho->hisid)) { - if (debug) - warn("sif6addr failed"); - ipv6cp_close(f->unit, "Interface configuration failed"); - return; - } + /* Set the interface to the new addresses */ + if (!sif6addr(f->pcb, go->ourid, ho->hisid)) { + if (debug) + warn("sif6addr failed"); + ipv6cp_close(f->unit, "Interface configuration failed"); + return; + } - } - demand_rexmit(PPP_IPV6); - sifnpmode(f->unit, PPP_IPV6, NPMODE_PASS); + } + demand_rexmit(PPP_IPV6); + sifnpmode(f->unit, PPP_IPV6, NPMODE_PASS); } else #endif /* DEMAND_SUPPORT */ { - /* - * Set LL addresses - */ - if (!sif6addr(f->pcb, go->ourid, ho->hisid)) { - PPPDEBUG(LOG_DEBUG, ("sif6addr failed")); - ipv6cp_close(f->pcb, "Interface configuration failed"); - return; - } + /* + * Set LL addresses + */ + if (!sif6addr(f->pcb, go->ourid, ho->hisid)) { + PPPDEBUG(LOG_DEBUG, ("sif6addr failed")); + ipv6cp_close(f->pcb, "Interface configuration failed"); + return; + } - /* bring the interface up for IPv6 */ - if (!sif6up(f->pcb)) { - PPPDEBUG(LOG_DEBUG, ("sif6up failed (IPV6)")); - ipv6cp_close(f->pcb, "Interface configuration failed"); - return; - } + /* bring the interface up for IPv6 */ + if (!sif6up(f->pcb)) { + PPPDEBUG(LOG_DEBUG, ("sif6up failed (IPV6)")); + ipv6cp_close(f->pcb, "Interface configuration failed"); + return; + } #if DEMAND_SUPPORT - sifnpmode(f->pcb, PPP_IPV6, NPMODE_PASS); + sifnpmode(f->pcb, PPP_IPV6, NPMODE_PASS); #endif /* DEMAND_SUPPORT */ - ppp_notice("local LL address %s", llv6_ntoa(go->ourid)); - ppp_notice("remote LL address %s", llv6_ntoa(ho->hisid)); + ppp_notice("local LL address %s", llv6_ntoa(go->ourid)); + ppp_notice("remote LL address %s", llv6_ntoa(ho->hisid)); } np_up(f->pcb, PPP_IPV6); @@ -1255,11 +1255,11 @@ static void ipv6cp_up(fsm *f) { #if 0 /* UNUSED */ /* * Execute the ipv6-up script, like this: - * /etc/ppp/ipv6-up interface tty speed local-LL remote-LL + * /etc/ppp/ipv6-up interface tty speed local-LL remote-LL */ if (ipv6cp_script_state == s_down && ipv6cp_script_pid == 0) { - ipv6cp_script_state = s_up; - ipv6cp_script(_PATH_IPV6UP); + ipv6cp_script_state = s_up; + ipv6cp_script(_PATH_IPV6UP); } #endif /* UNUSED */ } @@ -1281,8 +1281,8 @@ static void ipv6cp_down(fsm *f) { update_link_stats(f->unit); #endif /* PPP_STATS_SUPPORT */ if (pcb->ipv6cp_is_up) { - pcb->ipv6cp_is_up = 0; - np_down(f->pcb, PPP_IPV6); + pcb->ipv6cp_is_up = 0; + np_down(f->pcb, PPP_IPV6); } #ifdef IPV6CP_COMP sif6comp(f->unit, 0); @@ -1294,24 +1294,24 @@ static void ipv6cp_down(fsm *f) { * to queue up outgoing packets (for now). */ if (demand) { - sifnpmode(f->pcb, PPP_IPV6, NPMODE_QUEUE); + sifnpmode(f->pcb, PPP_IPV6, NPMODE_QUEUE); } else #endif /* DEMAND_SUPPORT */ { #if DEMAND_SUPPORT - sifnpmode(f->pcb, PPP_IPV6, NPMODE_DROP); + sifnpmode(f->pcb, PPP_IPV6, NPMODE_DROP); #endif /* DEMAND_SUPPORT */ - ipv6cp_clear_addrs(f->pcb, - go->ourid, - ho->hisid); - sif6down(f->pcb); + ipv6cp_clear_addrs(f->pcb, + go->ourid, + ho->hisid); + sif6down(f->pcb); } #if 0 /* UNUSED */ /* Execute the ipv6-down script */ if (ipv6cp_script_state == s_up && ipv6cp_script_pid == 0) { - ipv6cp_script_state = s_down; - ipv6cp_script(_PATH_IPV6DOWN); + ipv6cp_script_state = s_down; + ipv6cp_script(_PATH_IPV6DOWN); } #endif /* UNUSED */ } @@ -1346,17 +1346,17 @@ ipv6cp_script_done(arg) ipv6cp_script_pid = 0; switch (ipv6cp_script_state) { case s_up: - if (ipv6cp_fsm[0].state != PPP_FSM_OPENED) { - ipv6cp_script_state = s_down; - ipv6cp_script(_PATH_IPV6DOWN); - } - break; + if (ipv6cp_fsm[0].state != PPP_FSM_OPENED) { + ipv6cp_script_state = s_down; + ipv6cp_script(_PATH_IPV6DOWN); + } + break; case s_down: - if (ipv6cp_fsm[0].state == PPP_FSM_OPENED) { - ipv6cp_script_state = s_up; - ipv6cp_script(_PATH_IPV6UP); - } - break; + if (ipv6cp_fsm[0].state == PPP_FSM_OPENED) { + ipv6cp_script_state = s_up; + ipv6cp_script(_PATH_IPV6UP); + } + break; } } @@ -1386,7 +1386,7 @@ ipv6cp_script(script) argv[7] = NULL; ipv6cp_script_pid = run_program(script, argv, 0, ipv6cp_script_done, - NULL, 0); + NULL, 0); } #endif /* UNUSED */ @@ -1400,7 +1400,7 @@ static const char* const ipv6cp_codenames[] = { }; static int ipv6cp_printpkt(const u_char *p, int plen, - void (*printer)(void *, const char *, ...), void *arg) { + void (*printer)(void *, const char *, ...), void *arg) { int code, id, len, olen; const u_char *pstart, *optend; #ifdef IPV6CP_COMP @@ -1409,18 +1409,18 @@ static int ipv6cp_printpkt(const u_char *p, int plen, eui64_t ifaceid; if (plen < HEADERLEN) - return 0; + return 0; pstart = p; GETCHAR(code, p); GETCHAR(id, p); GETSHORT(len, p); if (len < HEADERLEN || len > plen) - return 0; + return 0; if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(ipv6cp_codenames)) - printer(arg, " %s", ipv6cp_codenames[code-1]); + printer(arg, " %s", ipv6cp_codenames[code-1]); else - printer(arg, " code=0x%x", code); + printer(arg, " code=0x%x", code); printer(arg, " id=0x%x", id); len -= HEADERLEN; switch (code) { @@ -1428,63 +1428,63 @@ static int ipv6cp_printpkt(const u_char *p, int plen, case CONFACK: case CONFNAK: case CONFREJ: - /* print option list */ - while (len >= 2) { - GETCHAR(code, p); - GETCHAR(olen, p); - p -= 2; - if (olen < 2 || olen > len) { - break; - } - printer(arg, " <"); - len -= olen; - optend = p + olen; - switch (code) { + /* print option list */ + while (len >= 2) { + GETCHAR(code, p); + GETCHAR(olen, p); + p -= 2; + if (olen < 2 || olen > len) { + break; + } + printer(arg, " <"); + len -= olen; + optend = p + olen; + switch (code) { #ifdef IPV6CP_COMP - case CI_COMPRESSTYPE: - if (olen >= CILEN_COMPRESS) { - p += 2; - GETSHORT(cishort, p); - printer(arg, "compress "); - printer(arg, "0x%x", cishort); - } - break; + case CI_COMPRESSTYPE: + if (olen >= CILEN_COMPRESS) { + p += 2; + GETSHORT(cishort, p); + printer(arg, "compress "); + printer(arg, "0x%x", cishort); + } + break; #endif /* IPV6CP_COMP */ - case CI_IFACEID: - if (olen == CILEN_IFACEID) { - p += 2; - eui64_get(ifaceid, p); - printer(arg, "addr %s", llv6_ntoa(ifaceid)); - } - break; - default: - break; - } - while (p < optend) { - GETCHAR(code, p); - printer(arg, " %.2x", code); - } - printer(arg, ">"); - } - break; + case CI_IFACEID: + if (olen == CILEN_IFACEID) { + p += 2; + eui64_get(ifaceid, p); + printer(arg, "addr %s", llv6_ntoa(ifaceid)); + } + break; + default: + break; + } + while (p < optend) { + GETCHAR(code, p); + printer(arg, " %.2x", code); + } + printer(arg, ">"); + } + break; case TERMACK: case TERMREQ: - if (len > 0 && *p >= ' ' && *p < 0x7f) { - printer(arg, " "); - ppp_print_string(p, len, printer, arg); - p += len; - len = 0; - } - break; + if (len > 0 && *p >= ' ' && *p < 0x7f) { + printer(arg, " "); + ppp_print_string(p, len, printer, arg); + p += len; + len = 0; + } + break; default: - break; + break; } /* print the rest of the bytes in the packet */ for (; len > 0; --len) { - GETCHAR(code, p); - printer(arg, " %.2x", code); + GETCHAR(code, p); + printer(arg, " %.2x", code); } return p - pstart; @@ -1497,19 +1497,19 @@ static int ipv6cp_printpkt(const u_char *p, int plen, * We don't bring the link up for IP fragments or for TCP FIN packets * with no data. */ -#define IP6_HDRLEN 40 /* bytes */ -#define IP6_NHDR_FRAG 44 /* fragment IPv6 header */ -#define TCP_HDRLEN 20 -#define TH_FIN 0x01 +#define IP6_HDRLEN 40 /* bytes */ +#define IP6_NHDR_FRAG 44 /* fragment IPv6 header */ +#define TCP_HDRLEN 20 +#define TH_FIN 0x01 /* * We use these macros because the IP header may be at an odd address, * and some compilers might use word loads to get th_off or ip_hl. */ -#define get_ip6nh(x) (((unsigned char *)(x))[6]) -#define get_tcpoff(x) (((unsigned char *)(x))[12] >> 4) -#define get_tcpflags(x) (((unsigned char *)(x))[13]) +#define get_ip6nh(x) (((unsigned char *)(x))[6]) +#define get_tcpoff(x) (((unsigned char *)(x))[12] >> 4) +#define get_tcpflags(x) (((unsigned char *)(x))[13]) static int ipv6_active_pkt(u_char *pkt, int len) { u_char *tcp; @@ -1517,16 +1517,16 @@ static int ipv6_active_pkt(u_char *pkt, int len) { len -= PPP_HDRLEN; pkt += PPP_HDRLEN; if (len < IP6_HDRLEN) - return 0; + return 0; if (get_ip6nh(pkt) == IP6_NHDR_FRAG) - return 0; + return 0; if (get_ip6nh(pkt) != IPPROTO_TCP) - return 1; + return 1; if (len < IP6_HDRLEN + TCP_HDRLEN) - return 0; + return 0; tcp = pkt + IP6_HDRLEN; if ((get_tcpflags(tcp) & TH_FIN) != 0 && len == IP6_HDRLEN + get_tcpoff(tcp) * 4) - return 0; + return 0; return 1; } #endif /* DEMAND_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/lcp.c b/components/network/lwip/src/netif/ppp/lcp.c index 90ed183b..04013563 100644 --- a/components/network/lwip/src/netif/ppp/lcp.c +++ b/components/network/lwip/src/netif/ppp/lcp.c @@ -68,7 +68,7 @@ * configure-requests. We do this by delaying the fsm_lowerup call. */ /* steal a bit in fsm flags word */ -#define DELAYED_UP 0x80 +#define DELAYED_UP 0x80 static void lcp_delayed_up(void *arg); @@ -76,8 +76,8 @@ static void lcp_delayed_up(void *arg); * LCP-related command-line options. */ #if 0 /* UNUSED */ -int lcp_echo_interval = 0; /* Interval between LCP echo-requests */ -int lcp_echo_fails = 0; /* Tolerance to unanswered echo-requests */ +int lcp_echo_interval = 0; /* Interval between LCP echo-requests */ +int lcp_echo_fails = 0; /* Tolerance to unanswered echo-requests */ #endif /* UNUSED */ #if 0 /* UNUSED */ @@ -88,10 +88,10 @@ static u_int lcp_echo_fails = LCP_MAXECHOFAILS; /* Tolerance to unanswer #if 0 /* UNUSED */ #if PPP_LCP_ADAPTIVE -bool lcp_echo_adaptive = 0; /* request echo only if the link was idle */ +bool lcp_echo_adaptive = 0; /* request echo only if the link was idle */ #endif -bool lax_recv = 0; /* accept control chars in asyncmap */ -bool noendpoint = 0; /* don't send/accept endpoint discriminator */ +bool lax_recv = 0; /* accept control chars in asyncmap */ +bool noendpoint = 0; /* don't send/accept endpoint discriminator */ #endif /* UNUSED */ #if PPP_OPTIONS @@ -101,7 +101,7 @@ static int noopt (char **); #ifdef HAVE_MULTILINK static int setendpoint (char **); static void printendpoint (option_t *, void (*)(void *, char *, ...), - void *); + void *); #endif /* HAVE_MULTILINK */ #if PPP_OPTIONS @@ -215,17 +215,17 @@ static option_t lcp_option_list[] = { /* * Callbacks for fsm code. (CI = Configuration Information) */ -static void lcp_resetci(fsm *f); /* Reset our CI */ -static int lcp_cilen(fsm *f); /* Return length of our CI */ +static void lcp_resetci(fsm *f); /* Reset our CI */ +static int lcp_cilen(fsm *f); /* Return length of our CI */ static void lcp_addci(fsm *f, u_char *ucp, int *lenp); /* Add our CI to pkt */ static int lcp_ackci(fsm *f, u_char *p, int len); /* Peer ack'd our CI */ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject); /* Peer nak'd our CI */ static int lcp_rejci(fsm *f, u_char *p, int len); /* Peer rej'd our CI */ static int lcp_reqci(fsm *f, u_char *inp, int *lenp, int reject_if_disagree); /* Rcv peer CI */ -static void lcp_up(fsm *f); /* We're UP */ -static void lcp_down(fsm *f); /* We're DOWN */ -static void lcp_starting (fsm *); /* We need lower layer up */ -static void lcp_finished (fsm *); /* We need lower layer down */ +static void lcp_up(fsm *f); /* We're UP */ +static void lcp_down(fsm *f); /* We're DOWN */ +static void lcp_starting (fsm *); /* We need lower layer up */ +static void lcp_finished (fsm *); /* We need lower layer down */ static int lcp_extcode(fsm *f, int code, int id, u_char *inp, int len); static void lcp_rprotrej(fsm *f, u_char *inp, int len); @@ -241,22 +241,22 @@ static void LcpSendEchoRequest(fsm *f); static void LcpLinkFailure(fsm *f); static void LcpEchoCheck(fsm *f); -static const fsm_callbacks lcp_callbacks = { /* LCP callback routines */ - lcp_resetci, /* Reset our Configuration Information */ - lcp_cilen, /* Length of our Configuration Information */ - lcp_addci, /* Add our Configuration Information */ - lcp_ackci, /* ACK our Configuration Information */ - lcp_nakci, /* NAK our Configuration Information */ - lcp_rejci, /* Reject our Configuration Information */ - lcp_reqci, /* Request peer's Configuration Information */ - lcp_up, /* Called when fsm reaches OPENED state */ - lcp_down, /* Called when fsm leaves OPENED state */ - lcp_starting, /* Called when we want the lower layer up */ - lcp_finished, /* Called when we want the lower layer down */ - NULL, /* Called when Protocol-Reject received */ - NULL, /* Retransmission is necessary */ - lcp_extcode, /* Called to handle LCP-specific codes */ - "LCP" /* String name of protocol */ +static const fsm_callbacks lcp_callbacks = { /* LCP callback routines */ + lcp_resetci, /* Reset our Configuration Information */ + lcp_cilen, /* Length of our Configuration Information */ + lcp_addci, /* Add our Configuration Information */ + lcp_ackci, /* ACK our Configuration Information */ + lcp_nakci, /* NAK our Configuration Information */ + lcp_rejci, /* Reject our Configuration Information */ + lcp_reqci, /* Request peer's Configuration Information */ + lcp_up, /* Called when fsm reaches OPENED state */ + lcp_down, /* Called when fsm leaves OPENED state */ + lcp_starting, /* Called when we want the lower layer up */ + lcp_finished, /* Called when we want the lower layer down */ + NULL, /* Called when Protocol-Reject received */ + NULL, /* Retransmission is necessary */ + lcp_extcode, /* Called to handle LCP-specific codes */ + "LCP" /* String name of protocol */ }; /* @@ -269,7 +269,7 @@ static void lcp_input(ppp_pcb *pcb, u_char *p, int len); static void lcp_protrej(ppp_pcb *pcb); #if PRINTPKT_SUPPORT static int lcp_printpkt(const u_char *p, int plen, - void (*printer) (void *, const char *, ...), void *arg); + void (*printer) (void *, const char *, ...), void *arg); #endif /* PRINTPKT_SUPPORT */ const struct protent lcp_protent = { @@ -304,20 +304,20 @@ const struct protent lcp_protent = { /* * Length of each type of configuration option (in octets) */ -#define CILEN_VOID 2 -#define CILEN_CHAR 3 -#define CILEN_SHORT 4 /* CILEN_VOID + 2 */ +#define CILEN_VOID 2 +#define CILEN_CHAR 3 +#define CILEN_SHORT 4 /* CILEN_VOID + 2 */ #if CHAP_SUPPORT -#define CILEN_CHAP 5 /* CILEN_VOID + 2 + 1 */ +#define CILEN_CHAP 5 /* CILEN_VOID + 2 + 1 */ #endif /* CHAP_SUPPORT */ -#define CILEN_LONG 6 /* CILEN_VOID + 4 */ +#define CILEN_LONG 6 /* CILEN_VOID + 4 */ #if LQR_SUPPORT -#define CILEN_LQR 8 /* CILEN_VOID + 2 + 4 */ +#define CILEN_LQR 8 /* CILEN_VOID + 2 + 4 */ #endif /* LQR_SUPPORT */ -#define CILEN_CBCP 3 +#define CILEN_CBCP 3 -#define CODENAME(x) ((x) == CONFACK ? "ACK" : \ - (x) == CONFNAK ? "NAK" : "REJ") +#define CODENAME(x) ((x) == CONFACK ? "ACK" : \ + (x) == CONFNAK ? "NAK" : "REJ") #if PPP_OPTIONS /* @@ -340,8 +340,8 @@ setendpoint(argv) char **argv; { if (str_to_epdisc(&lcp_wantoptions[0].endpoint, *argv)) { - lcp_wantoptions[0].neg_endpoint = 1; - return 1; + lcp_wantoptions[0].neg_endpoint = 1; + return 1; } option_error("Can't parse '%s' as an endpoint discriminator", *argv); return 0; @@ -353,7 +353,7 @@ printendpoint(opt, printer, arg) void (*printer) (void *, char *, ...); void *arg; { - printer(arg, "%s", epdisc_to_str(&lcp_wantoptions[0].endpoint)); + printer(arg, "%s", epdisc_to_str(&lcp_wantoptions[0].endpoint)); } #endif /* HAVE_MULTILINK */ @@ -409,9 +409,9 @@ void lcp_open(ppp_pcb *pcb) { f->flags &= ~(OPT_PASSIVE | OPT_SILENT); if (wo->passive) - f->flags |= OPT_PASSIVE; + f->flags |= OPT_PASSIVE; if (wo->silent) - f->flags |= OPT_SILENT; + f->flags |= OPT_SILENT; fsm_open(f); } @@ -428,25 +428,25 @@ void lcp_close(ppp_pcb *pcb, const char *reason) { && pcb->phase != PPP_PHASE_MASTER #endif /* HAVE_MULTILINK */ ) - new_phase(pcb, PPP_PHASE_TERMINATE); + new_phase(pcb, PPP_PHASE_TERMINATE); if (f->flags & DELAYED_UP) { - UNTIMEOUT(lcp_delayed_up, f); - f->state = PPP_FSM_STOPPED; + UNTIMEOUT(lcp_delayed_up, f); + f->state = PPP_FSM_STOPPED; } oldstate = f->state; fsm_close(f, reason); if (oldstate == PPP_FSM_STOPPED && (f->flags & (OPT_PASSIVE|OPT_SILENT|DELAYED_UP))) { - /* - * This action is not strictly according to the FSM in RFC1548, - * but it does mean that the program terminates if you do a - * lcp_close() when a connection hasn't been established - * because we are in passive/silent mode or because we have - * delayed the fsm_lowerup() call and it hasn't happened yet. - */ - f->flags &= ~DELAYED_UP; - lcp_finished(f); + /* + * This action is not strictly according to the FSM in RFC1548, + * but it does mean that the program terminates if you do a + * lcp_close() when a connection hasn't been established + * because we are in passive/silent mode or because we have + * delayed the fsm_lowerup() call and it hasn't happened yet. + */ + f->flags &= ~DELAYED_UP; + lcp_finished(f); } } @@ -463,16 +463,16 @@ void lcp_lowerup(ppp_pcb *pcb) { * if we are going to ask for A/C and protocol compression. */ if (ppp_send_config(pcb, PPP_MRU, 0xffffffff, 0, 0) < 0 - || ppp_recv_config(pcb, PPP_MRU, (pcb->settings.lax_recv? 0: 0xffffffff), - wo->neg_pcompression, wo->neg_accompression) < 0) - return; + || ppp_recv_config(pcb, PPP_MRU, (pcb->settings.lax_recv? 0: 0xffffffff), + wo->neg_pcompression, wo->neg_accompression) < 0) + return; pcb->peer_mru = PPP_MRU; if (pcb->settings.listen_time != 0) { - f->flags |= DELAYED_UP; - TIMEOUTMS(lcp_delayed_up, f, pcb->settings.listen_time); + f->flags |= DELAYED_UP; + TIMEOUTMS(lcp_delayed_up, f, pcb->settings.listen_time); } else - fsm_lowerup(f); + fsm_lowerup(f); } @@ -483,10 +483,10 @@ void lcp_lowerdown(ppp_pcb *pcb) { fsm *f = &pcb->lcp_fsm; if (f->flags & DELAYED_UP) { - f->flags &= ~DELAYED_UP; - UNTIMEOUT(lcp_delayed_up, f); + f->flags &= ~DELAYED_UP; + UNTIMEOUT(lcp_delayed_up, f); } else - fsm_lowerdown(f); + fsm_lowerdown(f); } @@ -497,8 +497,8 @@ static void lcp_delayed_up(void *arg) { fsm *f = (fsm*)arg; if (f->flags & DELAYED_UP) { - f->flags &= ~DELAYED_UP; - fsm_lowerup(f); + f->flags &= ~DELAYED_UP; + fsm_lowerup(f); } } @@ -510,9 +510,9 @@ static void lcp_input(ppp_pcb *pcb, u_char *p, int len) { fsm *f = &pcb->lcp_fsm; if (f->flags & DELAYED_UP) { - f->flags &= ~DELAYED_UP; - UNTIMEOUT(lcp_delayed_up, f); - fsm_lowerup(f); + f->flags &= ~DELAYED_UP; + UNTIMEOUT(lcp_delayed_up, f); + fsm_lowerup(f); } fsm_input(f, p, len); } @@ -527,33 +527,33 @@ static int lcp_extcode(fsm *f, int code, int id, u_char *inp, int len) { switch( code ){ case PROTREJ: - lcp_rprotrej(f, inp, len); - break; - + lcp_rprotrej(f, inp, len); + break; + case ECHOREQ: - if (f->state != PPP_FSM_OPENED) - break; - magp = inp; - PUTLONG(go->magicnumber, magp); - fsm_sdata(f, ECHOREP, id, inp, len); - break; - + if (f->state != PPP_FSM_OPENED) + break; + magp = inp; + PUTLONG(go->magicnumber, magp); + fsm_sdata(f, ECHOREP, id, inp, len); + break; + case ECHOREP: - lcp_received_echo_reply(f, id, inp, len); - break; + lcp_received_echo_reply(f, id, inp, len); + break; case DISCREQ: case IDENTIF: case TIMEREM: - break; + break; default: - return 0; + return 0; } return 1; } - + /* * lcp_rprotrej - Receive an Protocol-Reject. * @@ -568,8 +568,8 @@ static void lcp_rprotrej(fsm *f, u_char *inp, int len) { #endif /* PPP_PROTOCOLNAME */ if (len < 2) { - LCPDEBUG(("lcp_rprotrej: Rcvd short Protocol-Reject packet!")); - return; + LCPDEBUG(("lcp_rprotrej: Rcvd short Protocol-Reject packet!")); + return; } GETSHORT(prot, inp); @@ -579,8 +579,8 @@ static void lcp_rprotrej(fsm *f, u_char *inp, int len) { * OPENED state SHOULD be silently discarded. */ if( f->state != PPP_FSM_OPENED ){ - LCPDEBUG(("Protocol-Reject discarded: LCP in state %d", f->state)); - return; + LCPDEBUG(("Protocol-Reject discarded: LCP in state %d", f->state)); + return; } #if PPP_PROTOCOLNAME @@ -591,25 +591,25 @@ static void lcp_rprotrej(fsm *f, u_char *inp, int len) { * Upcall the proper Protocol-Reject routine. */ for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (protp->protocol == prot) { + if (protp->protocol == prot) { #if PPP_PROTOCOLNAME - if (pname != NULL) - ppp_dbglog("Protocol-Reject for '%s' (0x%x) received", pname, - prot); - else + if (pname != NULL) + ppp_dbglog("Protocol-Reject for '%s' (0x%x) received", pname, + prot); + else #endif /* PPP_PROTOCOLNAME */ - ppp_dbglog("Protocol-Reject for 0x%x received", prot); - (*protp->protrej)(f->pcb); - return; - } + ppp_dbglog("Protocol-Reject for 0x%x received", prot); + (*protp->protrej)(f->pcb); + return; + } #if PPP_PROTOCOLNAME if (pname != NULL) - ppp_warn("Protocol-Reject for unsupported protocol '%s' (0x%x)", pname, - prot); + ppp_warn("Protocol-Reject for unsupported protocol '%s' (0x%x)", pname, + prot); else #endif /* #if PPP_PROTOCOLNAME */ - ppp_warn("Protocol-Reject for unsupported protocol 0x%x", prot); + ppp_warn("Protocol-Reject for unsupported protocol 0x%x", prot); } @@ -641,7 +641,7 @@ void lcp_sprotrej(ppp_pcb *pcb, u_char *p, int len) { #endif fsm_sdata(f, PROTREJ, ++f->id, - p, len); + p, len); } @@ -748,15 +748,15 @@ static void lcp_resetci(fsm *f) { *go = *wo; #ifdef HAVE_MULTILINK if (!multilink) { - go->neg_mrru = 0; + go->neg_mrru = 0; #endif /* HAVE_MULTILINK */ - go->neg_ssnhf = 0; - go->neg_endpoint = 0; + go->neg_ssnhf = 0; + go->neg_endpoint = 0; #ifdef HAVE_MULTILINK } #endif /* HAVE_MULTILINK */ if (pcb->settings.noendpoint) - ao->neg_endpoint = 0; + ao->neg_endpoint = 0; pcb->peer_mru = PPP_MRU; #if 0 /* UNUSED */ auth_reset(pcb); @@ -771,60 +771,60 @@ static int lcp_cilen(fsm *f) { ppp_pcb *pcb = f->pcb; lcp_options *go = &pcb->lcp_gotoptions; -#define LENCIVOID(neg) ((neg) ? CILEN_VOID : 0) +#define LENCIVOID(neg) ((neg) ? CILEN_VOID : 0) #if CHAP_SUPPORT -#define LENCICHAP(neg) ((neg) ? CILEN_CHAP : 0) +#define LENCICHAP(neg) ((neg) ? CILEN_CHAP : 0) #endif /* CHAP_SUPPORT */ -#define LENCISHORT(neg) ((neg) ? CILEN_SHORT : 0) -#define LENCILONG(neg) ((neg) ? CILEN_LONG : 0) +#define LENCISHORT(neg) ((neg) ? CILEN_SHORT : 0) +#define LENCILONG(neg) ((neg) ? CILEN_LONG : 0) #if LQR_SUPPORT -#define LENCILQR(neg) ((neg) ? CILEN_LQR: 0) +#define LENCILQR(neg) ((neg) ? CILEN_LQR: 0) #endif /* LQR_SUPPORT */ -#define LENCICBCP(neg) ((neg) ? CILEN_CBCP: 0) +#define LENCICBCP(neg) ((neg) ? CILEN_CBCP: 0) /* * NB: we only ask for one of CHAP, UPAP, or EAP, even if we will * accept more than one. We prefer EAP first, then CHAP, then * PAP. */ return (LENCISHORT(go->neg_mru && go->mru != PPP_DEFMRU) + - LENCILONG(go->neg_asyncmap && go->asyncmap != 0xFFFFFFFF) + + LENCILONG(go->neg_asyncmap && go->asyncmap != 0xFFFFFFFF) + #if EAP_SUPPORT - LENCISHORT(go->neg_eap) + + LENCISHORT(go->neg_eap) + #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT /* cannot be improved, embedding a directive within macro arguments is not portable */ #if EAP_SUPPORT - LENCICHAP(!go->neg_eap && go->neg_chap) + + LENCICHAP(!go->neg_eap && go->neg_chap) + #endif /* EAP_SUPPORT */ #if !EAP_SUPPORT - LENCICHAP(go->neg_chap) + + LENCICHAP(go->neg_chap) + #endif /* !EAP_SUPPORT */ #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT /* cannot be improved, embedding a directive within macro arguments is not portable */ #if EAP_SUPPORT && CHAP_SUPPORT - LENCISHORT(!go->neg_eap && !go->neg_chap && go->neg_upap) + + LENCISHORT(!go->neg_eap && !go->neg_chap && go->neg_upap) + #endif /* EAP_SUPPORT && CHAP_SUPPORT */ #if EAP_SUPPORT && !CHAP_SUPPORT - LENCISHORT(!go->neg_eap && go->neg_upap) + + LENCISHORT(!go->neg_eap && go->neg_upap) + #endif /* EAP_SUPPORT && !CHAP_SUPPORT */ #if !EAP_SUPPORT && CHAP_SUPPORT - LENCISHORT(!go->neg_chap && go->neg_upap) + + LENCISHORT(!go->neg_chap && go->neg_upap) + #endif /* !EAP_SUPPORT && CHAP_SUPPORT */ #if !EAP_SUPPORT && !CHAP_SUPPORT - LENCISHORT(go->neg_upap) + + LENCISHORT(go->neg_upap) + #endif /* !EAP_SUPPORT && !CHAP_SUPPORT */ #endif /* PAP_SUPPORT */ #if LQR_SUPPORT - LENCILQR(go->neg_lqr) + + LENCILQR(go->neg_lqr) + #endif /* LQR_SUPPORT */ - LENCICBCP(go->neg_cbcp) + - LENCILONG(go->neg_magicnumber) + - LENCIVOID(go->neg_pcompression) + - LENCIVOID(go->neg_accompression) + + LENCICBCP(go->neg_cbcp) + + LENCILONG(go->neg_magicnumber) + + LENCIVOID(go->neg_pcompression) + + LENCIVOID(go->neg_accompression) + #ifdef HAVE_MULTILINK - LENCISHORT(go->neg_mrru) + + LENCISHORT(go->neg_mrru) + #endif /* HAVE_MULTILINK */ - LENCIVOID(go->neg_ssnhf) + - (go->neg_endpoint? CILEN_CHAR + go->endpoint.length: 0)); + LENCIVOID(go->neg_ssnhf) + + (go->neg_endpoint? CILEN_CHAR + go->endpoint.length: 0)); } @@ -838,58 +838,58 @@ static void lcp_addci(fsm *f, u_char *ucp, int *lenp) { #define ADDCIVOID(opt, neg) \ if (neg) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_VOID, ucp); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_VOID, ucp); \ } #define ADDCISHORT(opt, neg, val) \ if (neg) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_SHORT, ucp); \ - PUTSHORT(val, ucp); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_SHORT, ucp); \ + PUTSHORT(val, ucp); \ } #if CHAP_SUPPORT #define ADDCICHAP(opt, neg, val) \ if (neg) { \ - PUTCHAR((opt), ucp); \ - PUTCHAR(CILEN_CHAP, ucp); \ - PUTSHORT(PPP_CHAP, ucp); \ - PUTCHAR((CHAP_DIGEST(val)), ucp); \ + PUTCHAR((opt), ucp); \ + PUTCHAR(CILEN_CHAP, ucp); \ + PUTSHORT(PPP_CHAP, ucp); \ + PUTCHAR((CHAP_DIGEST(val)), ucp); \ } #endif /* CHAP_SUPPORT */ #define ADDCILONG(opt, neg, val) \ if (neg) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_LONG, ucp); \ - PUTLONG(val, ucp); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_LONG, ucp); \ + PUTLONG(val, ucp); \ } #if LQR_SUPPORT #define ADDCILQR(opt, neg, val) \ if (neg) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_LQR, ucp); \ - PUTSHORT(PPP_LQR, ucp); \ - PUTLONG(val, ucp); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_LQR, ucp); \ + PUTSHORT(PPP_LQR, ucp); \ + PUTLONG(val, ucp); \ } #endif /* LQR_SUPPORT */ #define ADDCICHAR(opt, neg, val) \ if (neg) { \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_CHAR, ucp); \ - PUTCHAR(val, ucp); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_CHAR, ucp); \ + PUTCHAR(val, ucp); \ } #define ADDCIENDP(opt, neg, class, val, len) \ if (neg) { \ - int i; \ - PUTCHAR(opt, ucp); \ - PUTCHAR(CILEN_CHAR + len, ucp); \ - PUTCHAR(class, ucp); \ - for (i = 0; i < len; ++i) \ - PUTCHAR(val[i], ucp); \ + int i; \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_CHAR + len, ucp); \ + PUTCHAR(class, ucp); \ + for (i = 0; i < len; ++i) \ + PUTCHAR(val[i], ucp); \ } ADDCISHORT(CI_MRU, go->neg_mru && go->mru != PPP_DEFMRU, go->mru); ADDCILONG(CI_ASYNCMAP, go->neg_asyncmap && go->asyncmap != 0xFFFFFFFF, - go->asyncmap); + go->asyncmap); #if EAP_SUPPORT ADDCISHORT(CI_AUTHTYPE, go->neg_eap, PPP_EAP); #endif /* EAP_SUPPORT */ @@ -927,11 +927,11 @@ static void lcp_addci(fsm *f, u_char *ucp, int *lenp) { #endif ADDCIVOID(CI_SSNHF, go->neg_ssnhf); ADDCIENDP(CI_EPDISC, go->neg_endpoint, go->endpoint.class_, - go->endpoint.value, go->endpoint.length); + go->endpoint.value, go->endpoint.length); if (ucp - start_ucp != *lenp) { - /* this should never happen, because peer_mtu should be 1500 */ - ppp_error("Bug in lcp_addci: wrong length"); + /* this should never happen, because peer_mtu should be 1500 */ + ppp_error("Bug in lcp_addci: wrong length"); } } @@ -941,8 +941,8 @@ static void lcp_addci(fsm *f, u_char *ucp, int *lenp) { * This should not modify any state if the Ack is bad. * * Returns: - * 0 - Ack was bad. - * 1 - Ack was good. + * 0 - Ack was bad. + * 1 - Ack was good. */ static int lcp_ackci(fsm *f, u_char *p, int len) { ppp_pcb *pcb = f->pcb; @@ -958,112 +958,112 @@ static int lcp_ackci(fsm *f, u_char *p, int len) { */ #define ACKCIVOID(opt, neg) \ if (neg) { \ - if ((len -= CILEN_VOID) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_VOID || \ - citype != opt) \ - goto bad; \ + if ((len -= CILEN_VOID) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_VOID || \ + citype != opt) \ + goto bad; \ } #define ACKCISHORT(opt, neg, val) \ if (neg) { \ - if ((len -= CILEN_SHORT) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_SHORT || \ - citype != opt) \ - goto bad; \ - GETSHORT(cishort, p); \ - if (cishort != val) \ - goto bad; \ + if ((len -= CILEN_SHORT) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_SHORT || \ + citype != opt) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != val) \ + goto bad; \ } #define ACKCICHAR(opt, neg, val) \ if (neg) { \ - if ((len -= CILEN_CHAR) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_CHAR || \ - citype != opt) \ - goto bad; \ - GETCHAR(cichar, p); \ - if (cichar != val) \ - goto bad; \ + if ((len -= CILEN_CHAR) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_CHAR || \ + citype != opt) \ + goto bad; \ + GETCHAR(cichar, p); \ + if (cichar != val) \ + goto bad; \ } #if CHAP_SUPPORT #define ACKCICHAP(opt, neg, val) \ if (neg) { \ - if ((len -= CILEN_CHAP) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_CHAP || \ - citype != (opt)) \ - goto bad; \ - GETSHORT(cishort, p); \ - if (cishort != PPP_CHAP) \ - goto bad; \ - GETCHAR(cichar, p); \ - if (cichar != (CHAP_DIGEST(val))) \ - goto bad; \ + if ((len -= CILEN_CHAP) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_CHAP || \ + citype != (opt)) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != PPP_CHAP) \ + goto bad; \ + GETCHAR(cichar, p); \ + if (cichar != (CHAP_DIGEST(val))) \ + goto bad; \ } #endif /* CHAP_SUPPORT */ #define ACKCILONG(opt, neg, val) \ if (neg) { \ - if ((len -= CILEN_LONG) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_LONG || \ - citype != opt) \ - goto bad; \ - GETLONG(cilong, p); \ - if (cilong != val) \ - goto bad; \ + if ((len -= CILEN_LONG) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_LONG || \ + citype != opt) \ + goto bad; \ + GETLONG(cilong, p); \ + if (cilong != val) \ + goto bad; \ } #if LQR_SUPPORT #define ACKCILQR(opt, neg, val) \ if (neg) { \ - if ((len -= CILEN_LQR) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_LQR || \ - citype != opt) \ - goto bad; \ - GETSHORT(cishort, p); \ - if (cishort != PPP_LQR) \ - goto bad; \ - GETLONG(cilong, p); \ - if (cilong != val) \ - goto bad; \ + if ((len -= CILEN_LQR) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_LQR || \ + citype != opt) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != PPP_LQR) \ + goto bad; \ + GETLONG(cilong, p); \ + if (cilong != val) \ + goto bad; \ } #endif /* LQR_SUPPORT */ #define ACKCIENDP(opt, neg, class, val, vlen) \ if (neg) { \ - int i; \ - if ((len -= CILEN_CHAR + vlen) < 0) \ - goto bad; \ - GETCHAR(citype, p); \ - GETCHAR(cilen, p); \ - if (cilen != CILEN_CHAR + vlen || \ - citype != opt) \ - goto bad; \ - GETCHAR(cichar, p); \ - if (cichar != class) \ - goto bad; \ - for (i = 0; i < vlen; ++i) { \ - GETCHAR(cichar, p); \ - if (cichar != val[i]) \ - goto bad; \ - } \ + int i; \ + if ((len -= CILEN_CHAR + vlen) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_CHAR + vlen || \ + citype != opt) \ + goto bad; \ + GETCHAR(cichar, p); \ + if (cichar != class) \ + goto bad; \ + for (i = 0; i < vlen; ++i) { \ + GETCHAR(cichar, p); \ + if (cichar != val[i]) \ + goto bad; \ + } \ } ACKCISHORT(CI_MRU, go->neg_mru && go->mru != PPP_DEFMRU, go->mru); ACKCILONG(CI_ASYNCMAP, go->neg_asyncmap && go->asyncmap != 0xFFFFFFFF, - go->asyncmap); + go->asyncmap); #if EAP_SUPPORT ACKCISHORT(CI_AUTHTYPE, go->neg_eap, PPP_EAP); #endif /* EAP_SUPPORT */ @@ -1101,13 +1101,13 @@ static int lcp_ackci(fsm *f, u_char *p, int len) { #endif /* HAVE_MULTILINK */ ACKCIVOID(CI_SSNHF, go->neg_ssnhf); ACKCIENDP(CI_EPDISC, go->neg_endpoint, go->endpoint.class_, - go->endpoint.value, go->endpoint.length); + go->endpoint.value, go->endpoint.length); /* * If there are any remaining CIs, then this packet is bad. */ if (len != 0) - goto bad; + goto bad; return (1); bad: LCPDEBUG(("lcp_acki: received bad Ack!")); @@ -1121,8 +1121,8 @@ bad: * or if LCP is in the OPENED state. * * Returns: - * 0 - Nak was bad. - * 1 - Nak was good. + * 0 - Nak was bad. + * 1 - Nak was good. */ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { ppp_pcb *pcb = f->pcb; @@ -1131,8 +1131,8 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { u_char citype, cichar, *next; u_short cishort; u32_t cilong; - lcp_options no; /* options we've seen Naks for */ - lcp_options try_; /* options to request next time */ + lcp_options no; /* options we've seen Naks for */ + lcp_options try_; /* options to request next time */ int looped_back = 0; int cilen; @@ -1146,85 +1146,85 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { */ #define NAKCIVOID(opt, neg) \ if (go->neg && \ - len >= CILEN_VOID && \ - p[1] == CILEN_VOID && \ - p[0] == opt) { \ - len -= CILEN_VOID; \ - INCPTR(CILEN_VOID, p); \ - no.neg = 1; \ - try_.neg = 0; \ + len >= CILEN_VOID && \ + p[1] == CILEN_VOID && \ + p[0] == opt) { \ + len -= CILEN_VOID; \ + INCPTR(CILEN_VOID, p); \ + no.neg = 1; \ + try_.neg = 0; \ } #if CHAP_SUPPORT #define NAKCICHAP(opt, neg, code) \ if (go->neg && \ - len >= CILEN_CHAP && \ - p[1] == CILEN_CHAP && \ - p[0] == opt) { \ - len -= CILEN_CHAP; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - GETCHAR(cichar, p); \ - no.neg = 1; \ - code \ + len >= CILEN_CHAP && \ + p[1] == CILEN_CHAP && \ + p[0] == opt) { \ + len -= CILEN_CHAP; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETCHAR(cichar, p); \ + no.neg = 1; \ + code \ } #endif /* CHAP_SUPPORT */ #define NAKCICHAR(opt, neg, code) \ if (go->neg && \ - len >= CILEN_CHAR && \ - p[1] == CILEN_CHAR && \ - p[0] == opt) { \ - len -= CILEN_CHAR; \ - INCPTR(2, p); \ - GETCHAR(cichar, p); \ - no.neg = 1; \ - code \ + len >= CILEN_CHAR && \ + p[1] == CILEN_CHAR && \ + p[0] == opt) { \ + len -= CILEN_CHAR; \ + INCPTR(2, p); \ + GETCHAR(cichar, p); \ + no.neg = 1; \ + code \ } #define NAKCISHORT(opt, neg, code) \ if (go->neg && \ - len >= CILEN_SHORT && \ - p[1] == CILEN_SHORT && \ - p[0] == opt) { \ - len -= CILEN_SHORT; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - no.neg = 1; \ - code \ + len >= CILEN_SHORT && \ + p[1] == CILEN_SHORT && \ + p[0] == opt) { \ + len -= CILEN_SHORT; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + no.neg = 1; \ + code \ } #define NAKCILONG(opt, neg, code) \ if (go->neg && \ - len >= CILEN_LONG && \ - p[1] == CILEN_LONG && \ - p[0] == opt) { \ - len -= CILEN_LONG; \ - INCPTR(2, p); \ - GETLONG(cilong, p); \ - no.neg = 1; \ - code \ + len >= CILEN_LONG && \ + p[1] == CILEN_LONG && \ + p[0] == opt) { \ + len -= CILEN_LONG; \ + INCPTR(2, p); \ + GETLONG(cilong, p); \ + no.neg = 1; \ + code \ } #if LQR_SUPPORT #define NAKCILQR(opt, neg, code) \ if (go->neg && \ - len >= CILEN_LQR && \ - p[1] == CILEN_LQR && \ - p[0] == opt) { \ - len -= CILEN_LQR; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - GETLONG(cilong, p); \ - no.neg = 1; \ - code \ + len >= CILEN_LQR && \ + p[1] == CILEN_LQR && \ + p[0] == opt) { \ + len -= CILEN_LQR; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETLONG(cilong, p); \ + no.neg = 1; \ + code \ } #endif /* LQR_SUPPORT */ #define NAKCIENDP(opt, neg) \ if (go->neg && \ - len >= CILEN_CHAR && \ - p[0] == opt && \ - p[1] >= CILEN_CHAR && \ - p[1] <= len) { \ - len -= p[1]; \ - INCPTR(p[1], p); \ - no.neg = 1; \ - try_.neg = 0; \ + len >= CILEN_CHAR && \ + p[0] == opt && \ + p[1] >= CILEN_CHAR && \ + p[1] <= len) { \ + len -= p[1]; \ + INCPTR(p[1], p); \ + no.neg = 1; \ + try_.neg = 0; \ } /* @@ -1239,19 +1239,19 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * the limit of the default MRU we'd get if we didn't negotiate. */ if (go->neg_mru && go->mru != PPP_DEFMRU) { - NAKCISHORT(CI_MRU, neg_mru, - if (cishort <= wo->mru || cishort <= PPP_DEFMRU) - try_.mru = cishort; - ); + NAKCISHORT(CI_MRU, neg_mru, + if (cishort <= wo->mru || cishort <= PPP_DEFMRU) + try_.mru = cishort; + ); } /* * Add any characters they want to our (receive-side) asyncmap. */ if (go->neg_asyncmap && go->asyncmap != 0xFFFFFFFF) { - NAKCILONG(CI_ASYNCMAP, neg_asyncmap, - try_.asyncmap = go->asyncmap | cilong; - ); + NAKCILONG(CI_ASYNCMAP, neg_asyncmap, + try_.asyncmap = go->asyncmap | cilong; + ); } /* @@ -1270,125 +1270,125 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { || go->neg_eap #endif /* EAP_SUPPORT */ ) - && len >= CILEN_SHORT - && p[0] == CI_AUTHTYPE && p[1] >= CILEN_SHORT && p[1] <= len) { - cilen = p[1]; - len -= cilen; + && len >= CILEN_SHORT + && p[0] == CI_AUTHTYPE && p[1] >= CILEN_SHORT && p[1] <= len) { + cilen = p[1]; + len -= cilen; #if CHAP_SUPPORT - no.neg_chap = go->neg_chap; + no.neg_chap = go->neg_chap; #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - no.neg_upap = go->neg_upap; + no.neg_upap = go->neg_upap; #endif /* PAP_SUPPORT */ #if EAP_SUPPORT - no.neg_eap = go->neg_eap; + no.neg_eap = go->neg_eap; #endif /* EAP_SUPPORT */ - INCPTR(2, p); - GETSHORT(cishort, p); + INCPTR(2, p); + GETSHORT(cishort, p); #if PAP_SUPPORT - if (cishort == PPP_PAP && cilen == CILEN_SHORT) { + if (cishort == PPP_PAP && cilen == CILEN_SHORT) { #if EAP_SUPPORT - /* If we were asking for EAP, then we need to stop that. */ - if (go->neg_eap) - try_.neg_eap = 0; - else + /* If we were asking for EAP, then we need to stop that. */ + if (go->neg_eap) + try_.neg_eap = 0; + else #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT - /* If we were asking for CHAP, then we need to stop that. */ - if (go->neg_chap) - try_.neg_chap = 0; - else + /* If we were asking for CHAP, then we need to stop that. */ + if (go->neg_chap) + try_.neg_chap = 0; + else #endif /* CHAP_SUPPORT */ - /* - * If we weren't asking for CHAP or EAP, then we were asking for - * PAP, in which case this Nak is bad. - */ - goto bad; - } else + /* + * If we weren't asking for CHAP or EAP, then we were asking for + * PAP, in which case this Nak is bad. + */ + goto bad; + } else #endif /* PAP_SUPPORT */ #if CHAP_SUPPORT - if (cishort == PPP_CHAP && cilen == CILEN_CHAP) { - GETCHAR(cichar, p); + if (cishort == PPP_CHAP && cilen == CILEN_CHAP) { + GETCHAR(cichar, p); #if EAP_SUPPORT - /* Stop asking for EAP, if we were. */ - if (go->neg_eap) { - try_.neg_eap = 0; - /* Try to set up to use their suggestion, if possible */ - if (CHAP_CANDIGEST(go->chap_mdtype, cichar)) - try_.chap_mdtype = CHAP_MDTYPE_D(cichar); - } else + /* Stop asking for EAP, if we were. */ + if (go->neg_eap) { + try_.neg_eap = 0; + /* Try to set up to use their suggestion, if possible */ + if (CHAP_CANDIGEST(go->chap_mdtype, cichar)) + try_.chap_mdtype = CHAP_MDTYPE_D(cichar); + } else #endif /* EAP_SUPPORT */ - if (go->neg_chap) { - /* - * We were asking for our preferred algorithm, they must - * want something different. - */ - if (cichar != CHAP_DIGEST(go->chap_mdtype)) { - if (CHAP_CANDIGEST(go->chap_mdtype, cichar)) { - /* Use their suggestion if we support it ... */ - try_.chap_mdtype = CHAP_MDTYPE_D(cichar); - } else { - /* ... otherwise, try our next-preferred algorithm. */ - try_.chap_mdtype &= ~(CHAP_MDTYPE(try_.chap_mdtype)); - if (try_.chap_mdtype == MDTYPE_NONE) /* out of algos */ - try_.neg_chap = 0; - } - } else { - /* - * Whoops, they Nak'd our algorithm of choice - * but then suggested it back to us. - */ - goto bad; - } - } else { - /* - * Stop asking for PAP if we were asking for it. - */ + if (go->neg_chap) { + /* + * We were asking for our preferred algorithm, they must + * want something different. + */ + if (cichar != CHAP_DIGEST(go->chap_mdtype)) { + if (CHAP_CANDIGEST(go->chap_mdtype, cichar)) { + /* Use their suggestion if we support it ... */ + try_.chap_mdtype = CHAP_MDTYPE_D(cichar); + } else { + /* ... otherwise, try our next-preferred algorithm. */ + try_.chap_mdtype &= ~(CHAP_MDTYPE(try_.chap_mdtype)); + if (try_.chap_mdtype == MDTYPE_NONE) /* out of algos */ + try_.neg_chap = 0; + } + } else { + /* + * Whoops, they Nak'd our algorithm of choice + * but then suggested it back to us. + */ + goto bad; + } + } else { + /* + * Stop asking for PAP if we were asking for it. + */ #if PAP_SUPPORT - try_.neg_upap = 0; + try_.neg_upap = 0; #endif /* PAP_SUPPORT */ - } + } - } else + } else #endif /* CHAP_SUPPORT */ - { + { #if EAP_SUPPORT - /* - * If we were asking for EAP, and they're Conf-Naking EAP, - * well, that's just strange. Nobody should do that. - */ - if (cishort == PPP_EAP && cilen == CILEN_SHORT && go->neg_eap) - ppp_dbglog("Unexpected Conf-Nak for EAP"); + /* + * If we were asking for EAP, and they're Conf-Naking EAP, + * well, that's just strange. Nobody should do that. + */ + if (cishort == PPP_EAP && cilen == CILEN_SHORT && go->neg_eap) + ppp_dbglog("Unexpected Conf-Nak for EAP"); - /* - * We don't recognize what they're suggesting. - * Stop asking for what we were asking for. - */ - if (go->neg_eap) - try_.neg_eap = 0; - else + /* + * We don't recognize what they're suggesting. + * Stop asking for what we were asking for. + */ + if (go->neg_eap) + try_.neg_eap = 0; + else #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT - if (go->neg_chap) - try_.neg_chap = 0; - else + if (go->neg_chap) + try_.neg_chap = 0; + else #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - if(1) - try_.neg_upap = 0; - else + if(1) + try_.neg_upap = 0; + else #endif /* PAP_SUPPORT */ - {} + {} - p += cilen - CILEN_SHORT; - } + p += cilen - CILEN_SHORT; + } } #if LQR_SUPPORT @@ -1398,11 +1398,11 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * If they Nak the reporting period, take their value XXX ? */ NAKCILQR(CI_QUALITY, neg_lqr, - if (cishort != PPP_LQR) - try_.neg_lqr = 0; - else - try_.lqr_period = cilong; - ); + if (cishort != PPP_LQR) + try_.neg_lqr = 0; + else + try_.lqr_period = cilong; + ); #endif /* LQR_SUPPORT */ /* @@ -1417,9 +1417,9 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * Check for a looped-back line. */ NAKCILONG(CI_MAGICNUMBER, neg_magicnumber, - try_.magicnumber = magic(); - looped_back = 1; - ); + try_.magicnumber = magic(); + looped_back = 1; + ); /* * Peer shouldn't send Nak for protocol compression or @@ -1435,12 +1435,12 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * than the one we want. */ if (go->neg_mrru) { - NAKCISHORT(CI_MRRU, neg_mrru, - if (treat_as_reject) - try_.neg_mrru = 0; - else if (cishort <= wo->mrru) - try_.mrru = cishort; - ); + NAKCISHORT(CI_MRRU, neg_mrru, + if (treat_as_reject) + try_.neg_mrru = 0; + else if (cishort <= wo->mrru) + try_.mrru = cishort; + ); } #else /* HAVE_MULTILINK */ LWIP_UNUSED_ARG(treat_as_reject); @@ -1475,30 +1475,30 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * negotiate some option we don't support, so ignore it. */ while (len >= CILEN_VOID) { - GETCHAR(citype, p); - GETCHAR(cilen, p); - if (cilen < CILEN_VOID || (len -= cilen) < 0) - goto bad; - next = p + cilen - 2; + GETCHAR(citype, p); + GETCHAR(cilen, p); + if (cilen < CILEN_VOID || (len -= cilen) < 0) + goto bad; + next = p + cilen - 2; - switch (citype) { - case CI_MRU: - if ((go->neg_mru && go->mru != PPP_DEFMRU) - || no.neg_mru || cilen != CILEN_SHORT) - goto bad; - GETSHORT(cishort, p); - if (cishort < PPP_DEFMRU) { - try_.neg_mru = 1; - try_.mru = cishort; - } - break; - case CI_ASYNCMAP: - if ((go->neg_asyncmap && go->asyncmap != 0xFFFFFFFF) - || no.neg_asyncmap || cilen != CILEN_LONG) - goto bad; - break; - case CI_AUTHTYPE: - if (0 + switch (citype) { + case CI_MRU: + if ((go->neg_mru && go->mru != PPP_DEFMRU) + || no.neg_mru || cilen != CILEN_SHORT) + goto bad; + GETSHORT(cishort, p); + if (cishort < PPP_DEFMRU) { + try_.neg_mru = 1; + try_.mru = cishort; + } + break; + case CI_ASYNCMAP: + if ((go->neg_asyncmap && go->asyncmap != 0xFFFFFFFF) + || no.neg_asyncmap || cilen != CILEN_LONG) + goto bad; + break; + case CI_AUTHTYPE: + if (0 #if CHAP_SUPPORT || go->neg_chap || no.neg_chap #endif /* CHAP_SUPPORT */ @@ -1506,51 +1506,51 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { || go->neg_upap || no.neg_upap #endif /* PAP_SUPPORT */ #if EAP_SUPPORT - || go->neg_eap || no.neg_eap + || go->neg_eap || no.neg_eap #endif /* EAP_SUPPORT */ - ) - goto bad; - break; - case CI_MAGICNUMBER: - if (go->neg_magicnumber || no.neg_magicnumber || - cilen != CILEN_LONG) - goto bad; - break; - case CI_PCOMPRESSION: - if (go->neg_pcompression || no.neg_pcompression - || cilen != CILEN_VOID) - goto bad; - break; - case CI_ACCOMPRESSION: - if (go->neg_accompression || no.neg_accompression - || cilen != CILEN_VOID) - goto bad; - break; + ) + goto bad; + break; + case CI_MAGICNUMBER: + if (go->neg_magicnumber || no.neg_magicnumber || + cilen != CILEN_LONG) + goto bad; + break; + case CI_PCOMPRESSION: + if (go->neg_pcompression || no.neg_pcompression + || cilen != CILEN_VOID) + goto bad; + break; + case CI_ACCOMPRESSION: + if (go->neg_accompression || no.neg_accompression + || cilen != CILEN_VOID) + goto bad; + break; #if LQR_SUPPORT - case CI_QUALITY: - if (go->neg_lqr || no.neg_lqr || cilen != CILEN_LQR) - goto bad; - break; + case CI_QUALITY: + if (go->neg_lqr || no.neg_lqr || cilen != CILEN_LQR) + goto bad; + break; #endif /* LQR_SUPPORT */ #ifdef HAVE_MULTILINK - case CI_MRRU: - if (go->neg_mrru || no.neg_mrru || cilen != CILEN_SHORT) - goto bad; - break; + case CI_MRRU: + if (go->neg_mrru || no.neg_mrru || cilen != CILEN_SHORT) + goto bad; + break; #endif /* HAVE_MULTILINK */ - case CI_SSNHF: - if (go->neg_ssnhf || no.neg_ssnhf || cilen != CILEN_VOID) - goto bad; - try_.neg_ssnhf = 1; - break; - case CI_EPDISC: - if (go->neg_endpoint || no.neg_endpoint || cilen < CILEN_CHAR) - goto bad; - break; - default: - break; - } - p = next; + case CI_SSNHF: + if (go->neg_ssnhf || no.neg_ssnhf || cilen != CILEN_VOID) + goto bad; + try_.neg_ssnhf = 1; + break; + case CI_EPDISC: + if (go->neg_endpoint || no.neg_endpoint || cilen < CILEN_CHAR) + goto bad; + break; + default: + break; + } + p = next; } /* @@ -1558,15 +1558,15 @@ static int lcp_nakci(fsm *f, u_char *p, int len, int treat_as_reject) { * If there are any options left we ignore them. */ if (f->state != PPP_FSM_OPENED) { - if (looped_back) { - if (++try_.numloops >= pcb->settings.lcp_loopbackfail) { - ppp_notice("Serial line is looped back."); - pcb->err_code = PPPERR_LOOPBACK; - lcp_close(f->pcb, "Loopback detected"); - } - } else - try_.numloops = 0; - *go = try_; + if (looped_back) { + if (++try_.numloops >= pcb->settings.lcp_loopbackfail) { + ppp_notice("Serial line is looped back."); + pcb->err_code = PPPERR_LOOPBACK; + lcp_close(f->pcb, "Loopback detected"); + } + } else + try_.numloops = 0; + *go = try_; } return 1; @@ -1583,8 +1583,8 @@ bad: * or if LCP is in the OPENED state. * * Returns: - * 0 - Reject was bad. - * 1 - Reject was good. + * 0 - Reject was bad. + * 1 - Reject was good. */ static int lcp_rejci(fsm *f, u_char *p, int len) { ppp_pcb *pcb = f->pcb; @@ -1592,7 +1592,7 @@ static int lcp_rejci(fsm *f, u_char *p, int len) { u_char cichar; u_short cishort; u32_t cilong; - lcp_options try_; /* options to request next time */ + lcp_options try_; /* options to request next time */ try_ = *go; @@ -1603,157 +1603,157 @@ static int lcp_rejci(fsm *f, u_char *p, int len) { */ #define REJCIVOID(opt, neg) \ if (go->neg && \ - len >= CILEN_VOID && \ - p[1] == CILEN_VOID && \ - p[0] == opt) { \ - len -= CILEN_VOID; \ - INCPTR(CILEN_VOID, p); \ - try_.neg = 0; \ + len >= CILEN_VOID && \ + p[1] == CILEN_VOID && \ + p[0] == opt) { \ + len -= CILEN_VOID; \ + INCPTR(CILEN_VOID, p); \ + try_.neg = 0; \ } #define REJCISHORT(opt, neg, val) \ if (go->neg && \ - len >= CILEN_SHORT && \ - p[1] == CILEN_SHORT && \ - p[0] == opt) { \ - len -= CILEN_SHORT; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - /* Check rejected value. */ \ - if (cishort != val) \ - goto bad; \ - try_.neg = 0; \ + len >= CILEN_SHORT && \ + p[1] == CILEN_SHORT && \ + p[0] == opt) { \ + len -= CILEN_SHORT; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + /* Check rejected value. */ \ + if (cishort != val) \ + goto bad; \ + try_.neg = 0; \ } #if CHAP_SUPPORT && EAP_SUPPORT && PAP_SUPPORT #define REJCICHAP(opt, neg, val) \ if (go->neg && \ - len >= CILEN_CHAP && \ - p[1] == CILEN_CHAP && \ - p[0] == opt) { \ - len -= CILEN_CHAP; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - GETCHAR(cichar, p); \ - /* Check rejected value. */ \ - if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ - goto bad; \ - try_.neg = 0; \ - try_.neg_eap = try_.neg_upap = 0; \ + len >= CILEN_CHAP && \ + p[1] == CILEN_CHAP && \ + p[0] == opt) { \ + len -= CILEN_CHAP; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETCHAR(cichar, p); \ + /* Check rejected value. */ \ + if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ + goto bad; \ + try_.neg = 0; \ + try_.neg_eap = try_.neg_upap = 0; \ } #endif /* CHAP_SUPPORT && EAP_SUPPORT && PAP_SUPPORT */ #if CHAP_SUPPORT && !EAP_SUPPORT && PAP_SUPPORT #define REJCICHAP(opt, neg, val) \ if (go->neg && \ - len >= CILEN_CHAP && \ - p[1] == CILEN_CHAP && \ - p[0] == opt) { \ - len -= CILEN_CHAP; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - GETCHAR(cichar, p); \ - /* Check rejected value. */ \ - if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ - goto bad; \ - try_.neg = 0; \ - try_.neg_upap = 0; \ + len >= CILEN_CHAP && \ + p[1] == CILEN_CHAP && \ + p[0] == opt) { \ + len -= CILEN_CHAP; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETCHAR(cichar, p); \ + /* Check rejected value. */ \ + if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ + goto bad; \ + try_.neg = 0; \ + try_.neg_upap = 0; \ } #endif /* CHAP_SUPPORT && !EAP_SUPPORT && PAP_SUPPORT */ #if CHAP_SUPPORT && EAP_SUPPORT && !PAP_SUPPORT #define REJCICHAP(opt, neg, val) \ if (go->neg && \ - len >= CILEN_CHAP && \ - p[1] == CILEN_CHAP && \ - p[0] == opt) { \ - len -= CILEN_CHAP; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - GETCHAR(cichar, p); \ - /* Check rejected value. */ \ - if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ - goto bad; \ - try_.neg = 0; \ - try_.neg_eap = 0; \ + len >= CILEN_CHAP && \ + p[1] == CILEN_CHAP && \ + p[0] == opt) { \ + len -= CILEN_CHAP; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETCHAR(cichar, p); \ + /* Check rejected value. */ \ + if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ + goto bad; \ + try_.neg = 0; \ + try_.neg_eap = 0; \ } #endif /* CHAP_SUPPORT && EAP_SUPPORT && !PAP_SUPPORT */ #if CHAP_SUPPORT && !EAP_SUPPORT && !PAP_SUPPORT #define REJCICHAP(opt, neg, val) \ if (go->neg && \ - len >= CILEN_CHAP && \ - p[1] == CILEN_CHAP && \ - p[0] == opt) { \ - len -= CILEN_CHAP; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - GETCHAR(cichar, p); \ - /* Check rejected value. */ \ - if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ - goto bad; \ - try_.neg = 0; \ + len >= CILEN_CHAP && \ + p[1] == CILEN_CHAP && \ + p[0] == opt) { \ + len -= CILEN_CHAP; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETCHAR(cichar, p); \ + /* Check rejected value. */ \ + if ((cishort != PPP_CHAP) || (cichar != (CHAP_DIGEST(val)))) \ + goto bad; \ + try_.neg = 0; \ } #endif /* CHAP_SUPPORT && !EAP_SUPPORT && !PAP_SUPPORT */ #define REJCILONG(opt, neg, val) \ if (go->neg && \ - len >= CILEN_LONG && \ - p[1] == CILEN_LONG && \ - p[0] == opt) { \ - len -= CILEN_LONG; \ - INCPTR(2, p); \ - GETLONG(cilong, p); \ - /* Check rejected value. */ \ - if (cilong != val) \ - goto bad; \ - try_.neg = 0; \ + len >= CILEN_LONG && \ + p[1] == CILEN_LONG && \ + p[0] == opt) { \ + len -= CILEN_LONG; \ + INCPTR(2, p); \ + GETLONG(cilong, p); \ + /* Check rejected value. */ \ + if (cilong != val) \ + goto bad; \ + try_.neg = 0; \ } #if LQR_SUPPORT #define REJCILQR(opt, neg, val) \ if (go->neg && \ - len >= CILEN_LQR && \ - p[1] == CILEN_LQR && \ - p[0] == opt) { \ - len -= CILEN_LQR; \ - INCPTR(2, p); \ - GETSHORT(cishort, p); \ - GETLONG(cilong, p); \ - /* Check rejected value. */ \ - if (cishort != PPP_LQR || cilong != val) \ - goto bad; \ - try_.neg = 0; \ + len >= CILEN_LQR && \ + p[1] == CILEN_LQR && \ + p[0] == opt) { \ + len -= CILEN_LQR; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETLONG(cilong, p); \ + /* Check rejected value. */ \ + if (cishort != PPP_LQR || cilong != val) \ + goto bad; \ + try_.neg = 0; \ } #endif /* LQR_SUPPORT */ #define REJCICBCP(opt, neg, val) \ if (go->neg && \ - len >= CILEN_CBCP && \ - p[1] == CILEN_CBCP && \ - p[0] == opt) { \ - len -= CILEN_CBCP; \ - INCPTR(2, p); \ - GETCHAR(cichar, p); \ - /* Check rejected value. */ \ - if (cichar != val) \ - goto bad; \ - try_.neg = 0; \ + len >= CILEN_CBCP && \ + p[1] == CILEN_CBCP && \ + p[0] == opt) { \ + len -= CILEN_CBCP; \ + INCPTR(2, p); \ + GETCHAR(cichar, p); \ + /* Check rejected value. */ \ + if (cichar != val) \ + goto bad; \ + try_.neg = 0; \ } #define REJCIENDP(opt, neg, class, val, vlen) \ if (go->neg && \ - len >= CILEN_CHAR + vlen && \ - p[0] == opt && \ - p[1] == CILEN_CHAR + vlen) { \ - int i; \ - len -= CILEN_CHAR + vlen; \ - INCPTR(2, p); \ - GETCHAR(cichar, p); \ - if (cichar != class) \ - goto bad; \ - for (i = 0; i < vlen; ++i) { \ - GETCHAR(cichar, p); \ - if (cichar != val[i]) \ - goto bad; \ - } \ - try_.neg = 0; \ + len >= CILEN_CHAR + vlen && \ + p[0] == opt && \ + p[1] == CILEN_CHAR + vlen) { \ + int i; \ + len -= CILEN_CHAR + vlen; \ + INCPTR(2, p); \ + GETCHAR(cichar, p); \ + if (cichar != class) \ + goto bad; \ + for (i = 0; i < vlen; ++i) { \ + GETCHAR(cichar, p); \ + if (cichar != val[i]) \ + goto bad; \ + } \ + try_.neg = 0; \ } REJCISHORT(CI_MRU, neg_mru, go->mru); @@ -1763,14 +1763,14 @@ static int lcp_rejci(fsm *f, u_char *p, int len) { if (!go->neg_eap) { #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT - REJCICHAP(CI_AUTHTYPE, neg_chap, go->chap_mdtype); - if (!go->neg_chap) { + REJCICHAP(CI_AUTHTYPE, neg_chap, go->chap_mdtype); + if (!go->neg_chap) { #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - REJCISHORT(CI_AUTHTYPE, neg_upap, PPP_PAP); + REJCISHORT(CI_AUTHTYPE, neg_upap, PPP_PAP); #endif /* PAP_SUPPORT */ #if CHAP_SUPPORT - } + } #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT } @@ -1787,18 +1787,18 @@ static int lcp_rejci(fsm *f, u_char *p, int len) { #endif /* HAVE_MULTILINK */ REJCIVOID(CI_SSNHF, neg_ssnhf); REJCIENDP(CI_EPDISC, neg_endpoint, go->endpoint.class_, - go->endpoint.value, go->endpoint.length); + go->endpoint.value, go->endpoint.length); /* * If there are any remaining CIs, then this packet is bad. */ if (len != 0) - goto bad; + goto bad; /* * Now we can update state. */ if (f->state != PPP_FSM_OPENED) - *go = try_; + *go = try_; return 1; bad: @@ -1822,17 +1822,17 @@ static int lcp_reqci(fsm *f, u_char *inp, int *lenp, int reject_if_disagree) { lcp_options *go = &pcb->lcp_gotoptions; lcp_options *ho = &pcb->lcp_hisoptions; lcp_options *ao = &pcb->lcp_allowoptions; - u_char *cip, *next; /* Pointer to current and next CIs */ - int cilen, citype, cichar; /* Parsed len, type, char value */ - u_short cishort; /* Parsed short value */ - u32_t cilong; /* Parse long value */ - int rc = CONFACK; /* Final packet return code */ - int orc; /* Individual option return code */ - u_char *p; /* Pointer to next char to parse */ - u_char *rejp; /* Pointer to next char in reject frame */ + u_char *cip, *next; /* Pointer to current and next CIs */ + int cilen, citype, cichar; /* Parsed len, type, char value */ + u_short cishort; /* Parsed short value */ + u32_t cilong; /* Parse long value */ + int rc = CONFACK; /* Final packet return code */ + int orc; /* Individual option return code */ + u_char *p; /* Pointer to next char to parse */ + u_char *rejp; /* Pointer to next char in reject frame */ struct pbuf *nakp; /* Nak buffer */ - u_char *nakoutp; /* Pointer to next char in Nak frame */ - int l = *lenp; /* Length left */ + u_char *nakoutp; /* Pointer to next char in Nak frame */ + int l = *lenp; /* Length left */ /* * Reset all his options. @@ -1854,403 +1854,403 @@ static int lcp_reqci(fsm *f, u_char *inp, int *lenp, int reject_if_disagree) { nakoutp = (u_char*)nakp->payload; rejp = inp; while (l) { - orc = CONFACK; /* Assume success */ - cip = p = next; /* Remember begining of CI */ - if (l < 2 || /* Not enough data for CI header or */ - p[1] < 2 || /* CI length too small or */ - p[1] > l) { /* CI length too big? */ - LCPDEBUG(("lcp_reqci: bad CI length!")); - orc = CONFREJ; /* Reject bad CI */ - cilen = l; /* Reject till end of packet */ - l = 0; /* Don't loop again */ - citype = 0; - goto endswitch; - } - GETCHAR(citype, p); /* Parse CI type */ - GETCHAR(cilen, p); /* Parse CI length */ - l -= cilen; /* Adjust remaining length */ - next += cilen; /* Step to next CI */ + orc = CONFACK; /* Assume success */ + cip = p = next; /* Remember begining of CI */ + if (l < 2 || /* Not enough data for CI header or */ + p[1] < 2 || /* CI length too small or */ + p[1] > l) { /* CI length too big? */ + LCPDEBUG(("lcp_reqci: bad CI length!")); + orc = CONFREJ; /* Reject bad CI */ + cilen = l; /* Reject till end of packet */ + l = 0; /* Don't loop again */ + citype = 0; + goto endswitch; + } + GETCHAR(citype, p); /* Parse CI type */ + GETCHAR(cilen, p); /* Parse CI length */ + l -= cilen; /* Adjust remaining length */ + next += cilen; /* Step to next CI */ - switch (citype) { /* Check CI type */ - case CI_MRU: - if (!ao->neg_mru || /* Allow option? */ - cilen != CILEN_SHORT) { /* Check CI length */ - orc = CONFREJ; /* Reject CI */ - break; - } - GETSHORT(cishort, p); /* Parse MRU */ + switch (citype) { /* Check CI type */ + case CI_MRU: + if (!ao->neg_mru || /* Allow option? */ + cilen != CILEN_SHORT) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } + GETSHORT(cishort, p); /* Parse MRU */ - /* - * He must be able to receive at least our minimum. - * No need to check a maximum. If he sends a large number, - * we'll just ignore it. - */ - if (cishort < PPP_MINMRU) { - orc = CONFNAK; /* Nak CI */ - PUTCHAR(CI_MRU, nakoutp); - PUTCHAR(CILEN_SHORT, nakoutp); - PUTSHORT(PPP_MINMRU, nakoutp); /* Give him a hint */ - break; - } - ho->neg_mru = 1; /* Remember he sent MRU */ - ho->mru = cishort; /* And remember value */ - break; + /* + * He must be able to receive at least our minimum. + * No need to check a maximum. If he sends a large number, + * we'll just ignore it. + */ + if (cishort < PPP_MINMRU) { + orc = CONFNAK; /* Nak CI */ + PUTCHAR(CI_MRU, nakoutp); + PUTCHAR(CILEN_SHORT, nakoutp); + PUTSHORT(PPP_MINMRU, nakoutp); /* Give him a hint */ + break; + } + ho->neg_mru = 1; /* Remember he sent MRU */ + ho->mru = cishort; /* And remember value */ + break; - case CI_ASYNCMAP: - if (!ao->neg_asyncmap || - cilen != CILEN_LONG) { - orc = CONFREJ; - break; - } - GETLONG(cilong, p); + case CI_ASYNCMAP: + if (!ao->neg_asyncmap || + cilen != CILEN_LONG) { + orc = CONFREJ; + break; + } + GETLONG(cilong, p); - /* - * Asyncmap must have set at least the bits - * which are set in lcp_allowoptions[unit].asyncmap. - */ - if ((ao->asyncmap & ~cilong) != 0) { - orc = CONFNAK; - PUTCHAR(CI_ASYNCMAP, nakoutp); - PUTCHAR(CILEN_LONG, nakoutp); - PUTLONG(ao->asyncmap | cilong, nakoutp); - break; - } - ho->neg_asyncmap = 1; - ho->asyncmap = cilong; - break; + /* + * Asyncmap must have set at least the bits + * which are set in lcp_allowoptions[unit].asyncmap. + */ + if ((ao->asyncmap & ~cilong) != 0) { + orc = CONFNAK; + PUTCHAR(CI_ASYNCMAP, nakoutp); + PUTCHAR(CILEN_LONG, nakoutp); + PUTLONG(ao->asyncmap | cilong, nakoutp); + break; + } + ho->neg_asyncmap = 1; + ho->asyncmap = cilong; + break; - case CI_AUTHTYPE: - if (cilen < CILEN_SHORT || - !(0 + case CI_AUTHTYPE: + if (cilen < CILEN_SHORT || + !(0 #if PAP_SUPPORT - || ao->neg_upap + || ao->neg_upap #endif /* PAP_SUPPORT */ #if CHAP_SUPPORT - || ao->neg_chap + || ao->neg_chap #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT - || ao->neg_eap + || ao->neg_eap #endif /* EAP_SUPPORT */ - )) { - /* - * Reject the option if we're not willing to authenticate. - */ - ppp_dbglog("No auth is possible"); - orc = CONFREJ; - break; - } - GETSHORT(cishort, p); + )) { + /* + * Reject the option if we're not willing to authenticate. + */ + ppp_dbglog("No auth is possible"); + orc = CONFREJ; + break; + } + GETSHORT(cishort, p); - /* - * Authtype must be PAP, CHAP, or EAP. - * - * Note: if more than one of ao->neg_upap, ao->neg_chap, and - * ao->neg_eap are set, and the peer sends a Configure-Request - * with two or more authenticate-protocol requests, then we will - * reject the second request. - * Whether we end up doing CHAP, UPAP, or EAP depends then on - * the ordering of the CIs in the peer's Configure-Request. + /* + * Authtype must be PAP, CHAP, or EAP. + * + * Note: if more than one of ao->neg_upap, ao->neg_chap, and + * ao->neg_eap are set, and the peer sends a Configure-Request + * with two or more authenticate-protocol requests, then we will + * reject the second request. + * Whether we end up doing CHAP, UPAP, or EAP depends then on + * the ordering of the CIs in the peer's Configure-Request. */ #if PAP_SUPPORT - if (cishort == PPP_PAP) { - /* we've already accepted CHAP or EAP */ - if (0 + if (cishort == PPP_PAP) { + /* we've already accepted CHAP or EAP */ + if (0 #if CHAP_SUPPORT - || ho->neg_chap + || ho->neg_chap #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT - || ho->neg_eap + || ho->neg_eap #endif /* EAP_SUPPORT */ - || cilen != CILEN_SHORT) { - LCPDEBUG(("lcp_reqci: rcvd AUTHTYPE PAP, rejecting...")); - orc = CONFREJ; - break; - } - if (!ao->neg_upap) { /* we don't want to do PAP */ - orc = CONFNAK; /* NAK it and suggest CHAP or EAP */ - PUTCHAR(CI_AUTHTYPE, nakoutp); + || cilen != CILEN_SHORT) { + LCPDEBUG(("lcp_reqci: rcvd AUTHTYPE PAP, rejecting...")); + orc = CONFREJ; + break; + } + if (!ao->neg_upap) { /* we don't want to do PAP */ + orc = CONFNAK; /* NAK it and suggest CHAP or EAP */ + PUTCHAR(CI_AUTHTYPE, nakoutp); #if EAP_SUPPORT - if (ao->neg_eap) { - PUTCHAR(CILEN_SHORT, nakoutp); - PUTSHORT(PPP_EAP, nakoutp); - } else { + if (ao->neg_eap) { + PUTCHAR(CILEN_SHORT, nakoutp); + PUTSHORT(PPP_EAP, nakoutp); + } else { #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT - PUTCHAR(CILEN_CHAP, nakoutp); - PUTSHORT(PPP_CHAP, nakoutp); - PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); + PUTCHAR(CILEN_CHAP, nakoutp); + PUTSHORT(PPP_CHAP, nakoutp); + PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT - } + } #endif /* EAP_SUPPORT */ - break; - } - ho->neg_upap = 1; - break; - } + break; + } + ho->neg_upap = 1; + break; + } #endif /* PAP_SUPPORT */ #if CHAP_SUPPORT - if (cishort == PPP_CHAP) { - /* we've already accepted PAP or EAP */ - if ( + if (cishort == PPP_CHAP) { + /* we've already accepted PAP or EAP */ + if ( #if PAP_SUPPORT - ho->neg_upap || + ho->neg_upap || #endif /* PAP_SUPPORT */ #if EAP_SUPPORT - ho->neg_eap || + ho->neg_eap || #endif /* EAP_SUPPORT */ - cilen != CILEN_CHAP) { - LCPDEBUG(("lcp_reqci: rcvd AUTHTYPE CHAP, rejecting...")); - orc = CONFREJ; - break; - } - if (!ao->neg_chap) { /* we don't want to do CHAP */ - orc = CONFNAK; /* NAK it and suggest EAP or PAP */ - PUTCHAR(CI_AUTHTYPE, nakoutp); - PUTCHAR(CILEN_SHORT, nakoutp); + cilen != CILEN_CHAP) { + LCPDEBUG(("lcp_reqci: rcvd AUTHTYPE CHAP, rejecting...")); + orc = CONFREJ; + break; + } + if (!ao->neg_chap) { /* we don't want to do CHAP */ + orc = CONFNAK; /* NAK it and suggest EAP or PAP */ + PUTCHAR(CI_AUTHTYPE, nakoutp); + PUTCHAR(CILEN_SHORT, nakoutp); #if EAP_SUPPORT - if (ao->neg_eap) { - PUTSHORT(PPP_EAP, nakoutp); - } else + if (ao->neg_eap) { + PUTSHORT(PPP_EAP, nakoutp); + } else #endif /* EAP_SUPPORT */ #if PAP_SUPPORT - if(1) { - PUTSHORT(PPP_PAP, nakoutp); - } - else + if(1) { + PUTSHORT(PPP_PAP, nakoutp); + } + else #endif /* PAP_SUPPORT */ - {} - break; - } - GETCHAR(cichar, p); /* get digest type */ - if (!(CHAP_CANDIGEST(ao->chap_mdtype, cichar))) { - /* - * We can't/won't do the requested type, - * suggest something else. - */ - orc = CONFNAK; - PUTCHAR(CI_AUTHTYPE, nakoutp); - PUTCHAR(CILEN_CHAP, nakoutp); - PUTSHORT(PPP_CHAP, nakoutp); - PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); - break; - } - ho->chap_mdtype = CHAP_MDTYPE_D(cichar); /* save md type */ - ho->neg_chap = 1; - break; - } + {} + break; + } + GETCHAR(cichar, p); /* get digest type */ + if (!(CHAP_CANDIGEST(ao->chap_mdtype, cichar))) { + /* + * We can't/won't do the requested type, + * suggest something else. + */ + orc = CONFNAK; + PUTCHAR(CI_AUTHTYPE, nakoutp); + PUTCHAR(CILEN_CHAP, nakoutp); + PUTSHORT(PPP_CHAP, nakoutp); + PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); + break; + } + ho->chap_mdtype = CHAP_MDTYPE_D(cichar); /* save md type */ + ho->neg_chap = 1; + break; + } #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT - if (cishort == PPP_EAP) { - /* we've already accepted CHAP or PAP */ - if ( + if (cishort == PPP_EAP) { + /* we've already accepted CHAP or PAP */ + if ( #if CHAP_SUPPORT - ho->neg_chap || + ho->neg_chap || #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - ho->neg_upap || + ho->neg_upap || #endif /* PAP_SUPPORT */ - cilen != CILEN_SHORT) { - LCPDEBUG(("lcp_reqci: rcvd AUTHTYPE EAP, rejecting...")); - orc = CONFREJ; - break; - } - if (!ao->neg_eap) { /* we don't want to do EAP */ - orc = CONFNAK; /* NAK it and suggest CHAP or PAP */ - PUTCHAR(CI_AUTHTYPE, nakoutp); + cilen != CILEN_SHORT) { + LCPDEBUG(("lcp_reqci: rcvd AUTHTYPE EAP, rejecting...")); + orc = CONFREJ; + break; + } + if (!ao->neg_eap) { /* we don't want to do EAP */ + orc = CONFNAK; /* NAK it and suggest CHAP or PAP */ + PUTCHAR(CI_AUTHTYPE, nakoutp); #if CHAP_SUPPORT - if (ao->neg_chap) { - PUTCHAR(CILEN_CHAP, nakoutp); - PUTSHORT(PPP_CHAP, nakoutp); - PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); - } else + if (ao->neg_chap) { + PUTCHAR(CILEN_CHAP, nakoutp); + PUTSHORT(PPP_CHAP, nakoutp); + PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); + } else #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - if(1) { - PUTCHAR(CILEN_SHORT, nakoutp); - PUTSHORT(PPP_PAP, nakoutp); - } else + if(1) { + PUTCHAR(CILEN_SHORT, nakoutp); + PUTSHORT(PPP_PAP, nakoutp); + } else #endif /* PAP_SUPPORT */ - {} - break; - } - ho->neg_eap = 1; - break; - } + {} + break; + } + ho->neg_eap = 1; + break; + } #endif /* EAP_SUPPORT */ - /* - * We don't recognize the protocol they're asking for. - * Nak it with something we're willing to do. - * (At this point we know ao->neg_upap || ao->neg_chap || - * ao->neg_eap.) - */ - orc = CONFNAK; - PUTCHAR(CI_AUTHTYPE, nakoutp); + /* + * We don't recognize the protocol they're asking for. + * Nak it with something we're willing to do. + * (At this point we know ao->neg_upap || ao->neg_chap || + * ao->neg_eap.) + */ + orc = CONFNAK; + PUTCHAR(CI_AUTHTYPE, nakoutp); #if EAP_SUPPORT - if (ao->neg_eap) { - PUTCHAR(CILEN_SHORT, nakoutp); - PUTSHORT(PPP_EAP, nakoutp); - } else + if (ao->neg_eap) { + PUTCHAR(CILEN_SHORT, nakoutp); + PUTSHORT(PPP_EAP, nakoutp); + } else #endif /* EAP_SUPPORT */ #if CHAP_SUPPORT - if (ao->neg_chap) { - PUTCHAR(CILEN_CHAP, nakoutp); - PUTSHORT(PPP_CHAP, nakoutp); - PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); - } else + if (ao->neg_chap) { + PUTCHAR(CILEN_CHAP, nakoutp); + PUTSHORT(PPP_CHAP, nakoutp); + PUTCHAR(CHAP_DIGEST(ao->chap_mdtype), nakoutp); + } else #endif /* CHAP_SUPPORT */ #if PAP_SUPPORT - if(1) { - PUTCHAR(CILEN_SHORT, nakoutp); - PUTSHORT(PPP_PAP, nakoutp); - } else + if(1) { + PUTCHAR(CILEN_SHORT, nakoutp); + PUTSHORT(PPP_PAP, nakoutp); + } else #endif /* PAP_SUPPORT */ - {} - break; + {} + break; #if LQR_SUPPORT - case CI_QUALITY: - if (!ao->neg_lqr || - cilen != CILEN_LQR) { - orc = CONFREJ; - break; - } + case CI_QUALITY: + if (!ao->neg_lqr || + cilen != CILEN_LQR) { + orc = CONFREJ; + break; + } - GETSHORT(cishort, p); - GETLONG(cilong, p); + GETSHORT(cishort, p); + GETLONG(cilong, p); - /* - * Check the protocol and the reporting period. - * XXX When should we Nak this, and what with? - */ - if (cishort != PPP_LQR) { - orc = CONFNAK; - PUTCHAR(CI_QUALITY, nakoutp); - PUTCHAR(CILEN_LQR, nakoutp); - PUTSHORT(PPP_LQR, nakoutp); - PUTLONG(ao->lqr_period, nakoutp); - break; - } - break; + /* + * Check the protocol and the reporting period. + * XXX When should we Nak this, and what with? + */ + if (cishort != PPP_LQR) { + orc = CONFNAK; + PUTCHAR(CI_QUALITY, nakoutp); + PUTCHAR(CILEN_LQR, nakoutp); + PUTSHORT(PPP_LQR, nakoutp); + PUTLONG(ao->lqr_period, nakoutp); + break; + } + break; #endif /* LQR_SUPPORT */ - case CI_MAGICNUMBER: - if (!(ao->neg_magicnumber || go->neg_magicnumber) || - cilen != CILEN_LONG) { - orc = CONFREJ; - break; - } - GETLONG(cilong, p); + case CI_MAGICNUMBER: + if (!(ao->neg_magicnumber || go->neg_magicnumber) || + cilen != CILEN_LONG) { + orc = CONFREJ; + break; + } + GETLONG(cilong, p); - /* - * He must have a different magic number. - */ - if (go->neg_magicnumber && - cilong == go->magicnumber) { - cilong = magic(); /* Don't put magic() inside macro! */ - orc = CONFNAK; - PUTCHAR(CI_MAGICNUMBER, nakoutp); - PUTCHAR(CILEN_LONG, nakoutp); - PUTLONG(cilong, nakoutp); - break; - } - ho->neg_magicnumber = 1; - ho->magicnumber = cilong; - break; + /* + * He must have a different magic number. + */ + if (go->neg_magicnumber && + cilong == go->magicnumber) { + cilong = magic(); /* Don't put magic() inside macro! */ + orc = CONFNAK; + PUTCHAR(CI_MAGICNUMBER, nakoutp); + PUTCHAR(CILEN_LONG, nakoutp); + PUTLONG(cilong, nakoutp); + break; + } + ho->neg_magicnumber = 1; + ho->magicnumber = cilong; + break; - case CI_PCOMPRESSION: - if (!ao->neg_pcompression || - cilen != CILEN_VOID) { - orc = CONFREJ; - break; - } - ho->neg_pcompression = 1; - break; + case CI_PCOMPRESSION: + if (!ao->neg_pcompression || + cilen != CILEN_VOID) { + orc = CONFREJ; + break; + } + ho->neg_pcompression = 1; + break; - case CI_ACCOMPRESSION: - if (!ao->neg_accompression || - cilen != CILEN_VOID) { - orc = CONFREJ; - break; - } - ho->neg_accompression = 1; - break; + case CI_ACCOMPRESSION: + if (!ao->neg_accompression || + cilen != CILEN_VOID) { + orc = CONFREJ; + break; + } + ho->neg_accompression = 1; + break; #ifdef HAVE_MULTILINK - case CI_MRRU: - if (!ao->neg_mrru - || !multilink - || cilen != CILEN_SHORT) { - orc = CONFREJ; - break; - } + case CI_MRRU: + if (!ao->neg_mrru + || !multilink + || cilen != CILEN_SHORT) { + orc = CONFREJ; + break; + } - GETSHORT(cishort, p); - /* possibly should insist on a minimum/maximum MRRU here */ - ho->neg_mrru = 1; - ho->mrru = cishort; - break; + GETSHORT(cishort, p); + /* possibly should insist on a minimum/maximum MRRU here */ + ho->neg_mrru = 1; + ho->mrru = cishort; + break; #endif /* HAVE_MULTILINK */ - case CI_SSNHF: - if (!ao->neg_ssnhf + case CI_SSNHF: + if (!ao->neg_ssnhf #ifdef HAVE_MULTILINK - || !multilink + || !multilink #endif /* HAVE_MULTILINK */ - || cilen != CILEN_VOID) { - orc = CONFREJ; - break; - } - ho->neg_ssnhf = 1; - break; + || cilen != CILEN_VOID) { + orc = CONFREJ; + break; + } + ho->neg_ssnhf = 1; + break; - case CI_EPDISC: - if (!ao->neg_endpoint || - cilen < CILEN_CHAR || - cilen > CILEN_CHAR + MAX_ENDP_LEN) { - orc = CONFREJ; - break; - } - GETCHAR(cichar, p); - cilen -= CILEN_CHAR; - ho->neg_endpoint = 1; - ho->endpoint.class_ = cichar; - ho->endpoint.length = cilen; - MEMCPY(ho->endpoint.value, p, cilen); - INCPTR(cilen, p); - break; + case CI_EPDISC: + if (!ao->neg_endpoint || + cilen < CILEN_CHAR || + cilen > CILEN_CHAR + MAX_ENDP_LEN) { + orc = CONFREJ; + break; + } + GETCHAR(cichar, p); + cilen -= CILEN_CHAR; + ho->neg_endpoint = 1; + ho->endpoint.class_ = cichar; + ho->endpoint.length = cilen; + MEMCPY(ho->endpoint.value, p, cilen); + INCPTR(cilen, p); + break; - default: - LCPDEBUG(("lcp_reqci: rcvd unknown option %d", citype)); - orc = CONFREJ; - break; - } + default: + LCPDEBUG(("lcp_reqci: rcvd unknown option %d", citype)); + orc = CONFREJ; + break; + } endswitch: - if (orc == CONFACK && /* Good CI */ - rc != CONFACK) /* but prior CI wasnt? */ - continue; /* Don't send this one */ + if (orc == CONFACK && /* Good CI */ + rc != CONFACK) /* but prior CI wasnt? */ + continue; /* Don't send this one */ - if (orc == CONFNAK) { /* Nak this CI? */ - if (reject_if_disagree /* Getting fed up with sending NAKs? */ - && citype != CI_MAGICNUMBER) { - orc = CONFREJ; /* Get tough if so */ - } else { - if (rc == CONFREJ) /* Rejecting prior CI? */ - continue; /* Don't send this one */ - rc = CONFNAK; - } - } - if (orc == CONFREJ) { /* Reject this CI */ - rc = CONFREJ; - if (cip != rejp) /* Need to move rejected CI? */ - MEMCPY(rejp, cip, cilen); /* Move it */ - INCPTR(cilen, rejp); /* Update output pointer */ - } + if (orc == CONFNAK) { /* Nak this CI? */ + if (reject_if_disagree /* Getting fed up with sending NAKs? */ + && citype != CI_MAGICNUMBER) { + orc = CONFREJ; /* Get tough if so */ + } else { + if (rc == CONFREJ) /* Rejecting prior CI? */ + continue; /* Don't send this one */ + rc = CONFNAK; + } + } + if (orc == CONFREJ) { /* Reject this CI */ + rc = CONFREJ; + if (cip != rejp) /* Need to move rejected CI? */ + MEMCPY(rejp, cip, cilen); /* Move it */ + INCPTR(cilen, rejp); /* Update output pointer */ + } } /* @@ -2262,25 +2262,25 @@ endswitch: switch (rc) { case CONFACK: - *lenp = next - inp; - break; + *lenp = next - inp; + break; case CONFNAK: - /* - * Copy the Nak'd options from the nak buffer to the caller's buffer. - */ - *lenp = nakoutp - (u_char*)nakp->payload; - MEMCPY(inp, nakp->payload, *lenp); - break; + /* + * Copy the Nak'd options from the nak buffer to the caller's buffer. + */ + *lenp = nakoutp - (u_char*)nakp->payload; + MEMCPY(inp, nakp->payload, *lenp); + break; case CONFREJ: - *lenp = rejp - inp; - break; + *lenp = rejp - inp; + break; default: - break; + break; } pbuf_free(nakp); LCPDEBUG(("lcp_reqci: returning CONF%s.", CODENAME(rc))); - return (rc); /* Return final code */ + return (rc); /* Return final code */ } @@ -2296,9 +2296,9 @@ static void lcp_up(fsm *f) { int mtu, mru; if (!go->neg_magicnumber) - go->magicnumber = 0; + go->magicnumber = 0; if (!ho->neg_magicnumber) - ho->magicnumber = 0; + ho->magicnumber = 0; /* * Set our MTU to the smaller of the MTU we wanted and @@ -2314,16 +2314,16 @@ static void lcp_up(fsm *f) { #ifdef HAVE_MULTILINK if (!(multilink && go->neg_mrru && ho->neg_mrru)) #endif /* HAVE_MULTILINK */ - netif_set_mtu(pcb, LWIP_MIN(LWIP_MIN(mtu, mru), ao->mru)); + netif_set_mtu(pcb, LWIP_MIN(LWIP_MIN(mtu, mru), ao->mru)); ppp_send_config(pcb, mtu, - (ho->neg_asyncmap? ho->asyncmap: 0xffffffff), - ho->neg_pcompression, ho->neg_accompression); + (ho->neg_asyncmap? ho->asyncmap: 0xffffffff), + ho->neg_pcompression, ho->neg_accompression); ppp_recv_config(pcb, mru, - (pcb->settings.lax_recv? 0: go->neg_asyncmap? go->asyncmap: 0xffffffff), - go->neg_pcompression, go->neg_accompression); + (pcb->settings.lax_recv? 0: go->neg_asyncmap? go->asyncmap: 0xffffffff), + go->neg_pcompression, go->neg_accompression); if (ho->neg_mru) - pcb->peer_mru = ho->mru; + pcb->peer_mru = ho->mru; lcp_echo_lowerup(f->pcb); /* Enable echo messages */ @@ -2346,8 +2346,8 @@ static void lcp_down(fsm *f) { ppp_send_config(pcb, PPP_MRU, 0xffffffff, 0, 0); ppp_recv_config(pcb, PPP_MRU, - (go->neg_asyncmap? go->asyncmap: 0xffffffff), - go->neg_pcompression, go->neg_accompression); + (go->neg_asyncmap? go->asyncmap: 0xffffffff), + go->neg_pcompression, go->neg_accompression); pcb->peer_mru = PPP_MRU; } @@ -2382,25 +2382,25 @@ static const char* const lcp_codenames[] = { }; static int lcp_printpkt(const u_char *p, int plen, - void (*printer) (void *, const char *, ...), void *arg) { + void (*printer) (void *, const char *, ...), void *arg) { int code, id, len, olen, i; const u_char *pstart, *optend; u_short cishort; u32_t cilong; if (plen < HEADERLEN) - return 0; + return 0; pstart = p; GETCHAR(code, p); GETCHAR(id, p); GETSHORT(len, p); if (len < HEADERLEN || len > plen) - return 0; + return 0; if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(lcp_codenames)) - printer(arg, " %s", lcp_codenames[code-1]); + printer(arg, " %s", lcp_codenames[code-1]); else - printer(arg, " code=0x%x", code); + printer(arg, " code=0x%x", code); printer(arg, " id=0x%x", id); len -= HEADERLEN; switch (code) { @@ -2408,224 +2408,224 @@ static int lcp_printpkt(const u_char *p, int plen, case CONFACK: case CONFNAK: case CONFREJ: - /* print option list */ - while (len >= 2) { - GETCHAR(code, p); - GETCHAR(olen, p); - p -= 2; - if (olen < 2 || olen > len) { - break; - } - printer(arg, " <"); - len -= olen; - optend = p + olen; - switch (code) { - case CI_MRU: - if (olen == CILEN_SHORT) { - p += 2; - GETSHORT(cishort, p); - printer(arg, "mru %d", cishort); - } - break; - case CI_ASYNCMAP: - if (olen == CILEN_LONG) { - p += 2; - GETLONG(cilong, p); - printer(arg, "asyncmap 0x%x", cilong); - } - break; - case CI_AUTHTYPE: - if (olen >= CILEN_SHORT) { - p += 2; - printer(arg, "auth "); - GETSHORT(cishort, p); - switch (cishort) { + /* print option list */ + while (len >= 2) { + GETCHAR(code, p); + GETCHAR(olen, p); + p -= 2; + if (olen < 2 || olen > len) { + break; + } + printer(arg, " <"); + len -= olen; + optend = p + olen; + switch (code) { + case CI_MRU: + if (olen == CILEN_SHORT) { + p += 2; + GETSHORT(cishort, p); + printer(arg, "mru %d", cishort); + } + break; + case CI_ASYNCMAP: + if (olen == CILEN_LONG) { + p += 2; + GETLONG(cilong, p); + printer(arg, "asyncmap 0x%x", cilong); + } + break; + case CI_AUTHTYPE: + if (olen >= CILEN_SHORT) { + p += 2; + printer(arg, "auth "); + GETSHORT(cishort, p); + switch (cishort) { #if PAP_SUPPORT - case PPP_PAP: - printer(arg, "pap"); - break; + case PPP_PAP: + printer(arg, "pap"); + break; #endif /* PAP_SUPPORT */ #if CHAP_SUPPORT - case PPP_CHAP: - printer(arg, "chap"); - if (p < optend) { - switch (*p) { - case CHAP_MD5: - printer(arg, " MD5"); - ++p; - break; + case PPP_CHAP: + printer(arg, "chap"); + if (p < optend) { + switch (*p) { + case CHAP_MD5: + printer(arg, " MD5"); + ++p; + break; #if MSCHAP_SUPPORT - case CHAP_MICROSOFT: - printer(arg, " MS"); - ++p; - break; + case CHAP_MICROSOFT: + printer(arg, " MS"); + ++p; + break; - case CHAP_MICROSOFT_V2: - printer(arg, " MS-v2"); - ++p; - break; + case CHAP_MICROSOFT_V2: + printer(arg, " MS-v2"); + ++p; + break; #endif /* MSCHAP_SUPPORT */ - default: - break; - } - } - break; + default: + break; + } + } + break; #endif /* CHAP_SUPPORT */ #if EAP_SUPPORT - case PPP_EAP: - printer(arg, "eap"); - break; + case PPP_EAP: + printer(arg, "eap"); + break; #endif /* EAP_SUPPORT */ - default: - printer(arg, "0x%x", cishort); - } - } - break; + default: + printer(arg, "0x%x", cishort); + } + } + break; #if LQR_SUPPORT - case CI_QUALITY: - if (olen >= CILEN_SHORT) { - p += 2; - printer(arg, "quality "); - GETSHORT(cishort, p); - switch (cishort) { - case PPP_LQR: - printer(arg, "lqr"); - break; - default: - printer(arg, "0x%x", cishort); - } - } - break; + case CI_QUALITY: + if (olen >= CILEN_SHORT) { + p += 2; + printer(arg, "quality "); + GETSHORT(cishort, p); + switch (cishort) { + case PPP_LQR: + printer(arg, "lqr"); + break; + default: + printer(arg, "0x%x", cishort); + } + } + break; #endif /* LQR_SUPPORT */ - case CI_CALLBACK: - if (olen >= CILEN_CHAR) { - p += 2; - printer(arg, "callback "); - GETCHAR(cishort, p); - switch (cishort) { - case CBCP_OPT: - printer(arg, "CBCP"); - break; - default: - printer(arg, "0x%x", cishort); - } - } - break; - case CI_MAGICNUMBER: - if (olen == CILEN_LONG) { - p += 2; - GETLONG(cilong, p); - printer(arg, "magic 0x%x", cilong); - } - break; - case CI_PCOMPRESSION: - if (olen == CILEN_VOID) { - p += 2; - printer(arg, "pcomp"); - } - break; - case CI_ACCOMPRESSION: - if (olen == CILEN_VOID) { - p += 2; - printer(arg, "accomp"); - } - break; - case CI_MRRU: - if (olen == CILEN_SHORT) { - p += 2; - GETSHORT(cishort, p); - printer(arg, "mrru %d", cishort); - } - break; - case CI_SSNHF: - if (olen == CILEN_VOID) { - p += 2; - printer(arg, "ssnhf"); - } - break; - case CI_EPDISC: + case CI_CALLBACK: + if (olen >= CILEN_CHAR) { + p += 2; + printer(arg, "callback "); + GETCHAR(cishort, p); + switch (cishort) { + case CBCP_OPT: + printer(arg, "CBCP"); + break; + default: + printer(arg, "0x%x", cishort); + } + } + break; + case CI_MAGICNUMBER: + if (olen == CILEN_LONG) { + p += 2; + GETLONG(cilong, p); + printer(arg, "magic 0x%x", cilong); + } + break; + case CI_PCOMPRESSION: + if (olen == CILEN_VOID) { + p += 2; + printer(arg, "pcomp"); + } + break; + case CI_ACCOMPRESSION: + if (olen == CILEN_VOID) { + p += 2; + printer(arg, "accomp"); + } + break; + case CI_MRRU: + if (olen == CILEN_SHORT) { + p += 2; + GETSHORT(cishort, p); + printer(arg, "mrru %d", cishort); + } + break; + case CI_SSNHF: + if (olen == CILEN_VOID) { + p += 2; + printer(arg, "ssnhf"); + } + break; + case CI_EPDISC: #ifdef HAVE_MULTILINK - if (olen >= CILEN_CHAR) { - struct epdisc epd; - p += 2; - GETCHAR(epd.class, p); - epd.length = olen - CILEN_CHAR; - if (epd.length > MAX_ENDP_LEN) - epd.length = MAX_ENDP_LEN; - if (epd.length > 0) { - MEMCPY(epd.value, p, epd.length); - p += epd.length; - } - printer(arg, "endpoint [%s]", epdisc_to_str(&epd)); - } + if (olen >= CILEN_CHAR) { + struct epdisc epd; + p += 2; + GETCHAR(epd.class, p); + epd.length = olen - CILEN_CHAR; + if (epd.length > MAX_ENDP_LEN) + epd.length = MAX_ENDP_LEN; + if (epd.length > 0) { + MEMCPY(epd.value, p, epd.length); + p += epd.length; + } + printer(arg, "endpoint [%s]", epdisc_to_str(&epd)); + } #else - printer(arg, "endpoint"); + printer(arg, "endpoint"); #endif - break; - default: - break; - } - while (p < optend) { - GETCHAR(code, p); - printer(arg, " %.2x", code); - } - printer(arg, ">"); - } - break; + break; + default: + break; + } + while (p < optend) { + GETCHAR(code, p); + printer(arg, " %.2x", code); + } + printer(arg, ">"); + } + break; case TERMACK: case TERMREQ: - if (len > 0 && *p >= ' ' && *p < 0x7f) { - printer(arg, " "); - ppp_print_string(p, len, printer, arg); - p += len; - len = 0; - } - break; + if (len > 0 && *p >= ' ' && *p < 0x7f) { + printer(arg, " "); + ppp_print_string(p, len, printer, arg); + p += len; + len = 0; + } + break; case ECHOREQ: case ECHOREP: case DISCREQ: - if (len >= 4) { - GETLONG(cilong, p); - printer(arg, " magic=0x%x", cilong); - len -= 4; - } - break; + if (len >= 4) { + GETLONG(cilong, p); + printer(arg, " magic=0x%x", cilong); + len -= 4; + } + break; case IDENTIF: case TIMEREM: - if (len >= 4) { - GETLONG(cilong, p); - printer(arg, " magic=0x%x", cilong); - len -= 4; - } - if (code == TIMEREM) { - if (len < 4) - break; - GETLONG(cilong, p); - printer(arg, " seconds=%u", cilong); - len -= 4; - } - if (len > 0) { - printer(arg, " "); - ppp_print_string(p, len, printer, arg); - p += len; - len = 0; - } - break; + if (len >= 4) { + GETLONG(cilong, p); + printer(arg, " magic=0x%x", cilong); + len -= 4; + } + if (code == TIMEREM) { + if (len < 4) + break; + GETLONG(cilong, p); + printer(arg, " seconds=%u", cilong); + len -= 4; + } + if (len > 0) { + printer(arg, " "); + ppp_print_string(p, len, printer, arg); + p += len; + len = 0; + } + break; default: - break; + break; } /* print the rest of the bytes in the packet */ for (i = 0; i < len && i < 32; ++i) { - GETCHAR(code, p); - printer(arg, " %.2x", code); + GETCHAR(code, p); + printer(arg, " %.2x", code); } if (i < len) { - printer(arg, " ..."); - p += len - i; + printer(arg, " ..."); + p += len - i; } return p - pstart; @@ -2639,10 +2639,10 @@ static int lcp_printpkt(const u_char *p, int plen, static void LcpLinkFailure(fsm *f) { ppp_pcb *pcb = f->pcb; if (f->state == PPP_FSM_OPENED) { - ppp_info("No response to %d echo-requests", pcb->lcp_echos_pending); + ppp_info("No response to %d echo-requests", pcb->lcp_echos_pending); ppp_notice("Serial link appears to be disconnected."); - pcb->err_code = PPPERR_PEERDEAD; - lcp_close(pcb, "Peer not responding"); + pcb->err_code = PPPERR_PEERDEAD; + lcp_close(pcb, "Peer not responding"); } } @@ -2655,13 +2655,13 @@ static void LcpEchoCheck(fsm *f) { LcpSendEchoRequest (f); if (f->state != PPP_FSM_OPENED) - return; + return; /* * Start the timer for the next interval. */ if (pcb->lcp_echo_timer_running) - ppp_warn("assertion lcp_echo_timer_running==0 failed"); + ppp_warn("assertion lcp_echo_timer_running==0 failed"); TIMEOUT (LcpEchoTimeout, f, pcb->settings.lcp_echo_interval); pcb->lcp_echo_timer_running = 1; } @@ -2691,14 +2691,14 @@ static void lcp_received_echo_reply(fsm *f, int id, u_char *inp, int len) { /* Check the magic number - don't count replies from ourselves. */ if (len < 4) { - ppp_dbglog("lcp: received short Echo-Reply, length %d", len); - return; + ppp_dbglog("lcp: received short Echo-Reply, length %d", len); + return; } GETLONG(magic_val, inp); if (go->neg_magicnumber - && magic_val == go->magicnumber) { - ppp_warn("appear to have received our own echo-reply!"); - return; + && magic_val == go->magicnumber) { + ppp_warn("appear to have received our own echo-reply!"); + return; } /* Reset the number of outstanding echo frames */ @@ -2722,7 +2722,7 @@ static void LcpSendEchoRequest(fsm *f) { if (pcb->lcp_echos_pending >= pcb->settings.lcp_echo_fails) { LcpLinkFailure(f); pcb->lcp_echos_pending = 0; - } + } } #if PPP_LCP_ADAPTIVE @@ -2731,17 +2731,17 @@ static void LcpSendEchoRequest(fsm *f) { * no traffic was received since the last one. */ if (pcb->settings.lcp_echo_adaptive) { - static unsigned int last_pkts_in = 0; + static unsigned int last_pkts_in = 0; #if PPP_STATS_SUPPORT - update_link_stats(f->unit); - link_stats_valid = 0; + update_link_stats(f->unit); + link_stats_valid = 0; #endif /* PPP_STATS_SUPPORT */ - if (link_stats.pkts_in != last_pkts_in) { - last_pkts_in = link_stats.pkts_in; - return; - } + if (link_stats.pkts_in != last_pkts_in) { + last_pkts_in = link_stats.pkts_in; + return; + } } #endif @@ -2750,10 +2750,10 @@ static void LcpSendEchoRequest(fsm *f) { */ if (f->state == PPP_FSM_OPENED) { lcp_magic = go->magicnumber; - pktp = pkt; - PUTLONG(lcp_magic, pktp); + pktp = pkt; + PUTLONG(lcp_magic, pktp); fsm_sdata(f, ECHOREQ, pcb->lcp_echo_number++, pkt, pktp - pkt); - ++pcb->lcp_echos_pending; + ++pcb->lcp_echos_pending; } } @@ -2768,7 +2768,7 @@ static void lcp_echo_lowerup(ppp_pcb *pcb) { pcb->lcp_echos_pending = 0; pcb->lcp_echo_number = 0; pcb->lcp_echo_timer_running = 0; - + /* If a timeout interval is specified then start the timer */ if (pcb->settings.lcp_echo_interval != 0) LcpEchoCheck (f); diff --git a/components/network/lwip/src/netif/ppp/mppe.c b/components/network/lwip/src/netif/ppp/mppe.c index 4cca89de..6e9ffe67 100644 --- a/components/network/lwip/src/netif/ppp/mppe.c +++ b/components/network/lwip/src/netif/ppp/mppe.c @@ -39,20 +39,20 @@ #define SHA1_SIGNATURE_SIZE 20 /* ppp_mppe_state.bits definitions */ -#define MPPE_BIT_A 0x80 /* Encryption table were (re)inititalized */ -#define MPPE_BIT_B 0x40 /* MPPC only (not implemented) */ -#define MPPE_BIT_C 0x20 /* MPPC only (not implemented) */ -#define MPPE_BIT_D 0x10 /* This is an encrypted frame */ +#define MPPE_BIT_A 0x80 /* Encryption table were (re)inititalized */ +#define MPPE_BIT_B 0x40 /* MPPC only (not implemented) */ +#define MPPE_BIT_C 0x20 /* MPPC only (not implemented) */ +#define MPPE_BIT_D 0x10 /* This is an encrypted frame */ -#define MPPE_BIT_FLUSHED MPPE_BIT_A -#define MPPE_BIT_ENCRYPTED MPPE_BIT_D +#define MPPE_BIT_FLUSHED MPPE_BIT_A +#define MPPE_BIT_ENCRYPTED MPPE_BIT_D #define MPPE_BITS(p) ((p)[0] & 0xf0) #define MPPE_CCOUNT(p) ((((p)[0] & 0x0f) << 8) + (p)[1]) -#define MPPE_CCOUNT_SPACE 0x1000 /* The size of the ccount space */ +#define MPPE_CCOUNT_SPACE 0x1000 /* The size of the ccount space */ -#define MPPE_OVHD 2 /* MPPE overhead/packet */ -#define SANITY_MAX 1600 /* Max bogon factor we will tolerate */ +#define MPPE_OVHD 2 /* MPPE overhead/packet */ +#define SANITY_MAX 1600 /* Max bogon factor we will tolerate */ /* * Perform the MPPE rekey algorithm, from RFC 3078, sec. 7.3. @@ -60,37 +60,37 @@ */ static void mppe_rekey(ppp_mppe_state * state, int initial_key) { - lwip_sha1_context sha1_ctx; - u8_t sha1_digest[SHA1_SIGNATURE_SIZE]; + lwip_sha1_context sha1_ctx; + u8_t sha1_digest[SHA1_SIGNATURE_SIZE]; - /* - * Key Derivation, from RFC 3078, RFC 3079. - * Equivalent to Get_Key() for MS-CHAP as described in RFC 3079. - */ - lwip_sha1_init(&sha1_ctx); - lwip_sha1_starts(&sha1_ctx); - lwip_sha1_update(&sha1_ctx, state->master_key, state->keylen); - lwip_sha1_update(&sha1_ctx, mppe_sha1_pad1, SHA1_PAD_SIZE); - lwip_sha1_update(&sha1_ctx, state->session_key, state->keylen); - lwip_sha1_update(&sha1_ctx, mppe_sha1_pad2, SHA1_PAD_SIZE); - lwip_sha1_finish(&sha1_ctx, sha1_digest); - lwip_sha1_free(&sha1_ctx); - MEMCPY(state->session_key, sha1_digest, state->keylen); + /* + * Key Derivation, from RFC 3078, RFC 3079. + * Equivalent to Get_Key() for MS-CHAP as described in RFC 3079. + */ + lwip_sha1_init(&sha1_ctx); + lwip_sha1_starts(&sha1_ctx); + lwip_sha1_update(&sha1_ctx, state->master_key, state->keylen); + lwip_sha1_update(&sha1_ctx, mppe_sha1_pad1, SHA1_PAD_SIZE); + lwip_sha1_update(&sha1_ctx, state->session_key, state->keylen); + lwip_sha1_update(&sha1_ctx, mppe_sha1_pad2, SHA1_PAD_SIZE); + lwip_sha1_finish(&sha1_ctx, sha1_digest); + lwip_sha1_free(&sha1_ctx); + MEMCPY(state->session_key, sha1_digest, state->keylen); - if (!initial_key) { - lwip_arc4_init(&state->arc4); - lwip_arc4_setup(&state->arc4, sha1_digest, state->keylen); - lwip_arc4_crypt(&state->arc4, state->session_key, state->keylen); - lwip_arc4_free(&state->arc4); - } - if (state->keylen == 8) { - /* See RFC 3078 */ - state->session_key[0] = 0xd1; - state->session_key[1] = 0x26; - state->session_key[2] = 0x9e; - } - lwip_arc4_init(&state->arc4); - lwip_arc4_setup(&state->arc4, state->session_key, state->keylen); + if (!initial_key) { + lwip_arc4_init(&state->arc4); + lwip_arc4_setup(&state->arc4, sha1_digest, state->keylen); + lwip_arc4_crypt(&state->arc4, state->session_key, state->keylen); + lwip_arc4_free(&state->arc4); + } + if (state->keylen == 8) { + /* See RFC 3078 */ + state->session_key[0] = 0xd1; + state->session_key[1] = 0x26; + state->session_key[2] = 0x9e; + } + lwip_arc4_init(&state->arc4); + lwip_arc4_setup(&state->arc4, state->session_key, state->keylen); } /* @@ -98,8 +98,8 @@ static void mppe_rekey(ppp_mppe_state * state, int initial_key) * don't have to keep multiple copies of keys. */ void mppe_set_key(ppp_pcb *pcb, ppp_mppe_state *state, u8_t *key) { - LWIP_UNUSED_ARG(pcb); - MEMCPY(state->master_key, key, MPPE_MAX_KEY_LEN); + LWIP_UNUSED_ARG(pcb); + MEMCPY(state->master_key, key, MPPE_MAX_KEY_LEN); } /* @@ -109,64 +109,64 @@ void mppe_init(ppp_pcb *pcb, ppp_mppe_state *state, u8_t options) { #if PPP_DEBUG - const u8_t *debugstr = (const u8_t*)"mppe_comp_init"; - if (&pcb->mppe_decomp == state) { - debugstr = (const u8_t*)"mppe_decomp_init"; - } + const u8_t *debugstr = (const u8_t*)"mppe_comp_init"; + if (&pcb->mppe_decomp == state) { + debugstr = (const u8_t*)"mppe_decomp_init"; + } #endif /* PPP_DEBUG */ - /* Save keys. */ - MEMCPY(state->session_key, state->master_key, sizeof(state->master_key)); + /* Save keys. */ + MEMCPY(state->session_key, state->master_key, sizeof(state->master_key)); - if (options & MPPE_OPT_128) - state->keylen = 16; - else if (options & MPPE_OPT_40) - state->keylen = 8; - else { - PPPDEBUG(LOG_DEBUG, ("%s[%d]: unknown key length\n", debugstr, - pcb->netif->num)); - lcp_close(pcb, "MPPE required but peer negotiation failed"); - return; - } - if (options & MPPE_OPT_STATEFUL) - state->stateful = 1; + if (options & MPPE_OPT_128) + state->keylen = 16; + else if (options & MPPE_OPT_40) + state->keylen = 8; + else { + PPPDEBUG(LOG_DEBUG, ("%s[%d]: unknown key length\n", debugstr, + pcb->netif->num)); + lcp_close(pcb, "MPPE required but peer negotiation failed"); + return; + } + if (options & MPPE_OPT_STATEFUL) + state->stateful = 1; - /* Generate the initial session key. */ - mppe_rekey(state, 1); + /* Generate the initial session key. */ + mppe_rekey(state, 1); #if PPP_DEBUG - { - int i; - char mkey[sizeof(state->master_key) * 2 + 1]; - char skey[sizeof(state->session_key) * 2 + 1]; + { + int i; + char mkey[sizeof(state->master_key) * 2 + 1]; + char skey[sizeof(state->session_key) * 2 + 1]; - PPPDEBUG(LOG_DEBUG, ("%s[%d]: initialized with %d-bit %s mode\n", - debugstr, pcb->netif->num, (state->keylen == 16) ? 128 : 40, - (state->stateful) ? "stateful" : "stateless")); + PPPDEBUG(LOG_DEBUG, ("%s[%d]: initialized with %d-bit %s mode\n", + debugstr, pcb->netif->num, (state->keylen == 16) ? 128 : 40, + (state->stateful) ? "stateful" : "stateless")); - for (i = 0; i < (int)sizeof(state->master_key); i++) - sprintf(mkey + i * 2, "%02x", state->master_key[i]); - for (i = 0; i < (int)sizeof(state->session_key); i++) - sprintf(skey + i * 2, "%02x", state->session_key[i]); - PPPDEBUG(LOG_DEBUG, - ("%s[%d]: keys: master: %s initial session: %s\n", - debugstr, pcb->netif->num, mkey, skey)); - } + for (i = 0; i < (int)sizeof(state->master_key); i++) + sprintf(mkey + i * 2, "%02x", state->master_key[i]); + for (i = 0; i < (int)sizeof(state->session_key); i++) + sprintf(skey + i * 2, "%02x", state->session_key[i]); + PPPDEBUG(LOG_DEBUG, + ("%s[%d]: keys: master: %s initial session: %s\n", + debugstr, pcb->netif->num, mkey, skey)); + } #endif /* PPP_DEBUG */ - /* - * Initialize the coherency count. The initial value is not specified - * in RFC 3078, but we can make a reasonable assumption that it will - * start at 0. Setting it to the max here makes the comp/decomp code - * do the right thing (determined through experiment). - */ - state->ccount = MPPE_CCOUNT_SPACE - 1; + /* + * Initialize the coherency count. The initial value is not specified + * in RFC 3078, but we can make a reasonable assumption that it will + * start at 0. Setting it to the max here makes the comp/decomp code + * do the right thing (determined through experiment). + */ + state->ccount = MPPE_CCOUNT_SPACE - 1; - /* - * Note that even though we have initialized the key table, we don't - * set the FLUSHED bit. This is contrary to RFC 3078, sec. 3.1. - */ - state->bits = MPPE_BIT_ENCRYPTED; + /* + * Note that even though we have initialized the key table, we don't + * set the FLUSHED bit. This is contrary to RFC 3078, sec. 3.1. + */ + state->bits = MPPE_BIT_ENCRYPTED; } /* @@ -180,8 +180,8 @@ mppe_init(ppp_pcb *pcb, ppp_mppe_state *state, u8_t options) */ void mppe_comp_reset(ppp_pcb *pcb, ppp_mppe_state *state) { - LWIP_UNUSED_ARG(pcb); - state->bits |= MPPE_BIT_FLUSHED; + LWIP_UNUSED_ARG(pcb); + state->bits |= MPPE_BIT_FLUSHED; } /* @@ -192,74 +192,74 @@ void mppe_comp_reset(ppp_pcb *pcb, ppp_mppe_state *state) err_t mppe_compress(ppp_pcb *pcb, ppp_mppe_state *state, struct pbuf **pb, u16_t protocol) { - struct pbuf *n, *np; - u8_t *pl; - err_t err; + struct pbuf *n, *np; + u8_t *pl; + err_t err; - LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(pcb); - /* TCP stack requires that we don't change the packet payload, therefore we copy - * the whole packet before encryption. - */ - np = pbuf_alloc(PBUF_RAW, MPPE_OVHD + sizeof(protocol) + (*pb)->tot_len, PBUF_RAM); - if (!np) { - return ERR_MEM; - } + /* TCP stack requires that we don't change the packet payload, therefore we copy + * the whole packet before encryption. + */ + np = pbuf_alloc(PBUF_RAW, MPPE_OVHD + sizeof(protocol) + (*pb)->tot_len, PBUF_RAM); + if (!np) { + return ERR_MEM; + } - /* Hide MPPE header + protocol */ - pbuf_remove_header(np, MPPE_OVHD + sizeof(protocol)); + /* Hide MPPE header + protocol */ + pbuf_remove_header(np, MPPE_OVHD + sizeof(protocol)); - if ((err = pbuf_copy(np, *pb)) != ERR_OK) { - pbuf_free(np); - return err; - } + if ((err = pbuf_copy(np, *pb)) != ERR_OK) { + pbuf_free(np); + return err; + } - /* Reveal MPPE header + protocol */ - pbuf_add_header(np, MPPE_OVHD + sizeof(protocol)); + /* Reveal MPPE header + protocol */ + pbuf_add_header(np, MPPE_OVHD + sizeof(protocol)); - *pb = np; - pl = (u8_t*)np->payload; + *pb = np; + pl = (u8_t*)np->payload; - state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; - PPPDEBUG(LOG_DEBUG, ("mppe_compress[%d]: ccount %d\n", pcb->netif->num, state->ccount)); - /* FIXME: use PUT* macros */ - pl[0] = state->ccount>>8; - pl[1] = state->ccount; + state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; + PPPDEBUG(LOG_DEBUG, ("mppe_compress[%d]: ccount %d\n", pcb->netif->num, state->ccount)); + /* FIXME: use PUT* macros */ + pl[0] = state->ccount>>8; + pl[1] = state->ccount; - if (!state->stateful || /* stateless mode */ - ((state->ccount & 0xff) == 0xff) || /* "flag" packet */ - (state->bits & MPPE_BIT_FLUSHED)) { /* CCP Reset-Request */ - /* We must rekey */ - if (state->stateful) { - PPPDEBUG(LOG_DEBUG, ("mppe_compress[%d]: rekeying\n", pcb->netif->num)); - } - mppe_rekey(state, 0); - state->bits |= MPPE_BIT_FLUSHED; - } - pl[0] |= state->bits; - state->bits &= ~MPPE_BIT_FLUSHED; /* reset for next xmit */ - pl += MPPE_OVHD; + if (!state->stateful || /* stateless mode */ + ((state->ccount & 0xff) == 0xff) || /* "flag" packet */ + (state->bits & MPPE_BIT_FLUSHED)) { /* CCP Reset-Request */ + /* We must rekey */ + if (state->stateful) { + PPPDEBUG(LOG_DEBUG, ("mppe_compress[%d]: rekeying\n", pcb->netif->num)); + } + mppe_rekey(state, 0); + state->bits |= MPPE_BIT_FLUSHED; + } + pl[0] |= state->bits; + state->bits &= ~MPPE_BIT_FLUSHED; /* reset for next xmit */ + pl += MPPE_OVHD; - /* Add protocol */ - /* FIXME: add PFC support */ - pl[0] = protocol >> 8; - pl[1] = protocol; + /* Add protocol */ + /* FIXME: add PFC support */ + pl[0] = protocol >> 8; + pl[1] = protocol; - /* Hide MPPE header */ - pbuf_remove_header(np, MPPE_OVHD); + /* Hide MPPE header */ + pbuf_remove_header(np, MPPE_OVHD); - /* Encrypt packet */ - for (n = np; n != NULL; n = n->next) { - lwip_arc4_crypt(&state->arc4, (u8_t*)n->payload, n->len); - if (n->tot_len == n->len) { - break; - } - } + /* Encrypt packet */ + for (n = np; n != NULL; n = n->next) { + lwip_arc4_crypt(&state->arc4, (u8_t*)n->payload, n->len); + if (n->tot_len == n->len) { + break; + } + } - /* Reveal MPPE header */ - pbuf_add_header(np, MPPE_OVHD); + /* Reveal MPPE header */ + pbuf_add_header(np, MPPE_OVHD); - return ERR_OK; + return ERR_OK; } /* @@ -267,9 +267,9 @@ mppe_compress(ppp_pcb *pcb, ppp_mppe_state *state, struct pbuf **pb, u16_t proto */ void mppe_decomp_reset(ppp_pcb *pcb, ppp_mppe_state *state) { - LWIP_UNUSED_ARG(pcb); - LWIP_UNUSED_ARG(state); - return; + LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(state); + return; } /* @@ -278,135 +278,135 @@ void mppe_decomp_reset(ppp_pcb *pcb, ppp_mppe_state *state) err_t mppe_decompress(ppp_pcb *pcb, ppp_mppe_state *state, struct pbuf **pb) { - struct pbuf *n0 = *pb, *n; - u8_t *pl; - u16_t ccount; - u8_t flushed; + struct pbuf *n0 = *pb, *n; + u8_t *pl; + u16_t ccount; + u8_t flushed; - /* MPPE Header */ - if (n0->len < MPPE_OVHD) { - PPPDEBUG(LOG_DEBUG, - ("mppe_decompress[%d]: short pkt (%d)\n", - pcb->netif->num, n0->len)); - state->sanity_errors += 100; - goto sanity_error; - } + /* MPPE Header */ + if (n0->len < MPPE_OVHD) { + PPPDEBUG(LOG_DEBUG, + ("mppe_decompress[%d]: short pkt (%d)\n", + pcb->netif->num, n0->len)); + state->sanity_errors += 100; + goto sanity_error; + } - pl = (u8_t*)n0->payload; - flushed = MPPE_BITS(pl) & MPPE_BIT_FLUSHED; - ccount = MPPE_CCOUNT(pl); - PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: ccount %d\n", - pcb->netif->num, ccount)); + pl = (u8_t*)n0->payload; + flushed = MPPE_BITS(pl) & MPPE_BIT_FLUSHED; + ccount = MPPE_CCOUNT(pl); + PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: ccount %d\n", + pcb->netif->num, ccount)); - /* sanity checks -- terminate with extreme prejudice */ - if (!(MPPE_BITS(pl) & MPPE_BIT_ENCRYPTED)) { - PPPDEBUG(LOG_DEBUG, - ("mppe_decompress[%d]: ENCRYPTED bit not set!\n", - pcb->netif->num)); - state->sanity_errors += 100; - goto sanity_error; - } - if (!state->stateful && !flushed) { - PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: FLUSHED bit not set in " - "stateless mode!\n", pcb->netif->num)); - state->sanity_errors += 100; - goto sanity_error; - } - if (state->stateful && ((ccount & 0xff) == 0xff) && !flushed) { - PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: FLUSHED bit not set on " - "flag packet!\n", pcb->netif->num)); - state->sanity_errors += 100; - goto sanity_error; - } + /* sanity checks -- terminate with extreme prejudice */ + if (!(MPPE_BITS(pl) & MPPE_BIT_ENCRYPTED)) { + PPPDEBUG(LOG_DEBUG, + ("mppe_decompress[%d]: ENCRYPTED bit not set!\n", + pcb->netif->num)); + state->sanity_errors += 100; + goto sanity_error; + } + if (!state->stateful && !flushed) { + PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: FLUSHED bit not set in " + "stateless mode!\n", pcb->netif->num)); + state->sanity_errors += 100; + goto sanity_error; + } + if (state->stateful && ((ccount & 0xff) == 0xff) && !flushed) { + PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: FLUSHED bit not set on " + "flag packet!\n", pcb->netif->num)); + state->sanity_errors += 100; + goto sanity_error; + } - /* - * Check the coherency count. - */ + /* + * Check the coherency count. + */ - if (!state->stateful) { - /* Discard late packet */ - if ((ccount - state->ccount) % MPPE_CCOUNT_SPACE > MPPE_CCOUNT_SPACE / 2) { - state->sanity_errors++; - goto sanity_error; - } + if (!state->stateful) { + /* Discard late packet */ + if ((ccount - state->ccount) % MPPE_CCOUNT_SPACE > MPPE_CCOUNT_SPACE / 2) { + state->sanity_errors++; + goto sanity_error; + } - /* RFC 3078, sec 8.1. Rekey for every packet. */ - while (state->ccount != ccount) { - mppe_rekey(state, 0); - state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; - } - } else { - /* RFC 3078, sec 8.2. */ - if (!state->discard) { - /* normal state */ - state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; - if (ccount != state->ccount) { - /* - * (ccount > state->ccount) - * Packet loss detected, enter the discard state. - * Signal the peer to rekey (by sending a CCP Reset-Request). - */ - state->discard = 1; - ccp_resetrequest(pcb); - return ERR_BUF; - } - } else { - /* discard state */ - if (!flushed) { - /* ccp.c will be silent (no additional CCP Reset-Requests). */ - return ERR_BUF; - } else { - /* Rekey for every missed "flag" packet. */ - while ((ccount & ~0xff) != - (state->ccount & ~0xff)) { - mppe_rekey(state, 0); - state->ccount = - (state->ccount + - 256) % MPPE_CCOUNT_SPACE; - } + /* RFC 3078, sec 8.1. Rekey for every packet. */ + while (state->ccount != ccount) { + mppe_rekey(state, 0); + state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; + } + } else { + /* RFC 3078, sec 8.2. */ + if (!state->discard) { + /* normal state */ + state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE; + if (ccount != state->ccount) { + /* + * (ccount > state->ccount) + * Packet loss detected, enter the discard state. + * Signal the peer to rekey (by sending a CCP Reset-Request). + */ + state->discard = 1; + ccp_resetrequest(pcb); + return ERR_BUF; + } + } else { + /* discard state */ + if (!flushed) { + /* ccp.c will be silent (no additional CCP Reset-Requests). */ + return ERR_BUF; + } else { + /* Rekey for every missed "flag" packet. */ + while ((ccount & ~0xff) != + (state->ccount & ~0xff)) { + mppe_rekey(state, 0); + state->ccount = + (state->ccount + + 256) % MPPE_CCOUNT_SPACE; + } - /* reset */ - state->discard = 0; - state->ccount = ccount; - /* - * Another problem with RFC 3078 here. It implies that the - * peer need not send a Reset-Ack packet. But RFC 1962 - * requires it. Hopefully, M$ does send a Reset-Ack; even - * though it isn't required for MPPE synchronization, it is - * required to reset CCP state. - */ - } - } - if (flushed) - mppe_rekey(state, 0); - } + /* reset */ + state->discard = 0; + state->ccount = ccount; + /* + * Another problem with RFC 3078 here. It implies that the + * peer need not send a Reset-Ack packet. But RFC 1962 + * requires it. Hopefully, M$ does send a Reset-Ack; even + * though it isn't required for MPPE synchronization, it is + * required to reset CCP state. + */ + } + } + if (flushed) + mppe_rekey(state, 0); + } - /* Hide MPPE header */ - pbuf_remove_header(n0, MPPE_OVHD); + /* Hide MPPE header */ + pbuf_remove_header(n0, MPPE_OVHD); - /* Decrypt the packet. */ - for (n = n0; n != NULL; n = n->next) { - lwip_arc4_crypt(&state->arc4, (u8_t*)n->payload, n->len); - if (n->tot_len == n->len) { - break; - } - } + /* Decrypt the packet. */ + for (n = n0; n != NULL; n = n->next) { + lwip_arc4_crypt(&state->arc4, (u8_t*)n->payload, n->len); + if (n->tot_len == n->len) { + break; + } + } - /* good packet credit */ - state->sanity_errors >>= 1; + /* good packet credit */ + state->sanity_errors >>= 1; - return ERR_OK; + return ERR_OK; sanity_error: - if (state->sanity_errors >= SANITY_MAX) { - /* - * Take LCP down if the peer is sending too many bogons. - * We don't want to do this for a single or just a few - * instances since it could just be due to packet corruption. - */ - lcp_close(pcb, "Too many MPPE errors"); - } - return ERR_BUF; + if (state->sanity_errors >= SANITY_MAX) { + /* + * Take LCP down if the peer is sending too many bogons. + * We don't want to do this for a single or just a few + * instances since it could just be due to packet corruption. + */ + lcp_close(pcb, "Too many MPPE errors"); + } + return ERR_BUF; } #endif /* PPP_SUPPORT && MPPE_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/multilink.c b/components/network/lwip/src/netif/ppp/multilink.c index 62014e8c..08e8130d 100644 --- a/components/network/lwip/src/netif/ppp/multilink.c +++ b/components/network/lwip/src/netif/ppp/multilink.c @@ -55,11 +55,11 @@ #include "netif/ppp/lcp.h" #include "netif/ppp/tdb.h" -bool endpoint_specified; /* user gave explicit endpoint discriminator */ -char *bundle_id; /* identifier for our bundle */ -char *blinks_id; /* key for the list of links */ -bool doing_multilink; /* multilink was enabled and agreed to */ -bool multilink_master; /* we own the multilink bundle */ +bool endpoint_specified; /* user gave explicit endpoint discriminator */ +char *bundle_id; /* identifier for our bundle */ +char *blinks_id; /* key for the list of links */ +bool doing_multilink; /* multilink was enabled and agreed to */ +bool multilink_master; /* we own the multilink bundle */ extern TDB_CONTEXT *pppdb; extern char db_key[]; @@ -72,43 +72,43 @@ static int get_default_epdisc (struct epdisc *); static int parse_num (char *str, const char *key, int *valp); static int owns_unit (TDB_DATA pid, int unit); -#define set_ip_epdisc(ep, addr) do { \ - ep->length = 4; \ - ep->value[0] = addr >> 24; \ - ep->value[1] = addr >> 16; \ - ep->value[2] = addr >> 8; \ - ep->value[3] = addr; \ +#define set_ip_epdisc(ep, addr) do { \ + ep->length = 4; \ + ep->value[0] = addr >> 24; \ + ep->value[1] = addr >> 16; \ + ep->value[2] = addr >> 8; \ + ep->value[3] = addr; \ } while (0) -#define LOCAL_IP_ADDR(addr) \ - (((addr) & 0xff000000) == 0x0a000000 /* 10.x.x.x */ \ - || ((addr) & 0xfff00000) == 0xac100000 /* 172.16.x.x */ \ - || ((addr) & 0xffff0000) == 0xc0a80000) /* 192.168.x.x */ +#define LOCAL_IP_ADDR(addr) \ + (((addr) & 0xff000000) == 0x0a000000 /* 10.x.x.x */ \ + || ((addr) & 0xfff00000) == 0xac100000 /* 172.16.x.x */ \ + || ((addr) & 0xffff0000) == 0xc0a80000) /* 192.168.x.x */ -#define process_exists(n) (kill((n), 0) == 0 || errno != ESRCH) +#define process_exists(n) (kill((n), 0) == 0 || errno != ESRCH) void mp_check_options() { - lcp_options *wo = &lcp_wantoptions[0]; - lcp_options *ao = &lcp_allowoptions[0]; + lcp_options *wo = &lcp_wantoptions[0]; + lcp_options *ao = &lcp_allowoptions[0]; - doing_multilink = 0; - if (!multilink) - return; - /* if we're doing multilink, we have to negotiate MRRU */ - if (!wo->neg_mrru) { - /* mrru not specified, default to mru */ - wo->mrru = wo->mru; - wo->neg_mrru = 1; - } - ao->mrru = ao->mru; - ao->neg_mrru = 1; + doing_multilink = 0; + if (!multilink) + return; + /* if we're doing multilink, we have to negotiate MRRU */ + if (!wo->neg_mrru) { + /* mrru not specified, default to mru */ + wo->mrru = wo->mru; + wo->neg_mrru = 1; + } + ao->mrru = ao->mru; + ao->neg_mrru = 1; - if (!wo->neg_endpoint && !noendpoint) { - /* get a default endpoint value */ - wo->neg_endpoint = get_default_epdisc(&wo->endpoint); - } + if (!wo->neg_endpoint && !noendpoint) { + /* get a default endpoint value */ + wo->neg_endpoint = get_default_epdisc(&wo->endpoint); + } } /* @@ -118,289 +118,289 @@ mp_check_options() int mp_join_bundle() { - lcp_options *go = &lcp_gotoptions[0]; - lcp_options *ho = &lcp_hisoptions[0]; - lcp_options *ao = &lcp_allowoptions[0]; - int unit, pppd_pid; - int l, mtu; - char *p; - TDB_DATA key, pid, rec; + lcp_options *go = &lcp_gotoptions[0]; + lcp_options *ho = &lcp_hisoptions[0]; + lcp_options *ao = &lcp_allowoptions[0]; + int unit, pppd_pid; + int l, mtu; + char *p; + TDB_DATA key, pid, rec; - if (doing_multilink) { - /* have previously joined a bundle */ - if (!go->neg_mrru || !ho->neg_mrru) { - notice("oops, didn't get multilink on renegotiation"); - lcp_close(pcb, "multilink required"); - return 0; - } - /* XXX should check the peer_authname and ho->endpoint - are the same as previously */ - return 0; - } + if (doing_multilink) { + /* have previously joined a bundle */ + if (!go->neg_mrru || !ho->neg_mrru) { + notice("oops, didn't get multilink on renegotiation"); + lcp_close(pcb, "multilink required"); + return 0; + } + /* XXX should check the peer_authname and ho->endpoint + are the same as previously */ + return 0; + } - if (!go->neg_mrru || !ho->neg_mrru) { - /* not doing multilink */ - if (go->neg_mrru) - notice("oops, multilink negotiated only for receive"); - mtu = ho->neg_mru? ho->mru: PPP_MRU; - if (mtu > ao->mru) - mtu = ao->mru; - if (demand) { - /* already have a bundle */ - cfg_bundle(0, 0, 0, 0); - netif_set_mtu(pcb, mtu); - return 0; - } - make_new_bundle(0, 0, 0, 0); - set_ifunit(1); - netif_set_mtu(pcb, mtu); - return 0; - } + if (!go->neg_mrru || !ho->neg_mrru) { + /* not doing multilink */ + if (go->neg_mrru) + notice("oops, multilink negotiated only for receive"); + mtu = ho->neg_mru? ho->mru: PPP_MRU; + if (mtu > ao->mru) + mtu = ao->mru; + if (demand) { + /* already have a bundle */ + cfg_bundle(0, 0, 0, 0); + netif_set_mtu(pcb, mtu); + return 0; + } + make_new_bundle(0, 0, 0, 0); + set_ifunit(1); + netif_set_mtu(pcb, mtu); + return 0; + } - doing_multilink = 1; + doing_multilink = 1; - /* - * Find the appropriate bundle or join a new one. - * First we make up a name for the bundle. - * The length estimate is worst-case assuming every - * character has to be quoted. - */ - l = 4 * strlen(peer_authname) + 10; - if (ho->neg_endpoint) - l += 3 * ho->endpoint.length + 8; - if (bundle_name) - l += 3 * strlen(bundle_name) + 2; - bundle_id = malloc(l); - if (bundle_id == 0) - novm("bundle identifier"); + /* + * Find the appropriate bundle or join a new one. + * First we make up a name for the bundle. + * The length estimate is worst-case assuming every + * character has to be quoted. + */ + l = 4 * strlen(peer_authname) + 10; + if (ho->neg_endpoint) + l += 3 * ho->endpoint.length + 8; + if (bundle_name) + l += 3 * strlen(bundle_name) + 2; + bundle_id = malloc(l); + if (bundle_id == 0) + novm("bundle identifier"); - p = bundle_id; - p += slprintf(p, l-1, "BUNDLE=\"%q\"", peer_authname); - if (ho->neg_endpoint || bundle_name) - *p++ = '/'; - if (ho->neg_endpoint) - p += slprintf(p, bundle_id+l-p, "%s", - epdisc_to_str(&ho->endpoint)); - if (bundle_name) - p += slprintf(p, bundle_id+l-p, "/%v", bundle_name); + p = bundle_id; + p += slprintf(p, l-1, "BUNDLE=\"%q\"", peer_authname); + if (ho->neg_endpoint || bundle_name) + *p++ = '/'; + if (ho->neg_endpoint) + p += slprintf(p, bundle_id+l-p, "%s", + epdisc_to_str(&ho->endpoint)); + if (bundle_name) + p += slprintf(p, bundle_id+l-p, "/%v", bundle_name); - /* Make the key for the list of links belonging to the bundle */ - l = p - bundle_id; - blinks_id = malloc(l + 7); - if (blinks_id == NULL) - novm("bundle links key"); - slprintf(blinks_id, l + 7, "BUNDLE_LINKS=%s", bundle_id + 7); + /* Make the key for the list of links belonging to the bundle */ + l = p - bundle_id; + blinks_id = malloc(l + 7); + if (blinks_id == NULL) + novm("bundle links key"); + slprintf(blinks_id, l + 7, "BUNDLE_LINKS=%s", bundle_id + 7); - /* - * For demand mode, we only need to configure the bundle - * and attach the link. - */ - mtu = LWIP_MIN(ho->mrru, ao->mru); - if (demand) { - cfg_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf); - netif_set_mtu(pcb, mtu); - script_setenv("BUNDLE", bundle_id + 7, 1); - return 0; - } + /* + * For demand mode, we only need to configure the bundle + * and attach the link. + */ + mtu = LWIP_MIN(ho->mrru, ao->mru); + if (demand) { + cfg_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf); + netif_set_mtu(pcb, mtu); + script_setenv("BUNDLE", bundle_id + 7, 1); + return 0; + } - /* - * Check if the bundle ID is already in the database. - */ - unit = -1; - lock_db(); - key.dptr = bundle_id; - key.dsize = p - bundle_id; - pid = tdb_fetch(pppdb, key); - if (pid.dptr != NULL) { - /* bundle ID exists, see if the pppd record exists */ - rec = tdb_fetch(pppdb, pid); - if (rec.dptr != NULL && rec.dsize > 0) { - /* make sure the string is null-terminated */ - rec.dptr[rec.dsize-1] = 0; - /* parse the interface number */ - parse_num(rec.dptr, "IFNAME=ppp", &unit); - /* check the pid value */ - if (!parse_num(rec.dptr, "PPPD_PID=", &pppd_pid) - || !process_exists(pppd_pid) - || !owns_unit(pid, unit)) - unit = -1; - free(rec.dptr); - } - free(pid.dptr); - } + /* + * Check if the bundle ID is already in the database. + */ + unit = -1; + lock_db(); + key.dptr = bundle_id; + key.dsize = p - bundle_id; + pid = tdb_fetch(pppdb, key); + if (pid.dptr != NULL) { + /* bundle ID exists, see if the pppd record exists */ + rec = tdb_fetch(pppdb, pid); + if (rec.dptr != NULL && rec.dsize > 0) { + /* make sure the string is null-terminated */ + rec.dptr[rec.dsize-1] = 0; + /* parse the interface number */ + parse_num(rec.dptr, "IFNAME=ppp", &unit); + /* check the pid value */ + if (!parse_num(rec.dptr, "PPPD_PID=", &pppd_pid) + || !process_exists(pppd_pid) + || !owns_unit(pid, unit)) + unit = -1; + free(rec.dptr); + } + free(pid.dptr); + } - if (unit >= 0) { - /* attach to existing unit */ - if (bundle_attach(unit)) { - set_ifunit(0); - script_setenv("BUNDLE", bundle_id + 7, 0); - make_bundle_links(1); - unlock_db(); - info("Link attached to %s", ifname); - return 1; - } - /* attach failed because bundle doesn't exist */ - } + if (unit >= 0) { + /* attach to existing unit */ + if (bundle_attach(unit)) { + set_ifunit(0); + script_setenv("BUNDLE", bundle_id + 7, 0); + make_bundle_links(1); + unlock_db(); + info("Link attached to %s", ifname); + return 1; + } + /* attach failed because bundle doesn't exist */ + } - /* we have to make a new bundle */ - make_new_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf); - set_ifunit(1); - netif_set_mtu(pcb, mtu); - script_setenv("BUNDLE", bundle_id + 7, 1); - make_bundle_links(pcb); - unlock_db(); - info("New bundle %s created", ifname); - multilink_master = 1; - return 0; + /* we have to make a new bundle */ + make_new_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf); + set_ifunit(1); + netif_set_mtu(pcb, mtu); + script_setenv("BUNDLE", bundle_id + 7, 1); + make_bundle_links(pcb); + unlock_db(); + info("New bundle %s created", ifname); + multilink_master = 1; + return 0; } void mp_exit_bundle() { - lock_db(); - remove_bundle_link(); - unlock_db(); + lock_db(); + remove_bundle_link(); + unlock_db(); } static void sendhup(char *str) { - int pid; + int pid; - if (parse_num(str, "PPPD_PID=", &pid) && pid != getpid()) { - if (debug) - dbglog("sending SIGHUP to process %d", pid); - kill(pid, SIGHUP); - } + if (parse_num(str, "PPPD_PID=", &pid) && pid != getpid()) { + if (debug) + dbglog("sending SIGHUP to process %d", pid); + kill(pid, SIGHUP); + } } void mp_bundle_terminated() { - TDB_DATA key; + TDB_DATA key; - bundle_terminating = 1; - upper_layers_down(pcb); - notice("Connection terminated."); + bundle_terminating = 1; + upper_layers_down(pcb); + notice("Connection terminated."); #if PPP_STATS_SUPPORT - print_link_stats(); + print_link_stats(); #endif /* PPP_STATS_SUPPORT */ - if (!demand) { - remove_pidfiles(); - script_unsetenv("IFNAME"); - } + if (!demand) { + remove_pidfiles(); + script_unsetenv("IFNAME"); + } - lock_db(); - destroy_bundle(); - iterate_bundle_links(sendhup); - key.dptr = blinks_id; - key.dsize = strlen(blinks_id); - tdb_delete(pppdb, key); - unlock_db(); + lock_db(); + destroy_bundle(); + iterate_bundle_links(sendhup); + key.dptr = blinks_id; + key.dsize = strlen(blinks_id); + tdb_delete(pppdb, key); + unlock_db(); - new_phase(PPP_PHASE_DEAD); + new_phase(PPP_PHASE_DEAD); - doing_multilink = 0; - multilink_master = 0; + doing_multilink = 0; + multilink_master = 0; } static void make_bundle_links(int append) { - TDB_DATA key, rec; - char *p; - char entry[32]; - int l; + TDB_DATA key, rec; + char *p; + char entry[32]; + int l; - key.dptr = blinks_id; - key.dsize = strlen(blinks_id); - slprintf(entry, sizeof(entry), "%s;", db_key); - p = entry; - if (append) { - rec = tdb_fetch(pppdb, key); - if (rec.dptr != NULL && rec.dsize > 0) { - rec.dptr[rec.dsize-1] = 0; - if (strstr(rec.dptr, db_key) != NULL) { - /* already in there? strange */ - warn("link entry already exists in tdb"); - return; - } - l = rec.dsize + strlen(entry); - p = malloc(l); - if (p == NULL) - novm("bundle link list"); - slprintf(p, l, "%s%s", rec.dptr, entry); - } else { - warn("bundle link list not found"); - } - if (rec.dptr != NULL) - free(rec.dptr); - } - rec.dptr = p; - rec.dsize = strlen(p) + 1; - if (tdb_store(pppdb, key, rec, TDB_REPLACE)) - error("couldn't %s bundle link list", - append? "update": "create"); - if (p != entry) - free(p); + key.dptr = blinks_id; + key.dsize = strlen(blinks_id); + slprintf(entry, sizeof(entry), "%s;", db_key); + p = entry; + if (append) { + rec = tdb_fetch(pppdb, key); + if (rec.dptr != NULL && rec.dsize > 0) { + rec.dptr[rec.dsize-1] = 0; + if (strstr(rec.dptr, db_key) != NULL) { + /* already in there? strange */ + warn("link entry already exists in tdb"); + return; + } + l = rec.dsize + strlen(entry); + p = malloc(l); + if (p == NULL) + novm("bundle link list"); + slprintf(p, l, "%s%s", rec.dptr, entry); + } else { + warn("bundle link list not found"); + } + if (rec.dptr != NULL) + free(rec.dptr); + } + rec.dptr = p; + rec.dsize = strlen(p) + 1; + if (tdb_store(pppdb, key, rec, TDB_REPLACE)) + error("couldn't %s bundle link list", + append? "update": "create"); + if (p != entry) + free(p); } static void remove_bundle_link() { - TDB_DATA key, rec; - char entry[32]; - char *p, *q; - int l; + TDB_DATA key, rec; + char entry[32]; + char *p, *q; + int l; - key.dptr = blinks_id; - key.dsize = strlen(blinks_id); - slprintf(entry, sizeof(entry), "%s;", db_key); + key.dptr = blinks_id; + key.dsize = strlen(blinks_id); + slprintf(entry, sizeof(entry), "%s;", db_key); - rec = tdb_fetch(pppdb, key); - if (rec.dptr == NULL || rec.dsize <= 0) { - if (rec.dptr != NULL) - free(rec.dptr); - return; - } - rec.dptr[rec.dsize-1] = 0; - p = strstr(rec.dptr, entry); - if (p != NULL) { - q = p + strlen(entry); - l = strlen(q) + 1; - memmove(p, q, l); - rec.dsize = p - rec.dptr + l; - if (tdb_store(pppdb, key, rec, TDB_REPLACE)) - error("couldn't update bundle link list (removal)"); - } - free(rec.dptr); + rec = tdb_fetch(pppdb, key); + if (rec.dptr == NULL || rec.dsize <= 0) { + if (rec.dptr != NULL) + free(rec.dptr); + return; + } + rec.dptr[rec.dsize-1] = 0; + p = strstr(rec.dptr, entry); + if (p != NULL) { + q = p + strlen(entry); + l = strlen(q) + 1; + memmove(p, q, l); + rec.dsize = p - rec.dptr + l; + if (tdb_store(pppdb, key, rec, TDB_REPLACE)) + error("couldn't update bundle link list (removal)"); + } + free(rec.dptr); } static void iterate_bundle_links(void (*func)(char *)) { - TDB_DATA key, rec, pp; - char *p, *q; + TDB_DATA key, rec, pp; + char *p, *q; - key.dptr = blinks_id; - key.dsize = strlen(blinks_id); - rec = tdb_fetch(pppdb, key); - if (rec.dptr == NULL || rec.dsize <= 0) { - error("bundle link list not found (iterating list)"); - if (rec.dptr != NULL) - free(rec.dptr); - return; - } - p = rec.dptr; - p[rec.dsize-1] = 0; - while ((q = strchr(p, ';')) != NULL) { - *q = 0; - key.dptr = p; - key.dsize = q - p; - pp = tdb_fetch(pppdb, key); - if (pp.dptr != NULL && pp.dsize > 0) { - pp.dptr[pp.dsize-1] = 0; - func(pp.dptr); - } - if (pp.dptr != NULL) - free(pp.dptr); - p = q + 1; - } - free(rec.dptr); + key.dptr = blinks_id; + key.dsize = strlen(blinks_id); + rec = tdb_fetch(pppdb, key); + if (rec.dptr == NULL || rec.dsize <= 0) { + error("bundle link list not found (iterating list)"); + if (rec.dptr != NULL) + free(rec.dptr); + return; + } + p = rec.dptr; + p[rec.dsize-1] = 0; + while ((q = strchr(p, ';')) != NULL) { + *q = 0; + key.dptr = p; + key.dsize = q - p; + pp = tdb_fetch(pppdb, key); + if (pp.dptr != NULL && pp.dsize > 0) { + pp.dptr[pp.dsize-1] = 0; + func(pp.dptr); + } + if (pp.dptr != NULL) + free(pp.dptr); + p = q + 1; + } + free(rec.dptr); } static int @@ -409,19 +409,19 @@ parse_num(str, key, valp) const char *key; int *valp; { - char *p, *endp; - int i; + char *p, *endp; + int i; - p = strstr(str, key); - if (p != 0) { - p += strlen(key); - i = strtol(p, &endp, 10); - if (endp != p && (*endp == 0 || *endp == ';')) { - *valp = i; - return 1; - } - } - return 0; + p = strstr(str, key); + if (p != 0) { + p += strlen(key); + i = strtol(p, &endp, 10); + if (endp != p && (*endp == 0 || *endp == ';')) { + *valp = i; + return 1; + } + } + return 0; } /* @@ -432,53 +432,53 @@ owns_unit(key, unit) TDB_DATA key; int unit; { - char ifkey[32]; - TDB_DATA kd, vd; - int ret = 0; + char ifkey[32]; + TDB_DATA kd, vd; + int ret = 0; - slprintf(ifkey, sizeof(ifkey), "IFNAME=ppp%d", unit); - kd.dptr = ifkey; - kd.dsize = strlen(ifkey); - vd = tdb_fetch(pppdb, kd); - if (vd.dptr != NULL) { - ret = vd.dsize == key.dsize - && memcmp(vd.dptr, key.dptr, vd.dsize) == 0; - free(vd.dptr); - } - return ret; + slprintf(ifkey, sizeof(ifkey), "IFNAME=ppp%d", unit); + kd.dptr = ifkey; + kd.dsize = strlen(ifkey); + vd = tdb_fetch(pppdb, kd); + if (vd.dptr != NULL) { + ret = vd.dsize == key.dsize + && memcmp(vd.dptr, key.dptr, vd.dsize) == 0; + free(vd.dptr); + } + return ret; } static int get_default_epdisc(ep) struct epdisc *ep; { - char *p; - struct hostent *hp; - u32_t addr; + char *p; + struct hostent *hp; + u32_t addr; - /* First try for an ethernet MAC address */ - p = get_first_ethernet(); - if (p != 0 && get_if_hwaddr(ep->value, p) >= 0) { - ep->class = EPD_MAC; - ep->length = 6; - return 1; - } + /* First try for an ethernet MAC address */ + p = get_first_ethernet(); + if (p != 0 && get_if_hwaddr(ep->value, p) >= 0) { + ep->class = EPD_MAC; + ep->length = 6; + return 1; + } - /* see if our hostname corresponds to a reasonable IP address */ - hp = gethostbyname(hostname); - if (hp != NULL) { - addr = *(u32_t *)hp->h_addr; - if (!bad_ip_adrs(addr)) { - addr = lwip_ntohl(addr); - if (!LOCAL_IP_ADDR(addr)) { - ep->class = EPD_IP; - set_ip_epdisc(ep, addr); - return 1; - } - } - } + /* see if our hostname corresponds to a reasonable IP address */ + hp = gethostbyname(hostname); + if (hp != NULL) { + addr = *(u32_t *)hp->h_addr; + if (!bad_ip_adrs(addr)) { + addr = lwip_ntohl(addr); + if (!LOCAL_IP_ADDR(addr)) { + ep->class = EPD_IP; + set_ip_epdisc(ep, addr); + return 1; + } + } + } - return 0; + return 0; } /* @@ -493,51 +493,51 @@ char * epdisc_to_str(ep) struct epdisc *ep; { - static char str[MAX_ENDP_LEN*3+8]; - u_char *p = ep->value; - int i, mask = 0; - char *q, c, c2; + static char str[MAX_ENDP_LEN*3+8]; + u_char *p = ep->value; + int i, mask = 0; + char *q, c, c2; - if (ep->class == EPD_NULL && ep->length == 0) - return "null"; - if (ep->class == EPD_IP && ep->length == 4) { - u32_t addr; + if (ep->class == EPD_NULL && ep->length == 0) + return "null"; + if (ep->class == EPD_IP && ep->length == 4) { + u32_t addr; - GETLONG(addr, p); - slprintf(str, sizeof(str), "IP:%I", lwip_htonl(addr)); - return str; - } + GETLONG(addr, p); + slprintf(str, sizeof(str), "IP:%I", lwip_htonl(addr)); + return str; + } - c = ':'; - c2 = '.'; - if (ep->class == EPD_MAC && ep->length == 6) - c2 = ':'; - else if (ep->class == EPD_MAGIC && (ep->length % 4) == 0) - mask = 3; - q = str; - if (ep->class <= EPD_PHONENUM) - q += slprintf(q, sizeof(str)-1, "%s", - endp_class_names[ep->class]); - else - q += slprintf(q, sizeof(str)-1, "%d", ep->class); - c = ':'; - for (i = 0; i < ep->length && i < MAX_ENDP_LEN; ++i) { - if ((i & mask) == 0) { - *q++ = c; - c = c2; - } - q += slprintf(q, str + sizeof(str) - q, "%.2x", ep->value[i]); - } - return str; + c = ':'; + c2 = '.'; + if (ep->class == EPD_MAC && ep->length == 6) + c2 = ':'; + else if (ep->class == EPD_MAGIC && (ep->length % 4) == 0) + mask = 3; + q = str; + if (ep->class <= EPD_PHONENUM) + q += slprintf(q, sizeof(str)-1, "%s", + endp_class_names[ep->class]); + else + q += slprintf(q, sizeof(str)-1, "%d", ep->class); + c = ':'; + for (i = 0; i < ep->length && i < MAX_ENDP_LEN; ++i) { + if ((i & mask) == 0) { + *q++ = c; + c = c2; + } + q += slprintf(q, str + sizeof(str) - q, "%.2x", ep->value[i]); + } + return str; } static int hexc_val(int c) { - if (c >= 'a') - return c - 'a' + 10; - if (c >= 'A') - return c - 'A' + 10; - return c - '0'; + if (c >= 'a') + return c - 'a' + 10; + if (c >= 'A') + return c - 'A' + 10; + return c - '0'; } int @@ -545,65 +545,65 @@ str_to_epdisc(ep, str) struct epdisc *ep; char *str; { - int i, l; - char *p, *endp; + int i, l; + char *p, *endp; - for (i = EPD_NULL; i <= EPD_PHONENUM; ++i) { - int sl = strlen(endp_class_names[i]); - if (strncasecmp(str, endp_class_names[i], sl) == 0) { - str += sl; - break; - } - } - if (i > EPD_PHONENUM) { - /* not a class name, try a decimal class number */ - i = strtol(str, &endp, 10); - if (endp == str) - return 0; /* can't parse class number */ - str = endp; - } - ep->class = i; - if (*str == 0) { - ep->length = 0; - return 1; - } - if (*str != ':' && *str != '.') - return 0; - ++str; + for (i = EPD_NULL; i <= EPD_PHONENUM; ++i) { + int sl = strlen(endp_class_names[i]); + if (strncasecmp(str, endp_class_names[i], sl) == 0) { + str += sl; + break; + } + } + if (i > EPD_PHONENUM) { + /* not a class name, try a decimal class number */ + i = strtol(str, &endp, 10); + if (endp == str) + return 0; /* can't parse class number */ + str = endp; + } + ep->class = i; + if (*str == 0) { + ep->length = 0; + return 1; + } + if (*str != ':' && *str != '.') + return 0; + ++str; - if (i == EPD_IP) { - u32_t addr; - i = parse_dotted_ip(str, &addr); - if (i == 0 || str[i] != 0) - return 0; - set_ip_epdisc(ep, addr); - return 1; - } - if (i == EPD_MAC && get_if_hwaddr(ep->value, str) >= 0) { - ep->length = 6; - return 1; - } + if (i == EPD_IP) { + u32_t addr; + i = parse_dotted_ip(str, &addr); + if (i == 0 || str[i] != 0) + return 0; + set_ip_epdisc(ep, addr); + return 1; + } + if (i == EPD_MAC && get_if_hwaddr(ep->value, str) >= 0) { + ep->length = 6; + return 1; + } - p = str; - for (l = 0; l < MAX_ENDP_LEN; ++l) { - if (*str == 0) - break; - if (p <= str) - for (p = str; isxdigit(*p); ++p) - ; - i = p - str; - if (i == 0) - return 0; - ep->value[l] = hexc_val(*str++); - if ((i & 1) == 0) - ep->value[l] = (ep->value[l] << 4) + hexc_val(*str++); - if (*str == ':' || *str == '.') - ++str; - } - if (*str != 0 || (ep->class == EPD_MAC && l != 6)) - return 0; - ep->length = l; - return 1; + p = str; + for (l = 0; l < MAX_ENDP_LEN; ++l) { + if (*str == 0) + break; + if (p <= str) + for (p = str; isxdigit(*p); ++p) + ; + i = p - str; + if (i == 0) + return 0; + ep->value[l] = hexc_val(*str++); + if ((i & 1) == 0) + ep->value[l] = (ep->value[l] << 4) + hexc_val(*str++); + if (*str == ':' || *str == '.') + ++str; + } + if (*str != 0 || (ep->class == EPD_MAC && l != 6)) + return 0; + ep->length = l; + return 1; } #endif /* PPP_SUPPORT && HAVE_MULTILINK */ diff --git a/components/network/lwip/src/netif/ppp/polarssl/arc4.c b/components/network/lwip/src/netif/ppp/polarssl/arc4.c index 6e17ec42..cb31b876 100644 --- a/components/network/lwip/src/netif/ppp/polarssl/arc4.c +++ b/components/network/lwip/src/netif/ppp/polarssl/arc4.c @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/netif/ppp/polarssl/des.c b/components/network/lwip/src/netif/ppp/polarssl/des.c index 9a89d007..b01e07fa 100644 --- a/components/network/lwip/src/netif/ppp/polarssl/des.c +++ b/components/network/lwip/src/netif/ppp/polarssl/des.c @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/netif/ppp/polarssl/md4.c b/components/network/lwip/src/netif/ppp/polarssl/md4.c index b1701a07..34e5b10c 100644 --- a/components/network/lwip/src/netif/ppp/polarssl/md4.c +++ b/components/network/lwip/src/netif/ppp/polarssl/md4.c @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/netif/ppp/polarssl/md5.c b/components/network/lwip/src/netif/ppp/polarssl/md5.c index 1ec4d81a..fa636584 100644 --- a/components/network/lwip/src/netif/ppp/polarssl/md5.c +++ b/components/network/lwip/src/netif/ppp/polarssl/md5.c @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 @@ -156,7 +156,7 @@ static void md5_process( md5_context *ctx, const unsigned char data[64] ) P( B, C, D, A, 12, 20, 0x8D2A4C8A ); #undef F - + #define F(x,y,z) (x ^ y ^ z) P( A, B, C, D, 5, 4, 0xFFFA3942 ); diff --git a/components/network/lwip/src/netif/ppp/polarssl/sha1.c b/components/network/lwip/src/netif/ppp/polarssl/sha1.c index c2192eac..6079af3b 100644 --- a/components/network/lwip/src/netif/ppp/polarssl/sha1.c +++ b/components/network/lwip/src/netif/ppp/polarssl/sha1.c @@ -10,7 +10,7 @@ * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * + * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright @@ -19,7 +19,7 @@ * * Neither the names of PolarSSL or XySSL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * 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 diff --git a/components/network/lwip/src/netif/ppp/ppp.c b/components/network/lwip/src/netif/ppp/ppp.c index a9c18e30..d2eaf559 100644 --- a/components/network/lwip/src/netif/ppp/ppp.c +++ b/components/network/lwip/src/netif/ppp/ppp.c @@ -633,7 +633,7 @@ int ppp_init(void) return 0; } - + /* * Create a new PPP control block. * diff --git a/components/network/lwip/src/netif/ppp/pppapi.c b/components/network/lwip/src/netif/ppp/pppapi.c index 947f7ba8..0ad8e986 100644 --- a/components/network/lwip/src/netif/ppp/pppapi.c +++ b/components/network/lwip/src/netif/ppp/pppapi.c @@ -57,10 +57,10 @@ LWIP_MEMPOOL_DECLARE(PPPAPI_MSG, MEMP_NUM_PPP_API_MSG, sizeof(struct pppapi_msg) static err_t pppapi_do_ppp_set_default(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; - + ppp_set_default(msg->msg.ppp); return ERR_OK; } @@ -90,7 +90,7 @@ pppapi_set_default(ppp_pcb *pcb) static err_t pppapi_do_ppp_set_notify_phase_callback(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -125,7 +125,7 @@ pppapi_set_notify_phase_callback(ppp_pcb *pcb, ppp_notify_phase_cb_fn notify_pha static err_t pppapi_do_pppos_create(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -166,7 +166,7 @@ pppapi_pppos_create(struct netif *pppif, pppos_output_cb_fn output_cb, static err_t pppapi_do_pppoe_create(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -211,7 +211,7 @@ pppapi_pppoe_create(struct netif *pppif, struct netif *ethif, const char *servic static err_t pppapi_do_pppol2tp_create(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -270,7 +270,7 @@ pppapi_pppol2tp_create(struct netif *pppif, struct netif *netif, ip_addr_t *ipad static err_t pppapi_do_ppp_connect(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -303,7 +303,7 @@ pppapi_connect(ppp_pcb *pcb, u16_t holdoff) static err_t pppapi_do_ppp_listen(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -335,7 +335,7 @@ pppapi_listen(ppp_pcb *pcb) static err_t pppapi_do_ppp_close(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -367,7 +367,7 @@ pppapi_close(ppp_pcb *pcb, u8_t nocarrier) static err_t pppapi_do_ppp_free(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; @@ -398,7 +398,7 @@ pppapi_free(ppp_pcb *pcb) static err_t pppapi_do_ppp_ioctl(struct tcpip_api_call_data *m) { - /* cast through void* to silence alignment warnings. + /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct pppapi_msg */ struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m; diff --git a/components/network/lwip/src/netif/ppp/pppcrypt.c b/components/network/lwip/src/netif/ppp/pppcrypt.c index 82d78c13..81e4008d 100644 --- a/components/network/lwip/src/netif/ppp/pppcrypt.c +++ b/components/network/lwip/src/netif/ppp/pppcrypt.c @@ -39,28 +39,28 @@ static u_char pppcrypt_get_7bits(u_char *input, int startBit) { - unsigned int word; + unsigned int word; - word = (unsigned)input[startBit / 8] << 8; - word |= (unsigned)input[startBit / 8 + 1]; + word = (unsigned)input[startBit / 8] << 8; + word |= (unsigned)input[startBit / 8 + 1]; - word >>= 15 - (startBit % 8 + 7); + word >>= 15 - (startBit % 8 + 7); - return word & 0xFE; + return word & 0xFE; } /* IN 56 bit DES key missing parity bits * OUT 64 bit DES key with parity bits added */ void pppcrypt_56_to_64_bit_key(u_char *key, u_char * des_key) { - des_key[0] = pppcrypt_get_7bits(key, 0); - des_key[1] = pppcrypt_get_7bits(key, 7); - des_key[2] = pppcrypt_get_7bits(key, 14); - des_key[3] = pppcrypt_get_7bits(key, 21); - des_key[4] = pppcrypt_get_7bits(key, 28); - des_key[5] = pppcrypt_get_7bits(key, 35); - des_key[6] = pppcrypt_get_7bits(key, 42); - des_key[7] = pppcrypt_get_7bits(key, 49); + des_key[0] = pppcrypt_get_7bits(key, 0); + des_key[1] = pppcrypt_get_7bits(key, 7); + des_key[2] = pppcrypt_get_7bits(key, 14); + des_key[3] = pppcrypt_get_7bits(key, 21); + des_key[4] = pppcrypt_get_7bits(key, 28); + des_key[5] = pppcrypt_get_7bits(key, 35); + des_key[6] = pppcrypt_get_7bits(key, 42); + des_key[7] = pppcrypt_get_7bits(key, 49); } #endif /* PPP_SUPPORT && MSCHAP_SUPPORT */ diff --git a/components/network/lwip/src/netif/ppp/pppoe.c b/components/network/lwip/src/netif/ppp/pppoe.c index 8ed2d638..461e8bce 100644 --- a/components/network/lwip/src/netif/ppp/pppoe.c +++ b/components/network/lwip/src/netif/ppp/pppoe.c @@ -6,13 +6,13 @@ * The authors hereby grant permission to use, copy, modify, distribute, * and license this software and its documentation for any purpose, provided * that existing copyright notices are retained in all copies and that this -* notice and the following disclaimer are included verbatim in any +* notice and the following disclaimer are included verbatim in any * distributions. No written agreement, license, or royalty fee is required * for any of the authorized uses. * * THIS SOFTWARE IS PROVIDED BY THE 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. +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE 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, @@ -666,7 +666,7 @@ pppoe_data_input(struct netif *netif, struct pbuf *pb) PPPDEBUG(LOG_ERR, ("pppoe_data_input: pbuf_remove_header failed\n")); LINK_STATS_INC(link.lenerr); goto drop; - } + } if (pb->len < sizeof(*ph)) { PPPDEBUG(LOG_DEBUG, ("pppoe_data_input: could not get PPPoE header\n")); @@ -699,7 +699,7 @@ pppoe_data_input(struct netif *netif, struct pbuf *pb) PPPDEBUG(LOG_ERR, ("pppoe_data_input: pbuf_remove_header PPPOE_HEADERLEN failed\n")); LINK_STATS_INC(link.lenerr); goto drop; - } + } PPPDEBUG(LOG_DEBUG, ("pppoe_data_input: %c%c%"U16_F": pkthdr.len=%d, pppoe.len=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, diff --git a/components/network/lwip/src/netif/ppp/upap.c b/components/network/lwip/src/netif/ppp/upap.c index 3b2399dc..23891284 100644 --- a/components/network/lwip/src/netif/ppp/upap.c +++ b/components/network/lwip/src/netif/ppp/upap.c @@ -166,12 +166,12 @@ void upap_authwithpeer(ppp_pcb *pcb, const char *user, const char *password) { /* Lower layer up yet? */ if (pcb->upap.us_clientstate == UPAPCS_INITIAL || - pcb->upap.us_clientstate == UPAPCS_PENDING) { - pcb->upap.us_clientstate = UPAPCS_PENDING; - return; + pcb->upap.us_clientstate == UPAPCS_PENDING) { + pcb->upap.us_clientstate = UPAPCS_PENDING; + return; } - upap_sauthreq(pcb); /* Start protocol */ + upap_sauthreq(pcb); /* Start protocol */ } #if PPP_SERVER @@ -184,14 +184,14 @@ void upap_authpeer(ppp_pcb *pcb) { /* Lower layer up yet? */ if (pcb->upap.us_serverstate == UPAPSS_INITIAL || - pcb->upap.us_serverstate == UPAPSS_PENDING) { - pcb->upap.us_serverstate = UPAPSS_PENDING; - return; + pcb->upap.us_serverstate == UPAPSS_PENDING) { + pcb->upap.us_serverstate = UPAPSS_PENDING; + return; } pcb->upap.us_serverstate = UPAPSS_LISTEN; if (pcb->settings.pap_req_timeout > 0) - TIMEOUT(upap_reqtimeout, pcb, pcb->settings.pap_req_timeout); + TIMEOUT(upap_reqtimeout, pcb, pcb->settings.pap_req_timeout); } #endif /* PPP_SERVER */ @@ -202,17 +202,17 @@ static void upap_timeout(void *arg) { ppp_pcb *pcb = (ppp_pcb*)arg; if (pcb->upap.us_clientstate != UPAPCS_AUTHREQ) - return; + return; if (pcb->upap.us_transmits >= pcb->settings.pap_max_transmits) { - /* give up in disgust */ - ppp_error("No response to PAP authenticate-requests"); - pcb->upap.us_clientstate = UPAPCS_BADAUTH; - auth_withpeer_fail(pcb, PPP_PAP); - return; + /* give up in disgust */ + ppp_error("No response to PAP authenticate-requests"); + pcb->upap.us_clientstate = UPAPCS_BADAUTH; + auth_withpeer_fail(pcb, PPP_PAP); + return; } - upap_sauthreq(pcb); /* Send Authenticate-Request */ + upap_sauthreq(pcb); /* Send Authenticate-Request */ } @@ -224,7 +224,7 @@ static void upap_reqtimeout(void *arg) { ppp_pcb *pcb = (ppp_pcb*)arg; if (pcb->upap.us_serverstate != UPAPSS_LISTEN) - return; /* huh?? */ + return; /* huh?? */ auth_peer_fail(pcb, PPP_PAP); pcb->upap.us_serverstate = UPAPSS_BADAUTH; @@ -240,18 +240,18 @@ static void upap_reqtimeout(void *arg) { static void upap_lowerup(ppp_pcb *pcb) { if (pcb->upap.us_clientstate == UPAPCS_INITIAL) - pcb->upap.us_clientstate = UPAPCS_CLOSED; + pcb->upap.us_clientstate = UPAPCS_CLOSED; else if (pcb->upap.us_clientstate == UPAPCS_PENDING) { - upap_sauthreq(pcb); /* send an auth-request */ + upap_sauthreq(pcb); /* send an auth-request */ } #if PPP_SERVER if (pcb->upap.us_serverstate == UPAPSS_INITIAL) - pcb->upap.us_serverstate = UPAPSS_CLOSED; + pcb->upap.us_serverstate = UPAPSS_CLOSED; else if (pcb->upap.us_serverstate == UPAPSS_PENDING) { - pcb->upap.us_serverstate = UPAPSS_LISTEN; - if (pcb->settings.pap_req_timeout > 0) - TIMEOUT(upap_reqtimeout, pcb, pcb->settings.pap_req_timeout); + pcb->upap.us_serverstate = UPAPSS_LISTEN; + if (pcb->settings.pap_req_timeout > 0) + TIMEOUT(upap_reqtimeout, pcb, pcb->settings.pap_req_timeout); } #endif /* PPP_SERVER */ } @@ -264,11 +264,11 @@ static void upap_lowerup(ppp_pcb *pcb) { */ static void upap_lowerdown(ppp_pcb *pcb) { - if (pcb->upap.us_clientstate == UPAPCS_AUTHREQ) /* Timeout pending? */ - UNTIMEOUT(upap_timeout, pcb); /* Cancel timeout */ + if (pcb->upap.us_clientstate == UPAPCS_AUTHREQ) /* Timeout pending? */ + UNTIMEOUT(upap_timeout, pcb); /* Cancel timeout */ #if PPP_SERVER if (pcb->upap.us_serverstate == UPAPSS_LISTEN && pcb->settings.pap_req_timeout > 0) - UNTIMEOUT(upap_reqtimeout, pcb); + UNTIMEOUT(upap_reqtimeout, pcb); #endif /* PPP_SERVER */ pcb->upap.us_clientstate = UPAPCS_INITIAL; @@ -286,13 +286,13 @@ static void upap_lowerdown(ppp_pcb *pcb) { static void upap_protrej(ppp_pcb *pcb) { if (pcb->upap.us_clientstate == UPAPCS_AUTHREQ) { - ppp_error("PAP authentication failed due to protocol-reject"); - auth_withpeer_fail(pcb, PPP_PAP); + ppp_error("PAP authentication failed due to protocol-reject"); + auth_withpeer_fail(pcb, PPP_PAP); } #if PPP_SERVER if (pcb->upap.us_serverstate == UPAPSS_LISTEN) { - ppp_error("PAP authentication of peer failed (protocol-reject)"); - auth_peer_fail(pcb, PPP_PAP); + ppp_error("PAP authentication of peer failed (protocol-reject)"); + auth_peer_fail(pcb, PPP_PAP); } #endif /* PPP_SERVER */ upap_lowerdown(pcb); @@ -313,19 +313,19 @@ static void upap_input(ppp_pcb *pcb, u_char *inpacket, int l) { */ inp = inpacket; if (l < UPAP_HEADERLEN) { - UPAPDEBUG(("pap_input: rcvd short header.")); - return; + UPAPDEBUG(("pap_input: rcvd short header.")); + return; } GETCHAR(code, inp); GETCHAR(id, inp); GETSHORT(len, inp); if (len < UPAP_HEADERLEN) { - UPAPDEBUG(("pap_input: rcvd illegal length.")); - return; + UPAPDEBUG(("pap_input: rcvd illegal length.")); + return; } if (len > l) { - UPAPDEBUG(("pap_input: rcvd short packet.")); - return; + UPAPDEBUG(("pap_input: rcvd short packet.")); + return; } len -= UPAP_HEADERLEN; @@ -335,20 +335,20 @@ static void upap_input(ppp_pcb *pcb, u_char *inpacket, int l) { switch (code) { case UPAP_AUTHREQ: #if PPP_SERVER - upap_rauthreq(pcb, inp, id, len); + upap_rauthreq(pcb, inp, id, len); #endif /* PPP_SERVER */ - break; + break; case UPAP_AUTHACK: - upap_rauthack(pcb, inp, id, len); - break; + upap_rauthack(pcb, inp, id, len); + break; case UPAP_AUTHNAK: - upap_rauthnak(pcb, inp, id, len); - break; + upap_rauthnak(pcb, inp, id, len); + break; - default: /* XXX Need code reject */ - break; + default: /* XXX Need code reject */ + break; } } @@ -366,40 +366,40 @@ static void upap_rauthreq(ppp_pcb *pcb, u_char *inp, int id, int len) { int msglen; if (pcb->upap.us_serverstate < UPAPSS_LISTEN) - return; + return; /* * If we receive a duplicate authenticate-request, we are * supposed to return the same status as for the first request. */ if (pcb->upap.us_serverstate == UPAPSS_OPEN) { - upap_sresp(pcb, UPAP_AUTHACK, id, "", 0); /* return auth-ack */ - return; + upap_sresp(pcb, UPAP_AUTHACK, id, "", 0); /* return auth-ack */ + return; } if (pcb->upap.us_serverstate == UPAPSS_BADAUTH) { - upap_sresp(pcb, UPAP_AUTHNAK, id, "", 0); /* return auth-nak */ - return; + upap_sresp(pcb, UPAP_AUTHNAK, id, "", 0); /* return auth-nak */ + return; } /* * Parse user/passwd. */ if (len < 1) { - UPAPDEBUG(("pap_rauth: rcvd short packet.")); - return; + UPAPDEBUG(("pap_rauth: rcvd short packet.")); + return; } GETCHAR(ruserlen, inp); len -= sizeof (u_char) + ruserlen + sizeof (u_char); if (len < 0) { - UPAPDEBUG(("pap_rauth: rcvd short packet.")); - return; + UPAPDEBUG(("pap_rauth: rcvd short packet.")); + return; } ruser = (char *) inp; INCPTR(ruserlen, inp); GETCHAR(rpasswdlen, inp); if (len < rpasswdlen) { - UPAPDEBUG(("pap_rauth: rcvd short packet.")); - return; + UPAPDEBUG(("pap_rauth: rcvd short packet.")); + return; } rpasswd = (char *) inp; @@ -420,16 +420,16 @@ static void upap_rauthreq(ppp_pcb *pcb, u_char *inp, int id, int len) { * return an authenticate failure, is leaving it for us to verify. */ if (retcode == UPAP_AUTHACK) { - if (!auth_number()) { - /* We do not want to leak info about the pap result. */ - retcode = UPAP_AUTHNAK; /* XXX exit value will be "wrong" */ - warn("calling number %q is not authorized", remote_number); - } + if (!auth_number()) { + /* We do not want to leak info about the pap result. */ + retcode = UPAP_AUTHNAK; /* XXX exit value will be "wrong" */ + warn("calling number %q is not authorized", remote_number); + } } msglen = strlen(msg); if (msglen > 255) - msglen = 255; + msglen = 255; #endif /* UNUSED */ upap_sresp(pcb, retcode, id, msg, msglen); @@ -438,17 +438,17 @@ static void upap_rauthreq(ppp_pcb *pcb, u_char *inp, int id, int len) { ppp_slprintf(rhostname, sizeof(rhostname), "%.*v", ruserlen, ruser); if (retcode == UPAP_AUTHACK) { - pcb->upap.us_serverstate = UPAPSS_OPEN; - ppp_notice("PAP peer authentication succeeded for %q", rhostname); - auth_peer_success(pcb, PPP_PAP, 0, ruser, ruserlen); + pcb->upap.us_serverstate = UPAPSS_OPEN; + ppp_notice("PAP peer authentication succeeded for %q", rhostname); + auth_peer_success(pcb, PPP_PAP, 0, ruser, ruserlen); } else { - pcb->upap.us_serverstate = UPAPSS_BADAUTH; - ppp_warn("PAP peer authentication failed for %q", rhostname); - auth_peer_fail(pcb, PPP_PAP); + pcb->upap.us_serverstate = UPAPSS_BADAUTH; + ppp_warn("PAP peer authentication failed for %q", rhostname); + auth_peer_fail(pcb, PPP_PAP); } if (pcb->settings.pap_req_timeout > 0) - UNTIMEOUT(upap_reqtimeout, pcb); + UNTIMEOUT(upap_reqtimeout, pcb); } #endif /* PPP_SERVER */ @@ -461,24 +461,24 @@ static void upap_rauthack(ppp_pcb *pcb, u_char *inp, int id, int len) { LWIP_UNUSED_ARG(id); if (pcb->upap.us_clientstate != UPAPCS_AUTHREQ) /* XXX */ - return; + return; /* * Parse message. */ if (len < 1) { - UPAPDEBUG(("pap_rauthack: ignoring missing msg-length.")); + UPAPDEBUG(("pap_rauthack: ignoring missing msg-length.")); } else { - GETCHAR(msglen, inp); - if (msglen > 0) { - len -= sizeof (u_char); - if (len < msglen) { - UPAPDEBUG(("pap_rauthack: rcvd short packet.")); - return; - } - msg = (char *) inp; - PRINTMSG(msg, msglen); - } + GETCHAR(msglen, inp); + if (msglen > 0) { + len -= sizeof (u_char); + if (len < msglen) { + UPAPDEBUG(("pap_rauthack: rcvd short packet.")); + return; + } + msg = (char *) inp; + PRINTMSG(msg, msglen); + } } pcb->upap.us_clientstate = UPAPCS_OPEN; @@ -496,24 +496,24 @@ static void upap_rauthnak(ppp_pcb *pcb, u_char *inp, int id, int len) { LWIP_UNUSED_ARG(id); if (pcb->upap.us_clientstate != UPAPCS_AUTHREQ) /* XXX */ - return; + return; /* * Parse message. */ if (len < 1) { - UPAPDEBUG(("pap_rauthnak: ignoring missing msg-length.")); + UPAPDEBUG(("pap_rauthnak: ignoring missing msg-length.")); } else { - GETCHAR(msglen, inp); - if (msglen > 0) { - len -= sizeof (u_char); - if (len < msglen) { - UPAPDEBUG(("pap_rauthnak: rcvd short packet.")); - return; - } - msg = (char *) inp; - PRINTMSG(msg, msglen); - } + GETCHAR(msglen, inp); + if (msglen > 0) { + len -= sizeof (u_char); + if (len < msglen) { + UPAPDEBUG(("pap_rauthnak: rcvd short packet.")); + return; + } + msg = (char *) inp; + PRINTMSG(msg, msglen); + } } pcb->upap.us_clientstate = UPAPCS_BADAUTH; @@ -532,7 +532,7 @@ static void upap_sauthreq(ppp_pcb *pcb) { int outlen; outlen = UPAP_HEADERLEN + 2 * sizeof (u_char) + - pcb->upap.us_userlen + pcb->upap.us_passwdlen; + pcb->upap.us_userlen + pcb->upap.us_passwdlen; p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN +outlen), PPP_CTRL_PBUF_TYPE); if(NULL == p) return; @@ -606,68 +606,68 @@ static int upap_printpkt(const u_char *p, int plen, void (*printer) (void *, con const u_char *pstart; if (plen < UPAP_HEADERLEN) - return 0; + return 0; pstart = p; GETCHAR(code, p); GETCHAR(id, p); GETSHORT(len, p); if (len < UPAP_HEADERLEN || len > plen) - return 0; + return 0; if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(upap_codenames)) - printer(arg, " %s", upap_codenames[code-1]); + printer(arg, " %s", upap_codenames[code-1]); else - printer(arg, " code=0x%x", code); + printer(arg, " code=0x%x", code); printer(arg, " id=0x%x", id); len -= UPAP_HEADERLEN; switch (code) { case UPAP_AUTHREQ: - if (len < 1) - break; - ulen = p[0]; - if (len < ulen + 2) - break; - wlen = p[ulen + 1]; - if (len < ulen + wlen + 2) - break; - user = (const u_char *) (p + 1); - pwd = (const u_char *) (p + ulen + 2); - p += ulen + wlen + 2; - len -= ulen + wlen + 2; - printer(arg, " user="); - ppp_print_string(user, ulen, printer, arg); - printer(arg, " password="); + if (len < 1) + break; + ulen = p[0]; + if (len < ulen + 2) + break; + wlen = p[ulen + 1]; + if (len < ulen + wlen + 2) + break; + user = (const u_char *) (p + 1); + pwd = (const u_char *) (p + ulen + 2); + p += ulen + wlen + 2; + len -= ulen + wlen + 2; + printer(arg, " user="); + ppp_print_string(user, ulen, printer, arg); + printer(arg, " password="); /* FIXME: require ppp_pcb struct as printpkt() argument */ #if 0 - if (!pcb->settings.hide_password) + if (!pcb->settings.hide_password) #endif - ppp_print_string(pwd, wlen, printer, arg); + ppp_print_string(pwd, wlen, printer, arg); #if 0 - else - printer(arg, ""); + else + printer(arg, ""); #endif - break; + break; case UPAP_AUTHACK: case UPAP_AUTHNAK: - if (len < 1) - break; - mlen = p[0]; - if (len < mlen + 1) - break; - msg = (const u_char *) (p + 1); - p += mlen + 1; - len -= mlen + 1; - printer(arg, " "); - ppp_print_string(msg, mlen, printer, arg); - break; + if (len < 1) + break; + mlen = p[0]; + if (len < mlen + 1) + break; + msg = (const u_char *) (p + 1); + p += mlen + 1; + len -= mlen + 1; + printer(arg, " "); + ppp_print_string(msg, mlen, printer, arg); + break; default: - break; + break; } /* print the rest of the bytes in the packet */ for (; len > 0; --len) { - GETCHAR(code, p); - printer(arg, " %.2x", code); + GETCHAR(code, p); + printer(arg, " %.2x", code); } return p - pstart; diff --git a/components/network/lwip/src/netif/ppp/utils.c b/components/network/lwip/src/netif/ppp/utils.c index f1366dae..e9c8ba1c 100644 --- a/components/network/lwip/src/netif/ppp/utils.c +++ b/components/network/lwip/src/netif/ppp/utils.c @@ -72,7 +72,7 @@ static void ppp_log_write(int level, char *buf); #if PRINTPKT_SUPPORT static void ppp_vslp_printer(void *arg, const char *fmt, ...); static void ppp_format_packet(const u_char *p, int len, - void (*printer) (void *, const char *, ...), void *arg); + void (*printer) (void *, const char *, ...), void *arg); struct buffer_info { char *ptr; @@ -88,12 +88,12 @@ size_t ppp_strlcpy(char *dest, const char *src, size_t len) { size_t ret = strlen(src); if (len != 0) { - if (ret < len) - strcpy(dest, src); - else { - strncpy(dest, src, len - 1); - dest[len-1] = 0; - } + if (ret < len) + strcpy(dest, src); + else { + strncpy(dest, src, len - 1); + dest[len-1] = 0; + } } return ret; } @@ -130,7 +130,7 @@ int ppp_slprintf(char *buf, int buflen, const char *fmt, ...) { /* * ppp_vslprintf - like ppp_slprintf, takes a va_list instead of a list of args. */ -#define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0) +#define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0) int ppp_vslprintf(char *buf, int buflen, const char *fmt, va_list args) { int c, i, n; @@ -153,249 +153,249 @@ int ppp_vslprintf(char *buf, int buflen, const char *fmt, va_list args) { buf0 = buf; --buflen; while (buflen > 0) { - for (f = fmt; *f != '%' && *f != 0; ++f) - ; - if (f > fmt) { - len = f - fmt; - if (len > buflen) - len = buflen; - memcpy(buf, fmt, len); - buf += len; - buflen -= len; - fmt = f; - } - if (*fmt == 0) - break; - c = *++fmt; - width = 0; - prec = -1; - fillch = ' '; - if (c == '0') { - fillch = '0'; - c = *++fmt; - } - if (c == '*') { - width = va_arg(args, int); - c = *++fmt; - } else { - while (lwip_isdigit(c)) { - width = width * 10 + c - '0'; - c = *++fmt; - } - } - if (c == '.') { - c = *++fmt; - if (c == '*') { - prec = va_arg(args, int); - c = *++fmt; - } else { - prec = 0; - while (lwip_isdigit(c)) { - prec = prec * 10 + c - '0'; - c = *++fmt; - } - } - } - str = 0; - base = 0; - neg = 0; - ++fmt; - switch (c) { - case 'l': - c = *fmt++; - switch (c) { - case 'd': - val = va_arg(args, long); - if ((long)val < 0) { - neg = 1; - val = (unsigned long)-(long)val; - } - base = 10; - break; - case 'u': - val = va_arg(args, unsigned long); - base = 10; - break; - default: - OUTCHAR('%'); - OUTCHAR('l'); - --fmt; /* so %lz outputs %lz etc. */ - continue; - } - break; - case 'd': - i = va_arg(args, int); - if (i < 0) { - neg = 1; - val = -i; - } else - val = i; - base = 10; - break; - case 'u': - val = va_arg(args, unsigned int); - base = 10; - break; - case 'o': - val = va_arg(args, unsigned int); - base = 8; - break; - case 'x': - case 'X': - val = va_arg(args, unsigned int); - base = 16; - break; + for (f = fmt; *f != '%' && *f != 0; ++f) + ; + if (f > fmt) { + len = f - fmt; + if (len > buflen) + len = buflen; + memcpy(buf, fmt, len); + buf += len; + buflen -= len; + fmt = f; + } + if (*fmt == 0) + break; + c = *++fmt; + width = 0; + prec = -1; + fillch = ' '; + if (c == '0') { + fillch = '0'; + c = *++fmt; + } + if (c == '*') { + width = va_arg(args, int); + c = *++fmt; + } else { + while (lwip_isdigit(c)) { + width = width * 10 + c - '0'; + c = *++fmt; + } + } + if (c == '.') { + c = *++fmt; + if (c == '*') { + prec = va_arg(args, int); + c = *++fmt; + } else { + prec = 0; + while (lwip_isdigit(c)) { + prec = prec * 10 + c - '0'; + c = *++fmt; + } + } + } + str = 0; + base = 0; + neg = 0; + ++fmt; + switch (c) { + case 'l': + c = *fmt++; + switch (c) { + case 'd': + val = va_arg(args, long); + if ((long)val < 0) { + neg = 1; + val = (unsigned long)-(long)val; + } + base = 10; + break; + case 'u': + val = va_arg(args, unsigned long); + base = 10; + break; + default: + OUTCHAR('%'); + OUTCHAR('l'); + --fmt; /* so %lz outputs %lz etc. */ + continue; + } + break; + case 'd': + i = va_arg(args, int); + if (i < 0) { + neg = 1; + val = -i; + } else + val = i; + base = 10; + break; + case 'u': + val = va_arg(args, unsigned int); + base = 10; + break; + case 'o': + val = va_arg(args, unsigned int); + base = 8; + break; + case 'x': + case 'X': + val = va_arg(args, unsigned int); + base = 16; + break; #if 0 /* unused (and wrong on LLP64 systems) */ - case 'p': - val = (unsigned long) va_arg(args, void *); - base = 16; - neg = 2; - break; + case 'p': + val = (unsigned long) va_arg(args, void *); + base = 16; + neg = 2; + break; #endif /* unused (and wrong on LLP64 systems) */ - case 's': - str = va_arg(args, char *); - break; - case 'c': - num[0] = va_arg(args, int); - num[1] = 0; - str = num; - break; + case 's': + str = va_arg(args, char *); + break; + case 'c': + num[0] = va_arg(args, int); + num[1] = 0; + str = num; + break; #if 0 /* do we always have strerror() in embedded ? */ - case 'm': - str = strerror(errno); - break; + case 'm': + str = strerror(errno); + break; #endif /* do we always have strerror() in embedded ? */ - case 'I': - ip = va_arg(args, u32_t); - ip = lwip_ntohl(ip); - ppp_slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff, - (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff); - str = num; - break; + case 'I': + ip = va_arg(args, u32_t); + ip = lwip_ntohl(ip); + ppp_slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff, + (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff); + str = num; + break; #if 0 /* need port */ - case 't': - time(&t); - str = ctime(&t); - str += 4; /* chop off the day name */ - str[15] = 0; /* chop off year and newline */ - break; + case 't': + time(&t); + str = ctime(&t); + str += 4; /* chop off the day name */ + str[15] = 0; /* chop off year and newline */ + break; #endif /* need port */ - case 'v': /* "visible" string */ - case 'q': /* quoted string */ - quoted = c == 'q'; - p = va_arg(args, unsigned char *); - if (p == NULL) - p = (const unsigned char *)""; - if (fillch == '0' && prec >= 0) { - n = prec; - } else { - n = strlen((const char *)p); - if (prec >= 0 && n > prec) - n = prec; - } - while (n > 0 && buflen > 0) { - c = *p++; - --n; - if (!quoted && c >= 0x80) { - OUTCHAR('M'); - OUTCHAR('-'); - c -= 0x80; - } - if (quoted && (c == '"' || c == '\\')) - OUTCHAR('\\'); - if (c < 0x20 || (0x7f <= c && c < 0xa0)) { - if (quoted) { - OUTCHAR('\\'); - switch (c) { - case '\t': OUTCHAR('t'); break; - case '\n': OUTCHAR('n'); break; - case '\b': OUTCHAR('b'); break; - case '\f': OUTCHAR('f'); break; - default: - OUTCHAR('x'); - OUTCHAR(hexchars[c >> 4]); - OUTCHAR(hexchars[c & 0xf]); - } - } else { - if (c == '\t') - OUTCHAR(c); - else { - OUTCHAR('^'); - OUTCHAR(c ^ 0x40); - } - } - } else - OUTCHAR(c); - } - continue; + case 'v': /* "visible" string */ + case 'q': /* quoted string */ + quoted = c == 'q'; + p = va_arg(args, unsigned char *); + if (p == NULL) + p = (const unsigned char *)""; + if (fillch == '0' && prec >= 0) { + n = prec; + } else { + n = strlen((const char *)p); + if (prec >= 0 && n > prec) + n = prec; + } + while (n > 0 && buflen > 0) { + c = *p++; + --n; + if (!quoted && c >= 0x80) { + OUTCHAR('M'); + OUTCHAR('-'); + c -= 0x80; + } + if (quoted && (c == '"' || c == '\\')) + OUTCHAR('\\'); + if (c < 0x20 || (0x7f <= c && c < 0xa0)) { + if (quoted) { + OUTCHAR('\\'); + switch (c) { + case '\t': OUTCHAR('t'); break; + case '\n': OUTCHAR('n'); break; + case '\b': OUTCHAR('b'); break; + case '\f': OUTCHAR('f'); break; + default: + OUTCHAR('x'); + OUTCHAR(hexchars[c >> 4]); + OUTCHAR(hexchars[c & 0xf]); + } + } else { + if (c == '\t') + OUTCHAR(c); + else { + OUTCHAR('^'); + OUTCHAR(c ^ 0x40); + } + } + } else + OUTCHAR(c); + } + continue; #if PRINTPKT_SUPPORT - case 'P': /* print PPP packet */ - bufinfo.ptr = buf; - bufinfo.len = buflen + 1; - p = va_arg(args, unsigned char *); - n = va_arg(args, int); - ppp_format_packet(p, n, ppp_vslp_printer, &bufinfo); - buf = bufinfo.ptr; - buflen = bufinfo.len - 1; - continue; + case 'P': /* print PPP packet */ + bufinfo.ptr = buf; + bufinfo.len = buflen + 1; + p = va_arg(args, unsigned char *); + n = va_arg(args, int); + ppp_format_packet(p, n, ppp_vslp_printer, &bufinfo); + buf = bufinfo.ptr; + buflen = bufinfo.len - 1; + continue; #endif /* PRINTPKT_SUPPORT */ - case 'B': - p = va_arg(args, unsigned char *); - for (n = prec; n > 0; --n) { - c = *p++; - if (fillch == ' ') - OUTCHAR(' '); - OUTCHAR(hexchars[(c >> 4) & 0xf]); - OUTCHAR(hexchars[c & 0xf]); - } - continue; - default: - *buf++ = '%'; - if (c != '%') - --fmt; /* so %z outputs %z etc. */ - --buflen; - continue; - } - if (base != 0) { - str = num + sizeof(num); - *--str = 0; - while (str > num + neg) { - *--str = hexchars[val % base]; - val = val / base; - if (--prec <= 0 && val == 0) - break; - } - switch (neg) { - case 1: - *--str = '-'; - break; - case 2: - *--str = 'x'; - *--str = '0'; - break; - default: - break; - } - len = num + sizeof(num) - 1 - str; - } else { - len = strlen(str); - if (prec >= 0 && len > prec) - len = prec; - } - if (width > 0) { - if (width > buflen) - width = buflen; - if ((n = width - len) > 0) { - buflen -= n; - for (; n > 0; --n) - *buf++ = fillch; - } - } - if (len > buflen) - len = buflen; - memcpy(buf, str, len); - buf += len; - buflen -= len; + case 'B': + p = va_arg(args, unsigned char *); + for (n = prec; n > 0; --n) { + c = *p++; + if (fillch == ' ') + OUTCHAR(' '); + OUTCHAR(hexchars[(c >> 4) & 0xf]); + OUTCHAR(hexchars[c & 0xf]); + } + continue; + default: + *buf++ = '%'; + if (c != '%') + --fmt; /* so %z outputs %z etc. */ + --buflen; + continue; + } + if (base != 0) { + str = num + sizeof(num); + *--str = 0; + while (str > num + neg) { + *--str = hexchars[val % base]; + val = val / base; + if (--prec <= 0 && val == 0) + break; + } + switch (neg) { + case 1: + *--str = '-'; + break; + case 2: + *--str = 'x'; + *--str = '0'; + break; + default: + break; + } + len = num + sizeof(num) - 1 - str; + } else { + len = strlen(str); + if (prec >= 0 && len > prec) + len = prec; + } + if (width > 0) { + if (width > buflen) + width = buflen; + if ((n = width - len) > 0) { + buflen -= n; + for (; n > 0; --n) + *buf++ = fillch; + } + } + if (len > buflen) + len = buflen; + memcpy(buf, str, len); + buf += len; + buflen -= len; } *buf = 0; return buf - buf0; @@ -432,9 +432,9 @@ log_packet(p, len, prefix, level) char *prefix; int level; { - init_pr_log(prefix, level); - ppp_format_packet(p, len, pr_log, &level); - end_pr_log(); + init_pr_log(prefix, level); + ppp_format_packet(p, len, pr_log, &level); + end_pr_log(); } #endif /* UNUSED */ @@ -444,43 +444,43 @@ log_packet(p, len, prefix, level) * calling `printer(arg, format, ...)' to output it. */ static void ppp_format_packet(const u_char *p, int len, - void (*printer) (void *, const char *, ...), void *arg) { + void (*printer) (void *, const char *, ...), void *arg) { int i, n; u_short proto; const struct protent *protp; if (len >= 2) { - GETSHORT(proto, p); - len -= 2; - for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (proto == protp->protocol) - break; - if (protp != NULL) { - printer(arg, "[%s", protp->name); - n = (*protp->printpkt)(p, len, printer, arg); - printer(arg, "]"); - p += n; - len -= n; - } else { - for (i = 0; (protp = protocols[i]) != NULL; ++i) - if (proto == (protp->protocol & ~0x8000)) - break; - if (protp != 0 && protp->data_name != 0) { - printer(arg, "[%s data]", protp->data_name); - if (len > 8) - printer(arg, "%.8B ...", p); - else - printer(arg, "%.*B", len, p); - len = 0; - } else - printer(arg, "[proto=0x%x]", proto); - } + GETSHORT(proto, p); + len -= 2; + for (i = 0; (protp = protocols[i]) != NULL; ++i) + if (proto == protp->protocol) + break; + if (protp != NULL) { + printer(arg, "[%s", protp->name); + n = (*protp->printpkt)(p, len, printer, arg); + printer(arg, "]"); + p += n; + len -= n; + } else { + for (i = 0; (protp = protocols[i]) != NULL; ++i) + if (proto == (protp->protocol & ~0x8000)) + break; + if (protp != 0 && protp->data_name != 0) { + printer(arg, "[%s data]", protp->data_name); + if (len > 8) + printer(arg, "%.8B ...", p); + else + printer(arg, "%.*B", len, p); + len = 0; + } else + printer(arg, "[proto=0x%x]", proto); + } } if (len > 32) - printer(arg, "%.32B ...", p); + printer(arg, "%.32B ...", p); else - printer(arg, "%.*B", len, p); + printer(arg, "%.*B", len, p); } #endif /* PRINTPKT_SUPPORT */ @@ -489,30 +489,30 @@ static void ppp_format_packet(const u_char *p, int len, * init_pr_log, end_pr_log - initialize and finish use of pr_log. */ -static char line[256]; /* line to be logged accumulated here */ -static char *linep; /* current pointer within line */ -static int llevel; /* level for logging */ +static char line[256]; /* line to be logged accumulated here */ +static char *linep; /* current pointer within line */ +static int llevel; /* level for logging */ void init_pr_log(prefix, level) const char *prefix; int level; { - linep = line; - if (prefix != NULL) { - ppp_strlcpy(line, prefix, sizeof(line)); - linep = line + strlen(line); - } - llevel = level; + linep = line; + if (prefix != NULL) { + ppp_strlcpy(line, prefix, sizeof(line)); + linep = line + strlen(line); + } + llevel = level; } void end_pr_log() { - if (linep != line) { - *linep = 0; - ppp_log_write(llevel, line); - } + if (linep != line) { + *linep = 0; + ppp_log_write(llevel, line); + } } /* @@ -521,47 +521,47 @@ end_pr_log() void pr_log (void *arg, const char *fmt, ...) { - int l, n; - va_list pvar; - char *p, *eol; - char buf[256]; + int l, n; + va_list pvar; + char *p, *eol; + char buf[256]; - va_start(pvar, fmt); - n = ppp_vslprintf(buf, sizeof(buf), fmt, pvar); - va_end(pvar); + va_start(pvar, fmt); + n = ppp_vslprintf(buf, sizeof(buf), fmt, pvar); + va_end(pvar); - p = buf; - eol = strchr(buf, '\n'); - if (linep != line) { - l = (eol == NULL)? n: eol - buf; - if (linep + l < line + sizeof(line)) { - if (l > 0) { - memcpy(linep, buf, l); - linep += l; - } - if (eol == NULL) - return; - p = eol + 1; - eol = strchr(p, '\n'); - } - *linep = 0; - ppp_log_write(llevel, line); - linep = line; - } + p = buf; + eol = strchr(buf, '\n'); + if (linep != line) { + l = (eol == NULL)? n: eol - buf; + if (linep + l < line + sizeof(line)) { + if (l > 0) { + memcpy(linep, buf, l); + linep += l; + } + if (eol == NULL) + return; + p = eol + 1; + eol = strchr(p, '\n'); + } + *linep = 0; + ppp_log_write(llevel, line); + linep = line; + } - while (eol != NULL) { - *eol = 0; - ppp_log_write(llevel, p); - p = eol + 1; - eol = strchr(p, '\n'); - } + while (eol != NULL) { + *eol = 0; + ppp_log_write(llevel, p); + p = eol + 1; + eol = strchr(p, '\n'); + } - /* assumes sizeof(buf) <= sizeof(line) */ - l = buf + n - p; - if (l > 0) { - memcpy(line, p, n); - linep = line + l; - } + /* assumes sizeof(buf) <= sizeof(line) */ + l = buf + n - p; + if (l > 0) { + memcpy(line, p, n); + linep = line + l; + } } #endif /* UNUSED */ @@ -574,27 +574,27 @@ void ppp_print_string(const u_char *p, int len, void (*printer) (void *, const c printer(arg, "\""); for (; len > 0; --len) { - c = *p++; - if (' ' <= c && c <= '~') { - if (c == '\\' || c == '"') - printer(arg, "\\"); - printer(arg, "%c", c); - } else { - switch (c) { - case '\n': - printer(arg, "\\n"); - break; - case '\r': - printer(arg, "\\r"); - break; - case '\t': - printer(arg, "\\t"); - break; - default: - printer(arg, "\\%.3o", (u8_t)c); - /* no break */ - } - } + c = *p++; + if (' ' <= c && c <= '~') { + if (c == '\\' || c == '"') + printer(arg, "\\"); + printer(arg, "%c", c); + } else { + switch (c) { + case '\n': + printer(arg, "\\n"); + break; + case '\r': + printer(arg, "\\r"); + break; + case '\t': + printer(arg, "\\t"); + break; + default: + printer(arg, "\\%.3o", (u8_t)c); + /* no break */ + } + } } printer(arg, "\""); } @@ -615,13 +615,13 @@ static void ppp_log_write(int level, char *buf) { PPPDEBUG(level, ("%s\n", buf) ); #if 0 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) { - int n = strlen(buf); + int n = strlen(buf); - if (n > 0 && buf[n-1] == '\n') - --n; - if (write(log_to_fd, buf, n) != n - || write(log_to_fd, "\n", 1) != 1) - log_to_fd = -1; + if (n > 0 && buf[n-1] == '\n') + --n; + if (write(log_to_fd, buf, n) != n + || write(log_to_fd, "\n", 1) != 1) + log_to_fd = -1; } #endif } @@ -710,18 +710,18 @@ void ppp_dump_packet(ppp_pcb *pcb, const char *tag, unsigned char *p, int len) { */ proto = (p[0] << 8) + p[1]; if (proto < 0xC000 && (proto & ~0x8000) == proto) - return; + return; /* * don't print valid LCP echo request/reply packets if the link is up. */ if (proto == PPP_LCP && pcb->phase == PPP_PHASE_RUNNING && len >= 2 + HEADERLEN) { - unsigned char *lcp = p + 2; - int l = (lcp[2] << 8) + lcp[3]; + unsigned char *lcp = p + 2; + int l = (lcp[2] << 8) + lcp[3]; - if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP) - && l >= HEADERLEN && l <= len - 2) - return; + if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP) + && l >= HEADERLEN && l <= len - 2) + return; } ppp_dbglog("%s %P", tag, p, len); @@ -737,34 +737,34 @@ void ppp_dump_packet(ppp_pcb *pcb, const char *tag, unsigned char *p, int len) { ssize_t complete_read(int fd, void *buf, size_t count) { - size_t done; - ssize_t nb; - char *ptr = buf; + size_t done; + ssize_t nb; + char *ptr = buf; - for (done = 0; done < count; ) { - nb = read(fd, ptr, count - done); - if (nb < 0) { - if (errno == EINTR) - continue; - return -1; - } - if (nb == 0) - break; - done += nb; - ptr += nb; - } - return done; + for (done = 0; done < count; ) { + nb = read(fd, ptr, count - done); + if (nb < 0) { + if (errno == EINTR) + continue; + return -1; + } + if (nb == 0) + break; + done += nb; + ptr += nb; + } + return done; } /* Procedures for locking the serial device using a lock file. */ #ifndef LOCK_DIR #ifdef __linux__ -#define LOCK_DIR "/var/lock" +#define LOCK_DIR "/var/lock" #else #ifdef SVR4 -#define LOCK_DIR "/var/spool/locks" +#define LOCK_DIR "/var/spool/locks" #else -#define LOCK_DIR "/var/spool/lock" +#define LOCK_DIR "/var/spool/lock" #endif #endif #endif /* LOCK_DIR */ @@ -783,14 +783,14 @@ lock(dev) result = mklock (dev, (void *) 0); if (result == 0) { - ppp_strlcpy(lock_file, dev, sizeof(lock_file)); - return 0; + ppp_strlcpy(lock_file, dev, sizeof(lock_file)); + return 0; } if (result > 0) ppp_notice("Device %s is locked by pid %d", dev, result); else - ppp_error("Can't create lock file %s", lock_file); + ppp_error("Can't create lock file %s", lock_file); return -1; #else /* LOCKLIB */ @@ -802,83 +802,83 @@ lock(dev) struct stat sbuf; if (stat(dev, &sbuf) < 0) { - ppp_error("Can't get device number for %s: %m", dev); - return -1; + ppp_error("Can't get device number for %s: %m", dev); + return -1; } if ((sbuf.st_mode & S_IFMT) != S_IFCHR) { - ppp_error("Can't lock %s: not a character device", dev); - return -1; + ppp_error("Can't lock %s: not a character device", dev); + return -1; } ppp_slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d", - LOCK_DIR, major(sbuf.st_dev), - major(sbuf.st_rdev), minor(sbuf.st_rdev)); + LOCK_DIR, major(sbuf.st_dev), + major(sbuf.st_rdev), minor(sbuf.st_rdev)); #else char *p; char lockdev[MAXPATHLEN]; if ((p = strstr(dev, "dev/")) != NULL) { - dev = p + 4; - strncpy(lockdev, dev, MAXPATHLEN-1); - lockdev[MAXPATHLEN-1] = 0; - while ((p = strrchr(lockdev, '/')) != NULL) { - *p = '_'; - } - dev = lockdev; + dev = p + 4; + strncpy(lockdev, dev, MAXPATHLEN-1); + lockdev[MAXPATHLEN-1] = 0; + while ((p = strrchr(lockdev, '/')) != NULL) { + *p = '_'; + } + dev = lockdev; } else - if ((p = strrchr(dev, '/')) != NULL) - dev = p + 1; + if ((p = strrchr(dev, '/')) != NULL) + dev = p + 1; ppp_slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev); #endif while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) { - if (errno != EEXIST) { - ppp_error("Can't create lock file %s: %m", lock_file); - break; - } + if (errno != EEXIST) { + ppp_error("Can't create lock file %s: %m", lock_file); + break; + } - /* Read the lock file to find out who has the device locked. */ - fd = open(lock_file, O_RDONLY, 0); - if (fd < 0) { - if (errno == ENOENT) /* This is just a timing problem. */ - continue; - ppp_error("Can't open existing lock file %s: %m", lock_file); - break; - } + /* Read the lock file to find out who has the device locked. */ + fd = open(lock_file, O_RDONLY, 0); + if (fd < 0) { + if (errno == ENOENT) /* This is just a timing problem. */ + continue; + ppp_error("Can't open existing lock file %s: %m", lock_file); + break; + } #ifndef LOCK_BINARY - n = read(fd, lock_buffer, 11); + n = read(fd, lock_buffer, 11); #else - n = read(fd, &pid, sizeof(pid)); + n = read(fd, &pid, sizeof(pid)); #endif /* LOCK_BINARY */ - close(fd); - fd = -1; - if (n <= 0) { - ppp_error("Can't read pid from lock file %s", lock_file); - break; - } + close(fd); + fd = -1; + if (n <= 0) { + ppp_error("Can't read pid from lock file %s", lock_file); + break; + } - /* See if the process still exists. */ + /* See if the process still exists. */ #ifndef LOCK_BINARY - lock_buffer[n] = 0; - pid = atoi(lock_buffer); + lock_buffer[n] = 0; + pid = atoi(lock_buffer); #endif /* LOCK_BINARY */ - if (pid == getpid()) - return 1; /* somebody else locked it for us */ - if (pid == 0 - || (kill(pid, 0) == -1 && errno == ESRCH)) { - if (unlink (lock_file) == 0) { - ppp_notice("Removed stale lock on %s (pid %d)", dev, pid); - continue; - } - ppp_warn("Couldn't remove stale lock on %s", dev); - } else - ppp_notice("Device %s is locked by pid %d", dev, pid); - break; + if (pid == getpid()) + return 1; /* somebody else locked it for us */ + if (pid == 0 + || (kill(pid, 0) == -1 && errno == ESRCH)) { + if (unlink (lock_file) == 0) { + ppp_notice("Removed stale lock on %s (pid %d)", dev, pid); + continue; + } + ppp_warn("Couldn't remove stale lock on %s", dev); + } else + ppp_notice("Device %s is locked by pid %d", dev, pid); + break; } if (fd < 0) { - lock_file[0] = 0; - return -1; + lock_file[0] = 0; + return -1; } pid = getpid(); @@ -916,12 +916,12 @@ relock(pid) char lock_buffer[12]; if (lock_file[0] == 0) - return -1; + return -1; fd = open(lock_file, O_WRONLY, 0); if (fd < 0) { - ppp_error("Couldn't reopen lock file %s: %m", lock_file); - lock_file[0] = 0; - return -1; + ppp_error("Couldn't reopen lock file %s: %m", lock_file); + lock_file[0] = 0; + return -1; } #ifndef LOCK_BINARY @@ -944,11 +944,11 @@ unlock() { if (lock_file[0]) { #ifdef LOCKLIB - (void) rmlock(lock_file, (void *) 0); + (void) rmlock(lock_file, (void *) 0); #else - unlink(lock_file); + unlink(lock_file); #endif - lock_file[0] = 0; + lock_file[0] = 0; } } diff --git a/components/network/lwip/test/fuzz/Makefile b/components/network/lwip/test/fuzz/Makefile index ccbe9561..c0d93502 100644 --- a/components/network/lwip/test/fuzz/Makefile +++ b/components/network/lwip/test/fuzz/Makefile @@ -1,8 +1,8 @@ # # Copyright (c) 2001, 2002 Swedish Institute of Computer Science. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, +# 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, @@ -11,21 +11,21 @@ # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. +# derived from this software without specific prior written permission. # -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. # # This file is part of the lwIP TCP/IP stack. -# +# # Author: Adam Dunkels # diff --git a/components/network/lwip/test/fuzz/fuzz.c b/components/network/lwip/test/fuzz/fuzz.c index 8aa07ecc..ecebc570 100644 --- a/components/network/lwip/test/fuzz/fuzz.c +++ b/components/network/lwip/test/fuzz/fuzz.c @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Erik Ekman * */ diff --git a/components/network/lwip/test/fuzz/lwipopts.h b/components/network/lwip/test/fuzz/lwipopts.h index 4ab26f28..50e60806 100644 --- a/components/network/lwip/test/fuzz/lwipopts.h +++ b/components/network/lwip/test/fuzz/lwipopts.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Simon Goldschmidt * */ diff --git a/components/network/lwip/test/sockets/sockets_stresstest.c b/components/network/lwip/test/sockets/sockets_stresstest.c index 3ac553b1..e73cfe3b 100644 --- a/components/network/lwip/test/sockets/sockets_stresstest.c +++ b/components/network/lwip/test/sockets/sockets_stresstest.c @@ -16,12 +16,12 @@ * - full duplex * - add asserts about internal socket/netconn/pcb state? */ - + /* * Copyright (c) 2017 Simon Goldschmidt * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * + * 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, @@ -30,21 +30,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Simon Goldschmidt * */ diff --git a/components/network/lwip/test/sockets/sockets_stresstest.h b/components/network/lwip/test/sockets/sockets_stresstest.h index 178e604a..256ea000 100644 --- a/components/network/lwip/test/sockets/sockets_stresstest.h +++ b/components/network/lwip/test/sockets/sockets_stresstest.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2017 Simon Goldschmidt * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Simon Goldschmidt * */ diff --git a/components/network/lwip/test/unit/Filelists.mk b/components/network/lwip/test/unit/Filelists.mk index 4b770782..97b5df3e 100644 --- a/components/network/lwip/test/unit/Filelists.mk +++ b/components/network/lwip/test/unit/Filelists.mk @@ -1,8 +1,8 @@ # # Copyright (c) 2001, 2002 Swedish Institute of Computer Science. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, +# 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, @@ -11,21 +11,21 @@ # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. +# derived from this software without specific prior written permission. # -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. # # This file is part of the lwIP TCP/IP stack. -# +# # Author: Adam Dunkels # diff --git a/components/network/lwip/test/unit/api/test_sockets.c b/components/network/lwip/test/unit/api/test_sockets.c index 472fa489..ed2b8112 100644 --- a/components/network/lwip/test/unit/api/test_sockets.c +++ b/components/network/lwip/test/unit/api/test_sockets.c @@ -255,7 +255,7 @@ static void test_sockets_msgapi_update_iovs(struct msghdr *msg, size_t bytes) /* note: this modifies the underyling iov_base and iov_len for a partial read for an individual vector. This updates the msg->msg_iov pointer to skip fully consumed vecotrs */ - + /* process fully consumed vectors */ for (i = 0; i < msg->msg_iovlen; i++) { if (msg->msg_iov[i].iov_len <= bytes) { @@ -395,7 +395,7 @@ static void test_sockets_msgapi_tcp(int domain) /* note: since we always receive after sending, there will be open space in the send buffer */ fail_unless(ret > 0); - + bytes_written += ret; if (bytes_written < TOTAL_DATA_SZ) { test_sockets_msgapi_update_iovs(&smsg, (size_t)ret); @@ -432,7 +432,7 @@ static void test_sockets_msgapi_tcp(int domain) } } while(ret > 0); } - + ret = lwip_close(s1); fail_unless(ret == 0); ret = lwip_close(s2); @@ -588,13 +588,13 @@ static void test_sockets_msgapi_cmsg(int domain) memset(rcv_buf, 0, sizeof(rcv_buf)); ret = lwip_sendto(s, snd_buf, sizeof(snd_buf), 0, (struct sockaddr*)&addr_storage, addr_size); fail_unless(ret == sizeof(snd_buf)); - + tcpip_thread_poll_one(); ret = lwip_recvmsg(s, &msg, 0); fail_unless(ret == sizeof(rcv_buf)); fail_unless(!memcmp(rcv_buf, snd_buf, sizeof(rcv_buf))); - + /* Verify message header */ cmsg = CMSG_FIRSTHDR(&msg); fail_unless(cmsg != NULL); diff --git a/components/network/lwip/test/unit/arch/sys_arch.c b/components/network/lwip/test/unit/arch/sys_arch.c index cf826ebf..a84e3784 100644 --- a/components/network/lwip/test/unit/arch/sys_arch.c +++ b/components/network/lwip/test/unit/arch/sys_arch.c @@ -1,8 +1,8 @@ /* * Copyright (c) 2017 Simon Goldschmidt - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Simon Goldschmidt * */ diff --git a/components/network/lwip/test/unit/arch/sys_arch.h b/components/network/lwip/test/unit/arch/sys_arch.h index 331c2f2f..ef829dec 100644 --- a/components/network/lwip/test/unit/arch/sys_arch.h +++ b/components/network/lwip/test/unit/arch/sys_arch.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2017 Simon Goldschmidt - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Simon Goldschmidt * */ diff --git a/components/network/lwip/test/unit/core/test_timers.c b/components/network/lwip/test/unit/core/test_timers.c index 820b7189..30f6ac4c 100644 --- a/components/network/lwip/test/unit/core/test_timers.c +++ b/components/network/lwip/test/unit/core/test_timers.c @@ -61,7 +61,7 @@ do_test_cyclic_timers(u32_t offset) fail_unless(cyclic_fired == 1); fail_unless((*list_head)->time == (u32_t)(lwip_sys_now + test_cyclic.interval_ms - HANDLER_EXECUTION_TIME)); - + sys_untimeout(lwip_cyclic_timer, &test_cyclic); @@ -128,7 +128,7 @@ static void do_test_timers(u32_t offset) { struct sys_timeo** list_head = sys_timeouts_get_next_timeout(); - + lwip_sys_now = offset + 0; sys_timeout(10, dummy_handler, LWIP_PTR_NUMERIC_CAST(void*, 0)); @@ -142,7 +142,7 @@ do_test_timers(u32_t offset) fail_unless((*list_head)->time == (u32_t)(lwip_sys_now + 5)); fail_unless((*list_head)->next->time == (u32_t)(lwip_sys_now + 10)); fail_unless((*list_head)->next->next->time == (u32_t)(lwip_sys_now + 20)); - + /* check timers expire in correct order */ memset(&fired, 0, sizeof(fired)); diff --git a/components/network/lwip/test/unit/lwipopts.h b/components/network/lwip/test/unit/lwipopts.h index c00ace15..7f077d21 100644 --- a/components/network/lwip/test/unit/lwipopts.h +++ b/components/network/lwip/test/unit/lwipopts.h @@ -1,8 +1,8 @@ /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, + * 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, @@ -11,21 +11,21 @@ * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * derived from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. - * + * * Author: Simon Goldschmidt * */ diff --git a/components/network/lwip/test/unit/tcp/tcp_helper.c b/components/network/lwip/test/unit/tcp/tcp_helper.c index 8689b71a..feaa3e5d 100644 --- a/components/network/lwip/test/unit/tcp/tcp_helper.c +++ b/components/network/lwip/test/unit/tcp/tcp_helper.c @@ -151,13 +151,13 @@ tcp_set_state(struct tcp_pcb* pcb, enum tcp_state state, const ip_addr_t* local_ /* @todo: are these all states? */ /* @todo: remove from previous list */ pcb->state = state; - + iss = tcp_next_iss(pcb); pcb->snd_wl2 = iss; pcb->snd_nxt = iss; pcb->lastack = iss; pcb->snd_lbb = iss; - + if (state == ESTABLISHED) { TCP_REG(&tcp_active_pcbs, pcb); ip_addr_copy(pcb->local_ip, *local_ip); diff --git a/components/network/lwip/test/unit/tcp/test_tcp.c b/components/network/lwip/test/unit/tcp/test_tcp.c index c7f85f6a..941e4f42 100644 --- a/components/network/lwip/test/unit/tcp/test_tcp.c +++ b/components/network/lwip/test/unit/tcp/test_tcp.c @@ -524,7 +524,7 @@ START_TEST(test_tcp_fast_retx_recover) EXPECT_RET(pcb->dupacks == 3); memset(&txcounters, 0, sizeof(txcounters)); /* @todo: check expected data?*/ - + /* send data5, not output yet */ err = tcp_write(pcb, data5, sizeof(data5), TCP_WRITE_FLAG_COPY); EXPECT_RET(err == ERR_OK); @@ -1263,7 +1263,7 @@ static void test_tcp_rto_timeout_impl(int link_down) /* check our pcb is no longer active */ for (cur = tcp_active_pcbs; cur != NULL; cur = cur->next) { EXPECT(cur != pcb); - } + } EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } @@ -1359,7 +1359,7 @@ static void test_tcp_rto_timeout_syn_sent_impl(int link_down) /* check our pcb is no longer active */ for (cur = tcp_active_pcbs; cur != NULL; cur = cur->next) { EXPECT(cur != pcb); - } + } EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } @@ -1409,7 +1409,7 @@ static void test_tcp_zwp_timeout_impl(int link_down) EXPECT(err == ERR_OK); err = tcp_output(pcb); EXPECT(err == ERR_OK); - + /* verify segment is in-flight */ EXPECT(pcb->unsent == NULL); check_seqnos(pcb->unacked, 1, seqnos); @@ -1488,7 +1488,7 @@ static void test_tcp_zwp_timeout_impl(int link_down) /* check our pcb is no longer active */ for (cur = tcp_active_pcbs; cur != NULL; cur = cur->next) { EXPECT(cur != pcb); - } + } EXPECT_RET(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0); } diff --git a/components/network/lwip_altcp_tls_mbedtls/bouffalo.mk b/components/network/lwip_altcp_tls_mbedtls/bouffalo.mk index f6681fbc..f8023ed5 100644 --- a/components/network/lwip_altcp_tls_mbedtls/bouffalo.mk +++ b/components/network/lwip_altcp_tls_mbedtls/bouffalo.mk @@ -6,7 +6,7 @@ COMPONENT_ADD_INCLUDEDIRS += include ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := include -## This component's src +## This component's src COMPONENT_SRCS := src/altcp_tls_mbedtls.c \ src/altcp_tls_mbedtls_mem.c COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) @@ -15,4 +15,4 @@ COMPONENT_SRCDIRS := src ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/network/lwip_altcp_tls_mbedtls/src/altcp_tls_mbedtls.c b/components/network/lwip_altcp_tls_mbedtls/src/altcp_tls_mbedtls.c index 2687e152..f2c3b09f 100644 --- a/components/network/lwip_altcp_tls_mbedtls/src/altcp_tls_mbedtls.c +++ b/components/network/lwip_altcp_tls_mbedtls/src/altcp_tls_mbedtls.c @@ -886,7 +886,7 @@ altcp_tls_free_config(struct altcp_tls_config *conf) } if (conf->ca) { mbedtls_x509_crt_free(conf->ca); - } + } altcp_mbedtls_free_config(conf); } diff --git a/components/network/lwip_dhcpd/bouffalo.mk b/components/network/lwip_dhcpd/bouffalo.mk index 3167ed38..73059e24 100644 --- a/components/network/lwip_dhcpd/bouffalo.mk +++ b/components/network/lwip_dhcpd/bouffalo.mk @@ -2,11 +2,11 @@ # ## These include paths would be exported to project level COMPONENT_ADD_INCLUDEDIRS += . - -## not be exported to project level -COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## not be exported to project level +COMPONENT_PRIV_INCLUDEDIRS := + +## This component's src COMPONENT_SRCS := dhcp_server_raw.c COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) @@ -14,4 +14,4 @@ COMPONENT_SRCDIRS := . ## -#CPPFLAGS += \ No newline at end of file +#CPPFLAGS += \ No newline at end of file diff --git a/components/network/lwip_dhcpd/dhcp_server_raw.c b/components/network/lwip_dhcpd/dhcp_server_raw.c index 925bd175..58b95ff3 100644 --- a/components/network/lwip_dhcpd/dhcp_server_raw.c +++ b/components/network/lwip_dhcpd/dhcp_server_raw.c @@ -27,7 +27,7 @@ /* DHCP server option */ #define DHCP_CLIENT_PORT 68 -#define DHCP_SERVER_PORT 67 +#define DHCP_SERVER_PORT 67 /* allocated client ip range */ #ifndef DHCPD_CLIENT_IP_MIN diff --git a/components/network/lwip_mdns/bouffalo.mk b/components/network/lwip_mdns/bouffalo.mk index 1a1990f7..7fc15d51 100644 --- a/components/network/lwip_mdns/bouffalo.mk +++ b/components/network/lwip_mdns/bouffalo.mk @@ -2,11 +2,11 @@ # ## These include paths would be exported to project level COMPONENT_ADD_INCLUDEDIRS += . - -## not be exported to project level -COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## not be exported to project level +COMPONENT_PRIV_INCLUDEDIRS := + +## This component's src COMPONENT_SRCS := mdns_server.c COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) @@ -14,4 +14,4 @@ COMPONENT_SRCDIRS := . ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/network/lwip_mdns/mdns_server.c b/components/network/lwip_mdns/mdns_server.c index 6bb4df54..5f33a516 100644 --- a/components/network/lwip_mdns/mdns_server.c +++ b/components/network/lwip_mdns/mdns_server.c @@ -2386,7 +2386,7 @@ mdns_resp_init(void) { err_t res; static u8_t flag = 1; - + /* LWIP_ASSERT_CORE_LOCKED(); is checked by udp_new() */ mdns_pcb = udp_new_ip_type(IPADDR_TYPE_ANY); @@ -2443,7 +2443,7 @@ int mdns_responder_start(struct netif *netif) return -1; } - mdns_resp_init(); + mdns_resp_init(); ret = mdns_resp_add_netif(netif, "mdns", 3600); if (ret != 0) { mdns_resp_deinit(); @@ -2468,7 +2468,7 @@ int mdns_responder_stop(struct netif *netif) printf("netif is NULL\r\n"); return -1; } - + ret = mdns_resp_remove_netif(netif); if (ret != 0) { printf("remove netif failed:%d\r\n", ret); diff --git a/components/network/netutils/bouffalo.mk b/components/network/netutils/bouffalo.mk index 81e875e3..6387912f 100644 --- a/components/network/netutils/bouffalo.mk +++ b/components/network/netutils/bouffalo.mk @@ -6,7 +6,7 @@ COMPONENT_ADD_INCLUDEDIRS += ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src COMPONENT_SRCS := tcpclient/tcpclient.c \ tcpserver/tcpserver.c \ iperf/iperf.c \ @@ -20,4 +20,4 @@ COMPONENT_SRCDIRS := tcpclient iperf netstat ping tcpserver ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/network/netutils/iperf/iperf.c b/components/network/netutils/iperf/iperf.c index 52784d35..21cd5394 100644 --- a/components/network/netutils/iperf/iperf.c +++ b/components/network/netutils/iperf/iperf.c @@ -449,7 +449,7 @@ static void iperf_server_udp_recv_fn(void *arg, struct udp_pcb *pcb, struct pbuf ctx->packet_id = (int32_t)udp_header.id; } - pbuf_free(p); + pbuf_free(p); } static void iperf_server_udp(void *arg) diff --git a/components/network/netutils/netstat/netstat.c b/components/network/netutils/netstat/netstat.c index 7260c3c0..575f2217 100644 --- a/components/network/netutils/netstat/netstat.c +++ b/components/network/netutils/netstat/netstat.c @@ -38,7 +38,7 @@ #if LWIP_STATS -static void cmd_netstat(char *buf, int len, int argc, char **argv) +static void cmd_netstat(char *buf, int len, int argc, char **argv) { tcpip_callback(stats_netstat, NULL); } @@ -46,7 +46,7 @@ static void cmd_netstat(char *buf, int len, int argc, char **argv) // STATIC_CLI_CMD_ATTRIBUTE makes this(these) command(s) static const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { {"netstat", "show current net states", cmd_netstat}, -}; +}; #endif @@ -55,6 +55,6 @@ int network_netutils_netstat_cli_register() // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/network/netutils/tcpclient/tcpclient.c b/components/network/netutils/tcpclient/tcpclient.c index 66febf86..0bcde5da 100644 --- a/components/network/netutils/tcpclient/tcpclient.c +++ b/components/network/netutils/tcpclient/tcpclient.c @@ -125,7 +125,7 @@ failed_nothing: for (i = 0; i < IPERF_BUFSZ; i ++) send_buf[i] = i & 0xff; - while (param.mode != IPERF_MODE_STOP) + while (param.mode != IPERF_MODE_STOP) { @@ -143,7 +143,7 @@ failed_nothing: sentlen = 0; tick1 = xTaskGetTickCount(); - while(param.mode != IPERF_MODE_STOP) + while(param.mode != IPERF_MODE_STOP) { tick2 = xTaskGetTickCount(); if (tick2 - tick1 >= 1000 * 5) @@ -159,7 +159,7 @@ failed_nothing: } ret = send(sock, send_buf, IPERF_BUFSZ, 0); - if (ret > 0) + if (ret > 0) { sentlen += ret; } @@ -201,13 +201,13 @@ void tcpclient_cmd(char *buf, int len, int argc, char **argv) // STATIC_CLI_CMD_ATTRIBUTE makes this(these) command(s) static const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { { "tcpc", "create a tcpc for in a new task", tcpclient_cmd}, -}; +}; int network_netutils_tcpclinet_cli_register() { // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/network/netutils/tcpclient/tools/tcp-echo-server.c b/components/network/netutils/tcpclient/tools/tcp-echo-server.c index 69860f6b..4d29166f 100644 --- a/components/network/netutils/tcpclient/tools/tcp-echo-server.c +++ b/components/network/netutils/tcpclient/tools/tcp-echo-server.c @@ -36,13 +36,13 @@ uv_loop_t *loop; struct sockaddr_in addr; -void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) +void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { buf->base = (char*)malloc(suggested_size); buf->len = suggested_size; } -void echo_write(uv_write_t *req, int status) +void echo_write(uv_write_t *req, int status) { if (status) { fprintf(stderr, "Write error %s\n", uv_strerror(status)); @@ -51,7 +51,7 @@ void echo_write(uv_write_t *req, int status) free(req); } -void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) +void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { if (nread < 0) { if (nread != UV_EOF) { @@ -70,7 +70,7 @@ void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) } } -void on_new_connection(uv_stream_t *server, int status) +void on_new_connection(uv_stream_t *server, int status) { if (status < 0) { fprintf(stderr, "New connection error %s\n", uv_strerror(status)); @@ -86,7 +86,7 @@ void on_new_connection(uv_stream_t *server, int status) } } -int main() +int main() { loop = uv_default_loop(); diff --git a/components/network/netutils/tcpserver/tcpserver.c b/components/network/netutils/tcpserver/tcpserver.c index 03383c25..15b52a24 100644 --- a/components/network/netutils/tcpserver/tcpserver.c +++ b/components/network/netutils/tcpserver/tcpserver.c @@ -48,7 +48,7 @@ void TCP_Server(void *pvParameters) char *data_buffer; int yes = 1; int connect_time[MAXCLIENTNUM]; - + int time_cur, time_diff[MAXCLIENTNUM], time_last[MAXCLIENTNUM]; fd_set fdsr; int maxsock; @@ -63,7 +63,7 @@ void TCP_Server(void *pvParameters) memset(time_diff, 0, sizeof(time_diff)); memset(time_last, 0, sizeof(time_last)); memset(connect_time, 0, sizeof(connect_time)); - + if ((listening_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) < 0)) { printf("socket creat failed\r\n"); @@ -87,7 +87,7 @@ void TCP_Server(void *pvParameters) } if (listen(listening_socket, MAXCLIENTNUM) < 0) { - printf("listen failed\r\n"); + printf("listen failed\r\n"); goto Failed; } @@ -169,7 +169,7 @@ void TCP_Server(void *pvParameters) } } } - /*client connect require*/ + /*client connect require*/ if (FD_ISSET(listening_socket, &fdsr)) { if ((new_connection = accept(listening_socket, (struct sockaddr *)&client_addr, &client_addrlen)) <= 0) { printf("accept failed\r\n"); @@ -178,7 +178,7 @@ void TCP_Server(void *pvParameters) printf("new_sock:%d\r\n", new_connection); } - printf("We successfully got a connection from %s:%d\r\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); + printf("We successfully got a connection from %s:%d\r\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); printf("We are waiting to receive data\r\n"); if (con_amount < MAXCLIENTNUM) { @@ -196,7 +196,7 @@ void TCP_Server(void *pvParameters) break; } } - } else { + } else { printf("Max connections arrived!\r\n"); send(new_connection, "Bye", 4, 0); closesocket(new_connection); @@ -221,13 +221,13 @@ static void cmd_tcp_server(char *buf, int len, int argc, char **argv) const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { { "tcps", "create a tcp server for in a new task", cmd_tcp_server}, -}; +}; int network_netutils_tcpserver_cli_register() { // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/network/sntp/bouffalo.mk b/components/network/sntp/bouffalo.mk index babd6526..fc34abef 100644 --- a/components/network/sntp/bouffalo.mk +++ b/components/network/sntp/bouffalo.mk @@ -6,7 +6,7 @@ COMPONENT_ADD_INCLUDEDIRS += include ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src COMPONENT_SRCS := sntp.c \ sntp_cli.c \ @@ -17,4 +17,4 @@ COMPONENT_SRCDIRS := . ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/network/sntp/sntp.c b/components/network/sntp/sntp.c index 043a5ff0..eb6048b8 100644 --- a/components/network/sntp/sntp.c +++ b/components/network/sntp/sntp.c @@ -452,7 +452,7 @@ sntp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u8_t mode; u8_t stratum; err_t err; - + printf("SNTP time now\r\n"); LWIP_UNUSED_ARG(arg); diff --git a/components/network/sntp/sntp_cli.c b/components/network/sntp/sntp_cli.c index f1265edc..89b3b9db 100644 --- a/components/network/sntp/sntp_cli.c +++ b/components/network/sntp/sntp_cli.c @@ -66,13 +66,13 @@ const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { { "sntp_start", "sntp start", cmd_sntp_start}, { "sntp_time", "sntp time", cmd_sntp_time}, { "sntp_date", "sntp date", cmd_sntp_date}, -}; +}; int sntp_cli_init(void) { // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/security/mbedtls/bouffalo.mk b/components/security/mbedtls/bouffalo.mk index cebda093..7baea5ff 100644 --- a/components/security/mbedtls/bouffalo.mk +++ b/components/security/mbedtls/bouffalo.mk @@ -12,7 +12,7 @@ $(NAME)_MBINS_TYPE := kernel $(NAME)_VERSION := 2.0.1 $(NAME)_SUMMARY := Mbed Transport Layer Security on Embedded Devices for AliOS Things -## This component's src +## This component's src COMPONENT_SRCS := src/aes.c COMPONENT_SRCS += src/aesni.c COMPONENT_SRCS += src/arc4.c @@ -95,4 +95,4 @@ COMPONENT_SRCDIRS := src ## -CPPFLAGS += -DLWIP_ENABLED -DCONFIG_PLAT_AOS +CPPFLAGS += -DLWIP_ENABLED -DCONFIG_PLAT_AOS diff --git a/components/security/mbedtls/src/ecjpake.c b/components/security/mbedtls/src/ecjpake.c index 1fa1c2d8..9218c5d1 100644 --- a/components/security/mbedtls/src/ecjpake.c +++ b/components/security/mbedtls/src/ecjpake.c @@ -299,7 +299,7 @@ cleanup: */ static int ecjpake_zkp_write( const mbedtls_md_info_t *md_info, const mbedtls_ecp_group *grp, - const int pf, + const int pf, const mbedtls_ecp_point *G, const mbedtls_mpi *x, const mbedtls_ecp_point *X, diff --git a/components/security/mbedtls/src/entropy.c b/components/security/mbedtls/src/entropy.c index fce66506..51839a8f 100644 --- a/components/security/mbedtls/src/entropy.c +++ b/components/security/mbedtls/src/entropy.c @@ -315,7 +315,7 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len ) * Always gather extra entropy before a call */ do - { + { if( count++ > ENTROPY_MAX_LOOP ) { ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; diff --git a/components/security/mbedtls/src/mbedtls_alt.c b/components/security/mbedtls/src/mbedtls_alt.c index def5dc68..532507a0 100644 --- a/components/security/mbedtls/src/mbedtls_alt.c +++ b/components/security/mbedtls/src/mbedtls_alt.c @@ -472,7 +472,7 @@ int rsa_sign_alt(void *ctx, size_t hash_id, return -1; } -int rsa_decrypt_alt(void *ctx, +int rsa_decrypt_alt(void *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen) { diff --git a/components/security/mbedtls/src/ssl_cli.c b/components/security/mbedtls/src/ssl_cli.c index 223823b3..bad8d28c 100644 --- a/components/security/mbedtls/src/ssl_cli.c +++ b/components/security/mbedtls/src/ssl_cli.c @@ -342,7 +342,7 @@ static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, *olen = 6; } -#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || +#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) @@ -1217,7 +1217,7 @@ static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl, { #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ssl->handshake->ecdh_ctx.point_format = p[0]; -#endif +#endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl->handshake->ecjpake_ctx.point_format = p[0]; #endif @@ -1232,7 +1232,7 @@ static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl, MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } -#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || +#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) diff --git a/components/security/mbedtls/src/x509_crt.c b/components/security/mbedtls/src/x509_crt.c index e3edfca8..4f53925f 100644 --- a/components/security/mbedtls/src/x509_crt.c +++ b/components/security/mbedtls/src/x509_crt.c @@ -749,7 +749,7 @@ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char * memcpy( p, buf, crt->raw.len ); - // Direct pointers to the new buffer + // Direct pointers to the new buffer p += crt->raw.len - len; end = crt_end = p + len; diff --git a/components/stage/atcmd/inc/at_debug.h b/components/stage/atcmd/inc/at_debug.h old mode 100755 new mode 100644 index af061190..c899ea62 --- a/components/stage/atcmd/inc/at_debug.h +++ b/components/stage/atcmd/inc/at_debug.h @@ -34,43 +34,43 @@ extern "C" { #endif -#define AT_DBG_ON 1 -#define AT_WRN_ON 1 -#define AT_ERR_ON 1 +#define AT_DBG_ON 1 +#define AT_WRN_ON 1 +#define AT_ERR_ON 1 -#define AT_AST_ON 1 +#define AT_AST_ON 1 -#define AT_CHECK_OVERFLOW 1 +#define AT_CHECK_OVERFLOW 1 -#define AT_SYSLOG printf -#define AT_ABORT() do { } while (1) //sys_abort() +#define AT_SYSLOG printf +#define AT_ABORT() do { } while (1) //sys_abort() -#define AT_LOG(flags, fmt, arg...) \ - do { \ - if (flags) \ - AT_SYSLOG(fmt, ##arg); \ - } while (0) +#define AT_LOG(flags, fmt, arg...) \ + do { \ + if (flags) \ + AT_SYSLOG(fmt, ##arg); \ + } while (0) -#define AT_DBG(fmt, arg...) AT_LOG(AT_DBG_ON, "[atcmd] "fmt, ##arg) -#define AT_WRN(fmt, arg...) AT_LOG(AT_WRN_ON, "[atcmd WARN] "fmt, ##arg) -#define AT_ERR(fmt, arg...) \ - do { \ - AT_LOG(AT_ERR_ON, "[atcmd ERR] %s():%d, "fmt, \ - __func__, __LINE__, ##arg); \ - if (AT_ERR_ON) \ - AT_ABORT(); \ - } while (0) +#define AT_DBG(fmt, arg...) AT_LOG(AT_DBG_ON, "[atcmd] "fmt, ##arg) +#define AT_WRN(fmt, arg...) AT_LOG(AT_WRN_ON, "[atcmd WARN] "fmt, ##arg) +#define AT_ERR(fmt, arg...) \ + do { \ + AT_LOG(AT_ERR_ON, "[atcmd ERR] %s():%d, "fmt, \ + __func__, __LINE__, ##arg); \ + if (AT_ERR_ON) \ + AT_ABORT(); \ + } while (0) #if AT_AST_ON == 1 -#define AT_ASSERT(con) \ - do { \ - if (!(con)) { \ - AT_LOG(AT_AST_ON, "[atcmd ASSERT] %s():%d assert \"%s\" faild!\n", \ - __func__, __LINE__, #con); \ - if (AT_AST_ON) \ - AT_ABORT(); \ - } \ - } while (0) +#define AT_ASSERT(con) \ + do { \ + if (!(con)) { \ + AT_LOG(AT_AST_ON, "[atcmd ASSERT] %s():%d assert \"%s\" faild!\n", \ + __func__, __LINE__, #con); \ + if (AT_AST_ON) \ + AT_ABORT(); \ + } \ + } while (0) #else #define AT_ASSERT(con, msg) #endif diff --git a/components/stage/atcmd/inc/at_private.h b/components/stage/atcmd/inc/at_private.h old mode 100755 new mode 100644 index 2f346aa4..149c0b56 --- a/components/stage/atcmd/inc/at_private.h +++ b/components/stage/atcmd/inc/at_private.h @@ -34,28 +34,28 @@ extern "C" { #endif -#define AT_MAX_PEER_NUM 5 -#define AT_CMD_MAX_SIZE 32 -#define AT_SOCKET_BUFFER_SIZE 1024L -#define MAX_DUMP_BUFF_SIZE 1024L +#define AT_MAX_PEER_NUM 5 +#define AT_CMD_MAX_SIZE 32 +#define AT_SOCKET_BUFFER_SIZE 1024L +#define MAX_DUMP_BUFF_SIZE 1024L #define CMD_CACHE_MAX_LEN (1024) #define CMD_SEND_DATA_MAX_LEN (1024 + 4) #define CMD_SEND_TIMEOUT (10) #define WLAN_SSID_MAX_LEN 32 -#define SYSINFO_SSID_LEN_MAX (32) -#define SYSINFO_PSK_LEN_MAX (65) +#define SYSINFO_SSID_LEN_MAX (32) +#define SYSINFO_PSK_LEN_MAX (65) #define MAX_SCAN_RESULTS 50 #define IP_ADDR_SIZE 15 #define PATH_MAX_LEN 64 -#define ANL_WINDOWS 0 -#define ANL_UNIX 1 -#define ANL_MAC 2 +#define ANL_WINDOWS 0 +#define ANL_UNIX 1 +#define ANL_MAC 2 -#ifndef BIT +#ifndef BIT #define BIT(bit) (1u << (bit)) #endif #define BIT_ISSET(data, bit) ((data) & BIT(bit)) @@ -65,56 +65,56 @@ extern "C" { #define NULL ((void *)0) #endif -#define SIZE_LIMIT_MASK ((AT_PARA_MAX_SIZE<<1)-1) -#define SIZE_LIMIT(opt) ((opt) & SIZE_LIMIT_MASK) -/* #define END_PARA(opt) ((((opt) & AET_PARA)!=0)?1:0) */ -/* #define END_LINE(opt) ((((opt) & AET_LINE)!=0)?1:0) */ +#define SIZE_LIMIT_MASK ((AT_PARA_MAX_SIZE<<1)-1) +#define SIZE_LIMIT(opt) ((opt) & SIZE_LIMIT_MASK) +/* #define END_PARA(opt) ((((opt) & AET_PARA)!=0)?1:0) */ +/* #define END_LINE(opt) ((((opt) & AET_LINE)!=0)?1:0) */ typedef enum { - APT_TEXT, /* text */ + APT_TEXT, /* text */ APT_TDATA, - APT_HEX, /* hex format data */ - APT_DI, /* decimal integer */ - APT_HI, /* hexadecimal integer */ - APT_IP, /* ip format data */ + APT_HEX, /* hex format data */ + APT_DI, /* decimal integer */ + APT_HI, /* hexadecimal integer */ + APT_IP, /* ip format data */ } AT_PARA_TYPE; typedef enum { - APO_RO, /* read only */ - APO_RW, /* read and write */ + APO_RO, /* read only */ + APO_RW, /* read and write */ } AT_PARA_OPTION; typedef enum { - AET_PARA=AT_PARA_MAX_SIZE<<2, - AET_LINE=AT_PARA_MAX_SIZE<<3, + AET_PARA=AT_PARA_MAX_SIZE<<2, + AET_LINE=AT_PARA_MAX_SIZE<<3, } AT_END_TYPE; typedef enum { - AM_CMD=0, - AM_DATA, + AM_CMD=0, + AM_DATA, } AT_MODE; typedef struct { - AT_PARA_TYPE pt; /* parameter type */ - void *pvar; /* the pointer to the variable */ - u32 option; /* | */ + AT_PARA_TYPE pt; /* parameter type */ + void *pvar; /* the pointer to the variable */ + u32 option; /* | */ } at_para_descriptor_t; typedef union { - at_text_t text[AT_PARA_MAX_SIZE]; - at_hex_t hex[AT_PARA_MAX_SIZE]; - at_di_t di; - at_hi_t hi; - at_ip_t ip; + at_text_t text[AT_PARA_MAX_SIZE]; + at_hex_t hex[AT_PARA_MAX_SIZE]; + at_di_t di; + at_hi_t hi; + at_ip_t ip; } at_value_t; typedef struct { - char *key; /* variable keyword */ - AT_PARA_TYPE pt; /* parameter type */ - AT_PARA_OPTION po; /* parameter option */ - void *pvar; /* pointer to variable */ - s32 vsize; /* data size limit */ - s32 (*verify)(at_value_t *value); /* check data range */ + char *key; /* variable keyword */ + AT_PARA_TYPE pt; /* parameter type */ + AT_PARA_OPTION po; /* parameter option */ + void *pvar; /* pointer to variable */ + s32 vsize; /* data size limit */ + s32 (*verify)(at_value_t *value); /* check data range */ } at_var_descriptor_t; /* variable descriptor */ #ifdef __cplusplus diff --git a/components/stage/atcmd/inc/at_server.h b/components/stage/atcmd/inc/at_server.h index 50bfa43a..c03bd591 100644 --- a/components/stage/atcmd/inc/at_server.h +++ b/components/stage/atcmd/inc/at_server.h @@ -11,24 +11,24 @@ typedef enum { AT_ASYNC_WIFI_CONNECTED = 1, - AT_ASYNC_DATA_IN, - AT_ASYNC_PSK_ERROR, - AT_ASYNC_NO_AP_FOUND, - AT_WIFI_DISCONNECT, - AT_WIFI_PRVO_DUMP, - AT_BLE_CONNECTED, - AT_BLE_DISCONNECTED, - AT_WIFI_IP_GET, + AT_ASYNC_DATA_IN, + AT_ASYNC_PSK_ERROR, + AT_ASYNC_NO_AP_FOUND, + AT_WIFI_DISCONNECT, + AT_WIFI_PRVO_DUMP, + AT_BLE_CONNECTED, + AT_BLE_DISCONNECTED, + AT_WIFI_IP_GET, } at_evt_t; #define ATCMDSEND_MAX_BUFF_SIZE (1024) #if 0 -// CA +// CA extern uint8_t *ca; extern size_t ca_length; -// cert +// cert extern uint8_t *cert; extern size_t cert_len; extern uint8_t *priv_key; diff --git a/components/stage/atcmd/inc/atcmd/at_command.h b/components/stage/atcmd/inc/atcmd/at_command.h old mode 100755 new mode 100644 index ed4b474f..69fc7c0e --- a/components/stage/atcmd/inc/atcmd/at_command.h +++ b/components/stage/atcmd/inc/atcmd/at_command.h @@ -145,9 +145,9 @@ typedef enum { ACC_SYSGPIOREAD, ACC_DELETEAP, ACC_OTA, - ACC_BLESYNC, + ACC_BLESYNC, ACC_CIPSTA_IP, - ACC_CIPSTA_IP_GET, + ACC_CIPSTA_IP_GET, } AT_CALLBACK_CMD; //////////////////////////////////////////////////// @@ -495,9 +495,9 @@ typedef struct { at_client_ssl_path_para_t client_ssl_path_cfg; at_client_ssl_sni_t client_ssl_sni_cfg; at_client_ssl_alpn_t client_ssl_alpn_cfg; - + at_ble_sync_mode_t ble_sync_mode; - + struct { int ID; int mode; diff --git a/components/stage/atcmd/inc/atcmd/at_config.h b/components/stage/atcmd/inc/atcmd/at_config.h old mode 100755 new mode 100644 index 7ab60cbc..4576fb9c --- a/components/stage/atcmd/inc/atcmd/at_config.h +++ b/components/stage/atcmd/inc/atcmd/at_config.h @@ -38,97 +38,97 @@ extern "C" { typedef struct { - at_di_t CIPMUX; - at_di_t apDhcp; - at_di_t staDhcp; - - at_di_t link_type[5]; // 0 TCP 1UDP - - - at_text_t nv_manuf[32]; /* ST TEXT[32] Manufacturer ID string */ - at_text_t nv_model[32]; /* SPWF01Sxyz TEXT[32] Manufacturer model string */ - at_text_t nv_serial[32]; /* 1214003 TEXT[32] Manufacturer serial number */ - at_hex_t nv_wifi_macaddr[6]; /* 02:4D:53:4D:00:01 HEX[6] Manufacturer assigned 802.11 MAC Address */ + at_di_t CIPMUX; + at_di_t apDhcp; + at_di_t staDhcp; - at_di_t blink_led; /* 0 INT Enable/disable the blinking led (default=0) */ - at_hi_t wind_off_low; /* 0x00000000 INT Wind 0:31 mask 0xFFFFFFFF are disabled all the 32 Wind indicator */ - at_hi_t wind_off_medium; /* 0x00000000 INT Wind 32:63 mask */ - at_hi_t wind_off_high; /* 0x00000000 INT Wind 64:95 mask */ - - at_text_t user_desc[64]; /* anonymous TEXT[64] Free form textual field for host use (used as basic authentication during Mini AP configuration) */ - at_text_t escape_seq[8]; /* at+s. TEXT[8] Escape sequence from data mode to command mode */ - at_di_t localecho1; /* 1 INT Echo command input: 0=off, 1=on */ - at_di_t console1_speed; /* 115200 INT Serial port speed: from 9600 to 921600, default: 115200 */ - at_di_t console1_hwfc; /* 0 INT Hardware flow control: 0=off, 1=on */ - at_di_t console1_enabled; /* 1 INT Enable console on UART1 */ - at_di_t sleep_enabled; /* 0 INT Enable/disable the sleep mode */ - at_di_t standby_enabled; /* 0 INT Enable/disable the standby mode */ - at_di_t standby_time; /* 10 INT Standby mode time, in seconds. Up to 232-1 sec */ - at_di_t wifi_tx_msdu_lifetime; /* 0 INT MSDU lifetime. From 0 to 2^32-1 TUs (1 TUs= 1024¦Ìs). Zero is default (automatic) */ - at_di_t wifi_rx_msdu_lifetime; /* 0 INT MSDU lifetime. From 0 to 2^32-1 TUs (1 TUs= 1024¦Ìs). Zero is default (automatic) */ - at_hi_t wifi_operational_mode; /* 0x00000011 INT Allows choosing Doze (11) or quiescent (12) power device modes */ - at_di_t wifi_beacon_wakeup; /* 1 INT Set the wakeup interval of the WLAN device, from 1 to 255 if wifi_listen_interval = 0; from 1 to 65535 if wifi_listen_interval = 1 */ - at_di_t wifi_beacon_interval; /* 100 INT Beaconing interval in MiniAP mode, from 0 to 2^16-1 */ - - at_di_t wifi_listen_interval; /* 0 INT Define the wakeup mode (0 = sleep up to the beacon_wakeup specified, 1 = sleep at least to the beacon_wakeup specified) */ - at_di_t wifi_rts_threshold; /* 3000 INT Frame size over which RTS/CTS is used. Limit: from 0 to 3000 */ - at_hex_t wifi_ssid[33]; /* 50:72:6F:64:75:63:74:69:6F:6E:31:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[32] Desired SSID specified in hex. All 32 octets should be written. Note that wifi_ssid_len must also be set. */ - at_di_t wifi_ssid_len; /* 11 INT Length of the actual SSID in the 32 byte buffer */ - at_di_t wifi_channelnum; /* 6 INT Channel number to use for MiniAP operation. The user must properly set the channel number to not violate IEEE 802.11 Wi-Fi/WLAN standards. */ - - at_hi_t wifi_opr_rate_mask; /* 0xFFFFFFFF INT Operational data rate mask, 0xffffffff is allenabled: - BIT0: 1 Mbps BIT1: 2 Mbps BIT2: 5.5 Mbps BIT3: 11 Mbps BIT6: 6 Mbps BIT7: 9 Mbps - BIT8: 12 Mbps BIT9: 18 Mbps BIT10: 24 Mbps BIT11: 36 Mbps BIT12: 48 Mbps BIT13: 54 Mbps - */ - at_hi_t wifi_bas_rate_mask; /* 0x0000000F INT Basic data rate mask, 0x0000000f is [1,2,5.5,11] */ - at_di_t wifi_mode; /* 1 INT Radio Mode. - 0=IDLE, - 1=STA (Supported Security Modes: OPEN,WEP OpenSystem,WEP SharedKey,WPA/WPA2), - 2=MiniAP (Supported Security Modes: OPEN, WEP OpenSystem -Supported Classes: b,g) - 3=IBSS(Supported Security Modes: OPEN, WEP OpenSystem, WEP SharedKey); - */ - at_di_t wifi_auth_type; /* 0 INT Authentication type used in IBSS mode: - 0=OpenSystem, - 1=SharedKey - */ - at_di_t wifi_powersave; /* 1 INT Allows choosing between Active (0), PS (1) or Fast-PS (2) */ - at_di_t wifi_tx_power; /* 18 INT Transmit power [from 0 to 18], in dBm */ - at_di_t wifi_rssi_thresh; /* -50 INT Low signal strength threshold */ - at_di_t wifi_rssi_hyst; /* 10 INT Amount of change in RSSI to trigger signal state change */ + at_di_t link_type[5]; // 0 TCP 1UDP - at_di_t wifi_ap_idle_timeout; /* 120 INT Seconds of inactivity to trigger disassociate of the client */ - at_di_t wifi_beacon_loss_thresh; /* 10 INT Number of consecutive loss beacon to detect the AP disassociation */ - at_di_t wifi_priv_mode; /* 2 INT Privacy Mode: 0=none,1=WEP, 2=WPAPersonal (TKIP/AES) or WPA2-Personal (TKIP/AES) */ - at_hex_t wifi_wep_keys[4][16]; /* - wifi_wep_keys[1] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer - wifi_wep_keys[1] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer - wifi_wep_keys[2] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer - wifi_wep_keys[3] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer - */ - at_hex_t wifi_wep_key_lens[4]; /* 00:00:00:00 HEX[4] Four octets specifying the length of the actual key data in each WEP key buffer.*/ - at_di_t wifi_wep_default_key; /* 0 INT Default WEP key used for authentication */ - at_hex_t wifi_wpa_psk_raw[32]; /* 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[32] Pre-calculated PSK key */ + at_text_t nv_manuf[32]; /* ST TEXT[32] Manufacturer ID string */ + at_text_t nv_model[32]; /* SPWF01Sxyz TEXT[32] Manufacturer model string */ + at_text_t nv_serial[32]; /* 1214003 TEXT[32] Manufacturer serial number */ + at_hex_t nv_wifi_macaddr[6]; /* 02:4D:53:4D:00:01 HEX[6] Manufacturer assigned 802.11 MAC Address */ - at_text_t wifi_wpa_psk_text[65]; /* a_psk_pass TEXT[64] WPA(2) PSK passphrase, if set the actual PSK will be generated from this.Used in STA, IBSS and MiniAP. */ - at_di_t ip_use_dhcp; /* 1 INT DHCP server on/off. Used in STA, IBSS and MiniAP. - 0=off (in STA mode: the variables ip_ipaddr, ip_netmask and ip_gw must be properly set to connect to the AP), - 1=on (in STA mode: the ipaddr, netmask and gw will be provided by the AP), - 2=on&customize (in MiniAP mode: user can customize the ip_ipaddr of the MiniAP, the ip_address of the client is automatically assigned by the MiniAP) - */ - at_di_t ip_use_httpd; /* 1 INT HTTP server on/off.0=off, 1=on */ - at_di_t ip_mtu; /* 1500 INT IP maximum transmission unit size. Limit: from 634 to 2412 (1500 for maximum compatibility with Ethernet networks) */ - at_text_t ip_hostname[32]; /* iwm-02-09-97 TEXT[32] IP local hostname */ - at_text_t ip_apdomainname[32]; /* captiveportal.net TEXT[32] IP domain name in Mini AP mode. - If the AP domain name is not quickly opened, it¡¯s suggested to turn off an eventual proxy server (check the connection settings of the device or the browser preferences). - */ - at_ip_t ip_ipaddr; /* 192.168.0.50 IP IP address for static usage (DHCP off) */ - at_ip_t ip_netmask; /* 255.255.255.0 IP IP netmask for static usage (DHCP off) */ - at_ip_t ip_gw; /* 192.168.0.1 IP IP default gateway for static usage (DHCP off) */ - at_ip_t ip_dns; /* 192.168.0.1 IP IP DNS server for static usage (DHCP off) */ - at_di_t ip_http_get_recv_timeout; /* 1000 INT HTTP_GET connection timeout in milliseconds */ - at_di_t ip_dhcp_timeout; /* 20 INT DHCP client timeout, in seconds */ - at_di_t ip_sockd_timeout; /* 250 INT Socket server - buffer timeout management (from 5 ms to 250 ms) Warning: 250 ms is suggested to avoid data loss */ + at_di_t blink_led; /* 0 INT Enable/disable the blinking led (default=0) */ + at_hi_t wind_off_low; /* 0x00000000 INT Wind 0:31 mask 0xFFFFFFFF are disabled all the 32 Wind indicator */ + at_hi_t wind_off_medium; /* 0x00000000 INT Wind 32:63 mask */ + at_hi_t wind_off_high; /* 0x00000000 INT Wind 64:95 mask */ + + at_text_t user_desc[64]; /* anonymous TEXT[64] Free form textual field for host use (used as basic authentication during Mini AP configuration) */ + at_text_t escape_seq[8]; /* at+s. TEXT[8] Escape sequence from data mode to command mode */ + at_di_t localecho1; /* 1 INT Echo command input: 0=off, 1=on */ + at_di_t console1_speed; /* 115200 INT Serial port speed: from 9600 to 921600, default: 115200 */ + at_di_t console1_hwfc; /* 0 INT Hardware flow control: 0=off, 1=on */ + at_di_t console1_enabled; /* 1 INT Enable console on UART1 */ + at_di_t sleep_enabled; /* 0 INT Enable/disable the sleep mode */ + at_di_t standby_enabled; /* 0 INT Enable/disable the standby mode */ + at_di_t standby_time; /* 10 INT Standby mode time, in seconds. Up to 232-1 sec */ + at_di_t wifi_tx_msdu_lifetime; /* 0 INT MSDU lifetime. From 0 to 2^32-1 TUs (1 TUs= 1024¦Ìs). Zero is default (automatic) */ + at_di_t wifi_rx_msdu_lifetime; /* 0 INT MSDU lifetime. From 0 to 2^32-1 TUs (1 TUs= 1024¦Ìs). Zero is default (automatic) */ + at_hi_t wifi_operational_mode; /* 0x00000011 INT Allows choosing Doze (11) or quiescent (12) power device modes */ + at_di_t wifi_beacon_wakeup; /* 1 INT Set the wakeup interval of the WLAN device, from 1 to 255 if wifi_listen_interval = 0; from 1 to 65535 if wifi_listen_interval = 1 */ + at_di_t wifi_beacon_interval; /* 100 INT Beaconing interval in MiniAP mode, from 0 to 2^16-1 */ + + at_di_t wifi_listen_interval; /* 0 INT Define the wakeup mode (0 = sleep up to the beacon_wakeup specified, 1 = sleep at least to the beacon_wakeup specified) */ + at_di_t wifi_rts_threshold; /* 3000 INT Frame size over which RTS/CTS is used. Limit: from 0 to 3000 */ + at_hex_t wifi_ssid[33]; /* 50:72:6F:64:75:63:74:69:6F:6E:31:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[32] Desired SSID specified in hex. All 32 octets should be written. Note that wifi_ssid_len must also be set. */ + at_di_t wifi_ssid_len; /* 11 INT Length of the actual SSID in the 32 byte buffer */ + at_di_t wifi_channelnum; /* 6 INT Channel number to use for MiniAP operation. The user must properly set the channel number to not violate IEEE 802.11 Wi-Fi/WLAN standards. */ + + at_hi_t wifi_opr_rate_mask; /* 0xFFFFFFFF INT Operational data rate mask, 0xffffffff is allenabled: + BIT0: 1 Mbps BIT1: 2 Mbps BIT2: 5.5 Mbps BIT3: 11 Mbps BIT6: 6 Mbps BIT7: 9 Mbps + BIT8: 12 Mbps BIT9: 18 Mbps BIT10: 24 Mbps BIT11: 36 Mbps BIT12: 48 Mbps BIT13: 54 Mbps + */ + at_hi_t wifi_bas_rate_mask; /* 0x0000000F INT Basic data rate mask, 0x0000000f is [1,2,5.5,11] */ + at_di_t wifi_mode; /* 1 INT Radio Mode. + 0=IDLE, + 1=STA (Supported Security Modes: OPEN,WEP OpenSystem,WEP SharedKey,WPA/WPA2), + 2=MiniAP (Supported Security Modes: OPEN, WEP OpenSystem -Supported Classes: b,g) + 3=IBSS(Supported Security Modes: OPEN, WEP OpenSystem, WEP SharedKey); + */ + at_di_t wifi_auth_type; /* 0 INT Authentication type used in IBSS mode: + 0=OpenSystem, + 1=SharedKey + */ + at_di_t wifi_powersave; /* 1 INT Allows choosing between Active (0), PS (1) or Fast-PS (2) */ + at_di_t wifi_tx_power; /* 18 INT Transmit power [from 0 to 18], in dBm */ + at_di_t wifi_rssi_thresh; /* -50 INT Low signal strength threshold */ + at_di_t wifi_rssi_hyst; /* 10 INT Amount of change in RSSI to trigger signal state change */ + + + at_di_t wifi_ap_idle_timeout; /* 120 INT Seconds of inactivity to trigger disassociate of the client */ + at_di_t wifi_beacon_loss_thresh; /* 10 INT Number of consecutive loss beacon to detect the AP disassociation */ + at_di_t wifi_priv_mode; /* 2 INT Privacy Mode: 0=none,1=WEP, 2=WPAPersonal (TKIP/AES) or WPA2-Personal (TKIP/AES) */ + at_hex_t wifi_wep_keys[4][16]; /* + wifi_wep_keys[1] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer + wifi_wep_keys[1] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer + wifi_wep_keys[2] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer + wifi_wep_keys[3] 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[16] WEP key buffer + */ + at_hex_t wifi_wep_key_lens[4]; /* 00:00:00:00 HEX[4] Four octets specifying the length of the actual key data in each WEP key buffer.*/ + at_di_t wifi_wep_default_key; /* 0 INT Default WEP key used for authentication */ + at_hex_t wifi_wpa_psk_raw[32]; /* 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 HEX[32] Pre-calculated PSK key */ + + at_text_t wifi_wpa_psk_text[65]; /* a_psk_pass TEXT[64] WPA(2) PSK passphrase, if set the actual PSK will be generated from this.Used in STA, IBSS and MiniAP. */ + at_di_t ip_use_dhcp; /* 1 INT DHCP server on/off. Used in STA, IBSS and MiniAP. + 0=off (in STA mode: the variables ip_ipaddr, ip_netmask and ip_gw must be properly set to connect to the AP), + 1=on (in STA mode: the ipaddr, netmask and gw will be provided by the AP), + 2=on&customize (in MiniAP mode: user can customize the ip_ipaddr of the MiniAP, the ip_address of the client is automatically assigned by the MiniAP) + */ + at_di_t ip_use_httpd; /* 1 INT HTTP server on/off.0=off, 1=on */ + at_di_t ip_mtu; /* 1500 INT IP maximum transmission unit size. Limit: from 634 to 2412 (1500 for maximum compatibility with Ethernet networks) */ + at_text_t ip_hostname[32]; /* iwm-02-09-97 TEXT[32] IP local hostname */ + at_text_t ip_apdomainname[32]; /* captiveportal.net TEXT[32] IP domain name in Mini AP mode. + If the AP domain name is not quickly opened, it¡¯s suggested to turn off an eventual proxy server (check the connection settings of the device or the browser preferences). + */ + at_ip_t ip_ipaddr; /* 192.168.0.50 IP IP address for static usage (DHCP off) */ + at_ip_t ip_netmask; /* 255.255.255.0 IP IP netmask for static usage (DHCP off) */ + at_ip_t ip_gw; /* 192.168.0.1 IP IP default gateway for static usage (DHCP off) */ + at_ip_t ip_dns; /* 192.168.0.1 IP IP DNS server for static usage (DHCP off) */ + at_di_t ip_http_get_recv_timeout; /* 1000 INT HTTP_GET connection timeout in milliseconds */ + at_di_t ip_dhcp_timeout; /* 20 INT DHCP client timeout, in seconds */ + at_di_t ip_sockd_timeout; /* 250 INT Socket server - buffer timeout management (from 5 ms to 250 ms) Warning: 250 ms is suggested to avoid data loss */ } at_config_t; extern at_config_t at_cfg; diff --git a/components/stage/atcmd/inc/atcmd/at_macros.h b/components/stage/atcmd/inc/atcmd/at_macros.h old mode 100755 new mode 100644 index 9d59f4c7..7f273889 --- a/components/stage/atcmd/inc/atcmd/at_macros.h +++ b/components/stage/atcmd/inc/atcmd/at_macros.h @@ -36,18 +36,18 @@ extern "C" { #define AT_PARA_MAX_SIZE 256UL /* should be pow2(n), n is a integer */ -#define AT_SEPARATOR ',' -#define AT_CR 0x0d -#define AT_LF 0x0a -#define AT_COLON ':' -#define AT_DOT '.' -#define AT_EQU '=' -#define AT_QUO '"' -#define AT_QUE '?' +#define AT_SEPARATOR ',' +#define AT_CR 0x0d +#define AT_LF 0x0a +#define AT_COLON ':' +#define AT_DOT '.' +#define AT_EQU '=' +#define AT_QUO '"' +#define AT_QUE '?' -#define TABLE_SIZE(tbl) (sizeof(tbl)/sizeof((tbl)[0])) +#define TABLE_SIZE(tbl) (sizeof(tbl)/sizeof((tbl)[0])) #ifdef __cplusplus } diff --git a/components/stage/atcmd/inc/atcmd/at_queue.h b/components/stage/atcmd/inc/atcmd/at_queue.h old mode 100755 new mode 100644 index 51b355cf..93d9d326 --- a/components/stage/atcmd/inc/atcmd/at_queue.h +++ b/components/stage/atcmd/inc/atcmd/at_queue.h @@ -37,18 +37,18 @@ extern "C" { #endif typedef enum { - AQEC_OK=0, - AQEC_FAIL, - AQEC_EMPTY, - AQEC_FULL + AQEC_OK=0, + AQEC_FAIL, + AQEC_EMPTY, + AQEC_FULL } AT_QUEUE_ERROR_CODE; typedef struct { - u8 *qbuf; - s32 qsize; - s32 qcnt; - s32 ridx; - s32 widx; + u8 *qbuf; + s32 qsize; + s32 qcnt; + s32 ridx; + s32 widx; } at_queue_t; typedef s32 (*at_queue_callback_t)(u8 *buf, s32 size); diff --git a/components/stage/atcmd/inc/atcmd/at_status.h b/components/stage/atcmd/inc/atcmd/at_status.h old mode 100755 new mode 100644 index a2338f52..74a1bde3 --- a/components/stage/atcmd/inc/atcmd/at_status.h +++ b/components/stage/atcmd/inc/atcmd/at_status.h @@ -37,85 +37,85 @@ extern "C" { #endif typedef struct { - at_text_t version[32]; /* 140128-caf4b79-SPWF01S SPWF01S Software Version */ - at_di_t reset_reason; /* 2 H/W reported reason for last reset - 0 = POWER_ON - 1 = WATCHDOG - 2 = SOFT RESET - 3 = LOW POWER - */ - at_di_t conf_flag; /* 5 Module HW revision */ - at_di_t system_uptime; /* 22006 System running time in seconds */ - at_di_t system_sleeptime; /* 500 System sleeping time in seconds */ - at_di_t gpio_enable; /* 0 Interrupt-enabled GPIO bitmask, expressed in base 10 */ - at_di_t captiveportal; /* 1 Mini AP enabled/disabled */ - at_di_t wifi_state; /* 10 - 0= Hardware power up - 1=Hardware failure - 2=Radio task terminated by user - 3=Radio idle - 4=Scan in progress - 5=Scan complete - 6=Join in progress - 7=Joined - 8=Access point started - 9=802.11 handshake complete - 10=Ready to transmit data (i.e. ¡°Link Up¡±) - */ - at_hex_t wifi_bssid[6]; /* 00:18:F8:3C:D9:18 BSSID of current association */ - at_di_t wifi_aid; /* 0 Association ID of current association */ - at_di_t wifi_channelnum; /* 11 Current radio channel number */ - at_hi_t wifi_sup_rate_mask; /* 0x003FFFCF Radio: supported data rate mask */ - at_hi_t wifi_bas_rate_mask; /* 0x0000000F AP reported: basic data rate mask */ - at_hi_t wifi_chan_activity2; /* 0x00003FFF Channels where we are allowed to transmit. Channel mask. i.e. 0x00003FFF => from channel 0 to channel 13 */ - at_di_t wifi_max_tx_power; /* 18 max allowed transmit power for the defined reg domain */ - at_di_t wifi_reg_country; /* IT Current regulatory domain */ - at_di_t wifi_dtim_period; /* 1 AP reported DTIM period (used in STA mode) */ - at_di_t wifi_sleeping; /* 0 Radio sleeping state (0 = active, 1 = sleep) */ - at_di_t wifi_num_assoc; /* 1 Number of the client associated to the module */ - at_ip_t ip_ipaddr; /* 192.168.121.184 Current IP address */ - at_ip_t ip_netmask; /* 255.255.252.0 Current IP netmask */ - at_ip_t ip_gw; /* 192.168.123.20 Current IP default gateway */ - at_ip_t ip_dns; /* 192.168.123.20 Current IP DNS server */ - at_di_t ip_sock_open; /* 0 Bitmask of Socket Client ID currently opened, expressed in base 10 (ip_sock_open=13 (00001101 in binary), - means that socket#0socket#2 and socket#3 are currently opened) */ - at_di_t ip_sockd_port; /* 0 Socket server port opened */ - at_di_t free_heap; /* 30472 Current free heap space */ - at_di_t min_heap; /* 26552 Minimum free heap space thus far */ - at_di_t current_time; /* 90643 Current time in seconds */ + at_text_t version[32]; /* 140128-caf4b79-SPWF01S SPWF01S Software Version */ + at_di_t reset_reason; /* 2 H/W reported reason for last reset + 0 = POWER_ON + 1 = WATCHDOG + 2 = SOFT RESET + 3 = LOW POWER + */ + at_di_t conf_flag; /* 5 Module HW revision */ + at_di_t system_uptime; /* 22006 System running time in seconds */ + at_di_t system_sleeptime; /* 500 System sleeping time in seconds */ + at_di_t gpio_enable; /* 0 Interrupt-enabled GPIO bitmask, expressed in base 10 */ + at_di_t captiveportal; /* 1 Mini AP enabled/disabled */ + at_di_t wifi_state; /* 10 + 0= Hardware power up + 1=Hardware failure + 2=Radio task terminated by user + 3=Radio idle + 4=Scan in progress + 5=Scan complete + 6=Join in progress + 7=Joined + 8=Access point started + 9=802.11 handshake complete + 10=Ready to transmit data (i.e. ¡°Link Up¡±) + */ + at_hex_t wifi_bssid[6]; /* 00:18:F8:3C:D9:18 BSSID of current association */ + at_di_t wifi_aid; /* 0 Association ID of current association */ + at_di_t wifi_channelnum; /* 11 Current radio channel number */ + at_hi_t wifi_sup_rate_mask; /* 0x003FFFCF Radio: supported data rate mask */ + at_hi_t wifi_bas_rate_mask; /* 0x0000000F AP reported: basic data rate mask */ + at_hi_t wifi_chan_activity2; /* 0x00003FFF Channels where we are allowed to transmit. Channel mask. i.e. 0x00003FFF => from channel 0 to channel 13 */ + at_di_t wifi_max_tx_power; /* 18 max allowed transmit power for the defined reg domain */ + at_di_t wifi_reg_country; /* IT Current regulatory domain */ + at_di_t wifi_dtim_period; /* 1 AP reported DTIM period (used in STA mode) */ + at_di_t wifi_sleeping; /* 0 Radio sleeping state (0 = active, 1 = sleep) */ + at_di_t wifi_num_assoc; /* 1 Number of the client associated to the module */ + at_ip_t ip_ipaddr; /* 192.168.121.184 Current IP address */ + at_ip_t ip_netmask; /* 255.255.252.0 Current IP netmask */ + at_ip_t ip_gw; /* 192.168.123.20 Current IP default gateway */ + at_ip_t ip_dns; /* 192.168.123.20 Current IP DNS server */ + at_di_t ip_sock_open; /* 0 Bitmask of Socket Client ID currently opened, expressed in base 10 (ip_sock_open=13 (00001101 in binary), + means that socket#0socket#2 and socket#3 are currently opened) */ + at_di_t ip_sockd_port; /* 0 Socket server port opened */ + at_di_t free_heap; /* 30472 Current free heap space */ + at_di_t min_heap; /* 26552 Minimum free heap space thus far */ + at_di_t current_time; /* 90643 Current time in seconds */ } at_status_t; typedef struct { - at_di_t link_id; /* 0 Identifier of the client */ - at_di_t state; /* 4 - 0 = Hardware Power Up - 1 = HW link initialization - 2 = Client Link identifier allocated - 3 = Authenticated - 4 = Associated - 5 = Peer lost beacons - 6 = Peer in power save state - */ - at_hex_t addr[6]; /* 90:18:7C:96:0D:0B MAC address of the client */ - at_di_t last_rx; /* 21244 Timestamp of last received packet */ - at_di_t last_tx; /* 21244 Timestamp of last transmitted packet */ - at_di_t rx_drops; /* 0 Count of frames dropped during reception */ - at_di_t tx_drops; /* 1 Count of frames dropped during transmission */ - at_di_t rx_pkts; /* 50 Count of received frames */ - at_di_t tx_pkts; /* 44 Count of transmitted frames */ - at_di_t tx_errs; /* 0 Count of errors detected during frame transmit */ - at_di_t rate_mask; /* 0x00003FCF AP reported Operational data rate mask */ - at_di_t cur_rate_idx; /* 3 Most significant byte of the rate_mask */ - at_di_t cur_rate_ok; /* 5 Counter to perform rate step up */ - at_di_t cur_rate_fail; /* 0 Counter to perform rate step down */ - at_di_t tx_consec_fail; /* 0 Counter to perform disassociation */ - at_hi_t rx_seqnum; /* 0x0000AF40 Sequence number of last RX directed frame */ - at_hi_t rx_seqnum_mc; /* 0x00000000 Sequence number of last RX multicast frame */ - at_di_t rx_rssi; /* -37 Signal strength of last received packet */ - at_di_t rx_rateidx; /* 0 Rate index of last received packet */ - at_di_t setprot; /* 0 Bitmask to indicate protection for TX (bit 1) and/or RX (bit 0) IEEE 802.11 frames */ - at_di_t listen_interval; /* 10 AP reported listen interval */ - at_hi_t capinfo; /* 0x00000000 Information about the AP capabilities */ + at_di_t link_id; /* 0 Identifier of the client */ + at_di_t state; /* 4 + 0 = Hardware Power Up + 1 = HW link initialization + 2 = Client Link identifier allocated + 3 = Authenticated + 4 = Associated + 5 = Peer lost beacons + 6 = Peer in power save state + */ + at_hex_t addr[6]; /* 90:18:7C:96:0D:0B MAC address of the client */ + at_di_t last_rx; /* 21244 Timestamp of last received packet */ + at_di_t last_tx; /* 21244 Timestamp of last transmitted packet */ + at_di_t rx_drops; /* 0 Count of frames dropped during reception */ + at_di_t tx_drops; /* 1 Count of frames dropped during transmission */ + at_di_t rx_pkts; /* 50 Count of received frames */ + at_di_t tx_pkts; /* 44 Count of transmitted frames */ + at_di_t tx_errs; /* 0 Count of errors detected during frame transmit */ + at_di_t rate_mask; /* 0x00003FCF AP reported Operational data rate mask */ + at_di_t cur_rate_idx; /* 3 Most significant byte of the rate_mask */ + at_di_t cur_rate_ok; /* 5 Counter to perform rate step up */ + at_di_t cur_rate_fail; /* 0 Counter to perform rate step down */ + at_di_t tx_consec_fail; /* 0 Counter to perform disassociation */ + at_hi_t rx_seqnum; /* 0x0000AF40 Sequence number of last RX directed frame */ + at_hi_t rx_seqnum_mc; /* 0x00000000 Sequence number of last RX multicast frame */ + at_di_t rx_rssi; /* -37 Signal strength of last received packet */ + at_di_t rx_rateidx; /* 0 Rate index of last received packet */ + at_di_t setprot; /* 0 Bitmask to indicate protection for TX (bit 1) and/or RX (bit 0) IEEE 802.11 frames */ + at_di_t listen_interval; /* 10 AP reported listen interval */ + at_hi_t capinfo; /* 0x00000000 Information about the AP capabilities */ } at_peer_t; #ifdef __cplusplus diff --git a/components/stage/atcmd/inc/atcmd/at_types.h b/components/stage/atcmd/inc/atcmd/at_types.h old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/inc/fdt.h b/components/stage/blfdt/inc/fdt.h old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/inc/libfdt.h b/components/stage/blfdt/inc/libfdt.h old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/inc/libfdt_env.h b/components/stage/blfdt/inc/libfdt_env.h old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/inc/libfdt_internal.h b/components/stage/blfdt/inc/libfdt_internal.h old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt.c b/components/stage/blfdt/src/fdt.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_addresses.c b/components/stage/blfdt/src/fdt_addresses.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_empty_tree.c b/components/stage/blfdt/src/fdt_empty_tree.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_overlay.c b/components/stage/blfdt/src/fdt_overlay.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_ro.c b/components/stage/blfdt/src/fdt_ro.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_rw.c b/components/stage/blfdt/src/fdt_rw.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_strerror.c b/components/stage/blfdt/src/fdt_strerror.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_sw.c b/components/stage/blfdt/src/fdt_sw.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/src/fdt_wip.c b/components/stage/blfdt/src/fdt_wip.c old mode 100755 new mode 100644 diff --git a/components/stage/blfdt/test/tc_blfdt_dump.c b/components/stage/blfdt/test/tc_blfdt_dump.c index 46591cb2..250619ff 100644 --- a/components/stage/blfdt/test/tc_blfdt_dump.c +++ b/components/stage/blfdt/test/tc_blfdt_dump.c @@ -751,15 +751,15 @@ int tc_blfdtdump(void) int result; result = blfdtdump(tc_wifi_dtb, TC_WIFI_DTB_LEN, true, true); - + if (result) { printf("dump failed\r\n"); } else { printf("dump successed\r\n"); } - + return result; - + // blfdtdump(tc_wifi_dtb, TC_WIFI_DTB_LEN, false, true); // blfdtdump(tc_wifi_dtb, TC_WIFI_DTB_LEN, false, false); } diff --git a/components/stage/blfdt/test/tc_blfdt_wifi.c b/components/stage/blfdt/test/tc_blfdt_wifi.c index 8683cfe0..63126929 100644 --- a/components/stage/blfdt/test/tc_blfdt_wifi.c +++ b/components/stage/blfdt/test/tc_blfdt_wifi.c @@ -220,7 +220,7 @@ static int tc_fdt_wifi_module(void) log_error("brd_rf NULL.\r\n"); return -1; } - + return 0; } @@ -228,12 +228,12 @@ int tc_fdt_wifi(void) { int result; result = tc_fdt_wifi_module(); - + if (result) { printf("fdt wifi module failed\r\n"); } else { printf("fdt wifi module successed\r\n"); } - + return result; } diff --git a/components/stage/blog/blog.c b/components/stage/blog/blog.c index e5bc47f9..00b484f1 100644 --- a/components/stage/blog/blog.c +++ b/components/stage/blog/blog.c @@ -158,7 +158,7 @@ void cmd_blog_info_dump(char *buf, int len, int argc, char **argv) { blog_info_t *info_c, *info_f, *info_p; char name_buf[BLOG_NAMELEN_MAX] = {0}; - + extern char _ld_bl_static_blogcomponent_code_start; extern char _ld_bl_static_blogcomponent_code_end; extern char _ld_bl_static_blogfile_code_start; @@ -180,14 +180,14 @@ void cmd_blog_info_dump(char *buf, int len, int argc, char **argv) if (0 == strcmp(name_buf, info_c->name)) { #if BLOG_DUMP_DEDUPLICATE continue; -#endif +#endif } else { memset(name_buf, 0, strlen(name_buf)); } } - + __blog_printf("[%-48s] = [%d]\r\n", info_c->name, *(info_c->level)); - + if ((name_buf[0] != 0) && (strcmp(info_c->name, name_buf) == 0)) { continue; } diff --git a/components/stage/blsync_ble/bouffalo.mk b/components/stage/blsync_ble/bouffalo.mk index 2f3dd8a5..1200a45d 100644 --- a/components/stage/blsync_ble/bouffalo.mk +++ b/components/stage/blsync_ble/bouffalo.mk @@ -12,8 +12,8 @@ COMPONENT_PRIV_INCLUDEDIRS := COMPONENT_SRCS := src/blsync_ble.c \ src/encrypt_layer.c \ src/payload.c \ - src/transfer.c - + src/transfer.c + COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) COMPONENT_SRCDIRS := src diff --git a/components/stage/blsync_ble/inc/blsync_ble.h b/components/stage/blsync_ble/inc/blsync_ble.h index 4b14c16e..be787a06 100644 --- a/components/stage/blsync_ble/inc/blsync_ble.h +++ b/components/stage/blsync_ble/inc/blsync_ble.h @@ -106,4 +106,4 @@ int bl_ble_sync_start(bl_ble_sync_t *index, int bl_ble_sync_stop(bl_ble_sync_t *index); -#endif +#endif diff --git a/components/stage/blsync_ble/src/blsync_ble.c b/components/stage/blsync_ble/src/blsync_ble.c index 17cfc083..c45a795f 100644 --- a/components/stage/blsync_ble/src/blsync_ble.c +++ b/components/stage/blsync_ble/src/blsync_ble.c @@ -32,44 +32,44 @@ static ssize_t read_data(struct bt_conn *conn, static void blsync_exchange_func(struct bt_conn *conn, u8_t err, - struct bt_gatt_exchange_params *params) + struct bt_gatt_exchange_params *params) { - printf("Exchange %s\r\n", err == 0U ? "successful" : "failed"); + printf("Exchange %s\r\n", err == 0U ? "successful" : "failed"); } static void blsync_disconnected(struct bt_conn *conn, u8_t reason) -{ - printf("disconnected (reason %u)%s\r\n",reason); - blsync_conn = NULL; +{ + printf("disconnected (reason %u)%s\r\n",reason); + blsync_conn = NULL; } static void blsync_connected(struct bt_conn *conn, u8_t err) { - int tx_octets = 0x00fb; - int tx_time = 0x0848; - int ret = -1; + int tx_octets = 0x00fb; + int tx_time = 0x0848; + int ret = -1; - printf("%s\n",__func__); - blsync_conn = conn; + printf("%s\n",__func__); + blsync_conn = conn; - //set data length after connected. - ret = bt_le_set_data_len(blsync_conn, tx_octets, tx_time); - if(!ret){ - printf("Set data length success.\n"); - } - else{ - printf("Set data length failure, err: %d\n", ret); - } + //set data length after connected. + ret = bt_le_set_data_len(blsync_conn, tx_octets, tx_time); + if(!ret){ + printf("Set data length success.\n"); + } + else{ + printf("Set data length failure, err: %d\n", ret); + } - //exchange mtu size after connected. - blsync_exchg_mtu.func = blsync_exchange_func; - ret = bt_gatt_exchange_mtu(blsync_conn, &blsync_exchg_mtu); - if (!ret) { - printf("Exchange mtu size pending.\n"); - } else { - printf("Exchange mtu size failure, err: %d\n", ret); - } -} + //exchange mtu size after connected. + blsync_exchg_mtu.func = blsync_exchange_func; + ret = bt_gatt_exchange_mtu(blsync_conn, &blsync_exchg_mtu); + if (!ret) { + printf("Exchange mtu size pending.\n"); + } else { + printf("Exchange mtu size failure, err: %d\n", ret); + } +} static void scan_complete_cb(void *param) { @@ -178,7 +178,7 @@ static int __recv_event(void *p_drv, struct pro_event *p_event) } } else if (p_event->type == PROTOCOL_EVENT_CMD) { - + switch (p_event->event_id) { case CMD_CONNECT_WIFI: if(gp_index->wifi_func->local_connect_remote_ap) { @@ -352,8 +352,8 @@ static struct bt_gatt_attr attrs[]= { const static struct bt_gatt_service wifiprov_server = BT_GATT_SERVICE(attrs); static struct bt_conn_cb blsync_conn_callbacks = { - .connected = blsync_connected, - .disconnected = blsync_disconnected, + .connected = blsync_connected, + .disconnected = blsync_disconnected, }; int bl_ble_sync_start(bl_ble_sync_t *index, diff --git a/components/stage/cjson/bouffalo.mk b/components/stage/cjson/bouffalo.mk index 44024c75..8af07c1d 100644 --- a/components/stage/cjson/bouffalo.mk +++ b/components/stage/cjson/bouffalo.mk @@ -6,7 +6,7 @@ COMPONENT_ADD_INCLUDEDIRS += . ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src COMPONENT_SRCS := cJSON.c @@ -16,4 +16,4 @@ COMPONENT_SRCDIRS := . ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/stage/cjson/cJSON.c b/components/stage/cjson/cJSON.c index 7f6542ef..ed8a1026 100644 --- a/components/stage/cjson/cJSON.c +++ b/components/stage/cjson/cJSON.c @@ -31,9 +31,9 @@ const char *cJSON_GetErrorPtr(void) {return ep;} static int cJSON_strcasecmp(const char *s1,const char *s2) { - if (!s1) return (s1==s2)?0:1;if (!s2) return 1; - for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; - return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); + if (!s1) return (s1==s2)?0:1;if (!s2) return 1; + for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; + return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); } static void *(*cJSON_malloc)(size_t sz) = malloc; @@ -58,248 +58,248 @@ void cJSON_InitHooks(cJSON_Hooks* hooks) return; } - cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; - cJSON_free = (hooks->free_fn)?hooks->free_fn:free; + cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; + cJSON_free = (hooks->free_fn)?hooks->free_fn:free; } /* Internal constructor. */ static cJSON *cJSON_New_Item(void) { - cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); - if (node) memset(node,0,sizeof(cJSON)); - return node; + cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); + if (node) memset(node,0,sizeof(cJSON)); + return node; } /* Delete a cJSON structure. */ void cJSON_Delete(cJSON *c) { - cJSON *next; - while (c) - { - next=c->next; - if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); - if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); - if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string); - cJSON_free(c); - c=next; - } + cJSON *next; + while (c) + { + next=c->next; + if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); + if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); + if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string); + cJSON_free(c); + c=next; + } } /* Parse the input text to generate a number, and populate the result into item. */ static const char *parse_number(cJSON *item,const char *num) { - double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; + double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; - if (*num=='-') sign=-1,num++; /* Has sign? */ - if (*num=='0') num++; /* is zero */ - if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ - if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ - if (*num=='e' || *num=='E') /* Exponent? */ - { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ - while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ - } + if (*num=='-') sign=-1,num++; /* Has sign? */ + if (*num=='0') num++; /* is zero */ + if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ + if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ + if (*num=='e' || *num=='E') /* Exponent? */ + { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ + while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ + } - n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ + n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ - item->valuedouble=n; - item->valueint=(int)n; - item->type=cJSON_Number; - return num; + item->valuedouble=n; + item->valueint=(int)n; + item->type=cJSON_Number; + return num; } -static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; } +static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; } typedef struct {char *buffer; int length; int offset; } printbuffer; static char* ensure(printbuffer *p,int needed) { - char *newbuffer;int newsize; - if (!p || !p->buffer) return 0; - needed+=p->offset; - if (needed<=p->length) return p->buffer+p->offset; + char *newbuffer;int newsize; + if (!p || !p->buffer) return 0; + needed+=p->offset; + if (needed<=p->length) return p->buffer+p->offset; - newsize=pow2gt(needed); - newbuffer=(char*)cJSON_malloc(newsize); - if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;} - if (newbuffer) memcpy(newbuffer,p->buffer,p->length); - cJSON_free(p->buffer); - p->length=newsize; - p->buffer=newbuffer; - return newbuffer+p->offset; + newsize=pow2gt(needed); + newbuffer=(char*)cJSON_malloc(newsize); + if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;} + if (newbuffer) memcpy(newbuffer,p->buffer,p->length); + cJSON_free(p->buffer); + p->length=newsize; + p->buffer=newbuffer; + return newbuffer+p->offset; } static int update(printbuffer *p) { - char *str; - if (!p || !p->buffer) return 0; - str=p->buffer+p->offset; - return p->offset+strlen(str); + char *str; + if (!p || !p->buffer) return 0; + str=p->buffer+p->offset; + return p->offset+strlen(str); } /* Render the number nicely from the given item into a string. */ static char *print_number(cJSON *item,printbuffer *p) { - char *str=0; - double d=item->valuedouble; - if (d==0) - { - if (p) str=ensure(p,2); - else str=(char*)cJSON_malloc(2); /* special case for 0. */ - if (str) strcpy(str,"0"); - } - else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) - { - if (p) str=ensure(p,21); - else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ - if (str) sprintf(str,"%d",item->valueint); - } - else - { - if (p) str=ensure(p,64); - else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ - if (str) - { - if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60)sprintf(str,"%.0f",d); - else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); - else sprintf(str,"%f",d); - } - } - return str; + char *str=0; + double d=item->valuedouble; + if (d==0) + { + if (p) str=ensure(p,2); + else str=(char*)cJSON_malloc(2); /* special case for 0. */ + if (str) strcpy(str,"0"); + } + else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) + { + if (p) str=ensure(p,21); + else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ + if (str) sprintf(str,"%d",item->valueint); + } + else + { + if (p) str=ensure(p,64); + else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ + if (str) + { + if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60)sprintf(str,"%.0f",d); + else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); + else sprintf(str,"%f",d); + } + } + return str; } static unsigned parse_hex4(const char *str) { - unsigned h=0; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - return h; + unsigned h=0; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + return h; } /* Parse the input text into an unescaped cstring, and populate item. */ static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; static const char *parse_string(cJSON *item,const char *str) { - const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; - if (*str!='\"') {ep=str;return 0;} /* not a string! */ + const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; + if (*str!='\"') {ep=str;return 0;} /* not a string! */ - while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ + while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ - out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ - if (!out) return 0; + out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ + if (!out) return 0; - ptr=str+1;ptr2=out; - while (*ptr!='\"' && *ptr) - { - if (*ptr!='\\') *ptr2++=*ptr++; - else - { - ptr++; - switch (*ptr) - { - case 'b': *ptr2++='\b'; break; - case 'f': *ptr2++='\f'; break; - case 'n': *ptr2++='\n'; break; - case 'r': *ptr2++='\r'; break; - case 't': *ptr2++='\t'; break; - case 'u': /* transcode utf16 to utf8. */ - uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ + ptr=str+1;ptr2=out; + while (*ptr!='\"' && *ptr) + { + if (*ptr!='\\') *ptr2++=*ptr++; + else + { + ptr++; + switch (*ptr) + { + case 'b': *ptr2++='\b'; break; + case 'f': *ptr2++='\f'; break; + case 'n': *ptr2++='\n'; break; + case 'r': *ptr2++='\r'; break; + case 't': *ptr2++='\t'; break; + case 'u': /* transcode utf16 to utf8. */ + uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ - if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */ + if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */ - if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ - { - if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */ - uc2=parse_hex4(ptr+3);ptr+=6; - if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */ - uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); - } + if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ + { + if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */ + uc2=parse_hex4(ptr+3);ptr+=6; + if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */ + uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); + } - len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; + len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; - switch (len) { - case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; __attribute__((fallthrough)); - case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; __attribute__((fallthrough)); - case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; __attribute__((fallthrough)); - case 1: *--ptr2 =(uc | firstByteMark[len]); - } - ptr2+=len; - break; - default: *ptr2++=*ptr; break; - } - ptr++; - } - } - *ptr2=0; - if (*ptr=='\"') ptr++; - item->valuestring=out; - item->type=cJSON_String; - return ptr; + switch (len) { + case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; __attribute__((fallthrough)); + case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; __attribute__((fallthrough)); + case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; __attribute__((fallthrough)); + case 1: *--ptr2 =(uc | firstByteMark[len]); + } + ptr2+=len; + break; + default: *ptr2++=*ptr; break; + } + ptr++; + } + } + *ptr2=0; + if (*ptr=='\"') ptr++; + item->valuestring=out; + item->type=cJSON_String; + return ptr; } /* Render the cstring provided to an escaped version that can be printed. */ static char *print_string_ptr(const char *str,printbuffer *p) { - const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token; - - for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0; - if (!flag) - { - len=ptr-str; - if (p) out=ensure(p,len+3); - else out=(char*)cJSON_malloc(len+3); - if (!out) return 0; - ptr2=out;*ptr2++='\"'; - strcpy(ptr2,str); - ptr2[len]='\"'; - ptr2[len+1]=0; - return out; - } - - if (!str) - { - if (p) out=ensure(p,3); - else out=(char*)cJSON_malloc(3); - if (!out) return 0; - strcpy(out,"\"\""); - return out; - } - ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} - - if (p) out=ensure(p,len+3); - else out=(char*)cJSON_malloc(len+3); - if (!out) return 0; + const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token; - ptr2=out;ptr=str; - *ptr2++='\"'; - while (*ptr) - { - if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; - else - { - *ptr2++='\\'; - switch (token=*ptr++) - { - case '\\': *ptr2++='\\'; break; - case '\"': *ptr2++='\"'; break; - case '\b': *ptr2++='b'; break; - case '\f': *ptr2++='f'; break; - case '\n': *ptr2++='n'; break; - case '\r': *ptr2++='r'; break; - case '\t': *ptr2++='t'; break; - default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ - } - } - } - *ptr2++='\"';*ptr2++=0; - return out; + for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0; + if (!flag) + { + len=ptr-str; + if (p) out=ensure(p,len+3); + else out=(char*)cJSON_malloc(len+3); + if (!out) return 0; + ptr2=out;*ptr2++='\"'; + strcpy(ptr2,str); + ptr2[len]='\"'; + ptr2[len+1]=0; + return out; + } + + if (!str) + { + if (p) out=ensure(p,3); + else out=(char*)cJSON_malloc(3); + if (!out) return 0; + strcpy(out,"\"\""); + return out; + } + ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} + + if (p) out=ensure(p,len+3); + else out=(char*)cJSON_malloc(len+3); + if (!out) return 0; + + ptr2=out;ptr=str; + *ptr2++='\"'; + while (*ptr) + { + if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; + else + { + *ptr2++='\\'; + switch (token=*ptr++) + { + case '\\': *ptr2++='\\'; break; + case '\"': *ptr2++='\"'; break; + case '\b': *ptr2++='b'; break; + case '\f': *ptr2++='f'; break; + case '\n': *ptr2++='n'; break; + case '\r': *ptr2++='r'; break; + case '\t': *ptr2++='t'; break; + default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ + } + } + } + *ptr2++='\"';*ptr2++=0; + return out; } /* Invote print_string_ptr (which is useful) on an item. */ -static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);} +static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);} /* Predeclare these prototypes. */ static const char *parse_value(cJSON *item,const char *value); @@ -315,345 +315,345 @@ static const char *skip(const char *in) {while (in && *in && (unsigned char)*in< /* Parse an object - create a new root, and populate. */ cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated) { - const char *end=0; - cJSON *c=cJSON_New_Item(); - ep=0; - if (!c) return 0; /* memory fail */ + const char *end=0; + cJSON *c=cJSON_New_Item(); + ep=0; + if (!c) return 0; /* memory fail */ - end=parse_value(c,skip(value)); - if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */ + end=parse_value(c,skip(value)); + if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */ - /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}} - if (return_parse_end) *return_parse_end=end; - return c; + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}} + if (return_parse_end) *return_parse_end=end; + return c; } /* Default options for cJSON_Parse */ cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);} /* Render a cJSON item/entity/structure to text. */ -char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);} -char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);} +char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);} +char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);} char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt) { - printbuffer p; - p.buffer=(char*)cJSON_malloc(prebuffer); - p.length=prebuffer; - p.offset=0; - return print_value(item,0,fmt,&p); - return p.buffer; + printbuffer p; + p.buffer=(char*)cJSON_malloc(prebuffer); + p.length=prebuffer; + p.offset=0; + return print_value(item,0,fmt,&p); + return p.buffer; } /* Parser core - when encountering text, process appropriately. */ static const char *parse_value(cJSON *item,const char *value) { - if (!value) return 0; /* Fail on null. */ - if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } - if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } - if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } - if (*value=='\"') { return parse_string(item,value); } - if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } - if (*value=='[') { return parse_array(item,value); } - if (*value=='{') { return parse_object(item,value); } + if (!value) return 0; /* Fail on null. */ + if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } + if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } + if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } + if (*value=='\"') { return parse_string(item,value); } + if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } + if (*value=='[') { return parse_array(item,value); } + if (*value=='{') { return parse_object(item,value); } - ep=value;return 0; /* failure. */ + ep=value;return 0; /* failure. */ } /* Render a value to text. */ static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p) { - char *out=0; - if (!item) return 0; - if (p) - { - switch ((item->type)&255) - { - case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;} - case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;} - case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;} - case cJSON_Number: out=print_number(item,p);break; - case cJSON_String: out=print_string(item,p);break; - case cJSON_Array: out=print_array(item,depth,fmt,p);break; - case cJSON_Object: out=print_object(item,depth,fmt,p);break; - } - } - else - { - switch ((item->type)&255) - { - case cJSON_NULL: out=cJSON_strdup("null"); break; - case cJSON_False: out=cJSON_strdup("false");break; - case cJSON_True: out=cJSON_strdup("true"); break; - case cJSON_Number: out=print_number(item,0);break; - case cJSON_String: out=print_string(item,0);break; - case cJSON_Array: out=print_array(item,depth,fmt,0);break; - case cJSON_Object: out=print_object(item,depth,fmt,0);break; - } - } - return out; + char *out=0; + if (!item) return 0; + if (p) + { + switch ((item->type)&255) + { + case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;} + case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;} + case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;} + case cJSON_Number: out=print_number(item,p);break; + case cJSON_String: out=print_string(item,p);break; + case cJSON_Array: out=print_array(item,depth,fmt,p);break; + case cJSON_Object: out=print_object(item,depth,fmt,p);break; + } + } + else + { + switch ((item->type)&255) + { + case cJSON_NULL: out=cJSON_strdup("null"); break; + case cJSON_False: out=cJSON_strdup("false");break; + case cJSON_True: out=cJSON_strdup("true"); break; + case cJSON_Number: out=print_number(item,0);break; + case cJSON_String: out=print_string(item,0);break; + case cJSON_Array: out=print_array(item,depth,fmt,0);break; + case cJSON_Object: out=print_object(item,depth,fmt,0);break; + } + } + return out; } /* Build an array from input text. */ static const char *parse_array(cJSON *item,const char *value) { - cJSON *child; - if (*value!='[') {ep=value;return 0;} /* not an array! */ + cJSON *child; + if (*value!='[') {ep=value;return 0;} /* not an array! */ - item->type=cJSON_Array; - value=skip(value+1); - if (*value==']') return value+1; /* empty array. */ + item->type=cJSON_Array; + value=skip(value+1); + if (*value==']') return value+1; /* empty array. */ - item->child=child=cJSON_New_Item(); - if (!item->child) return 0; /* memory fail */ - value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ - if (!value) return 0; + item->child=child=cJSON_New_Item(); + if (!item->child) return 0; /* memory fail */ + value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ + if (!value) return 0; - while (*value==',') - { - cJSON *new_item; - if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ - child->next=new_item;new_item->prev=child;child=new_item; - value=skip(parse_value(child,skip(value+1))); - if (!value) return 0; /* memory fail */ - } + while (*value==',') + { + cJSON *new_item; + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ + child->next=new_item;new_item->prev=child;child=new_item; + value=skip(parse_value(child,skip(value+1))); + if (!value) return 0; /* memory fail */ + } - if (*value==']') return value+1; /* end of array */ - ep=value;return 0; /* malformed. */ + if (*value==']') return value+1; /* end of array */ + ep=value;return 0; /* malformed. */ } /* Render an array to text */ static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p) { - char **entries; - char *out=0,*ptr,*ret;int len=5; - cJSON *child=item->child; - int numentries=0,i=0,fail=0; - size_t tmplen=0; - - /* How many entries in the array? */ - while (child) numentries++,child=child->next; - /* Explicitly handle numentries==0 */ - if (!numentries) - { - if (p) out=ensure(p,3); - else out=(char*)cJSON_malloc(3); - if (out) strcpy(out,"[]"); - return out; - } + char **entries; + char *out=0,*ptr,*ret;int len=5; + cJSON *child=item->child; + int numentries=0,i=0,fail=0; + size_t tmplen=0; - if (p) - { - /* Compose the output array. */ - i=p->offset; - ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++; - child=item->child; - while (child && !fail) - { - print_value(child,depth+1,fmt,p); - p->offset=update(p); - if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;} - child=child->next; - } - ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0; - out=(p->buffer)+i; - } - else - { - /* Allocate an array to hold the values for each */ - entries=(char**)cJSON_malloc(numentries*sizeof(char*)); - if (!entries) return 0; - memset(entries,0,numentries*sizeof(char*)); - /* Retrieve all the results: */ - child=item->child; - while (child && !fail) - { - ret=print_value(child,depth+1,fmt,0); - entries[i++]=ret; - if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; - child=child->next; - } - - /* If we didn't fail, try to malloc the output string */ - if (!fail) out=(char*)cJSON_malloc(len); - /* If that fails, we fail. */ - if (!out) fail=1; + /* How many entries in the array? */ + while (child) numentries++,child=child->next; + /* Explicitly handle numentries==0 */ + if (!numentries) + { + if (p) out=ensure(p,3); + else out=(char*)cJSON_malloc(3); + if (out) strcpy(out,"[]"); + return out; + } - /* Handle failure. */ - if (fail) - { - for (i=0;ioffset; + ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++; + child=item->child; + while (child && !fail) + { + print_value(child,depth+1,fmt,p); + p->offset=update(p); + if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;} + child=child->next; + } + ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0; + out=(p->buffer)+i; + } + else + { + /* Allocate an array to hold the values for each */ + entries=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!entries) return 0; + memset(entries,0,numentries*sizeof(char*)); + /* Retrieve all the results: */ + child=item->child; + while (child && !fail) + { + ret=print_value(child,depth+1,fmt,0); + entries[i++]=ret; + if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; + child=child->next; + } + + /* If we didn't fail, try to malloc the output string */ + if (!fail) out=(char*)cJSON_malloc(len); + /* If that fails, we fail. */ + if (!out) fail=1; + + /* Handle failure. */ + if (fail) + { + for (i=0;itype=cJSON_Object; - value=skip(value+1); - if (*value=='}') return value+1; /* empty array. */ + item->type=cJSON_Object; + value=skip(value+1); + if (*value=='}') return value+1; /* empty array. */ - item->child=child=cJSON_New_Item(); - if (!item->child) return 0; - value=skip(parse_string(child,skip(value))); - if (!value) return 0; - child->string=child->valuestring;child->valuestring=0; - if (*value!=':') {ep=value;return 0;} /* fail! */ - value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ - if (!value) return 0; + item->child=child=cJSON_New_Item(); + if (!item->child) return 0; + value=skip(parse_string(child,skip(value))); + if (!value) return 0; + child->string=child->valuestring;child->valuestring=0; + if (*value!=':') {ep=value;return 0;} /* fail! */ + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ + if (!value) return 0; - while (*value==',') - { - cJSON *new_item; - if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ - child->next=new_item;new_item->prev=child;child=new_item; - value=skip(parse_string(child,skip(value+1))); - if (!value) return 0; - child->string=child->valuestring;child->valuestring=0; - if (*value!=':') {ep=value;return 0;} /* fail! */ - value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ - if (!value) return 0; - } + while (*value==',') + { + cJSON *new_item; + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ + child->next=new_item;new_item->prev=child;child=new_item; + value=skip(parse_string(child,skip(value+1))); + if (!value) return 0; + child->string=child->valuestring;child->valuestring=0; + if (*value!=':') {ep=value;return 0;} /* fail! */ + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ + if (!value) return 0; + } - if (*value=='}') return value+1; /* end of array */ - ep=value;return 0; /* malformed. */ + if (*value=='}') return value+1; /* end of array */ + ep=value;return 0; /* malformed. */ } /* Render an object to text. */ static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p) { - char **entries=0,**names=0; - char *out=0,*ptr,*ret,*str;int len=7,i=0,j; - cJSON *child=item->child; - int numentries=0,fail=0; - size_t tmplen=0; - /* Count the number of entries. */ - while (child) numentries++,child=child->next; - /* Explicitly handle empty object case */ - if (!numentries) - { - if (p) out=ensure(p,fmt?depth+4:3); - else out=(char*)cJSON_malloc(fmt?depth+4:3); - if (!out) return 0; - ptr=out;*ptr++='{'; - if (fmt) {*ptr++='\n';for (i=0;ioffset; - len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0; - *ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len; - child=item->child;depth++; - while (child) - { - if (fmt) - { - ptr=ensure(p,depth); if (!ptr) return 0; - for (j=0;joffset+=depth; - } - print_string_ptr(child->string,p); - p->offset=update(p); - - len=fmt?2:1; - ptr=ensure(p,len); if (!ptr) return 0; - *ptr++=':';if (fmt) *ptr++='\t'; - p->offset+=len; - - print_value(child,depth,fmt,p); - p->offset=update(p); + char **entries=0,**names=0; + char *out=0,*ptr,*ret,*str;int len=7,i=0,j; + cJSON *child=item->child; + int numentries=0,fail=0; + size_t tmplen=0; + /* Count the number of entries. */ + while (child) numentries++,child=child->next; + /* Explicitly handle empty object case */ + if (!numentries) + { + if (p) out=ensure(p,fmt?depth+4:3); + else out=(char*)cJSON_malloc(fmt?depth+4:3); + if (!out) return 0; + ptr=out;*ptr++='{'; + if (fmt) {*ptr++='\n';for (i=0;ioffset; + len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0; + *ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len; + child=item->child;depth++; + while (child) + { + if (fmt) + { + ptr=ensure(p,depth); if (!ptr) return 0; + for (j=0;joffset+=depth; + } + print_string_ptr(child->string,p); + p->offset=update(p); - len=(fmt?1:0)+(child->next?1:0); - ptr=ensure(p,len+1); if (!ptr) return 0; - if (child->next) *ptr++=','; - if (fmt) *ptr++='\n';*ptr=0; - p->offset+=len; - child=child->next; - } - ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0; - if (fmt) for (i=0;ibuffer)+i; - } - else - { - /* Allocate space for the names and the objects */ - entries=(char**)cJSON_malloc(numentries*sizeof(char*)); - if (!entries) return 0; - names=(char**)cJSON_malloc(numentries*sizeof(char*)); - if (!names) {cJSON_free(entries);return 0;} - memset(entries,0,sizeof(char*)*numentries); - memset(names,0,sizeof(char*)*numentries); + len=fmt?2:1; + ptr=ensure(p,len); if (!ptr) return 0; + *ptr++=':';if (fmt) *ptr++='\t'; + p->offset+=len; - /* Collect all the results into our arrays: */ - child=item->child;depth++;if (fmt) len+=depth; - while (child) - { - names[i]=str=print_string_ptr(child->string,0); - entries[i++]=ret=print_value(child,depth,fmt,0); - if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; - child=child->next; - } - - /* Try to allocate the output string */ - if (!fail) out=(char*)cJSON_malloc(len); - if (!out) fail=1; + print_value(child,depth,fmt,p); + p->offset=update(p); - /* Handle failure */ - if (fail) - { - for (i=0;inext?1:0); + ptr=ensure(p,len+1); if (!ptr) return 0; + if (child->next) *ptr++=','; + if (fmt) *ptr++='\n';*ptr=0; + p->offset+=len; + child=child->next; + } + ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0; + if (fmt) for (i=0;ibuffer)+i; + } + else + { + /* Allocate space for the names and the objects */ + entries=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!entries) return 0; + names=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!names) {cJSON_free(entries);return 0;} + memset(entries,0,sizeof(char*)*numentries); + memset(names,0,sizeof(char*)*numentries); + + /* Collect all the results into our arrays: */ + child=item->child;depth++;if (fmt) len+=depth; + while (child) + { + names[i]=str=print_string_ptr(child->string,0); + entries[i++]=ret=print_value(child,depth,fmt,0); + if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; + child=child->next; + } + + /* Try to allocate the output string */ + if (!fail) out=(char*)cJSON_malloc(len); + if (!out) fail=1; + + /* Handle failure */ + if (fail) + { + for (i=0;ichild;int i=0;while(c)i++,c=c->next;return i;} -cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} -cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} +int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;} +cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} +cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} /* Utility for array list handling. */ static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;} @@ -661,83 +661,83 @@ static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=p static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;} /* Add item to array/object. */ -void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} -void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} -void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);} -void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} -void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} +void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} +void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} +void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);} +void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} +void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} -cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; - if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} -void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} +cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; + if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} +void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;} void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));} /* Replace array/object items with new ones. */ -void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;} - newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;} -void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; - newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; - if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} +void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;} + newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;} +void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; + newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; + if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} /* Create basic types: */ -cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} -cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} -cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} -cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} -cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} -cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} -cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} -cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} +cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} +cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} +cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} +cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} +cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} +cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} +cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} +cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} /* Create Arrays: */ -cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} /* Duplication */ cJSON *cJSON_Duplicate(cJSON *item,int recurse) { - cJSON *newitem,*cptr,*nptr=0,*newchild; - /* Bail on bad ptr */ - if (!item) return 0; - /* Create new item */ - newitem=cJSON_New_Item(); - if (!newitem) return 0; - /* Copy over all vars */ - newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; - if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}} - if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}} - /* If non-recursive, then we're done! */ - if (!recurse) return newitem; - /* Walk the ->next chain for the child. */ - cptr=item->child; - while (cptr) - { - newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */ - if (!newchild) {cJSON_Delete(newitem);return 0;} - if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */ - else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */ - cptr=cptr->next; - } - return newitem; + cJSON *newitem,*cptr,*nptr=0,*newchild; + /* Bail on bad ptr */ + if (!item) return 0; + /* Create new item */ + newitem=cJSON_New_Item(); + if (!newitem) return 0; + /* Copy over all vars */ + newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; + if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}} + if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}} + /* If non-recursive, then we're done! */ + if (!recurse) return newitem; + /* Walk the ->next chain for the child. */ + cptr=item->child; + while (cptr) + { + newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) {cJSON_Delete(newitem);return 0;} + if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */ + cptr=cptr->next; + } + return newitem; } void cJSON_Minify(char *json) { - char *into=json; - while (*json) - { - if (*json==' ') json++; - else if (*json=='\t') json++; /* Whitespace characters. */ - else if (*json=='\r') json++; - else if (*json=='\n') json++; - else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */ - else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */ - else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */ - else *into++=*json++; /* All other characters. */ - } - *into=0; /* and null-terminate. */ + char *into=json; + while (*json) + { + if (*json==' ') json++; + else if (*json=='\t') json++; /* Whitespace characters. */ + else if (*json=='\r') json++; + else if (*json=='\n') json++; + else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */ + else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */ + else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */ + else *into++=*json++; /* All other characters. */ + } + *into=0; /* and null-terminate. */ } diff --git a/components/stage/cjson/cJSON.h b/components/stage/cjson/cJSON.h index 671d5912..3b60bc6d 100644 --- a/components/stage/cjson/cJSON.h +++ b/components/stage/cjson/cJSON.h @@ -1,16 +1,16 @@ /* Copyright (c) 2009 Dave Gamble - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -44,22 +44,22 @@ extern "C" #define cJSON_String 4 #define cJSON_Array 5 #define cJSON_Object 6 - + #define cJSON_IsReference 256 #define cJSON_StringIsConst 512 /* The cJSON structure: */ typedef struct cJSON { - struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ - struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ - int type; /* The type of the item, as above. */ + int type; /* The type of the item, as above. */ - char *valuestring; /* The item's string, if type==cJSON_String */ - int valueint; /* The item's number, if type==cJSON_Number */ - double valuedouble; /* The item's number, if type==cJSON_Number */ + char *valuestring; /* The item's string, if type==cJSON_String */ + int valueint; /* The item's number, if type==cJSON_Number */ + double valuedouble; /* The item's number, if type==cJSON_Number */ - char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ } cJSON; typedef struct cJSON_Hooks { @@ -83,7 +83,7 @@ extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt); extern void cJSON_Delete(cJSON *c); /* Returns the number of items in an array (or object). */ -extern int cJSON_GetArraySize(cJSON *array); +extern int cJSON_GetArraySize(cJSON *array); /* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ extern cJSON *cJSON_GetArrayItem(cJSON *array,int item); /* Get item "string" from object. Case insensitive. */ @@ -91,7 +91,7 @@ extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string); /* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ extern const char *cJSON_GetErrorPtr(void); - + /* These calls create a cJSON item of the appropriate type. */ extern cJSON *cJSON_CreateNull(void); extern cJSON *cJSON_CreateTrue(void); @@ -110,20 +110,20 @@ extern cJSON *cJSON_CreateStringArray(const char **strings,int count); /* Append item to the specified array/object. */ extern void cJSON_AddItemToArray(cJSON *array, cJSON *item); -extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item); -extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */ +extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item); +extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */ /* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); -extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item); +extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item); /* Remove/Detatch items from Arrays/Objects. */ extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which); extern void cJSON_DeleteItemFromArray(cJSON *array,int which); extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string); extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string); - + /* Update array items. */ -extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */ +extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */ extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem); extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); @@ -139,16 +139,16 @@ extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_en extern void cJSON_Minify(char *json); /* Macros for creating things quickly. */ -#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) -#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) -#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) -#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b)) -#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) -#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) +#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b)) +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) /* When assigning an integer value, it needs to be propagated to valuedouble too. */ -#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) -#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) +#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) +#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) #ifdef __cplusplus } diff --git a/components/stage/cli/bouffalo.mk b/components/stage/cli/bouffalo.mk index 07c3e503..26fff88f 100644 --- a/components/stage/cli/bouffalo.mk +++ b/components/stage/cli/bouffalo.mk @@ -2,17 +2,17 @@ # ## These include paths would be exported to project level COMPONENT_ADD_INCLUDEDIRS += cli/include - -## not be exported to project level -COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## not be exported to project level +COMPONENT_PRIV_INCLUDEDIRS := + +## This component's src COMPONENT_SRCS := cli/cli.c - + COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) COMPONENT_SRCDIRS := cli ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/stage/cli/cli/cli.c b/components/stage/cli/cli/cli.c index 5e9219ab..3f3d4510 100644 --- a/components/stage/cli/cli/cli.c +++ b/components/stage/cli/cli/cli.c @@ -972,7 +972,7 @@ static void ps_cmd(char *buf, int len, int argc, char **argv) char *pcWriteBuffer, *info; const char *const pcHeader = "State Priority Stack # Base\r\n********************************************************\r\n"; BaseType_t xSpacePadding; - + info = pvPortMalloc(1536); if (NULL == info) { return; @@ -982,17 +982,17 @@ static void ps_cmd(char *buf, int len, int argc, char **argv) /* Generate a table of task stats. */ strcpy(pcWriteBuffer, "Task" ); pcWriteBuffer += strlen(pcWriteBuffer ); - + /* Minus three for the null terminator and half the number of characters in "Task" so the column lines up with the centre of the heading. */ - for ( xSpacePadding = strlen( "Task" ); xSpacePadding < ( configMAX_TASK_NAME_LEN - 3 ); xSpacePadding++ ) { + for ( xSpacePadding = strlen( "Task" ); xSpacePadding < ( configMAX_TASK_NAME_LEN - 3 ); xSpacePadding++ ) { /* Add a space to align columns after the task's name. */ - *pcWriteBuffer = ' '; - pcWriteBuffer++; - + *pcWriteBuffer = ' '; + pcWriteBuffer++; + /* Ensure always terminated. */ - *pcWriteBuffer = 0x00; - } + *pcWriteBuffer = 0x00; + } strcpy(pcWriteBuffer, pcHeader ); vTaskList(pcWriteBuffer + strlen(pcHeader)); cli_putstr(info); @@ -1095,7 +1095,7 @@ static void ls_cmd(char *buf, int len, int argc, char **argv) inode_forearch_name(cb_idnoe, &env); } else { aos_cli_printf("invalid parameter!\r\n"); - } + } } vPortFree(st); } @@ -1317,7 +1317,7 @@ init_general_err: } return ret; -#endif +#endif } static void console_cb_read(int fd, void *param) @@ -1334,12 +1334,12 @@ static void console_cb_read(int fd, void *param) printf("-------------BUG from aos_read for ret\r\n"); } } -} +} static void console_cb_write(int fd, void *param) { printf("Empty cb\r\n"); -} +} void *aos_cli_event_cb_read_get() { diff --git a/components/stage/easyflash4/bouffalo.mk b/components/stage/easyflash4/bouffalo.mk index ace6fa32..2d6f1dd8 100644 --- a/components/stage/easyflash4/bouffalo.mk +++ b/components/stage/easyflash4/bouffalo.mk @@ -4,7 +4,7 @@ COMPONENT_ADD_INCLUDEDIRS += inc ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := -## This component's src +## This component's src COMPONENT_SRCS := src/easyflash.c src/ef_env.c \ src/ef_env_legacy_wl.c src/ef_env_legacy.c \ src/ef_port.c src/ef_utils.c \ @@ -13,4 +13,4 @@ COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) COMPONENT_SRCDIRS := src ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/stage/easyflash4/src/easyflash_cli.c b/components/stage/easyflash4/src/easyflash_cli.c index 40769aff..de07f733 100644 --- a/components/stage/easyflash4/src/easyflash_cli.c +++ b/components/stage/easyflash4/src/easyflash_cli.c @@ -111,6 +111,6 @@ int easyflash_cli_init(void) // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/stage/easyflash4/src/ef_port.c b/components/stage/easyflash4/src/ef_port.c index 43247a9c..6e82ec66 100644 --- a/components/stage/easyflash4/src/ef_port.c +++ b/components/stage/easyflash4/src/ef_port.c @@ -75,7 +75,7 @@ EfErrCode ef_port_init(ef_env const **default_env, size_t *default_env_size) { printf("*default_env_size = 0x%08x\r\n", *default_env_size); env_cache_lock = xSemaphoreCreateMutex(); - + return EF_NO_ERR; } @@ -98,7 +98,7 @@ EfErrCode ef_port_read(uint32_t addr, uint32_t *buf, size_t size) { if (bl_mtd_read(handle, addr, size, (uint8_t*)buf) < 0) { result = EF_READ_ERR; } - + return result; } @@ -140,7 +140,7 @@ EfErrCode ef_port_write(uint32_t addr, const uint32_t *buf, size_t size) { EfErrCode result = EF_NO_ERR; //EF_ASSERT(size % 4 == 0); - + /* You can add your code under here. */ if (bl_mtd_write(handle, addr, size, (const uint8_t*)buf) < 0) { result = EF_WRITE_ERR; @@ -153,7 +153,7 @@ EfErrCode ef_port_write(uint32_t addr, const uint32_t *buf, size_t size) { * lock the ENV ram cache */ void ef_port_env_lock(void) { - + /* You can add your code under here. */ xSemaphoreTake( env_cache_lock, portMAX_DELAY ); @@ -163,7 +163,7 @@ void ef_port_env_lock(void) { * unlock the ENV ram cache */ void ef_port_env_unlock(void) { - + /* You can add your code under here. */ xSemaphoreGive( env_cache_lock ); } @@ -210,7 +210,7 @@ void ef_log_info(const char *format, ...) { /* You can add your code under here. */ vprint(format, args); - + va_end(args); } /** @@ -227,6 +227,6 @@ void ef_print(const char *format, ...) { /* You can add your code under here. */ vprint(format, args); - + va_end(args); } diff --git a/components/stage/yloop/bouffalo.mk b/components/stage/yloop/bouffalo.mk index 5de23762..f5e5ba64 100644 --- a/components/stage/yloop/bouffalo.mk +++ b/components/stage/yloop/bouffalo.mk @@ -2,18 +2,18 @@ # ## These include paths would be exported to project level COMPONENT_ADD_INCLUDEDIRS += include - + ## not be exported to project level COMPONENT_PRIV_INCLUDEDIRS := include -## This component's src +## This component's src COMPONENT_SRCS := src/yloop.c \ src/select.c \ src/aos_freertos.c \ src/device.c \ src/local_event.c \ - + COMPONENT_OBJS := $(patsubst %.c,%.o, $(COMPONENT_SRCS)) COMPONENT_SRCDIRS := src @@ -23,4 +23,4 @@ CFLAGS += -DUSE_STDLIB_MALLOC endif ## -#CPPFLAGS += +#CPPFLAGS += diff --git a/components/stage/yloop/include/aos/list.h b/components/stage/yloop/include/aos/list.h index 50a047f3..6282d0a3 100644 --- a/components/stage/yloop/include/aos/list.h +++ b/components/stage/yloop/include/aos/list.h @@ -184,12 +184,12 @@ static inline int dlist_empty(const dlist_t *head) */ static inline int dlist_entry_number(dlist_t *queue) { - int num; - dlist_t *cur = queue; - for (num=0;cur->next != queue;cur=cur->next, num++) - ; - - return num; + int num; + dlist_t *cur = queue; + for (num=0;cur->next != queue;cur=cur->next, num++) + ; + + return num; } @@ -321,12 +321,12 @@ static inline void slist_init(slist_t *head) */ static inline int slist_entry_number(slist_t *queue) { - int num; - slist_t *cur = queue; + int num; + slist_t *cur = queue; for (num=0;cur->next;cur=cur->next, num++) - ; - - return num; + ; + + return num; } diff --git a/components/stage/yloop/include/event_type_code.h b/components/stage/yloop/include/event_type_code.h index 66e1693c..c37ec745 100644 --- a/components/stage/yloop/include/event_type_code.h +++ b/components/stage/yloop/include/event_type_code.h @@ -437,8 +437,8 @@ #define EV_I2C 0x020F #define CODE_I2C_END 1 -#define CODE_I2C_ARB 2 -#define CODE_I2C_NAK 3 +#define CODE_I2C_ARB 2 +#define CODE_I2C_NAK 3 #define CODE_I2C_FER 4 diff --git a/components/stage/yloop/include/yloop_types.h b/components/stage/yloop/include/yloop_types.h index 3e914982..a69134e2 100644 --- a/components/stage/yloop/include/yloop_types.h +++ b/components/stage/yloop/include/yloop_types.h @@ -5,8 +5,8 @@ #define POLLOUT 0x2 #define POLLERR 0x4 struct pollfd { - int fd; - short events; + int fd; + short events; short revents; }; diff --git a/components/stage/yloop/src/aos_freertos.c b/components/stage/yloop/src/aos_freertos.c index e6154a37..fc064a5b 100644 --- a/components/stage/yloop/src/aos_freertos.c +++ b/components/stage/yloop/src/aos_freertos.c @@ -422,7 +422,7 @@ void *malloc(size_t size) #endif long long aos_now_ms(void) -{ +{ long long ms; TickType_t ticks = 0; BaseType_t overflow_count = 0; @@ -437,5 +437,5 @@ long long aos_now_ms(void) ms = ((long long)ticks) + ((TickType_t)(-1) * ((long long)overflow_count)); return ms; -} +} diff --git a/components/sys/bloop/bloop/src/bloop_base.c b/components/sys/bloop/bloop/src/bloop_base.c index f3fdc7bd..b30adf79 100644 --- a/components/sys/bloop/bloop/src/bloop_base.c +++ b/components/sys/bloop/bloop/src/bloop_base.c @@ -345,10 +345,10 @@ void bloop_evt_set_async(struct loop_ctx *loop, unsigned int evt, uint32_t evt_m { BL_ASSERT_ERROR(evt < LOOP_TASK_MAX); - taskENTER_CRITICAL(); + taskENTER_CRITICAL(); loop->bitmap_evt_async |= (1 << evt); loop->evt_type_map_async[evt] |= evt_map; - taskEXIT_CRITICAL(); + taskEXIT_CRITICAL(); /*wait up looper in case*/ xTaskNotifyGive(loop->looper); @@ -425,7 +425,7 @@ static void _dump_timer_dlist(utils_dlist_t *dlist) int bloop_status_dump(struct loop_ctx *loop) { int i; - + puts("====== bloop dump ======\r\n"); printf(" bitmap_evt %lx\r\n", loop->bitmap_evt_sync); printf(" bitmap_msg %lx\r\n", loop->bitmap_msg); diff --git a/components/sys/bloop/loopapps/loopalarm/include/ccronexpr.h b/components/sys/bloop/loopapps/loopalarm/include/ccronexpr.h index e5659423..1213126b 100644 --- a/components/sys/bloop/loopapps/loopalarm/include/ccronexpr.h +++ b/components/sys/bloop/loopapps/loopalarm/include/ccronexpr.h @@ -22,7 +22,7 @@ typedef struct { /** * Parses specified cron expression. - * + * * @param expression cron expression as nul-terminated string, * should be no longer that 256 bytes * @param pointer to cron expression structure, it's client code responsibility @@ -35,10 +35,10 @@ void cron_parse_expr(const char* expression, cron_expr* target, const char** err /** * Uses the specified expression to calculate the next 'fire' date after - * the specified date. All dates are processed as UTC (GMT) dates - * without timezones information. To use local dates (current system timezone) + * the specified date. All dates are processed as UTC (GMT) dates + * without timezones information. To use local dates (current system timezone) * instead of GMT compile with '-DCRON_USE_LOCAL_TIME' - * + * * @param expr parsed cron expression to use in next date calculation * @param date start date to start calculation from * @return next 'fire' date in case of success, '((time_t) -1)' in case of error. @@ -47,10 +47,10 @@ time_t cron_next(cron_expr* expr, time_t date); /** * Uses the specified expression to calculate the previous 'fire' date after - * the specified date. All dates are processed as UTC (GMT) dates - * without timezones information. To use local dates (current system timezone) + * the specified date. All dates are processed as UTC (GMT) dates + * without timezones information. To use local dates (current system timezone) * instead of GMT compile with '-DCRON_USE_LOCAL_TIME' - * + * * @param expr parsed cron expression to use in previous date calculation * @param date start date to start calculation from * @return previous 'fire' date in case of success, '((time_t) -1)' in case of error. diff --git a/components/sys/bloop/loopapps/loopalarm/include/cronalarms.h b/components/sys/bloop/loopapps/loopalarm/include/cronalarms.h index 65026653..a9e7387a 100644 --- a/components/sys/bloop/loopapps/loopalarm/include/cronalarms.h +++ b/components/sys/bloop/loopapps/loopalarm/include/cronalarms.h @@ -5,18 +5,18 @@ /** * @brief create cron alarm - * @param[in] cronstring: cron alarm command string. handler: callback. + * @param[in] cronstring: cron alarm command string. handler: callback. * @param oneshot: if only run once, oneshot is 1, else, oneshot is 0 - * - * @return - * - 0: success - * - -1: failed + * + * @return + * - 0: success + * - -1: failed * * */ int cron_alarm_create(const char * cronstring, void *handler, int oneshot); /** - * @brief cron alarm process. + * @brief cron alarm process. * * */ void cron_alarm_service(void); @@ -30,11 +30,11 @@ void cronalarminit(void); /** * @brief for demo.c test use. change time to check whether cron alarm run ok. * @param test_time: add seconds - * - * @return - * - seconds + * + * @return + * - seconds * * */ uint32_t cronal_time(uint32_t test_time); -#endif +#endif diff --git a/components/sys/bloop/loopapps/loopalarm/src/ccronexpr.c b/components/sys/bloop/loopapps/loopalarm/src/ccronexpr.c index 4a4a2775..528a4fd8 100644 --- a/components/sys/bloop/loopapps/loopalarm/src/ccronexpr.c +++ b/components/sys/bloop/loopapps/loopalarm/src/ccronexpr.c @@ -577,7 +577,7 @@ static char** split_str(const char* str, char del, size_t* len_out) { stlen += 1; if (stlen >= CRON_MAX_STR_LEN_TO_SPLIT) goto return_error; } - + for (i = 0; i < stlen; i++) { int c = str[i]; if (del == str[i]) { @@ -912,7 +912,7 @@ void cron_parse_expr(const char* expression, cron_expr* target, const char** err goto return_res; - return_res: + return_res: free_splitted(fields, len); } diff --git a/components/sys/bloop/loopapps/loopalarm/src/cronalarms.c b/components/sys/bloop/loopapps/loopalarm/src/cronalarms.c index dbf57380..43a6194a 100644 --- a/components/sys/bloop/loopapps/loopalarm/src/cronalarms.c +++ b/components/sys/bloop/loopapps/loopalarm/src/cronalarms.c @@ -16,15 +16,15 @@ typedef struct cronevent cron_expr expr; void (*handler)(void); uint32_t nexttrigger; - int enabled; - int oneshot; + int enabled; + int oneshot; }cronevent_t; static uint32_t test_count = 0;//for test use uint32_t cronal_time(uint32_t test_s) { uint32_t seconds = 0, frags = 0; - + sntp_get_time(&seconds, &frags); test_count = test_count + test_s; seconds = seconds + test_count; @@ -61,7 +61,7 @@ static void cronal_enable(cronevent_t *pstcron) pstcron->enabled = 1; update_next_trigger(pstcron); } - + return; } @@ -86,7 +86,7 @@ void cron_alarm_service(void) if(node->enabled == 1 && (cronal_time(0) >= node->nexttrigger)) { handler = node->handler; if (node->oneshot == 1) { - cronal_free(node); + cronal_free(node); } else { update_next_trigger(node); } @@ -95,17 +95,17 @@ void cron_alarm_service(void) } } else if (node->enabled == 0) { - cronal_enable(node); + cronal_enable(node); } else { - } - + } + } - + return; } int cron_alarm_create(const char * cronstring, void *handler, int oneshot) -{ +{ cronevent_t *pstcron; const char *err; @@ -119,7 +119,7 @@ int cron_alarm_create(const char * cronstring, void *handler, int oneshot) blog_error("malloc failed , return \r\n"); return -1; } - + memset(pstcron, 0, sizeof(cronevent_t)); cron_parse_expr(cronstring, &(pstcron->expr), &err); if (err) { @@ -129,8 +129,8 @@ int cron_alarm_create(const char * cronstring, void *handler, int oneshot) pstcron->handler = (void (*)(void))handler; pstcron->oneshot = oneshot; - cronal_enable(pstcron); + cronal_enable(pstcron); utils_dlist_add(&(pstcron->dlist_item), &cronalarm_queue); - + return 0; } diff --git a/components/sys/bloop/loopapps/loopalarm/src/loopset_cronalarm.c b/components/sys/bloop/loopapps/loopalarm/src/loopset_cronalarm.c index a5c3e726..c22b8360 100644 --- a/components/sys/bloop/loopapps/loopalarm/src/loopset_cronalarm.c +++ b/components/sys/bloop/loopapps/loopalarm/src/loopset_cronalarm.c @@ -26,7 +26,7 @@ static int _cronalarm_bloop_evt(struct loop_ctx *loop, const struct loop_evt_han { uint32_t map = *evt_type_map; redo: - if (map & EVT_MAP_CRON_ALARM_TRIGGER) { + if (map & EVT_MAP_CRON_ALARM_TRIGGER) { looprt_timer_register(&cronalarm_item.timer); map &= (~EVT_MAP_CRON_ALARM_TRIGGER); blog_debug("end once timer trigger \r\n"); diff --git a/components/sys/bloop/loopset/src/loopset_i2c.c b/components/sys/bloop/loopset/src/loopset_i2c.c index c8e8863b..c0037088 100644 --- a/components/sys/bloop/loopset/src/loopset_i2c.c +++ b/components/sys/bloop/loopset/src/loopset_i2c.c @@ -51,7 +51,7 @@ struct loop_evt_handler_holder { }; static int _i2c_bloop_evt(struct loop_ctx *loop, const struct loop_evt_handler *handler, uint32_t *bitmap_evt, uint32_t *evt_type_map) -{ +{ uint32_t map = *evt_type_map; redo: if (map & EVT_MAP_INSERT_I2C_TRIGGER) { @@ -72,14 +72,14 @@ redo: if (map & EVT_MAP_INSERT_I2C_TRIGGER) { aos_post_event(EV_I2C, CODE_I2C_NAK, 0); } else { } - + } else { BL_ASSERT_ERROR(0 == map); } if (map) { goto redo; - } + } *evt_type_map = 0; @@ -100,7 +100,7 @@ int loopset_i2c_hook_on_looprt(void) .evt = _i2c_bloop_evt, .handle = _i2c_bloop_msg, }, - + }; return looprt_handler_register(&_i2c_bloop_handler_holder.handler, LOOPSET_I2C_PRIORITY); diff --git a/components/sys/bloop/loopset/src/loopset_ir.c b/components/sys/bloop/loopset/src/loopset_ir.c index c98c87ab..f4ae719a 100644 --- a/components/sys/bloop/loopset/src/loopset_ir.c +++ b/components/sys/bloop/loopset/src/loopset_ir.c @@ -54,9 +54,9 @@ static int _ir_bloop_evt(struct loop_ctx *loop, const struct loop_evt_handler *h data = bl_receivedata(); if (0 == data) { - aos_post_event(EV_IR, CODE_IR_RECEIVE_NEC_REPEAT, 0); + aos_post_event(EV_IR, CODE_IR_RECEIVE_NEC_REPEAT, 0); } else { - aos_post_event(EV_IR, CODE_IR_RECEIVE_NEC, data); + aos_post_event(EV_IR, CODE_IR_RECEIVE_NEC, data); } bl_enable_rx_int(); @@ -77,7 +77,7 @@ int loopset_ir_hook_on_looprt(void) .name = "IR Trigger", .evt = _ir_bloop_evt, .handle = _ir_bloop_msg, - }, + }, }; //TODO use run-time priority based register diff --git a/components/sys/blota/bl_sys_ota_cli.c b/components/sys/blota/bl_sys_ota_cli.c index 7a98fdf9..2a10b157 100644 --- a/components/sys/blota/bl_sys_ota_cli.c +++ b/components/sys/blota/bl_sys_ota_cli.c @@ -207,7 +207,7 @@ static void ota_tcp_cmd(char *buf, int len, int argc, char **argv) bl_mtd_close(handle); return; } - + buffer_offset = 0; flash_offset = 0; ota_header_found = 0; @@ -328,6 +328,6 @@ int bl_sys_ota_cli_init(void) // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/sys/bltime/bl_sys_time_cli.c b/components/sys/bltime/bl_sys_time_cli.c index ddbb2bb3..287e4fa9 100644 --- a/components/sys/bltime/bl_sys_time_cli.c +++ b/components/sys/bltime/bl_sys_time_cli.c @@ -59,13 +59,13 @@ static void cmd_sys_time_now(char *buf, int len, int argc, char **argv) // STATIC_CLI_CMD_ATTRIBUTE makes this(these) command(s) static const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { { "bl_sys_time_now", "sys time now", cmd_sys_time_now}, -}; +}; int bl_sys_time_cli_init(void) { // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. - //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); + //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; } diff --git a/components/utils/include/utils_fec.h b/components/utils/include/utils_fec.h index 674d75ac..10a7f7fc 100644 --- a/components/utils/include/utils_fec.h +++ b/components/utils/include/utils_fec.h @@ -38,14 +38,14 @@ extern "C" { #endif -#define FEC_MSG_LENGTH 128 -#define FEC_ECC_LENGTH 126 +#define FEC_MSG_LENGTH 128 +#define FEC_ECC_LENGTH 126 #define bl_assert(expr) typedef struct { - int dummy[1120]; + int dummy[1120]; } fec_t; int reedsolomon_getmemsize(void); diff --git a/components/utils/include/utils_getopt.h b/components/utils/include/utils_getopt.h index 07b58bb9..e6be8670 100644 --- a/components/utils/include/utils_getopt.h +++ b/components/utils/include/utils_getopt.h @@ -38,7 +38,7 @@ typedef struct getopt_env { int optind; /*!< current index of argv*/ int opterr; /*!< non-zero enable error message output, while 0,no error message output*/ int optopt; /*!< contain unrecognized option character*/ - int __optpos; + int __optpos; } getopt_env_t; /** @@ -47,7 +47,7 @@ typedef struct getopt_env { * @param env pointer to struct getopt_env * @param opterr set error message output method * - * @return + * @return * - 0: success * - -1: fail */ @@ -57,12 +57,12 @@ int utils_getopt_init(getopt_env_t *env, int opterr); * @brief Parses the command-line arguments * * @param env pointer to struct getopt_env - * @param argc the argument count + * @param argc the argument count * @param argv the argument array * - * @return + * @return * - option character : an option was successfully found - * - -1 : all command-line options have been parsed + * - -1 : all command-line options have been parsed * - '?' : option character was not in optstring * - ':' or '?' : If utils_getopt() encounters an option with a missing argument, then the return value depends on the first character in optstring: if it is ':', then ':' is returned; otherwise '?' is returned * diff --git a/components/utils/include/utils_list.h b/components/utils/include/utils_list.h index 25001d12..157d9429 100644 --- a/components/utils/include/utils_list.h +++ b/components/utils/include/utils_list.h @@ -433,12 +433,12 @@ static inline int utils_dlist_empty(const utils_dlist_t *head) */ static inline int utils_dlist_entry_number(utils_dlist_t *queue) { - int num; - utils_dlist_t *cur = queue; - for (num=0;cur->next != queue;cur=cur->next, num++) - ; - - return num; + int num; + utils_dlist_t *cur = queue; + for (num=0;cur->next != queue;cur=cur->next, num++) + ; + + return num; } @@ -570,11 +570,11 @@ static inline void utils_slist_init(utils_slist_t *head) */ static inline int utils_slist_entry_number(utils_slist_t *queue) { - int num; - utils_slist_t *cur = queue; + int num; + utils_slist_t *cur = queue; for (num=0;cur->next;cur=cur->next, num++) - ; - - return num; + ; + + return num; } #endif diff --git a/components/utils/include/utils_time.h b/components/utils/include/utils_time.h index 9e5de451..840adb9f 100644 --- a/components/utils/include/utils_time.h +++ b/components/utils/include/utils_time.h @@ -40,7 +40,7 @@ typedef struct { unsigned char leap_year_ind; unsigned int ntp_year; unsigned int days_since_epoch; - unsigned int day_of_year; + unsigned int day_of_year; } utils_time_date_t; int utils_time_date_from_epoch(unsigned int epoch, utils_time_date_t *date); diff --git a/components/utils/src/test/test_utils_rbtree.c b/components/utils/src/test/test_utils_rbtree.c index ac1df304..aa0454bc 100644 --- a/components/utils/src/test/test_utils_rbtree.c +++ b/components/utils/src/test/test_utils_rbtree.c @@ -36,7 +36,7 @@ struct iovec { size_t iov_len; // [XSI] Size of region iov_base points to }; -static int my_cmp_cb(struct rb_tree *self, struct rb_node *node_a, struct rb_node *node_b) +static int my_cmp_cb(struct rb_tree *self, struct rb_node *node_a, struct rb_node *node_b) { struct iovec *a = (struct iovec *) node_a->value; struct iovec *b = (struct iovec *) node_b->value; diff --git a/components/utils/src/utils_crc.c b/components/utils/src/utils_crc.c index 59ecd251..94214122 100644 --- a/components/utils/src/utils_crc.c +++ b/components/utils/src/utils_crc.c @@ -36,9 +36,9 @@ // ---------------- POPULAR POLYNOMIALS ---------------- // CCITT: x^16 + x^12 + x^5 + x^0 (0x1021,init 0x0000) // CRC-16: x^16 + x^15 + x^2 + x^0 (0x8005,init 0xFFFF) -// we use 0x8005 here and +// we use 0x8005 here and -static const uint8_t chCRCHTalbe[] = +static const uint8_t chCRCHTalbe[] = { 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, @@ -64,7 +64,7 @@ static const uint8_t chCRCHTalbe[] = 0x00, 0xC1, 0x81, 0x40 }; -static const uint8_t chCRCLTalbe[] = +static const uint8_t chCRCLTalbe[] = { 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, @@ -92,79 +92,79 @@ static const uint8_t chCRCLTalbe[] = uint16_t utils_crc16(void * dataIn, uint32_t len) { - uint8_t chCRCHi = 0xFF; - uint8_t chCRCLo = 0xFF; - uint16_t wIndex; - uint8_t* data=(uint8_t *) dataIn; + uint8_t chCRCHi = 0xFF; + uint8_t chCRCLo = 0xFF; + uint16_t wIndex; + uint8_t* data=(uint8_t *) dataIn; - while (len--) - { - wIndex = chCRCLo ^ *data++ ; - chCRCLo = chCRCHi ^ chCRCHTalbe[wIndex]; - chCRCHi = chCRCLTalbe[wIndex] ; - } + while (len--) + { + wIndex = chCRCLo ^ *data++ ; + chCRCLo = chCRCHi ^ chCRCHTalbe[wIndex]; + chCRCHi = chCRCLTalbe[wIndex] ; + } - return ((chCRCHi << 8) | chCRCLo) ; + return ((chCRCHi << 8) | chCRCLo) ; } /* x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1 */ static const uint32_t crc32Tab[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; uint32_t utils_crc32(void *dataIn, uint32_t len) { - uint32_t crc=0; + uint32_t crc=0; uint8_t *data=(uint8_t *)dataIn; - - crc = crc ^ 0xffffffff; - while (len--) - crc = crc32Tab[(crc ^ *data++) & 0xFF] ^ (crc >> 8); + crc = crc ^ 0xffffffff; - return crc ^ 0xffffffff; + while (len--) + crc = crc32Tab[(crc ^ *data++) & 0xFF] ^ (crc >> 8); + + return crc ^ 0xffffffff; } diff --git a/components/utils/src/utils_hexdump.c b/components/utils/src/utils_hexdump.c index 6fa38a86..87422f2f 100644 --- a/components/utils/src/utils_hexdump.c +++ b/components/utils/src/utils_hexdump.c @@ -37,7 +37,7 @@ #endif //FIXME fix putchar extern int bl_putchar(int c); - + void utils_hexdump(void *mem, unsigned int len) { unsigned int i, j; @@ -74,4 +74,4 @@ void utils_hexdump(void *mem, unsigned int len) } } } - + diff --git a/components/utils/src/utils_memp.c b/components/utils/src/utils_memp.c index a4659b69..eb9f0535 100644 --- a/components/utils/src/utils_memp.c +++ b/components/utils/src/utils_memp.c @@ -106,7 +106,7 @@ void *utils_memp_malloc(utils_memp_pool_t *pool) pat = (uint32_t *)&node->next; *pat = UTILS_MEMP_ALLOCED_NODE_PATTERN; return (void *)node + sizeof(struct utils_memp_node); - } else { + } else { return NULL; } } diff --git a/components/utils/src/utils_rbtree.c b/components/utils/src/utils_rbtree.c index 2c5a8598..64067d02 100644 --- a/components/utils/src/utils_rbtree.c +++ b/components/utils/src/utils_rbtree.c @@ -33,12 +33,12 @@ // rb_node -struct rb_node * rb_node_alloc () +struct rb_node * rb_node_alloc () { return pvPortMalloc(sizeof(struct rb_node)); } -struct rb_node * rb_node_init (struct rb_node *self, void *value) +struct rb_node * rb_node_init (struct rb_node *self, void *value) { if (self) { self->red = 1; @@ -48,24 +48,24 @@ struct rb_node * rb_node_init (struct rb_node *self, void *value) return self; } -struct rb_node * rb_node_create (void *value) +struct rb_node * rb_node_create (void *value) { return rb_node_init(rb_node_alloc(), value); } -void rb_node_dealloc (struct rb_node *self) +void rb_node_dealloc (struct rb_node *self) { if (self) { vPortFree(self); } } -static int rb_node_is_red (const struct rb_node *self) +static int rb_node_is_red (const struct rb_node *self) { return self ? self->red : 0; } -static struct rb_node * rb_node_rotate (struct rb_node *self, int dir) +static struct rb_node * rb_node_rotate (struct rb_node *self, int dir) { struct rb_node *result = NULL; @@ -79,7 +79,7 @@ static struct rb_node * rb_node_rotate (struct rb_node *self, int dir) return result; } -static struct rb_node * rb_node_rotate2 (struct rb_node *self, int dir) +static struct rb_node * rb_node_rotate2 (struct rb_node *self, int dir) { struct rb_node *result = NULL; @@ -91,12 +91,12 @@ static struct rb_node * rb_node_rotate2 (struct rb_node *self, int dir) } // rb_tree - default callbacks -int rb_tree_node_cmp_ptr_cb (struct rb_tree *self, struct rb_node *a, struct rb_node *b) +int rb_tree_node_cmp_ptr_cb (struct rb_tree *self, struct rb_node *a, struct rb_node *b) { return (a->value > b->value) - (a->value < b->value); } -void rb_tree_node_dealloc_cb (struct rb_tree *self, struct rb_node *node) +void rb_tree_node_dealloc_cb (struct rb_tree *self, struct rb_node *node) { if (self) { if (node) { @@ -106,12 +106,12 @@ void rb_tree_node_dealloc_cb (struct rb_tree *self, struct rb_node *node) } // rb_tree -struct rb_tree * rb_tree_alloc () +struct rb_tree * rb_tree_alloc () { return pvPortMalloc(sizeof(struct rb_tree)); } -struct rb_tree * rb_tree_init (struct rb_tree *self, rb_tree_node_cmp_f node_cmp_cb) +struct rb_tree * rb_tree_init (struct rb_tree *self, rb_tree_node_cmp_f node_cmp_cb) { if (self) { self->root = NULL; @@ -122,18 +122,18 @@ struct rb_tree * rb_tree_init (struct rb_tree *self, rb_tree_node_cmp_f node_cmp return self; } -struct rb_tree * rb_tree_create (rb_tree_node_cmp_f node_cb) +struct rb_tree * rb_tree_create (rb_tree_node_cmp_f node_cb) { return rb_tree_init(rb_tree_alloc(), node_cb); } -void rb_tree_dealloc(struct rb_tree *self, rb_tree_node_f node_cb) +void rb_tree_dealloc(struct rb_tree *self, rb_tree_node_f node_cb) { if (self) { if (node_cb) { struct rb_node *node = self->root; struct rb_node *save = NULL; - + // Rotate away the left links so that // we can treat this like the destruction // of a linked list @@ -145,7 +145,7 @@ void rb_tree_dealloc(struct rb_tree *self, rb_tree_node_f node_cb) node_cb(self, node); node = NULL; } else { - + // Rotate away the left link and check again save = node->link[0]; node->link[0] = save->link[1]; @@ -158,16 +158,16 @@ void rb_tree_dealloc(struct rb_tree *self, rb_tree_node_f node_cb) } } -int rb_tree_test(struct rb_tree *self, struct rb_node *root) +int rb_tree_test(struct rb_tree *self, struct rb_node *root) { int lh, rh; - + if (NULL == root) { return 1; } else { struct rb_node *ln = root->link[0]; struct rb_node *rn = root->link[1]; - + /* Consecutive red links */ if (rb_node_is_red(root)) { if (rb_node_is_red(ln) || rb_node_is_red(rn)) { @@ -175,10 +175,10 @@ int rb_tree_test(struct rb_tree *self, struct rb_node *root) return 0; } } - + lh = rb_tree_test(self, ln); rh = rb_tree_test(self, rn); - + /* Invalid binary search tree */ if ( ( ln != NULL && self->cmp(self, ln, root) >= 0 ) || ( rn != NULL && self->cmp(self, rn, root) <= 0)) @@ -186,13 +186,13 @@ int rb_tree_test(struct rb_tree *self, struct rb_node *root) puts ( "Binary tree violation" ); return 0; } - + /* Black height mismatch */ if ( lh != 0 && rh != 0 && lh != rh ) { puts ( "Black violation" ); return 0; } - + /* Only count black links */ if ( lh != 0 && rh != 0 ) return rb_node_is_red ( root ) ? lh : lh + 1; @@ -201,7 +201,7 @@ int rb_tree_test(struct rb_tree *self, struct rb_node *root) } } -void * rb_tree_find(struct rb_tree *self, void *value) +void * rb_tree_find(struct rb_tree *self, void *value) { void *result = NULL; @@ -224,14 +224,14 @@ void * rb_tree_find(struct rb_tree *self, void *value) return result; } -// Creates (malloc'ates) -int rb_tree_insert(struct rb_tree *self, void *value) +// Creates (malloc'ates) +int rb_tree_insert(struct rb_tree *self, void *value) { return rb_tree_insert_node(self, rb_node_create(value)); } // Returns 1 on success, 0 otherwise. -int rb_tree_insert_node (struct rb_tree *self, struct rb_node *node) +int rb_tree_insert_node (struct rb_tree *self, struct rb_node *node) { if (self && node) { if (self->root == NULL) { @@ -254,7 +254,7 @@ int rb_tree_insert_node (struct rb_tree *self, struct rb_node *node) // Insert node at the first null link. p->link[dir] = q = node; } else if (rb_node_is_red(q->link[0]) && rb_node_is_red(q->link[1])) { - + // Simple red violation: color flip q->red = 1; q->link[0]->red = 0; @@ -271,7 +271,7 @@ int rb_tree_insert_node (struct rb_tree *self, struct rb_node *node) t->link[dir2] = rb_node_rotate2(g, !last); } } - + // Stop working if we inserted a node. This // check also disallows duplicates in the tree if (self->cmp(self, q, node) == 0) { @@ -298,14 +298,14 @@ int rb_tree_insert_node (struct rb_tree *self, struct rb_node *node) self->root->red = 0; ++self->size; } - + return 1; } // Returns 1 if the value was removed, 0 otherwise. Optional node callback // can be provided to dealloc node and/or user data. Use rb_tree_node_dealloc // default callback to deallocate node created by rb_tree_insert(...). -int rb_tree_remove_with_cb (struct rb_tree *self, void *value, rb_tree_node_f node_cb) +int rb_tree_remove_with_cb (struct rb_tree *self, void *value, rb_tree_node_f node_cb) { if (self->root != NULL) { struct rb_node head = {0}; // False tree root @@ -318,7 +318,7 @@ int rb_tree_remove_with_cb (struct rb_tree *self, void *value, rb_tree_node_f no q = &head; g = p = NULL; q->link[1] = self->root; - + // Search and push a red node down // to fix red violations as we go while (q->link[dir] != NULL) { @@ -328,7 +328,7 @@ int rb_tree_remove_with_cb (struct rb_tree *self, void *value, rb_tree_node_f no g = p, p = q; q = q->link[dir]; dir = self->cmp(self, q, &node) < 0; - + // Save the node with matching value and keep // going; we'll do removal tasks at the end if (self->cmp(self, q, &node) == 0) { @@ -355,7 +355,7 @@ int rb_tree_remove_with_cb (struct rb_tree *self, void *value, rb_tree_node_f no } else if (rb_node_is_red(s->link[!last])) { g->link[dir2] = rb_node_rotate(p, last); } - + // Ensure correct coloring q->red = g->link[dir2]->red = 1; g->link[dir2]->link[0]->red = 0; @@ -371,9 +371,9 @@ int rb_tree_remove_with_cb (struct rb_tree *self, void *value, rb_tree_node_f no void *tmp = f->value; f->value = q->value; q->value = tmp; - + p->link[p->link[1] == q] = q->link[q->link[0] == NULL]; - + if (node_cb) { node_cb(self, q); } @@ -393,7 +393,7 @@ int rb_tree_remove_with_cb (struct rb_tree *self, void *value, rb_tree_node_f no return 1; } -int rb_tree_remove (struct rb_tree *self, void *value) +int rb_tree_remove (struct rb_tree *self, void *value) { int result = 0; @@ -403,7 +403,7 @@ int rb_tree_remove (struct rb_tree *self, void *value) return result; } -size_t rb_tree_size (struct rb_tree *self) +size_t rb_tree_size (struct rb_tree *self) { size_t result = 0; @@ -414,12 +414,12 @@ size_t rb_tree_size (struct rb_tree *self) } // rb_iter -struct rb_iter * rb_iter_alloc () +struct rb_iter * rb_iter_alloc () { return pvPortMalloc(sizeof(struct rb_iter)); } -struct rb_iter * rb_iter_init (struct rb_iter *self) +struct rb_iter * rb_iter_init (struct rb_iter *self) { if (self) { self->tree = NULL; @@ -429,12 +429,12 @@ struct rb_iter * rb_iter_init (struct rb_iter *self) return self; } -struct rb_iter * rb_iter_create () +struct rb_iter * rb_iter_create () { return rb_iter_init(rb_iter_alloc()); } -void rb_iter_dealloc (struct rb_iter *self) +void rb_iter_dealloc (struct rb_iter *self) { if (self) { vPortFree(self); @@ -443,7 +443,7 @@ void rb_iter_dealloc (struct rb_iter *self) // Internal function, init traversal object, dir determines whether // to begin traversal at the smallest or largest valued node. -static void * rb_iter_start (struct rb_iter *self, struct rb_tree *tree, int dir) +static void * rb_iter_start (struct rb_iter *self, struct rb_tree *tree, int dir) { void *result = NULL; @@ -466,7 +466,7 @@ static void * rb_iter_start (struct rb_iter *self, struct rb_tree *tree, int dir } // Traverse a red black tree in the user-specified direction (0 asc, 1 desc) -static void * rb_iter_move(struct rb_iter *self, int dir) +static void * rb_iter_move(struct rb_iter *self, int dir) { if (self->node->link[dir] != NULL) { // Continue down this branch @@ -491,12 +491,12 @@ static void * rb_iter_move(struct rb_iter *self, int dir) return self->node == NULL ? NULL : self->node->value; } -void *rb_iter_first(struct rb_iter *self, struct rb_tree *tree) +void *rb_iter_first(struct rb_iter *self, struct rb_tree *tree) { return rb_iter_start(self, tree, 0); } -void * rb_iter_last(struct rb_iter *self, struct rb_tree *tree) +void * rb_iter_last(struct rb_iter *self, struct rb_tree *tree) { return rb_iter_start(self, tree, 1); } diff --git a/components/utils/src/utils_string.c b/components/utils/src/utils_string.c index 27b39b8a..5859194e 100644 --- a/components/utils/src/utils_string.c +++ b/components/utils/src/utils_string.c @@ -33,47 +33,47 @@ #include static int params_filter(char** params,uint32_t *r) -{ - char *p ; - uint32_t result=0; - uint8_t base=0; - - p = *params; - +{ + char *p ; + uint32_t result=0; + uint8_t base=0; + + p = *params; + if((*p == '0') && ((*(p+1) == 'x') || (*(p+1) == 'X')) ){ - p = p + 2; - base = 16; - - }else{ - base = 10; - } - - while(*p){ - result *= base; - if(*p >= '0' && *p<='9') - result += *p-'0'; - else if(base==10) - return -1; - - if(base==16){ - if(*p >= 'a' && *p<='f') - result += *p-'a' + 10; - else if(*p >= 'A' && *p<='F') - result += *p-'A' + 10; - - } - p++; - } - - *r = result; - return 0; - + p = p + 2; + base = 16; + + }else{ + base = 10; + } + + while(*p){ + result *= base; + if(*p >= '0' && *p<='9') + result += *p-'0'; + else if(base==10) + return -1; + + if(base==16){ + if(*p >= 'a' && *p<='f') + result += *p-'a' + 10; + else if(*p >= 'A' && *p<='F') + result += *p-'A' + 10; + + } + p++; + } + + *r = result; + return 0; + } void get_bytearray_from_string(char** params, uint8_t *result,int array_size) { - + int i = 0; char rand[3]; @@ -87,37 +87,37 @@ void get_bytearray_from_string(char** params, uint8_t *result,int array_size) void get_uint8_from_string(char** params, uint8_t *result) { - uint32_t p = 0; - int state=0; - - state = params_filter(params,&p); - if(!state){ - *result = p & 0xff; - }else - *result = 0; + uint32_t p = 0; + int state=0; + + state = params_filter(params,&p); + if(!state){ + *result = p & 0xff; + }else + *result = 0; } void get_uint16_from_string(char** params, uint16_t *result) { - uint32_t p = 0; - int state=0; - - state = params_filter(params,&p); - if(!state){ - *result = p & 0xffff; - }else - *result = 0; + uint32_t p = 0; + int state=0; + + state = params_filter(params,&p); + if(!state){ + *result = p & 0xffff; + }else + *result = 0; } void get_uint32_from_string(char** params, uint32_t *result) { uint32_t p = 0; - int state=0; - - state = params_filter(params,&p); - if(!state){ - *result = p; - }else - *result = 0; + int state=0; + + state = params_filter(params,&p); + if(!state){ + *result = p; + }else + *result = 0; } diff --git a/components/utils/src/utils_time.c b/components/utils/src/utils_time.c index eed7e107..c587ac6b 100644 --- a/components/utils/src/utils_time.c +++ b/components/utils/src/utils_time.c @@ -38,11 +38,11 @@ int utils_time_date_from_epoch(unsigned int epoch, utils_time_date_t *date) unsigned char month_days[12]={31,28,31,30,31,30,31,31,30,31,30,31}; unsigned char week_days[7] = {4,5,6,0,1,2,3}; - date->leap_days = 0; + date->leap_days = 0; date->leap_year_ind = 0; - // Add or substract time zone here. - //epoch += 19800; //GMT +5:30 = +19800 seconds + // Add or substract time zone here. + //epoch += 19800; //GMT +5:30 = +19800 seconds date->ntp_second = epoch%60; epoch /= 60; @@ -69,9 +69,9 @@ int utils_time_date_from_epoch(unsigned int epoch, utils_time_date_t *date) if (((date->ntp_year%4==0) && (date->ntp_year%100!=0)) || (date->ntp_year%400==0)) { month_days[1]=29; //February = 29 days for leap years - date->leap_year_ind = 1; //if current year is leap, set indicator to 1 + date->leap_year_ind = 1; //if current year is leap, set indicator to 1 } else { - month_days[1]=28; //February = 28 days for non-leap years + month_days[1]=28; //February = 28 days for non-leap years } temp_days = 0; @@ -79,7 +79,7 @@ int utils_time_date_from_epoch(unsigned int epoch, utils_time_date_t *date) for (date->ntp_month = 0; date->ntp_month <= 11; date->ntp_month++) { //calculating current Month if (date->day_of_year <= temp_days) { - break; + break; } temp_days = temp_days + month_days[date->ntp_month]; } diff --git a/image_conf/flash_build.py b/image_conf/flash_build.py index e41dd88f..29c7661f 100755 --- a/image_conf/flash_build.py +++ b/image_conf/flash_build.py @@ -54,7 +54,7 @@ def bl_find_file_list(key_val, endswith): def bl_find_file(key_val, endswith): - conf_path = os.path.join(app_path, "img_conf") + conf_path = os.path.join(app_path, "img_conf") if os.path.exists(conf_path): files = os.listdir(conf_path) for f in files: @@ -87,15 +87,15 @@ class bl_efuse_boothd_gen(): crcarray = self.utils.get_crc32_bytearray(pll_cfg) bootheader_data[pll_cfg_start + pll_cfg_len - 4:pll_cfg_start + pll_cfg_len] = crcarray return bootheader_data - - + + def get_int_mask(self, pos, length): ones = "1" * 32 zeros = "0" * 32 mask = ones[0:32 - pos - length] + zeros[0:length] + ones[0:pos] return int(mask, 2) - - + + def update_data_from_cfg(self, config_keys, config_file, section): cfg = BFConfigParser() cfg.read(config_file) @@ -120,7 +120,7 @@ class bl_efuse_boothd_gen(): offset = int(config_keys.get(key)["offset"], 10) pos = int(config_keys.get(key)["pos"], 10) bitlen = int(config_keys.get(key)["bitlen"], 10) - + oldval = self.utils.bytearray_to_int(self.utils.bytearray_reverse(data[offset:offset + 4])) oldval_mask = self.utils.bytearray_to_int(self.utils.bytearray_reverse(data_mask[offset:offset + 4])) newval = (oldval & self.get_int_mask(pos, bitlen)) + (val << pos) @@ -131,8 +131,8 @@ class bl_efuse_boothd_gen(): data[offset:offset + 4] = self.utils.int_to_4bytearray_l(newval) data_mask[offset:offset + 4] = self.utils.int_to_4bytearray_l(newval_mask) return data, data_mask - - + + def bootheader_create_do(self, chipname, chiptype, config_file, section, output_file=None, if_img=False): efuse_bootheader_path = os.path.join(app_path, bin_build_out_path) try: @@ -174,7 +174,7 @@ class bl_efuse_boothd_gen(): print("bootheader_create_do fail!!") print(err) traceback.print_exc(limit=5, file=sys.stdout) - + def bootheader_create_process(self, chipname, chiptype, config_file, output_file1=None, output_file2=None, if_img=False): fp = open(config_file, 'r') data = fp.read() @@ -185,8 +185,8 @@ class bl_efuse_boothd_gen(): self.bootheader_create_do(chipname, chiptype, config_file, "BOOTHEADER_CPU0_CFG", output_file1, if_img) if "BOOTHEADER_CPU1_CFG" in data: self.bootheader_create_do(chipname, chiptype, config_file, "BOOTHEADER_CPU1_CFG", output_file2, if_img) - - + + def efuse_create_process(self, chipname, chiptype, config_file, output_file=None): efuse_file = os.path.join(app_path, bin_build_out_path, "efusedata.bin") # sub_module = __import__("efuse_cfg_keys.py", fromlist=[chiptype]) @@ -205,36 +205,36 @@ class bl_efuse_boothd_gen(): fp = open(output_file.replace(".bin", "_mask.bin"), 'wb+') fp.write(mask) fp.close() - + def efuse_boothd_create_process(self, chipname, chiptype, config_file): self.bootheader_create_process(chipname, chiptype, config_file) self.efuse_create_process(chipname, chiptype, config_file) class bl_utils(): - + #12345678->0x12,0x34,0x56,0x78 def hexstr_to_bytearray_b(self, hexstring): return bytearray.fromhex(hexstring) - - + + def hexstr_to_bytearray(self, hexstring): return bytearray.fromhex(hexstring) - - + + def hexstr_to_bytearray_l(self, hexstring): b = bytearray.fromhex(hexstring) b.reverse() return b - - + + def int_to_2bytearray_l(self, intvalue): return struct.pack("H", intvalue) - - + + def int_to_4bytearray_l(self, intvalue): src = bytearray(4) src[3] = ((intvalue >> 24) & 0xFF) @@ -242,14 +242,14 @@ class bl_utils(): src[1] = ((intvalue >> 8) & 0xFF) src[0] = ((intvalue >> 0) & 0xFF) return src - - + + def int_to_4bytearray_b(self, intvalue): val = int_to_4bytearray_l(intvalue) val.reverse() return val - - + + def bytearray_reverse(self, a): l = len(a) b = bytearray(l) @@ -258,20 +258,20 @@ class bl_utils(): b[i] = a[l - i - 1] i = i + 1 return b - - + + def bytearray_to_int(self, b): return int(binascii.hexlify(b), 16) - - + + def string_to_bytearray(self, string): return bytes(string, encoding="utf8") - - + + def bytearray_to_str(self, bytesarray): return str(bytesarray) - - + + def get_random_hexstr(self, n_bytes): hextring = "" i = 0 @@ -279,13 +279,13 @@ class bl_utils(): hextring = hextring + str(binascii.hexlify(random.randint(0, 255))) i = i + 1 return hextring - - + + def get_crc32_bytearray(self, data): crc = binascii.crc32(data) return self.int_to_4bytearray_l(crc) - - + + def copyfile(self, srcfile, dstfile): if os.path.isfile(srcfile): fpath, fname = os.path.split(dstfile) @@ -295,30 +295,30 @@ class bl_utils(): else: print("Src file not exists") sys.exit() - + def enable_udp_send_log(self, server,local_echo): global udp_send_log,udp_socket_server,upd_log_local_echo udp_send_log=True upd_log_local_echo=local_echo udp_socket_server=server - + def add_udp_client(self, tid,upd_client): udp_clinet_dict[tid]=upd_client - + def remove_udp_client(self, tid): del udp_clinet_dict[tid] - + def Update_Cfg(self, cfg, section, key, value): if cfg.has_option(section, key): cfg.set(section, key, str(value)) else: #print key," not found,adding it" cfg.set(section, key, str(value)) - - + + def get_byte_array(self, str): return str.encode("utf-8") - + #class BFConfigParser(configparser.ConfigParser): # def __init__(self, defaults=None): # configparser.ConfigParser.__init__(self, defaults=defaults) @@ -891,7 +891,7 @@ class bl_img_create_do(bl_utils): # will something like "option -a not recognized") print(err) usage() - + if img_type == "media": flash_img = 1 @@ -1028,7 +1028,7 @@ class bl_whole_img_generate(): # python bflb_img_create.py -c np -i media -s none f = self.bl_image_gen_cfg(raw_bin_name, bintype) #exe_genitor(['bflb_img_create.exe', '-c', 'np', '-i', 'media', '-s', 'none']) - img_create = bl_img_create() + img_create = bl_img_create() img_create.create_sp_media_image_file(f) def bl_fw_boot_head_gen(self, boot2, xtal, config, encrypt=False, chipname="bl60x", chiptype="bl60x", cpu_type=None): @@ -1065,13 +1065,13 @@ class bl_whole_img_generate(): create.efuse_boothd_create_process(chipname, chiptype, config) def bl_whole_flash_bin_create(self, bin_file, boot2, ro_params, pt_parcel, media, mfg, flash_opt="1M"): - + d_files = [] d_addrs = [] if pt_parcel == None: return False - + if boot2 == True: d_files.append(os.path.join(app_path, bin_build_out_path, "bootinfo_boot2.bin")) d_addrs.append("00000000") @@ -1255,7 +1255,7 @@ class bl_img_ota(): for b in file_bytes: fw_ota_bin.append(b) fw_ota_bin_header = self.bl_mfg_ota_header(fw_ota_bin, use_xz=0) - + FW_OTA_path = os.path.join(app_path, bin_build_out_path, "ota") if not os.path.exists(FW_OTA_path): os.makedirs(FW_OTA_path) diff --git a/make_scripts_riscv/project.mk b/make_scripts_riscv/project.mk index cebbb9d3..9b041798 100644 --- a/make_scripts_riscv/project.mk +++ b/make_scripts_riscv/project.mk @@ -129,7 +129,7 @@ include_path += $(filter %/$(1), $(COMPONENTS_REAL_PATH)) endef $(foreach comp,$(INCLUDE_COMPONENTS),$(eval $(call include_comps_add,$(comp)))) INCLUDE_COMPONENTS_REAL_PATH := $(include_path) -# include components +# include components COMPONENTS := $(filter $(INCLUDE_COMPONENTS), $(COMPONENTS)) COMPONENTS_REAL_PATH := $(filter $(INCLUDE_COMPONENTS_REAL_PATH), $(COMPONENTS_REAL_PATH)) endif @@ -214,7 +214,7 @@ BL_CHIP_NAME := ${CONFIG_CHIP_NAME} # Set default LDFLAGS # -nostdlib -# --specs=nosys.specs +# --specs=nosys.specs EXTRA_LDFLAGS ?= -Wl,--cref -nostartfiles ifeq ($(CONFIG_ZIGBEE), 1) EXTRA_LDFLAGS += --specs=nosys.specs @@ -242,7 +242,7 @@ LDFLAGS ?= $(E21_CPU_LDFLAGS) \ # before including project.mk. Default flags will be added before the ones provided in application Makefile. # CPPFLAGS used by C preprocessor -# If any flags are defined in application Makefile, add them at the end. +# If any flags are defined in application Makefile, add them at the end. CPPFLAGS ?= ifeq ($(CONFIG_ENABLE_ACP),1) CPPFLAGS += -DCONF_USER_ENABLE_ACP @@ -291,7 +291,7 @@ COMMON_FLAGS_M4_EXT := \ -ffreestanding \ -fno-strict-aliasing - + COMMON_FLAGS += $(COMMON_FLAGS_M4_EXT) ifdef CONFIG_STACK_CHECK_NORM @@ -430,7 +430,7 @@ all_binaries: $(APP_BIN) $(APP_BIN): $(APP_ELF) @echo "Generating BIN File to $@" ifeq ($(CONFIG_ENABLE_ACP),1) - $(OBJCOPY) -S -O binary -R .rom.cpu1 $< $(@:.bin=.cpu0.bin) + $(OBJCOPY) -S -O binary -R .rom.cpu1 $< $(@:.bin=.cpu0.bin) $(OBJCOPY) -S -O binary -j .rom.cpu1 $< $(@:.bin=.cpu1.bin) cp $(@:.bin=.cpu0.bin) $(@:.bin=.acp.bin) dd if=$(@:.bin=.cpu1.bin) of=$(@:.bin=.acp.bin) bs=512 seek=2 conv=notrunc @@ -438,23 +438,23 @@ ifeq ($(CONFIG_ENABLE_ACP),1) else ifeq ($(CONFIG_LINK_ROM),1) $(OBJCOPY) -S -O binary -R .romdata -R .rom $< $@ - $(OBJCOPY) -S -O binary -j .rom $< $(@:.bin=.rom.bin) - $(OBJCOPY) -S -O binary -j .romdata $< $(@:.bin=.romdata.bin) - $(OBJCOPY) -S -O binary -R .romdata -R .rom $< $(@:.bin=.flash.bin) + $(OBJCOPY) -S -O binary -j .rom $< $(@:.bin=.rom.bin) + $(OBJCOPY) -S -O binary -j .romdata $< $(@:.bin=.romdata.bin) + $(OBJCOPY) -S -O binary -R .romdata -R .rom $< $(@:.bin=.flash.bin) else ifeq ($(CONFIG_GEN_ROM),1) $(OBJCOPY) -S -O binary -R .bleromro -R .bleromrw -R .rtosromro -R .rtosromrw $< $@ - $(OBJCOPY) -S -O binary -j .bleromro $< $(@:.bin=.bleromro.bin) - $(OBJCOPY) -S -O binary -j .bleromrw $< $(@:.bin=.bleromrw.bin) - $(OBJCOPY) -S -O binary -j .rtosromro $< $(@:.bin=.rtosromro.bin) - $(OBJCOPY) -S -O binary -j .rtosromrw $< $(@:.bin=.rtosromrw.bin) - $(OBJCOPY) -S -O binary -R .bleromro -R .bleromrw -R .rtosromro -R .rtosromrw $< $(@:.bin=.flash.bin) + $(OBJCOPY) -S -O binary -j .bleromro $< $(@:.bin=.bleromro.bin) + $(OBJCOPY) -S -O binary -j .bleromrw $< $(@:.bin=.bleromrw.bin) + $(OBJCOPY) -S -O binary -j .rtosromro $< $(@:.bin=.rtosromro.bin) + $(OBJCOPY) -S -O binary -j .rtosromrw $< $(@:.bin=.rtosromrw.bin) + $(OBJCOPY) -S -O binary -R .bleromro -R .bleromrw -R .rtosromro -R .rtosromrw $< $(@:.bin=.flash.bin) else $(OBJCOPY) -S -O binary $< $@ endif endif endif - + $(BUILD_DIR_BASE): mkdir -p $(BUILD_DIR_BASE) @@ -532,7 +532,7 @@ list-components: $(info $(COMPONENTS)) $(info $(call dequote,$(SEPARATOR))) $(info EXCLUDE_COMPONENTS (list of excluded names)) - $(info $(if $(EXCLUDE_COMPONENTS),$(EXCLUDE_COMPONENTS),(none provided))) + $(info $(if $(EXCLUDE_COMPONENTS),$(EXCLUDE_COMPONENTS),(none provided))) $(info $(call dequote,$(SEPARATOR))) $(info COMPONENT_PATHS (paths to all components):) $(foreach cp,$(COMPONENT_PATHS),$(info $(cp)))