• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Misc useful os-independent macros and functions.
3  *
4  * Copyright (C) 2020, Broadcom.
5  *
6  *      Unless you and Broadcom execute a separate written software license
7  * agreement governing use of this software, this software is licensed to you
8  * under the terms of the GNU General Public License version 2 (the "GPL"),
9  * available at http://www.broadcom.com/licenses/GPLv2.php, with the
10  * following added to such license:
11  *
12  *      As a special exception, the copyright holders of this software give you
13  * permission to link this software with independent modules, and to copy and
14  * distribute the resulting executable under terms of your choice, provided that
15  * you also meet, for each linked independent module, the terms and conditions of
16  * the license of that module.  An independent module is a module which is not
17  * derived from this software.  The special exception does not apply to any
18  * modifications of the software.
19  *
20  *
21  * <<Broadcom-WL-IPTag/Dual:>>
22  */
23 
24 #ifndef	_bcmutils_h_
25 #define	_bcmutils_h_
26 
27 #include <bcmtlv.h>
28 
29 /* For now, protect the bcmerror.h */
30 #ifdef BCMUTILS_ERR_CODES
31 #include <bcmerror.h>
32 #endif
33 
34 #ifdef __cplusplus
35 extern "C" {
36 #endif
37 
38 #define bcm_strncpy_s(dst, noOfElements, src, count)    strncpy((dst), (src), (count))
39 #ifdef FREEBSD
40 #define bcm_strncat_s(dst, noOfElements, src, count)    strcat((dst), (src))
41 #else
42 #define bcm_strncat_s(dst, noOfElements, src, count)    strncat((dst), (src), (count))
43 #endif /* FREEBSD */
44 #define bcm_snprintf_s snprintf
45 #define bcm_sprintf_s snprintf
46 
47 /*
48  * #define bcm_strcpy_s(dst, count, src)            strncpy((dst), (src), (count))
49  * Use bcm_strcpy_s instead as it is a safer option
50  * bcm_strcat_s: Use bcm_strncat_s as a safer option
51  *
52  */
53 
54 #define BCM_BIT(x)		(1u << (x))
55 /* useful to count number of set bit in x */
56 #define BCM_CLR_FISRT_BIT(x) ((x - 1) & x)
57 /* first bit set in x. Useful to iterate through a mask */
58 #define BCM_FIRST_BIT(x) (BCM_CLR_FISRT_BIT(x)^(x))
59 
60 /* Macro to iterate through the set bits in mask.
61  * NOTE: the argument "mask" will be cleared after
62  * the iteration.
63  */
64 
65 #define FOREACH_BIT(c, mask)\
66 	for (c = BCM_FIRST_BIT(mask); mask != 0; \
67 		 mask = BCM_CLR_FISRT_BIT(mask), c = BCM_FIRST_BIT(mask))
68 
69 /* ctype replacement */
70 #define _BCM_U	0x01	/* upper */
71 #define _BCM_L	0x02	/* lower */
72 #define _BCM_D	0x04	/* digit */
73 #define _BCM_C	0x08	/* cntrl */
74 #define _BCM_P	0x10	/* punct */
75 #define _BCM_S	0x20	/* white space (space/lf/tab) */
76 #define _BCM_X	0x40	/* hex digit */
77 #define _BCM_SP	0x80	/* hard space (0x20) */
78 
79 extern const unsigned char bcm_ctype[256];
80 #define bcm_ismask(x)	(bcm_ctype[(unsigned char)(x)])
81 
82 #define bcm_isalnum(c)	((bcm_ismask(c)&(_BCM_U|_BCM_L|_BCM_D)) != 0)
83 #define bcm_isalpha(c)	((bcm_ismask(c)&(_BCM_U|_BCM_L)) != 0)
84 #define bcm_iscntrl(c)	((bcm_ismask(c)&(_BCM_C)) != 0)
85 #define bcm_isdigit(c)	((bcm_ismask(c)&(_BCM_D)) != 0)
86 #define bcm_isgraph(c)	((bcm_ismask(c)&(_BCM_P|_BCM_U|_BCM_L|_BCM_D)) != 0)
87 #define bcm_islower(c)	((bcm_ismask(c)&(_BCM_L)) != 0)
88 #define bcm_isprint(c)	((bcm_ismask(c)&(_BCM_P|_BCM_U|_BCM_L|_BCM_D|_BCM_SP)) != 0)
89 #define bcm_ispunct(c)	((bcm_ismask(c)&(_BCM_P)) != 0)
90 #define bcm_isspace(c)	((bcm_ismask(c)&(_BCM_S)) != 0)
91 #define bcm_isupper(c)	((bcm_ismask(c)&(_BCM_U)) != 0)
92 #define bcm_isxdigit(c)	((bcm_ismask(c)&(_BCM_D|_BCM_X)) != 0)
93 #define bcm_tolower(c)	(bcm_isupper((c)) ? ((c) + 'a' - 'A') : (c))
94 #define bcm_toupper(c)	(bcm_islower((c)) ? ((c) + 'A' - 'a') : (c))
95 
96 #define CIRCULAR_ARRAY_FULL(rd_idx, wr_idx, max) ((wr_idx + 1)%max == rd_idx)
97 
98 #define KB(bytes)	(((bytes) + 1023) / 1024)
99 
100 /* Buffer structure for collecting string-formatted data
101 * using bcm_bprintf() API.
102 * Use bcm_binit() to initialize before use
103 */
104 
105 struct bcmstrbuf {
106 	char *buf;	/* pointer to current position in origbuf */
107 	unsigned int size;	/* current (residual) size in bytes */
108 	char *origbuf;	/* unmodified pointer to orignal buffer */
109 	unsigned int origsize;	/* unmodified orignal buffer size in bytes */
110 };
111 
112 #define BCMSTRBUF_LEN(b)	(b->size)
113 #define BCMSTRBUF_BUF(b)	(b->buf)
114 
115 struct ether_addr;
116 extern char *bcm_ether_ntoa(const struct ether_addr *ea, char *buf);
117 extern int bcm_ether_atoe(const char *p, struct ether_addr *ea);
118 
119 /* ** driver-only section ** */
120 #ifdef BCMDRIVER
121 
122 #include <osl.h>
123 #include <hnd_pktq.h>
124 #include <hnd_pktpool.h>
125 
126 #define GPIO_PIN_NOTDEFINED	0x20	/* Pin not defined */
127 
128 /*
129  * Spin at most 'us' microseconds while 'exp' is true.
130  * Caller should explicitly test 'exp' when this completes
131  * and take appropriate error action if 'exp' is still true.
132  */
133 #ifndef SPINWAIT_POLL_PERIOD
134 #define SPINWAIT_POLL_PERIOD	10U
135 #endif
136 
137 #ifdef BCMFUZZ
138 /* fake spinwait for fuzzing */
139 #define SPINWAIT(exp, us) { \
140 	uint countdown = (exp) != 0 ? 1 : 0; \
141 	while (countdown > 0) { \
142 		countdown--; \
143 	} \
144 }
145 
146 #elif defined(PHY_REG_TRACE_FRAMEWORK)
147 #include <phy_utils_log_api.h>
148 #define SPINWAIT(exp, us) { \
149 	uint countdown = (us) + (SPINWAIT_POLL_PERIOD - 1U); \
150 	phy_utils_log_spinwait_start(); \
151 	while (((exp) != 0) && (uint)(countdown >= SPINWAIT_POLL_PERIOD)) { \
152 		OSL_DELAY(SPINWAIT_POLL_PERIOD); \
153 		countdown -= SPINWAIT_POLL_PERIOD; \
154 	} \
155 	phy_utils_log_spinwait_end(us, countdown); \
156 }
157 
158 #else
159 #define SPINWAIT(exp, us) { \
160 	uint countdown = (us) + (SPINWAIT_POLL_PERIOD - 1U); \
161 	while (((exp) != 0) && (uint)(countdown >= SPINWAIT_POLL_PERIOD)) { \
162 		OSL_DELAY(SPINWAIT_POLL_PERIOD); \
163 		countdown -= SPINWAIT_POLL_PERIOD; \
164 	} \
165 }
166 #endif /* BCMFUZZ */
167 
168 /* forward definition of ether_addr structure used by some function prototypes */
169 
170 extern int ether_isbcast(const void *ea);
171 extern int ether_isnulladdr(const void *ea);
172 
173 #define UP_TABLE_MAX	((IPV4_TOS_DSCP_MASK >> IPV4_TOS_DSCP_SHIFT) + 1)	/* 64 max */
174 #define CORE_SLAVE_PORT_0	0
175 #define CORE_SLAVE_PORT_1	1
176 #define CORE_BASE_ADDR_0	0
177 #define CORE_BASE_ADDR_1	1
178 
179 #ifdef DONGLEBUILD
180 /* TRIM Tail bytes from lfrag */
181 extern void pktfrag_trim_tailbytes(osl_t * osh, void* p, uint16 len, uint8 type);
182 #define PKTFRAG_TRIM_TAILBYTES(osh, p, len, type)	pktfrag_trim_tailbytes(osh, p, len, type)
183 #else
184 #define PKTFRAG_TRIM_TAILBYTES(osh, p, len, type)	PKTSETLEN(osh, p, PKTLEN(osh, p) - len)
185 #endif /* DONGLEBUILD */
186 
187 /* externs */
188 /* packet */
189 extern uint pktcopy(osl_t *osh, void *p, uint offset, uint len, uchar *buf);
190 extern uint pktfrombuf(osl_t *osh, void *p, uint offset, uint len, uchar *buf);
191 extern uint pkttotlen(osl_t *osh, void *p);
192 extern uint pkttotcnt(osl_t *osh, void *p);
193 extern void *pktlast(osl_t *osh, void *p);
194 extern uint pktsegcnt(osl_t *osh, void *p);
195 extern uint8 *pktdataoffset(osl_t *osh, void *p,  uint offset);
196 extern void *pktoffset(osl_t *osh, void *p,  uint offset);
197 /* Add to adjust 802.1x priority */
198 extern void pktset8021xprio(void *pkt, int prio);
199 
200 #ifdef WLCSO
201 extern uint pkttotlen_no_sfhtoe_hdr(osl_t *osh, void *p, uint toe_hdr_len);
202 #else
203 #define pkttotlen_no_sfhtoe_hdr(osh, p, hdrlen)	pkttotlen(osh, p)
204 #endif /* WLCSO */
205 
206 /* Get priority from a packet and pass it back in scb (or equiv) */
207 #define	PKTPRIO_VDSCP	0x100u		/* DSCP prio found after VLAN tag */
208 #define	PKTPRIO_VLAN	0x200u		/* VLAN prio found */
209 #define	PKTPRIO_UPD	0x400u		/* DSCP used to update VLAN prio */
210 #define	PKTPRIO_DSCP	0x800u		/* DSCP prio found */
211 
212 /* DSCP type definitions (RFC4594) */
213 /* AF1x: High-Throughput Data (RFC2597) */
214 #define DSCP_AF11	0x0Au
215 #define DSCP_AF12	0x0Cu
216 #define DSCP_AF13	0x0Eu
217 /* AF2x: Low-Latency Data (RFC2597) */
218 #define DSCP_AF21	0x12u
219 #define DSCP_AF22	0x14u
220 #define DSCP_AF23	0x16u
221 /* CS2: OAM (RFC2474) */
222 #define DSCP_CS2	0x10u
223 /* AF3x: Multimedia Streaming (RFC2597) */
224 #define DSCP_AF31	0x1Au
225 #define DSCP_AF32	0x1Cu
226 #define DSCP_AF33	0x1Eu
227 /* CS3: Broadcast Video (RFC2474) */
228 #define DSCP_CS3	0x18u
229 /* VA: VOCIE-ADMIT (RFC5865) */
230 #define DSCP_VA		0x2Cu
231 /* EF: Telephony (RFC3246) */
232 #define DSCP_EF		0x2Eu
233 /* CS6: Network Control (RFC2474) */
234 #define DSCP_CS6	0x30u
235 /* CS7: Network Control (RFC2474) */
236 #define DSCP_CS7	0x38u
237 
238 extern uint pktsetprio(void *pkt, bool update_vtag);
239 extern uint pktsetprio_qms(void *pkt, uint8* up_table, bool update_vtag);
240 extern bool pktgetdscp(uint8 *pktdata, uint pktlen, uint8 *dscp);
241 
242 /* ethernet address */
243 extern uint64 bcm_ether_ntou64(const struct ether_addr *ea) BCMCONSTFN;
244 extern int bcm_addrmask_set(int enable);
245 extern int bcm_addrmask_get(int *val);
246 
247 /* ip address */
248 struct ipv4_addr;
249 extern char *bcm_ip_ntoa(struct ipv4_addr *ia, char *buf);
250 extern char *bcm_ipv6_ntoa(void *ipv6, char *buf);
251 extern int bcm_atoipv4(const char *p, struct ipv4_addr *ip);
252 
253 /* delay */
254 extern void bcm_mdelay(uint ms);
255 /* variable access */
256 #if defined(BCM_RECLAIM)
257 extern bool _nvram_reclaim_enb;
258 #define NVRAM_RECLAIM_ENAB() (_nvram_reclaim_enb)
259 #ifdef BCMDBG
260 #define NVRAM_RECLAIM_CHECK(name)							\
261 	if (NVRAM_RECLAIM_ENAB() && (bcm_attach_part_reclaimed == TRUE)) {		\
262 		printf("NVRAM already reclaimed, %s\n", (name));			\
263 		GCC_DIAGNOSTIC_PUSH_SUPPRESS_NULL_DEREF();				\
264 		*(char*) 0 = 0; /* TRAP */						\
265 		GCC_DIAGNOSTIC_POP();							\
266 		return NULL;								\
267 	}
268 #else /* BCMDBG */
269 #define NVRAM_RECLAIM_CHECK(name)							\
270 	if (NVRAM_RECLAIM_ENAB() && (bcm_attach_part_reclaimed == TRUE)) {		\
271 		GCC_DIAGNOSTIC_PUSH_SUPPRESS_NULL_DEREF();				\
272 		*(char*) 0 = 0; /* TRAP */						\
273 		GCC_DIAGNOSTIC_POP();							\
274 		return NULL;								\
275 	}
276 #endif /* BCMDBG */
277 #else /* BCM_RECLAIM */
278 #define NVRAM_RECLAIM_CHECK(name)
279 #endif /* BCM_RECLAIM */
280 
281 #ifdef WL_FWSIGN
282 #define getvar(vars, name)			(NULL)
283 #define getintvar(vars, name)			(0)
284 #define getintvararray(vars, name, index)	(0)
285 #define getintvararraysize(vars, name)		(0)
286 #else /* WL_FWSIGN */
287 extern char *getvar(char *vars, const char *name);
288 extern int getintvar(char *vars, const char *name);
289 extern int getintvararray(char *vars, const char *name, int index);
290 extern int getintvararraysize(char *vars, const char *name);
291 #endif /* WL_FWSIGN */
292 
293 /* Read an array of values from a possibly slice-specific nvram string */
294 extern int get_uint8_vararray_slicespecific(osl_t *osh, char *vars, char *vars_table_accessor,
295 	const char* name, uint8* dest_array, uint dest_size);
296 extern int get_int16_vararray_slicespecific(osl_t *osh, char *vars, char *vars_table_accessor,
297 	const char* name, int16* dest_array, uint dest_size);
298 /* Prepend a slice-specific accessor to an nvram string name */
299 extern uint get_slicespecific_var_name(osl_t *osh, char *vars_table_accessor,
300 	const char *name, char **name_out);
301 
302 extern uint getgpiopin(char *vars, char *pin_name, uint def_pin);
303 #ifdef BCMDBG
304 extern void prpkt(const char *msg, osl_t *osh, void *p0);
305 #endif /* BCMDBG */
306 #ifdef BCMPERFSTATS
307 extern void bcm_perf_enable(void);
308 extern void bcmstats(char *fmt);
309 extern void bcmlog(char *fmt, uint a1, uint a2);
310 extern void bcmdumplog(char *buf, int size);
311 extern int bcmdumplogent(char *buf, uint idx);
312 #else
313 #define bcm_perf_enable()
314 #define bcmstats(fmt)
315 #define	bcmlog(fmt, a1, a2)
316 #define	bcmdumplog(buf, size)	*buf = '\0'
317 #define	bcmdumplogent(buf, idx)	-1
318 #endif /* BCMPERFSTATS */
319 
320 #define TSF_TICKS_PER_MS	1000
321 #define TS_ENTER		0xdeadbeef	/* Timestamp profiling enter */
322 #define TS_EXIT			0xbeefcafe	/* Timestamp profiling exit */
323 
324 #if defined(BCMTSTAMPEDLOGS)
325 /* Store a TSF timestamp and a log line in the log buffer */
326 extern void bcmtslog(uint32 tstamp, const char *fmt, uint a1, uint a2);
327 /* Print out the log buffer with timestamps */
328 extern void bcmprinttslogs(void);
329 /* Print out a microsecond timestamp as "sec.ms.us " */
330 extern void bcmprinttstamp(uint32 us);
331 /* Dump to buffer a microsecond timestamp as "sec.ms.us " */
332 extern void bcmdumptslog(struct bcmstrbuf *b);
333 #else
334 #define bcmtslog(tstamp, fmt, a1, a2)
335 #define bcmprinttslogs()
336 #define bcmprinttstamp(us)
337 #define bcmdumptslog(b)
338 #endif /* BCMTSTAMPEDLOGS */
339 
340 bool bcm_match_buffers(const uint8 *b1, uint b1_len, const uint8 *b2, uint b2_len);
341 
342 /* Support for sharing code across in-driver iovar implementations.
343  * The intent is that a driver use this structure to map iovar names
344  * to its (private) iovar identifiers, and the lookup function to
345  * find the entry.  Macros are provided to map ids and get/set actions
346  * into a single number space for a switch statement.
347  */
348 
349 /* iovar structure */
350 typedef struct bcm_iovar {
351 	const char *name;	/* name for lookup and display */
352 	uint16 varid;		/* id for switch */
353 	uint16 flags;		/* driver-specific flag bits */
354 	uint8 flags2;		 /* driver-specific flag bits */
355 	uint8 type;		/* base type of argument */
356 	uint16 minlen;		/* min length for buffer vars */
357 } bcm_iovar_t;
358 
359 /* varid definitions are per-driver, may use these get/set bits */
360 
361 /* IOVar action bits for id mapping */
362 #define IOV_GET 0 /* Get an iovar */
363 #define IOV_SET 1 /* Set an iovar */
364 
365 /* Varid to actionid mapping */
366 #define IOV_GVAL(id)		((id) * 2)
367 #define IOV_SVAL(id)		((id) * 2 + IOV_SET)
368 #define IOV_ISSET(actionid)	((actionid & IOV_SET) == IOV_SET)
369 #define IOV_ID(actionid)	(actionid >> 1)
370 
371 /* flags are per-driver based on driver attributes */
372 
373 extern const bcm_iovar_t *bcm_iovar_lookup(const bcm_iovar_t *table, const char *name);
374 extern int bcm_iovar_lencheck(const bcm_iovar_t *table, void *arg, uint len, bool set);
375 
376 /* ioctl structure */
377 typedef struct wlc_ioctl_cmd {
378 	uint16 cmd;			/**< IOCTL command */
379 	uint16 flags;			/**< IOCTL command flags */
380 	uint16 min_len;			/**< IOCTL command minimum argument len (in bytes) */
381 } wlc_ioctl_cmd_t;
382 
383 #if defined(WLTINYDUMP) || defined(BCMDBG) || defined(WLMSG_INFORM) || \
384 	defined(WLMSG_ASSOC) || defined(WLMSG_PRPKT) || defined(WLMSG_WSEC)
385 extern int bcm_format_ssid(char* buf, const uchar ssid[], uint ssid_len);
386 #endif /* WLTINYDUMP || BCMDBG || WLMSG_INFORM || WLMSG_ASSOC || WLMSG_PRPKT */
387 #endif	/* BCMDRIVER */
388 
389 /* string */
390 extern int bcm_atoi(const char *s);
391 extern ulong bcm_strtoul(const char *cp, char **endp, uint base);
392 extern uint64 bcm_strtoull(const char *cp, char **endp, uint base);
393 extern char *bcmstrstr(const char *haystack, const char *needle);
394 extern char *bcmstrnstr(const char *s, uint s_len, const char *substr, uint substr_len);
395 extern char *bcmstrcat(char *dest, const char *src);
396 extern char *bcmstrncat(char *dest, const char *src, uint size);
397 extern ulong wchar2ascii(char *abuf, ushort *wbuf, ushort wbuflen, ulong abuflen);
398 char* bcmstrtok(char **string, const char *delimiters, char *tokdelim);
399 int bcmstricmp(const char *s1, const char *s2);
400 int bcmstrnicmp(const char* s1, const char* s2, int cnt);
401 uint16 bcmhex2bin(const uint8* hex, uint hex_len, uint8 *buf, uint buf_len);
402 
403 /* Base type definitions */
404 #define IOVT_VOID	0	/* no value (implictly set only) */
405 #define IOVT_BOOL	1	/* any value ok (zero/nonzero) */
406 #define IOVT_INT8	2	/* integer values are range-checked */
407 #define IOVT_UINT8	3	/* unsigned int 8 bits */
408 #define IOVT_INT16	4	/* int 16 bits */
409 #define IOVT_UINT16	5	/* unsigned int 16 bits */
410 #define IOVT_INT32	6	/* int 32 bits */
411 #define IOVT_UINT32	7	/* unsigned int 32 bits */
412 #define IOVT_BUFFER	8	/* buffer is size-checked as per minlen */
413 #define BCM_IOVT_VALID(type) (((unsigned int)(type)) <= IOVT_BUFFER)
414 
415 /* Initializer for IOV type strings */
416 #define BCM_IOV_TYPE_INIT { \
417 	"void", \
418 	"bool", \
419 	"int8", \
420 	"uint8", \
421 	"int16", \
422 	"uint16", \
423 	"int32", \
424 	"uint32", \
425 	"buffer", \
426 	"" }
427 
428 #define BCM_IOVT_IS_INT(type) (\
429 	(type == IOVT_BOOL) || \
430 	(type == IOVT_INT8) || \
431 	(type == IOVT_UINT8) || \
432 	(type == IOVT_INT16) || \
433 	(type == IOVT_UINT16) || \
434 	(type == IOVT_INT32) || \
435 	(type == IOVT_UINT32))
436 
437 /* ** driver/apps-shared section ** */
438 
439 #define BCME_STRLEN             64      /* Max string length for BCM errors */
440 #define VALID_BCMERROR(e)       valid_bcmerror(e)
441 
442 #ifdef DBG_BUS
443 /** tracks non typical execution paths, use gdb with arm sim + firmware dump to read counters */
444 #define DBG_BUS_INC(s, cnt) ((s)->dbg_bus->cnt++)
445 #else
446 #define DBG_BUS_INC(s, cnt)
447 #endif /* DBG_BUS */
448 
449 /* BCMUTILS_ERR_CODES is defined to use the error codes from bcmerror.h
450  * otherwise use from this file.
451  */
452 #ifndef BCMUTILS_ERR_CODES
453 
454 /*
455  * error codes could be added but the defined ones shouldn't be changed/deleted
456  * these error codes are exposed to the user code
457  * when ever a new error code is added to this list
458  * please update errorstring table with the related error string and
459  * update osl files with os specific errorcode map
460 */
461 
462 #define BCME_OK				0	/* Success */
463 #define BCME_ERROR			-1	/* Error generic */
464 #define BCME_BADARG			-2	/* Bad Argument */
465 #define BCME_BADOPTION			-3	/* Bad option */
466 #define BCME_NOTUP			-4	/* Not up */
467 #define BCME_NOTDOWN			-5	/* Not down */
468 #define BCME_NOTAP			-6	/* Not AP */
469 #define BCME_NOTSTA			-7	/* Not STA  */
470 #define BCME_BADKEYIDX			-8	/* BAD Key Index */
471 #define BCME_RADIOOFF			-9	/* Radio Off */
472 #define BCME_NOTBANDLOCKED		-10	/* Not  band locked */
473 #define BCME_NOCLK			-11	/* No Clock */
474 #define BCME_BADRATESET			-12	/* BAD Rate valueset */
475 #define BCME_BADBAND			-13	/* BAD Band */
476 #define BCME_BUFTOOSHORT		-14	/* Buffer too short */
477 #define BCME_BUFTOOLONG			-15	/* Buffer too long */
478 #define BCME_BUSY			-16	/* Busy */
479 #define BCME_NOTASSOCIATED		-17	/* Not Associated */
480 #define BCME_BADSSIDLEN			-18	/* Bad SSID len */
481 #define BCME_OUTOFRANGECHAN		-19	/* Out of Range Channel */
482 #define BCME_BADCHAN			-20	/* Bad Channel */
483 #define BCME_BADADDR			-21	/* Bad Address */
484 #define BCME_NORESOURCE			-22	/* Not Enough Resources */
485 #define BCME_UNSUPPORTED		-23	/* Unsupported */
486 #define BCME_BADLEN			-24	/* Bad length */
487 #define BCME_NOTREADY			-25	/* Not Ready */
488 #define BCME_EPERM			-26	/* Not Permitted */
489 #define BCME_NOMEM			-27	/* No Memory */
490 #define BCME_ASSOCIATED			-28	/* Associated */
491 #define BCME_RANGE			-29	/* Not In Range */
492 #define BCME_NOTFOUND			-30	/* Not Found */
493 #define BCME_WME_NOT_ENABLED		-31	/* WME Not Enabled */
494 #define BCME_TSPEC_NOTFOUND		-32	/* TSPEC Not Found */
495 #define BCME_ACM_NOTSUPPORTED		-33	/* ACM Not Supported */
496 #define BCME_NOT_WME_ASSOCIATION	-34	/* Not WME Association */
497 #define BCME_SDIO_ERROR			-35	/* SDIO Bus Error */
498 #define BCME_DONGLE_DOWN		-36	/* Dongle Not Accessible */
499 #define BCME_VERSION			-37	/* Incorrect version */
500 #define BCME_TXFAIL			-38	/* TX failure */
501 #define BCME_RXFAIL			-39	/* RX failure */
502 #define BCME_NODEVICE			-40	/* Device not present */
503 #define BCME_NMODE_DISABLED		-41	/* NMODE disabled */
504 #define BCME_MSCH_DUP_REG		-42	/* Duplicate slot registration */
505 #define BCME_SCANREJECT			-43	/* reject scan request */
506 #define BCME_USAGE_ERROR		-44	/* WLCMD usage error */
507 #define BCME_IOCTL_ERROR		-45	/* WLCMD ioctl error */
508 #define BCME_SERIAL_PORT_ERR		-46	/* RWL serial port error */
509 #define BCME_DISABLED			-47	/* Disabled in this build */
510 #define BCME_DECERR			-48	/* Decrypt error */
511 #define BCME_ENCERR			-49	/* Encrypt error */
512 #define BCME_MICERR			-50	/* Integrity/MIC error */
513 #define BCME_REPLAY			-51	/* Replay */
514 #define BCME_IE_NOTFOUND		-52	/* IE not found */
515 #define BCME_DATA_NOTFOUND		-53	/* Complete data not found in buffer */
516 #define BCME_NOT_GC			-54	/* expecting a group client */
517 #define BCME_PRS_REQ_FAILED		-55	/* GC presence req failed to sent */
518 #define BCME_NO_P2P_SE			-56	/* Could not find P2P-Subelement */
519 #define BCME_NOA_PND			-57	/* NoA pending, CB shuld be NULL */
520 #define BCME_FRAG_Q_FAILED		-58	/* queueing 80211 frag failedi */
521 #define BCME_GET_AF_FAILED		-59	/* Get p2p AF pkt failed */
522 #define BCME_MSCH_NOTREADY		-60	/* scheduler not ready */
523 #define BCME_IOV_LAST_CMD		-61	/* last batched iov sub-command */
524 #define BCME_MINIPMU_CAL_FAIL		-62	/* MiniPMU cal failed */
525 #define BCME_RCAL_FAIL			-63	/* Rcal failed */
526 #define BCME_LPF_RCCAL_FAIL		-64	/* RCCAL failed */
527 #define BCME_DACBUF_RCCAL_FAIL		-65	/* RCCAL failed */
528 #define BCME_VCOCAL_FAIL		-66	/* VCOCAL failed */
529 #define BCME_BANDLOCKED			-67	/* interface is restricted to a band */
530 #define BCME_BAD_IE_DATA		-68	/* Recieved ie with invalid/bad data */
531 #define BCME_REG_FAILED			-69	/* Generic registration failed */
532 #define BCME_NOCHAN			-70	/* Registration with 0 chans in list */
533 #define BCME_PKTTOSS			-71	/* Pkt tossed */
534 #define BCME_DNGL_DEVRESET		-72	/* dongle re-attach during DEVRESET */
535 #define BCME_ROAM			-73	/* Roam related failures */
536 #define BCME_NO_SIG_FILE		-74	/* Signature file is missing */
537 
538 #define BCME_LAST			BCME_NO_SIG_FILE
539 
540 #define BCME_NOTENABLED BCME_DISABLED
541 
542 /* This error code is *internal* to the driver, and is not propogated to users. It should
543  * only be used by IOCTL patch handlers as an indication that it did not handle the IOCTL.
544  * (Since the error code is internal, an entry in 'BCMERRSTRINGTABLE' is not required,
545  * nor does it need to be part of any OSL driver-to-OS error code mapping).
546  */
547 #define BCME_IOCTL_PATCH_UNSUPPORTED	-9999
548 #if (BCME_LAST <= BCME_IOCTL_PATCH_UNSUPPORTED)
549 	#error "BCME_LAST <= BCME_IOCTL_PATCH_UNSUPPORTED"
550 #endif
551 
552 /* These are collection of BCME Error strings */
553 #define BCMERRSTRINGTABLE {		\
554 	"OK",				\
555 	"Undefined error",		\
556 	"Bad Argument",			\
557 	"Bad Option",			\
558 	"Not up",			\
559 	"Not down",			\
560 	"Not AP",			\
561 	"Not STA",			\
562 	"Bad Key Index",		\
563 	"Radio Off",			\
564 	"Not band locked",		\
565 	"No clock",			\
566 	"Bad Rate valueset",		\
567 	"Bad Band",			\
568 	"Buffer too short",		\
569 	"Buffer too long",		\
570 	"Busy",				\
571 	"Not Associated",		\
572 	"Bad SSID len",			\
573 	"Out of Range Channel",		\
574 	"Bad Channel",			\
575 	"Bad Address",			\
576 	"Not Enough Resources",		\
577 	"Unsupported",			\
578 	"Bad length",			\
579 	"Not Ready",			\
580 	"Not Permitted",		\
581 	"No Memory",			\
582 	"Associated",			\
583 	"Not In Range",			\
584 	"Not Found",			\
585 	"WME Not Enabled",		\
586 	"TSPEC Not Found",		\
587 	"ACM Not Supported",		\
588 	"Not WME Association",		\
589 	"SDIO Bus Error",		\
590 	"Dongle Not Accessible",	\
591 	"Incorrect version",		\
592 	"TX Failure",			\
593 	"RX Failure",			\
594 	"Device Not Present",		\
595 	"NMODE Disabled",		\
596 	"Host Offload in device",	\
597 	"Scan Rejected",		\
598 	"WLCMD usage error",		\
599 	"WLCMD ioctl error",		\
600 	"RWL serial port error",	\
601 	"Disabled",			\
602 	"Decrypt error",		\
603 	"Encrypt error",		\
604 	"MIC error",			\
605 	"Replay",			\
606 	"IE not found",			\
607 	"Data not found",		\
608 	"NOT GC",			\
609 	"PRS REQ FAILED",		\
610 	"NO P2P SubElement",		\
611 	"NOA Pending",			\
612 	"FRAG Q FAILED",		\
613 	"GET ActionFrame failed",	\
614 	"scheduler not ready",		\
615 	"Last IOV batched sub-cmd",	\
616 	"Mini PMU Cal failed",		\
617 	"R-cal failed",			\
618 	"LPF RC Cal failed",		\
619 	"DAC buf RC Cal failed",	\
620 	"VCO Cal failed",		\
621 	"band locked",			\
622 	"Recieved ie with invalid data", \
623 	"registration failed",		\
624 	"Registration with zero channels", \
625 	"pkt toss",			\
626 	"Dongle Devreset",		\
627 	"Critical roam in progress",	\
628 	"Signature file is missing",	\
629 }
630 #endif	/* BCMUTILS_ERR_CODES */
631 
632 #ifndef ABS
633 #define	ABS(a)			(((a) < 0) ? -(a) : (a))
634 #endif /* ABS */
635 
636 #ifndef MIN
637 #define	MIN(a, b)		(((a) < (b)) ? (a) : (b))
638 #endif /* MIN */
639 
640 #ifndef MAX
641 #define	MAX(a, b)		(((a) > (b)) ? (a) : (b))
642 #endif /* MAX */
643 
644 /* limit to [min, max] */
645 #ifndef LIMIT_TO_RANGE
646 #define LIMIT_TO_RANGE(x, min, max) \
647 	((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))
648 #endif /* LIMIT_TO_RANGE */
649 
650 /* limit to  max */
651 #ifndef LIMIT_TO_MAX
652 #define LIMIT_TO_MAX(x, max) \
653 	(((x) > (max) ? (max) : (x)))
654 #endif /* LIMIT_TO_MAX */
655 
656 /* limit to min */
657 #ifndef LIMIT_TO_MIN
658 #define LIMIT_TO_MIN(x, min) \
659 	(((x) < (min) ? (min) : (x)))
660 #endif /* LIMIT_TO_MIN */
661 
662 #define SIZE_BITS(x) (sizeof(x) * NBBY)
663 #define SIZE_BITS32(x) ((uint)sizeof(x) * NBBY)
664 
665 #define DELTA(curr, prev) ((curr) > (prev) ? ((curr) - (prev)) : \
666 	(0xffffffff - (prev) + (curr) + 1))
667 #define CEIL(x, y)		(((x) + ((y) - 1)) / (y))
668 #define ROUNDUP(x, y)		((((x) + ((y) - 1)) / (y)) * (y))
669 #define ROUNDDN(p, align)	((p) & ~((align) - 1))
670 #define	ISALIGNED(a, x)		(((uintptr)(a) & ((x) - 1)) == 0)
671 #define ALIGN_ADDR(addr, boundary) (void *)(((uintptr)(addr) + (boundary) - 1) \
672 	                                         & ~((uintptr)(boundary) - 1))
673 #define ALIGN_SIZE(size, boundary) (((size) + (boundary) - 1) \
674 	                                         & ~((boundary) - 1))
675 #define	ISPOWEROF2(x)		((((x) - 1) & (x)) == 0)
676 #define VALID_MASK(mask)	!((mask) & ((mask) + 1))
677 
678 #ifndef OFFSETOF
679 #if ((__GNUC__ >= 4) && (__GNUC_MINOR__ >= 8))
680 	/* GCC 4.8+ complains when using our OFFSETOF macro in array length declarations. */
681 	#define	OFFSETOF(type, member)	__builtin_offsetof(type, member)
682 #else
683 #ifdef BCMFUZZ
684 	/* use 0x10 offset to avoid undefined behavior error due to NULL access */
685 	#define OFFSETOF(type, member)	(((uint)(uintptr)&((type *)0x10)->member) - 0x10)
686 #else
687 	#define	OFFSETOF(type, member)	((uint)(uintptr)&((type *)0)->member)
688 #endif /* BCMFUZZ */
689 #endif /* GCC 4.8 or newer */
690 #endif /* OFFSETOF */
691 
692 #ifndef CONTAINEROF
693 #define CONTAINEROF(ptr, type, member) ((type *)((char *)(ptr) - OFFSETOF(type, member)))
694 #endif /* CONTAINEROF */
695 
696 /* substruct size up to and including a member of the struct */
697 #ifndef STRUCT_SIZE_THROUGH
698 #define STRUCT_SIZE_THROUGH(sptr, fname) \
699 	(((uint8*)&((sptr)->fname) - (uint8*)(sptr)) + sizeof((sptr)->fname))
700 #endif
701 
702 /* Extracting the size of element in a structure */
703 #define SIZE_OF(type, field) sizeof(((type *)0)->field)
704 
705 /* Extracting the size of pointer element in a structure */
706 #define SIZE_OF_PV(type, pfield) sizeof(*((type *)0)->pfield)
707 
708 #ifndef ARRAYSIZE
709 #define ARRAYSIZE(a)		(uint32)(sizeof(a) / sizeof(a[0]))
710 #endif
711 
712 #ifndef ARRAYLAST /* returns pointer to last array element */
713 #define ARRAYLAST(a)		(&a[ARRAYSIZE(a)-1])
714 #endif
715 
716 /* Calculates the required pad size. This is mainly used in register structures */
717 #define PADSZ(start, end)       ((((end) - (start)) / 4) + 1)
718 
719 /* Reference a function; used to prevent a static function from being optimized out */
720 extern void *_bcmutils_dummy_fn;
721 #define REFERENCE_FUNCTION(f)	(_bcmutils_dummy_fn = (void *)(f))
722 
723 /* bit map related macros */
724 #ifndef setbit
725 #ifndef NBBY		/* the BSD family defines NBBY */
726 #define	NBBY	8	/* 8 bits per byte */
727 #endif /* #ifndef NBBY */
728 #ifdef BCMUTILS_BIT_MACROS_USE_FUNCS
729 extern void setbit(void *array, uint bit);
730 extern void clrbit(void *array, uint bit);
731 extern bool isset(const void *array, uint bit);
732 extern bool isclr(const void *array, uint bit);
733 #else
734 #define	setbit(a, i)	(((uint8 *)a)[(i) / NBBY] |= 1 << ((i) % NBBY))
735 #define	clrbit(a, i)	(((uint8 *)a)[(i) / NBBY] &= ~(1 << ((i) % NBBY)))
736 #define	isset(a, i)	(((const uint8 *)a)[(i) / NBBY] & (1 << ((i) % NBBY)))
737 #define	isclr(a, i)	((((const uint8 *)a)[(i) / NBBY] & (1 << ((i) % NBBY))) == 0)
738 #endif
739 #endif /* setbit */
740 
741 /* read/write/clear field in a consecutive bits in an octet array.
742  * 'addr' is the octet array's start byte address
743  * 'size' is the octet array's byte size
744  * 'stbit' is the value's start bit offset
745  * 'nbits' is the value's bit size
746  * This set of utilities are for convenience. Don't use them
747  * in time critical/data path as there's a great overhead in them.
748  */
749 void setbits(uint8 *addr, uint size, uint stbit, uint nbits, uint32 val);
750 uint32 getbits(const uint8 *addr, uint size, uint stbit, uint nbits);
751 #define clrbits(addr, size, stbit, nbits) setbits(addr, size, stbit, nbits, 0)
752 
753 extern void set_bitrange(void *array, uint start, uint end, uint maxbit);
754 extern void clr_bitrange(void *array, uint start, uint end, uint maxbit);
755 extern void set_bitrange_u32(void *array, uint start, uint end, uint maxbit);
756 extern void clr_bitrange_u32(void *array, uint start, uint end, uint maxbit);
757 
758 extern int bcm_find_fsb(uint32 num);
759 
760 #define	isbitset(a, i)	(((a) & (1 << (i))) != 0)
761 
762 #if defined DONGLEBUILD
763 #define	NBITS(type)	(sizeof(type) * 8)
764 #else
765 #define	NBITS(type)	((uint32)(sizeof(type) * 8))
766 #endif  /* DONGLEBUILD */
767 #define NBITVAL(nbits)	(1 << (nbits))
768 #define MAXBITVAL(nbits)	((1 << (nbits)) - 1)
769 #define	NBITMASK(nbits)	MAXBITVAL(nbits)
770 #define MAXNBVAL(nbyte)	MAXBITVAL((nbyte) * 8)
771 
772 enum {
773 	BCM_FMT_BASE32
774 };
775 typedef int bcm_format_t;
776 
777 /* encodes using specified format and returns length of output written on success
778  * or a status code BCME_XX on failure. Input and output buffers may overlap.
779  * input will be advanced to the position when function stoped.
780  * out value of in_len will specify the number of processed input bytes.
781  * on input pad_off represents the number of bits (MSBs of the first output byte)
782  * to preserve and on output number of pad bits (LSBs) set to 0 in the output.
783  */
784 int bcm_encode(uint8 **in, uint *in_len, bcm_format_t fmt,
785 		uint *pad_off, uint8 *out, uint out_size);
786 
787 /* decodes input in specified format, returns length of output written on success
788  * or a status code BCME_XX on failure. Input and output buffers may overlap.
789  * input will be advanced to the position when function stoped.
790  * out value of in_len will specify the number of processed input bytes.
791  * on input pad_off represents the number of bits (MSBs of the first output byte)
792  * to preserve and on output number of pad bits (LSBs) set to 0 in the output.
793  */
794 int bcm_decode(const uint8 **in, uint *in_len, bcm_format_t fmt,
795 		uint *pad_off, uint8 *out, uint out_size);
796 
797 extern void bcm_bitprint32(const uint32 u32);
798 
799 /*
800  * ----------------------------------------------------------------------------
801  * Multiword map of 2bits, nibbles
802  * setbit2 setbit4 (void *ptr, uint32 ix, uint32 val)
803  * getbit2 getbit4 (void *ptr, uint32 ix)
804  * ----------------------------------------------------------------------------
805  */
806 
807 #define DECLARE_MAP_API(NB, RSH, LSH, OFF, MSK)                     \
808 static INLINE void setbit##NB(void *ptr, uint32 ix, uint32 val)     \
809 {                                                                   \
810 	uint32 *addr = (uint32 *)ptr;                                   \
811 	uint32 *a = addr + (ix >> RSH); /* (ix / 2^RSH) */              \
812 	uint32 pos = (ix & OFF) << LSH; /* (ix % 2^RSH) * 2^LSH */      \
813 	uint32 mask = (MSK << pos);                                     \
814 	uint32 tmp = *a & ~mask;                                        \
815 	*a = tmp | (val << pos);                                        \
816 }                                                                   \
817 static INLINE uint32 getbit##NB(void *ptr, uint32 ix)               \
818 {                                                                   \
819 	uint32 *addr = (uint32 *)ptr;                                   \
820 	uint32 *a = addr + (ix >> RSH);                                 \
821 	uint32 pos = (ix & OFF) << LSH;                                 \
822 	return ((*a >> pos) & MSK);                                     \
823 }
824 
825 DECLARE_MAP_API(2, 4, 1, 15u, 0x0003u) /* setbit2() and getbit2() */
826 DECLARE_MAP_API(4, 3, 2, 7u, 0x000Fu) /* setbit4() and getbit4() */
827 DECLARE_MAP_API(8, 2, 3, 3u, 0x00FFu) /* setbit8() and getbit8() */
828 
829 /* basic mux operation - can be optimized on several architectures */
830 #define MUX(pred, true, false) ((pred) ? (true) : (false))
831 
832 /* modulo inc/dec - assumes x E [0, bound - 1] */
833 #define MODDEC(x, bound) MUX((x) == 0, (bound) - 1, (x) - 1)
834 #define MODINC(x, bound) MUX((x) == (bound) - 1, 0, (x) + 1)
835 
836 /* modulo inc/dec, bound = 2^k */
837 #define MODDEC_POW2(x, bound) (((x) - 1) & ((bound) - 1))
838 #define MODINC_POW2(x, bound) (((x) + 1) & ((bound) - 1))
839 
840 /* modulo add/sub - assumes x, y E [0, bound - 1] */
841 #define MODADD(x, y, bound) \
842     MUX((x) + (y) >= (bound), (x) + (y) - (bound), (x) + (y))
843 #define MODSUB(x, y, bound) \
844     MUX(((int)(x)) - ((int)(y)) < 0, (x) - (y) + (bound), (x) - (y))
845 
846 /* module add/sub, bound = 2^k */
847 #define MODADD_POW2(x, y, bound) (((x) + (y)) & ((bound) - 1))
848 #define MODSUB_POW2(x, y, bound) (((x) - (y)) & ((bound) - 1))
849 
850 /* crc defines */
851 #define CRC8_INIT_VALUE   0xffu			/* Initial CRC8 checksum value */
852 #define CRC8_GOOD_VALUE   0x9fu			/* Good final CRC8 checksum value */
853 #define CRC16_INIT_VALUE  0xffffu		/* Initial CRC16 checksum value */
854 #define CRC16_GOOD_VALUE  0xf0b8u		/* Good final CRC16 checksum value */
855 #define CRC32_INIT_VALUE  0xffffffffu		/* Initial CRC32 checksum value */
856 #define CRC32_GOOD_VALUE  0xdebb20e3u		/* Good final CRC32 checksum value */
857 
858 #ifdef DONGLEBUILD
859 #define MACF				"MACADDR:%08x%04x"
860 #define ETHERP_TO_MACF(ea)		(uint32)bcm_ether_ntou64(ea), \
861 					(uint32)(bcm_ether_ntou64(ea) >> 32)
862 
863 #define CONST_ETHERP_TO_MACF(ea)	ETHERP_TO_MACF(ea)
864 
865 #define ETHER_TO_MACF(ea)		ETHERP_TO_MACF(&ea)
866 
867 #else
868 /* use for direct output of MAC address in printf etc */
869 #define MACF				"%02x:%02x:%02x:%02x:%02x:%02x"
870 #define ETHERP_TO_MACF(ea)	((const struct ether_addr *) (ea))->octet[0], \
871 				((const struct ether_addr *) (ea))->octet[1], \
872 				((const struct ether_addr *) (ea))->octet[2], \
873 				((const struct ether_addr *) (ea))->octet[3], \
874 				((const struct ether_addr *) (ea))->octet[4], \
875 				((const struct ether_addr *) (ea))->octet[5]
876 
877 #define CONST_ETHERP_TO_MACF(ea)	ETHERP_TO_MACF(ea)
878 
879 #define ETHER_TO_MACF(ea)	(ea).octet[0], \
880 				(ea).octet[1], \
881 				(ea).octet[2], \
882 				(ea).octet[3], \
883 				(ea).octet[4], \
884 				(ea).octet[5]
885 #endif /* DONGLEBUILD */
886 /* use only for debug, the string length can be changed
887  * If you want to use this macro to the logic,
888  * USE MACF instead
889  */
890 #if !defined(SIMPLE_MAC_PRINT)
891 #define MACDBG "%02x:%02x:%02x:%02x:%02x:%02x"
892 #define MAC2STRDBG(ea)	((const uint8*)(ea))[0], \
893 			((const uint8*)(ea))[1], \
894 			((const uint8*)(ea))[2], \
895 			((const uint8*)(ea))[3], \
896 			((const uint8*)(ea))[4], \
897 			((const uint8*)(ea))[5]
898 #else
899 #define MACDBG				"%02x:xx:xx:xx:x%x:%02x"
900 #define MAC2STRDBG(ea)	((const uint8*)(ea))[0], \
901 			(((const uint8*)(ea))[4] & 0xf), \
902 			((const uint8*)(ea))[5]
903 #endif /* SIMPLE_MAC_PRINT */
904 
905 #define MACOUIDBG "%02x:%x:%02x"
906 #define MACOUI2STRDBG(ea)	((const uint8*)(ea))[0], \
907 				((const uint8*)(ea))[1] & 0xf, \
908 				((const uint8*)(ea))[2]
909 
910 #define MACOUI "%02x:%02x:%02x"
911 #define MACOUI2STR(ea) (ea)[0], (ea)[1], (ea)[2]
912 
913 /* bcm_format_flags() bit description structure */
914 typedef struct bcm_bit_desc {
915 	uint32	bit;
916 	const char* name;
917 } bcm_bit_desc_t;
918 
919 /* bcm_format_field */
920 typedef struct bcm_bit_desc_ex {
921 	uint32 mask;
922 	const bcm_bit_desc_t *bitfield;
923 } bcm_bit_desc_ex_t;
924 
925 /* buffer length for ethernet address from bcm_ether_ntoa() */
926 #define ETHER_ADDR_STR_LEN	18u	/* 18-bytes of Ethernet address buffer length */
927 
928 static INLINE uint32 /* 32bit word aligned xor-32 */
bcm_compute_xor32(volatile uint32 * u32_val,int num_u32)929 bcm_compute_xor32(volatile uint32 *u32_val, int num_u32)
930 {
931 	int idx;
932 	uint32 xor32 = 0;
933 	for (idx = 0; idx < num_u32; idx++)
934 		xor32 ^= *(u32_val + idx);
935 	return xor32;
936 }
937 
938 /* crypto utility function */
939 /* 128-bit xor: *dst = *src1 xor *src2. dst1, src1 and src2 may have any alignment */
940 static INLINE void
xor_128bit_block(const uint8 * src1,const uint8 * src2,uint8 * dst)941 xor_128bit_block(const uint8 *src1, const uint8 *src2, uint8 *dst)
942 {
943 	if (
944 #ifdef __i386__
945 	    1 ||
946 #endif
947 	    (((uintptr)src1 | (uintptr)src2 | (uintptr)dst) & 3) == 0) {
948 		/* ARM CM3 rel time: 1229 (727 if alignment check could be omitted) */
949 		/* x86 supports unaligned.  This version runs 6x-9x faster on x86. */
950 		((uint32 *)dst)[0] = ((const uint32 *)src1)[0] ^ ((const uint32 *)src2)[0];
951 		((uint32 *)dst)[1] = ((const uint32 *)src1)[1] ^ ((const uint32 *)src2)[1];
952 		((uint32 *)dst)[2] = ((const uint32 *)src1)[2] ^ ((const uint32 *)src2)[2];
953 		((uint32 *)dst)[3] = ((const uint32 *)src1)[3] ^ ((const uint32 *)src2)[3];
954 	} else {
955 		/* ARM CM3 rel time: 4668 (4191 if alignment check could be omitted) */
956 		int k;
957 		for (k = 0; k < 16; k++)
958 			dst[k] = src1[k] ^ src2[k];
959 	}
960 }
961 
962 /* externs */
963 /* crc */
964 uint8 hndcrc8(const uint8 *p, uint nbytes, uint8 crc);
965 uint16 hndcrc16(const uint8 *p, uint nbytes, uint16 crc);
966 uint32 hndcrc32(const uint8 *p, uint nbytes, uint32 crc);
967 
968 /* format/print */
969 /* print out the value a field has: fields may have 1-32 bits and may hold any value */
970 extern uint bcm_format_field(const bcm_bit_desc_ex_t *bd, uint32 field, char* buf, uint len);
971 /* print out which bits in flags are set */
972 extern int bcm_format_flags(const bcm_bit_desc_t *bd, uint32 flags, char* buf, uint len);
973 /* print out whcih bits in octet array 'addr' are set. bcm_bit_desc_t:bit is a bit offset. */
974 int bcm_format_octets(const bcm_bit_desc_t *bd, uint bdsz,
975 	const uint8 *addr, uint size, char *buf, uint len);
976 
977 extern int bcm_format_hex(char *str, const void *bytes, uint len);
978 
979 #ifdef BCMDBG
980 extern void deadbeef(void *p, uint len);
981 #endif
982 extern const char *bcm_crypto_algo_name(uint algo);
983 extern char *bcm_chipname(uint chipid, char *buf, uint len);
984 extern char *bcm_brev_str(uint32 brev, char *buf);
985 extern void printbig(char *buf);
986 extern void prhex(const char *msg, const uchar *buf, uint len);
987 extern void prhexstr(const char *prefix, const uint8 *buf, uint len, bool newline);
988 
989 /* bcmerror */
990 extern const char *bcmerrorstr(int bcmerror);
991 
992 #if defined(BCMDBG) || defined(WLMSG_ASSOC)
993 /* get 802.11 frame name based on frame kind - see frame types FC_.. in 802.11.h */
994 const char *bcm_80211_fk_name(uint fk);
995 #else
996 #define bcm_80211_fk_names(_x) ""
997 #endif
998 
999 extern int wl_set_up_table(uint8 *up_table, bcm_tlv_t *qos_map_ie);
1000 
1001 /* multi-bool data type: set of bools, mbool is true if any is set */
1002 typedef uint32 mbool;
1003 #define mboolset(mb, bit)		((mb) |= (bit))		/* set one bool */
1004 #define mboolclr(mb, bit)		((mb) &= ~(bit))	/* clear one bool */
1005 #define mboolisset(mb, bit)		(((mb) & (bit)) != 0)	/* TRUE if one bool is set */
1006 #define	mboolmaskset(mb, mask, val)	((mb) = (((mb) & ~(mask)) | (val)))
1007 
1008 /* generic datastruct to help dump routines */
1009 struct fielddesc {
1010 	const char *nameandfmt;
1011 	uint32 offset;
1012 	uint32 len;
1013 };
1014 
1015 extern void bcm_binit(struct bcmstrbuf *b, char *buf, uint size);
1016 #define bcm_bsize(b) ((b)->size)
1017 #define bcm_breset(b) do {bcm_binit(b, (b)->origbuf, (b)->origsize);} while (0)
1018 extern void bcm_bprhex(struct bcmstrbuf *b, const char *msg, bool newline,
1019 	const uint8 *buf, uint len);
1020 
1021 extern void bcm_inc_bytes(uchar *num, int num_bytes, uint8 amount);
1022 extern int bcm_cmp_bytes(const uchar *arg1, const uchar *arg2, uint8 nbytes);
1023 extern void bcm_print_bytes(const char *name, const uchar *cdata, uint len);
1024 
1025 typedef  uint32 (*bcmutl_rdreg_rtn)(void *arg0, uint arg1, uint32 offset);
1026 extern uint bcmdumpfields(bcmutl_rdreg_rtn func_ptr, void *arg0, uint arg1, struct fielddesc *str,
1027                           char *buf, uint32 bufsize);
1028 extern uint bcm_bitcount(const uint8 *bitmap, uint bytelength);
1029 
1030 extern int bcm_bprintf(struct bcmstrbuf *b, const char *fmt, ...);
1031 
1032 /* power conversion */
1033 extern uint16 bcm_qdbm_to_mw(uint8 qdbm);
1034 extern uint8 bcm_mw_to_qdbm(uint16 mw);
1035 extern uint bcm_mkiovar(const char *name, const char *data, uint datalen, char *buf, uint len);
1036 
1037 #ifdef BCMDBG_PKT  /* pkt logging for debugging */
1038 #define PKTLIST_SIZE 3000
1039 
1040 #ifdef BCMDBG_PTRACE
1041 #define PKTTRACE_MAX_BYTES	12
1042 #define PKTTRACE_MAX_BITS	(PKTTRACE_MAX_BYTES * NBBY)
1043 
1044 enum pkttrace_info {
1045 	PKTLIST_PRECQ,		/* Pkt in Prec Q */
1046 	PKTLIST_FAIL_PRECQ, 	/* Pkt failed to Q in PRECQ */
1047 	PKTLIST_DMAQ,		/* Pkt in DMA Q */
1048 	PKTLIST_MI_TFS_RCVD,	/* Received TX status */
1049 	PKTLIST_TXDONE,		/* Pkt TX done */
1050 	PKTLIST_TXFAIL,		/* Pkt TX failed */
1051 	PKTLIST_PKTFREE,	/* pkt is freed */
1052 	PKTLIST_PRECREQ,	/* Pkt requeued in precq */
1053 	PKTLIST_TXFIFO		/* To trace in wlc_fifo */
1054 };
1055 #endif /* BCMDBG_PTRACE */
1056 
1057 typedef struct pkt_dbginfo {
1058 	int     line;
1059 	char    *file;
1060 	void	*pkt;
1061 #ifdef BCMDBG_PTRACE
1062 	char	pkt_trace[PKTTRACE_MAX_BYTES];
1063 #endif /* BCMDBG_PTRACE */
1064 } pkt_dbginfo_t;
1065 
1066 typedef struct {
1067 	pkt_dbginfo_t list[PKTLIST_SIZE]; /* List of pointers to packets */
1068 	uint16 count; /* Total count of the packets */
1069 } pktlist_info_t;
1070 
1071 extern void pktlist_add(pktlist_info_t *pktlist, void *p, int len, char *file);
1072 extern void pktlist_remove(pktlist_info_t *pktlist, void *p);
1073 extern char* pktlist_dump(pktlist_info_t *pktlist, char *buf);
1074 #ifdef BCMDBG_PTRACE
1075 extern void pktlist_trace(pktlist_info_t *pktlist, void *pkt, uint16 bit);
1076 #endif /* BCMDBG_PTRACE */
1077 #endif  /* BCMDBG_PKT */
1078 unsigned int process_nvram_vars(char *varbuf, unsigned int len);
1079 bool replace_nvram_variable(char *varbuf, unsigned int buflen, const char *variable,
1080 	unsigned int *datalen);
1081 
1082 /* trace any object allocation / free, with / without features (flags) set to the object */
1083 #if (defined(DONGLEBUILD) && defined(BCMDBG_MEM) && (!defined(BCM_OBJECT_TRACE)))
1084 #define BCM_OBJECT_TRACE
1085 #endif /* (defined(DONGLEBUILD) && defined(BCMDBG_MEM) && (!defined(BCM_OBJECT_TRACE))) */
1086 
1087 #define BCM_OBJDBG_ADD           1
1088 #define BCM_OBJDBG_REMOVE        2
1089 #define BCM_OBJDBG_ADD_PKT       3
1090 
1091 /* object feature: set or clear flags */
1092 #define BCM_OBJECT_FEATURE_FLAG       1
1093 #define BCM_OBJECT_FEATURE_PKT_STATE  2
1094 /* object feature: flag bits */
1095 #define BCM_OBJECT_FEATURE_0     (1 << 0)
1096 #define BCM_OBJECT_FEATURE_1     (1 << 1)
1097 #define BCM_OBJECT_FEATURE_2     (1 << 2)
1098 /* object feature: clear flag bits field set with this flag */
1099 #define BCM_OBJECT_FEATURE_CLEAR (1 << 31)
1100 #if defined(BCM_OBJECT_TRACE) && !defined(BINCMP)
1101 #define bcm_pkt_validate_chk(obj, func)	do { \
1102 	void * pkttag; \
1103 	bcm_object_trace_chk(obj, 0, 0, \
1104 		func, __LINE__); \
1105 	if ((pkttag = PKTTAG(obj))) { \
1106 		bcm_object_trace_chk(obj, 1, DHD_PKTTAG_SN(pkttag), \
1107 			func, __LINE__); \
1108 	} \
1109 } while (0)
1110 extern void bcm_object_trace_opr(void *obj, uint32 opt, const char *caller, int line);
1111 extern void bcm_object_trace_upd(void *obj, void *obj_new);
1112 extern void bcm_object_trace_chk(void *obj, uint32 chksn, uint32 sn,
1113 	const char *caller, int line);
1114 extern void bcm_object_feature_set(void *obj, uint32 type, uint32 value);
1115 extern int  bcm_object_feature_get(void *obj, uint32 type, uint32 value);
1116 extern void bcm_object_trace_init(void);
1117 extern void bcm_object_trace_deinit(void);
1118 #else
1119 #define bcm_pkt_validate_chk(obj, func)
1120 #define bcm_object_trace_opr(a, b, c, d)
1121 #define bcm_object_trace_upd(a, b)
1122 #define bcm_object_trace_chk(a, b, c, d, e)
1123 #define bcm_object_feature_set(a, b, c)
1124 #define bcm_object_feature_get(a, b, c)
1125 #define bcm_object_trace_init()
1126 #define bcm_object_trace_deinit()
1127 #endif /* BCM_OBJECT_TRACE && !BINCMP */
1128 
1129 /* Public domain bit twiddling hacks/utilities: Sean Eron Anderson */
1130 
1131 /* Table driven count set bits. */
1132 static const uint8 /* Table only for use by bcm_cntsetbits */
1133 _CSBTBL[256] =
1134 {
1135 	#define B2(n)    n,     n + 1,     n + 1,     n + 2
1136 	#define B4(n) B2(n), B2(n + 1), B2(n + 1), B2(n + 2)
1137 	#define B6(n) B4(n), B4(n + 1), B4(n + 1), B4(n + 2)
1138 		B6(0), B6(0 + 1), B6(0 + 1), B6(0 + 2)
1139 };
1140 
1141 static INLINE uint32 /* Uses table _CSBTBL for fast counting of 1's in a u32 */
bcm_cntsetbits(const uint32 u32arg)1142 bcm_cntsetbits(const uint32 u32arg)
1143 {
1144 	/* function local scope declaration of const _CSBTBL[] */
1145 	const uint8 * p = (const uint8 *)&u32arg;
1146 	/* uint32 cast to avoid uint8 being promoted to int for arithmetic operation */
1147 	return ((uint32)_CSBTBL[p[0]] + _CSBTBL[p[1]] + _CSBTBL[p[2]] + _CSBTBL[p[3]]);
1148 }
1149 
1150 static INLINE int /* C equivalent count of leading 0's in a u32 */
C_bcm_count_leading_zeros(uint32 u32arg)1151 C_bcm_count_leading_zeros(uint32 u32arg)
1152 {
1153 	int shifts = 0;
1154 	while (u32arg) {
1155 		shifts++; u32arg >>= 1;
1156 	}
1157 	return (32 - shifts);
1158 }
1159 
1160 typedef struct bcm_rand_metadata {
1161 	uint32 count;		/* number of random numbers in bytes */
1162 	uint32 signature;	/* host fills it in, FW verfies before reading rand */
1163 } bcm_rand_metadata_t;
1164 
1165 #ifdef BCMDRIVER
1166 /*
1167  * Assembly instructions: Count Leading Zeros
1168  * "clz"	: MIPS, ARM
1169  * "cntlzw"	: PowerPC
1170  * "BSF"	: x86
1171  * "lzcnt"	: AMD, SPARC
1172  */
1173 
1174 #if defined(__arm__)
1175 #if defined(__ARM_ARCH_7M__) /* Cortex M3 */
1176 #define __USE_ASM_CLZ__
1177 #endif /* __ARM_ARCH_7M__ */
1178 #if defined(__ARM_ARCH_7R__) /* Cortex R4 */
1179 #define __USE_ASM_CLZ__
1180 #endif /* __ARM_ARCH_7R__ */
1181 #endif /* __arm__ */
1182 
1183 static INLINE int
bcm_count_leading_zeros(uint32 u32arg)1184 bcm_count_leading_zeros(uint32 u32arg)
1185 {
1186 #if defined(__USE_ASM_CLZ__)
1187 	int zeros;
1188 	__asm__ volatile("clz    %0, %1 \n" : "=r" (zeros) : "r"  (u32arg));
1189 	return zeros;
1190 #else	/* C equivalent */
1191 	return C_bcm_count_leading_zeros(u32arg);
1192 #endif  /* C equivalent */
1193 }
1194 
1195 /*
1196  * Macro to count leading zeroes
1197  *
1198  */
1199 #if defined(__GNUC__)
1200 #define CLZ(x) __builtin_clzl(x)
1201 #elif defined(__arm__)
1202 #define CLZ(x) __clz(x)
1203 #else
1204 #define CLZ(x) bcm_count_leading_zeros(x)
1205 #endif /* __GNUC__ */
1206 
1207 /* INTERFACE: Multiword bitmap based small id allocator. */
1208 struct bcm_mwbmap;	/* forward declaration for use as an opaque mwbmap handle */
1209 
1210 #define BCM_MWBMAP_INVALID_HDL	((struct bcm_mwbmap *)NULL)
1211 #define BCM_MWBMAP_INVALID_IDX	((uint32)(~0U))
1212 
1213 /* Incarnate a multiword bitmap based small index allocator */
1214 extern struct bcm_mwbmap * bcm_mwbmap_init(osl_t * osh, uint32 items_max);
1215 
1216 /* Free up the multiword bitmap index allocator */
1217 extern void bcm_mwbmap_fini(osl_t * osh, struct bcm_mwbmap * mwbmap_hdl);
1218 
1219 /* Allocate a unique small index using a multiword bitmap index allocator */
1220 extern uint32 bcm_mwbmap_alloc(struct bcm_mwbmap * mwbmap_hdl);
1221 
1222 /* Force an index at a specified position to be in use */
1223 extern void bcm_mwbmap_force(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix);
1224 
1225 /* Free a previously allocated index back into the multiword bitmap allocator */
1226 extern void bcm_mwbmap_free(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix);
1227 
1228 /* Fetch the toal number of free indices in the multiword bitmap allocator */
1229 extern uint32 bcm_mwbmap_free_cnt(struct bcm_mwbmap * mwbmap_hdl);
1230 
1231 /* Determine whether an index is inuse or free */
1232 extern bool bcm_mwbmap_isfree(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix);
1233 
1234 /* Debug dump a multiword bitmap allocator */
1235 extern void bcm_mwbmap_show(struct bcm_mwbmap * mwbmap_hdl);
1236 
1237 extern void bcm_mwbmap_audit(struct bcm_mwbmap * mwbmap_hdl);
1238 /* End - Multiword bitmap based small Id allocator. */
1239 
1240 /* INTERFACE: Simple unique 16bit Id Allocator using a stack implementation. */
1241 
1242 #define ID8_INVALID     0xFFu
1243 #define ID16_INVALID    0xFFFFu
1244 #define ID32_INVALID    0xFFFFFFFFu
1245 #define ID16_UNDEFINED              ID16_INVALID
1246 
1247 /*
1248  * Construct a 16bit id allocator, managing 16bit ids in the range:
1249  *    [start_val16 .. start_val16+total_ids)
1250  * Note: start_val16 is inclusive.
1251  * Returns an opaque handle to the 16bit id allocator.
1252  */
1253 extern void * id16_map_init(osl_t *osh, uint16 total_ids, uint16 start_val16);
1254 extern void * id16_map_fini(osl_t *osh, void * id16_map_hndl);
1255 extern void id16_map_clear(void * id16_map_hndl, uint16 total_ids, uint16 start_val16);
1256 
1257 /* Allocate a unique 16bit id */
1258 extern uint16 id16_map_alloc(void * id16_map_hndl);
1259 
1260 /* Free a 16bit id value into the id16 allocator */
1261 extern void id16_map_free(void * id16_map_hndl, uint16 val16);
1262 
1263 /* Get the number of failures encountered during id allocation. */
1264 extern uint32 id16_map_failures(void * id16_map_hndl);
1265 
1266 /* Audit the 16bit id allocator state. */
1267 extern bool id16_map_audit(void * id16_map_hndl);
1268 /* End - Simple 16bit Id Allocator. */
1269 #endif /* BCMDRIVER */
1270 
1271 void bcm_add_64(uint32* r_hi, uint32* r_lo, uint32 offset);
1272 void bcm_sub_64(uint32* r_hi, uint32* r_lo, uint32 offset);
1273 
1274 #define MASK_32_BITS	(~0)
1275 #define MASK_8_BITS	((1 << 8) - 1)
1276 
1277 #define EXTRACT_LOW32(num)	(uint32)(num & MASK_32_BITS)
1278 #define EXTRACT_HIGH32(num)	(uint32)(((uint64)num >> 32) & MASK_32_BITS)
1279 
1280 #define MAXIMUM(a, b) ((a > b) ? a : b)
1281 #define MINIMUM(a, b) ((a < b) ? a : b)
1282 #define LIMIT(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))
1283 
1284 /* calculate checksum for ip header, tcp / udp header / data */
1285 uint16 bcm_ip_cksum(uint8 *buf, uint32 len, uint32 sum);
1286 
1287 #ifndef _dll_t_
1288 #define _dll_t_
1289 /*
1290  * -----------------------------------------------------------------------------
1291  *                      Double Linked List Macros
1292  * -----------------------------------------------------------------------------
1293  *
1294  * All dll operations must be performed on a pre-initialized node.
1295  * Inserting an uninitialized node into a list effectively initialized it.
1296  *
1297  * When a node is deleted from a list, you may initialize it to avoid corruption
1298  * incurred by double deletion. You may skip initialization if the node is
1299  * immediately inserted into another list.
1300  *
1301  * By placing a dll_t element at the start of a struct, you may cast a dll_t *
1302  * to the struct or vice versa.
1303  *
1304  * Example of declaring an initializing someList and inserting nodeA, nodeB
1305  *
1306  *     typedef struct item {
1307  *         dll_t node;
1308  *         int someData;
1309  *     } Item_t;
1310  *     Item_t nodeA, nodeB, nodeC;
1311  *     nodeA.someData = 11111, nodeB.someData = 22222, nodeC.someData = 33333;
1312  *
1313  *     dll_t someList;
1314  *     dll_init(&someList);
1315  *
1316  *     dll_append(&someList, (dll_t *) &nodeA);
1317  *     dll_prepend(&someList, &nodeB.node);
1318  *     dll_insert((dll_t *)&nodeC, &nodeA.node);
1319  *
1320  *     dll_delete((dll_t *) &nodeB);
1321  *
1322  * Example of a for loop to walk someList of node_p
1323  *
1324  *   extern void mydisplay(Item_t * item_p);
1325  *
1326  *   dll_t * item_p, * next_p;
1327  *   for (item_p = dll_head_p(&someList); ! dll_end(&someList, item_p);
1328  *        item_p = next_p)
1329  *   {
1330  *       next_p = dll_next_p(item_p);
1331  *       ... use item_p at will, including removing it from list ...
1332  *       mydisplay((PItem_t)item_p);
1333  *   }
1334  *
1335  * -----------------------------------------------------------------------------
1336  */
1337 typedef struct dll {
1338 	struct dll * next_p;
1339 	struct dll * prev_p;
1340 } dll_t;
1341 
1342 static INLINE void
dll_init(dll_t * node_p)1343 dll_init(dll_t *node_p)
1344 {
1345 	node_p->next_p = node_p;
1346 	node_p->prev_p = node_p;
1347 }
1348 /* dll macros returing a pointer to dll_t */
1349 
1350 static INLINE dll_t *
BCMPOSTTRAPFN(dll_head_p)1351 BCMPOSTTRAPFN(dll_head_p)(dll_t *list_p)
1352 {
1353 	return list_p->next_p;
1354 }
1355 
1356 static INLINE dll_t *
BCMPOSTTRAPFN(dll_tail_p)1357 BCMPOSTTRAPFN(dll_tail_p)(dll_t *list_p)
1358 {
1359 	return (list_p)->prev_p;
1360 }
1361 
1362 static INLINE dll_t *
BCMPOSTTRAPFN(dll_next_p)1363 BCMPOSTTRAPFN(dll_next_p)(dll_t *node_p)
1364 {
1365 	return (node_p)->next_p;
1366 }
1367 
1368 static INLINE dll_t *
BCMPOSTTRAPFN(dll_prev_p)1369 BCMPOSTTRAPFN(dll_prev_p)(dll_t *node_p)
1370 {
1371 	return (node_p)->prev_p;
1372 }
1373 
1374 static INLINE bool
BCMPOSTTRAPFN(dll_empty)1375 BCMPOSTTRAPFN(dll_empty)(dll_t *list_p)
1376 {
1377 	return ((list_p)->next_p == (list_p));
1378 }
1379 
1380 static INLINE bool
BCMPOSTTRAPFN(dll_end)1381 BCMPOSTTRAPFN(dll_end)(dll_t *list_p, dll_t * node_p)
1382 {
1383 	return (list_p == node_p);
1384 }
1385 
1386 /* inserts the node new_p "after" the node at_p */
1387 static INLINE void
BCMPOSTTRAPFN(dll_insert)1388 BCMPOSTTRAPFN(dll_insert)(dll_t *new_p, dll_t * at_p)
1389 {
1390 	new_p->next_p = at_p->next_p;
1391 	new_p->prev_p = at_p;
1392 	at_p->next_p = new_p;
1393 	(new_p->next_p)->prev_p = new_p;
1394 }
1395 
1396 static INLINE void
BCMPOSTTRAPFN(dll_append)1397 BCMPOSTTRAPFN(dll_append)(dll_t *list_p, dll_t *node_p)
1398 {
1399 	dll_insert(node_p, dll_tail_p(list_p));
1400 }
1401 
1402 static INLINE void
BCMPOSTTRAPFN(dll_prepend)1403 BCMPOSTTRAPFN(dll_prepend)(dll_t *list_p, dll_t *node_p)
1404 {
1405 	dll_insert(node_p, list_p);
1406 }
1407 
1408 /* deletes a node from any list that it "may" be in, if at all. */
1409 static INLINE void
BCMPOSTTRAPFN(dll_delete)1410 BCMPOSTTRAPFN(dll_delete)(dll_t *node_p)
1411 {
1412 	node_p->prev_p->next_p = node_p->next_p;
1413 	node_p->next_p->prev_p = node_p->prev_p;
1414 }
1415 #endif  /* ! defined(_dll_t_) */
1416 
1417 /* Elements managed in a double linked list */
1418 
1419 typedef struct dll_pool {
1420 	dll_t       free_list;
1421 	uint16      free_count;
1422 	uint16      elems_max;
1423 	uint16      elem_size;
1424 	dll_t       elements[1];
1425 } dll_pool_t;
1426 
1427 dll_pool_t * dll_pool_init(void * osh, uint16 elems_max, uint16 elem_size);
1428 void * dll_pool_alloc(dll_pool_t * dll_pool_p);
1429 void dll_pool_free(dll_pool_t * dll_pool_p, void * elem_p);
1430 void dll_pool_free_tail(dll_pool_t * dll_pool_p, void * elem_p);
1431 typedef void (* dll_elem_dump)(void * elem_p);
1432 #ifdef BCMDBG
1433 void dll_pool_dump(dll_pool_t * dll_pool_p, dll_elem_dump dump);
1434 #endif
1435 void dll_pool_detach(void * osh, dll_pool_t * pool, uint16 elems_max, uint16 elem_size);
1436 
1437 int valid_bcmerror(int e);
1438 /* Stringify macro definition */
1439 #define BCM_STRINGIFY(s) #s
1440 /* Used to pass in a macro variable that gets expanded and then stringified */
1441 #define BCM_EXTENDED_STRINGIFY(s) BCM_STRINGIFY(s)
1442 
1443 /* calculate IPv4 header checksum
1444  * - input ip points to IP header in network order
1445  * - output cksum is in network order
1446  */
1447 uint16 ipv4_hdr_cksum(uint8 *ip, uint ip_len);
1448 
1449 /* calculate IPv4 TCP header checksum
1450  * - input ip and tcp points to IP and TCP header in network order
1451  * - output cksum is in network order
1452  */
1453 uint16 ipv4_tcp_hdr_cksum(uint8 *ip, uint8 *tcp, uint16 tcp_len);
1454 
1455 /* calculate IPv6 TCP header checksum
1456  * - input ipv6 and tcp points to IPv6 and TCP header in network order
1457  * - output cksum is in network order
1458  */
1459 uint16 ipv6_tcp_hdr_cksum(uint8 *ipv6, uint8 *tcp, uint16 tcp_len);
1460 
1461 #ifdef __cplusplus
1462 	}
1463 #endif
1464 
1465 /* #define DEBUG_COUNTER */
1466 #ifdef DEBUG_COUNTER
1467 #define CNTR_TBL_MAX 10
1468 typedef struct _counter_tbl_t {
1469 	char name[16];				/* name of this counter table */
1470 	uint32 prev_log_print;		/* Internal use. Timestamp of the previous log print */
1471 	uint log_print_interval;	/* Desired interval to print logs in ms */
1472 	uint needed_cnt;			/* How many counters need to be used */
1473 	uint32 cnt[CNTR_TBL_MAX];		/* Counting entries to increase at desired places */
1474 	bool enabled;				/* Whether to enable printing log */
1475 } counter_tbl_t;
1476 
1477 /*	How to use
1478 	Eg.: In dhd_linux.c
1479 	cnt[0]: How many times dhd_start_xmit() was called in every 1sec.
1480 	cnt[1]: How many bytes were requested to be sent in every 1sec.
1481 
1482 ++	static counter_tbl_t xmit_tbl = {"xmit", 0, 1000, 2, {0,}, 1};
1483 
1484 	int
1485 	dhd_start_xmit(struct sk_buff *skb, struct net_device *net)
1486 	{
1487 		..........
1488 ++		counter_printlog(&xmit_tbl);
1489 ++		xmit_tbl.cnt[0]++;
1490 
1491 		ifp = dhd->iflist[ifidx];
1492 		datalen  = PKTLEN(dhdp->osh, skb);
1493 
1494 ++		xmit_tbl.cnt[1] += datalen;
1495 		............
1496 
1497 		ret = dhd_sendpkt(&dhd->pub, ifidx, pktbuf);
1498 		...........
1499 	}
1500 */
1501 
1502 void counter_printlog(counter_tbl_t *ctr_tbl);
1503 #endif /* DEBUG_COUNTER */
1504 
1505 #if defined(__GNUC__)
1506 #define CALL_SITE __builtin_return_address(0)
1507 #elif defined(_WIN32)
1508 #define CALL_SITE _ReturnAddress()
1509 #else
1510 #define CALL_SITE ((void*) 0)
1511 #endif
1512 #ifdef SHOW_LOGTRACE
1513 #define TRACE_LOG_BUF_MAX_SIZE 1700
1514 #define RTT_LOG_BUF_MAX_SIZE 1700
1515 #define BUF_NOT_AVAILABLE	0
1516 #define NEXT_BUF_NOT_AVAIL	1
1517 #define NEXT_BUF_AVAIL		2
1518 
1519 typedef struct trace_buf_info {
1520 	int availability;
1521 	int size;
1522 	char buf[TRACE_LOG_BUF_MAX_SIZE];
1523 } trace_buf_info_t;
1524 #endif /* SHOW_LOGTRACE */
1525 
1526 enum dump_dongle_e {
1527 	DUMP_DONGLE_COREREG = 0,
1528 	DUMP_DONGLE_D11MEM
1529 };
1530 
1531 typedef struct {
1532 	uint32 type;     /**< specifies e.g dump of d11 memory, use enum dump_dongle_e  */
1533 	uint32 index;    /**< iterator1, specifies core index or d11 memory index */
1534 	uint32 offset;   /**< iterator2, byte offset within register set or memory */
1535 } dump_dongle_in_t;
1536 
1537 typedef struct {
1538 	uint32 address;  /**< e.g. backplane address of register */
1539 	uint32 id;       /**< id, e.g. core id */
1540 	uint32 rev;      /**< rev, e.g. core rev */
1541 	uint32 n_bytes;  /**< nbytes in array val[] */
1542 	uint32 val[1];   /**< out: values that were read out of registers or memory */
1543 } dump_dongle_out_t;
1544 
1545 extern uint32 sqrt_int(uint32 value);
1546 
1547 extern uint8 bcm_get_ceil_pow_2(uint val);
1548 
1549 #ifdef BCMDRIVER
1550 /* structures and routines to process variable sized data */
1551 typedef struct var_len_data {
1552 	uint32	vlen;
1553 	uint8	*vdata;
1554 } var_len_data_t;
1555 
1556 int bcm_vdata_alloc(osl_t *osh, var_len_data_t *vld, uint32 size);
1557 int bcm_vdata_free(osl_t *osh, var_len_data_t *vld);
1558 #if defined(PRIVACY_MASK)
1559 void bcm_ether_privacy_mask(struct ether_addr *addr);
1560 #else
1561 #define bcm_ether_privacy_mask(addr)
1562 #endif /* PRIVACY_MASK */
1563 #endif /* BCMDRIVER */
1564 
1565 /* Count the number of elements in an array that do not match the given value */
1566 extern int array_value_mismatch_count(uint8 value, uint8 *array, int array_size);
1567 /* Count the number of non-zero elements in an uint8 array */
1568 extern int array_nonzero_count(uint8 *array, int array_size);
1569 /* Count the number of non-zero elements in an int16 array */
1570 extern int array_nonzero_count_int16(int16 *array, int array_size);
1571 /* Count the number of zero elements in an uint8 array */
1572 extern int array_zero_count(uint8 *array, int array_size);
1573 /* Validate a uint8 ordered array.  Assert if invalid. */
1574 extern int verify_ordered_array_uint8(uint8 *array, int array_size, uint8 range_lo, uint8 range_hi);
1575 /* Validate a int16 configuration array that need not be zero-terminated.  Assert if invalid. */
1576 extern int verify_ordered_array_int16(int16 *array, int array_size, int16 range_lo, int16 range_hi);
1577 /* Validate all values in an array are in range */
1578 extern int verify_array_values(uint8 *array, int array_size,
1579 	int range_lo, int range_hi, bool zero_terminated);
1580 
1581 /*  To unwind from the trap_handler. */
1582 extern void (*const print_btrace_int_fn)(int depth, uint32 pc, uint32 lr, uint32 sp);
1583 extern void (*const print_btrace_fn)(int depth);
1584 #define PRINT_BACKTRACE(depth) if (print_btrace_fn) print_btrace_fn(depth)
1585 #define PRINT_BACKTRACE_INT(depth, pc, lr, sp) \
1586 	if (print_btrace_int_fn) print_btrace_int_fn(depth, pc, lr, sp)
1587 
1588 /* FW Signing - only in bootloader builds, never in dongle FW builds */
1589 #ifdef WL_FWSIGN
1590 	#define FWSIGN_ENAB()		(1)
1591 #else
1592 	#define FWSIGN_ENAB()		(0)
1593 #endif /* WL_FWSIGN */
1594 
1595 /* Utilities for reading SROM/SFlash vars */
1596 
1597 typedef struct varbuf {
1598 	char *base;		/* pointer to buffer base */
1599 	char *buf;		/* pointer to current position */
1600 	unsigned int size;	/* current (residual) size in bytes */
1601 } varbuf_t;
1602 
1603 /** Initialization of varbuf structure */
1604 void varbuf_init(varbuf_t *b, char *buf, uint size);
1605 /** append a null terminated var=value string */
1606 int varbuf_append(varbuf_t *b, const char *fmt, ...);
1607 #if defined(BCMDRIVER)
1608 int initvars_table(osl_t *osh, char *start, char *end, char **vars, uint *count);
1609 #endif
1610 
1611 /* Count the number of trailing zeros in uint32 val
1612  * Applying unary minus to unsigned value is intentional,
1613  * and doesn't influence counting of trailing zeros
1614  */
1615 static INLINE uint32
count_trailing_zeros(uint32 val)1616 count_trailing_zeros(uint32 val)
1617 {
1618 #ifdef BCMDRIVER
1619 	uint32 c = (uint32)CLZ(val & ((uint32)(-(int)val)));
1620 #else
1621 	uint32 c = (uint32)C_bcm_count_leading_zeros(val & ((uint32)(-(int)val)));
1622 #endif /* BCMDRIVER */
1623 	return val ? 31u - c : c;
1624 }
1625 
1626 /** Size in bytes of data block, defined by struct with last field, declared as
1627  * one/zero element vector - such as wl_uint32_list_t or bcm_xtlv_cbuf_s.
1628  * Arguments:
1629  * list - address of data block (value is ignored, only type is important)
1630  * last_var_len_field - name of last field (usually declared as ...[] or ...[1])
1631  * num_elems - number of elements in data block
1632  * Example:
1633  * wl_uint32_list_t *list;
1634  * WL_VAR_LEN_STRUCT_SIZE(list, element, 10);  // Size in bytes of 10-element list
1635  */
1636 #define WL_VAR_LEN_STRUCT_SIZE(list, last_var_len_field, num_elems) \
1637 	((size_t)((const char *)&((list)->last_var_len_field) - (const char *)(list)) + \
1638 	(sizeof((list)->last_var_len_field[0]) * (size_t)(num_elems)))
1639 
1640 int buf_shift_right(uint8 *buf, uint16 len, uint8 bits);
1641 #endif	/* _bcmutils_h_ */
1642