1 /*
2 * Misc useful os-independent macros and functions.
3 *
4 * Portions of this code are copyright (c) 2022 Cypress Semiconductor Corporation
5 *
6 * Copyright (C) 1999-2017, Broadcom Corporation
7 *
8 * Unless you and Broadcom execute a separate written software license
9 * agreement governing use of this software, this software is licensed to you
10 * under the terms of the GNU General Public License version 2 (the "GPL"),
11 * available at http://www.broadcom.com/licenses/GPLv2.php, with the
12 * following added to such license:
13 *
14 * As a special exception, the copyright holders of this software give you
15 * permission to link this software with independent modules, and to copy and
16 * distribute the resulting executable under terms of your choice, provided that
17 * you also meet, for each linked independent module, the terms and conditions of
18 * the license of that module. An independent module is a module which is not
19 * derived from this software. The special exception does not apply to any
20 * modifications of the software.
21 *
22 * Notwithstanding the above, under no circumstances may you combine this
23 * software in any way with any other Broadcom software provided under a license
24 * other than the GPL, without Broadcom's express prior written consent.
25 *
26 *
27 * <<Broadcom-WL-IPTag/Open:>>
28 *
29 * $Id: bcmutils.h 700843 2017-05-22 15:56:44Z $
30 */
31
32 #ifndef _bcmutils_h_
33 #define _bcmutils_h_
34
35 #include <bcmtlv.h>
36
37 #ifdef __cplusplus
38 extern "C" {
39 #endif // endif
40
41 #define bcm_strncpy_s(dst, noOfElements, src, count) strncpy((dst), (src), (count))
42 #ifdef FREEBSD
43 #define bcm_strncat_s(dst, noOfElements, src, count) strcat((dst), (src))
44 #else
45 #define bcm_strncat_s(dst, noOfElements, src, count) strncat((dst), (src), (count))
46 #endif /* FREEBSD */
47 #define bcm_snprintf_s snprintf
48 #define bcm_sprintf_s snprintf
49
50 /*
51 * #define bcm_strcpy_s(dst, count, src) strncpy((dst), (src), (count))
52 * Use bcm_strcpy_s instead as it is a safer option
53 * bcm_strcat_s: Use bcm_strncat_s as a safer option
54 *
55 */
56
57 #define BCM_BIT(x) (1 << (x))
58
59 /* ctype replacement */
60 #define _BCM_U 0x01 /* upper */
61 #define _BCM_L 0x02 /* lower */
62 #define _BCM_D 0x04 /* digit */
63 #define _BCM_C 0x08 /* cntrl */
64 #define _BCM_P 0x10 /* punct */
65 #define _BCM_S 0x20 /* white space (space/lf/tab) */
66 #define _BCM_X 0x40 /* hex digit */
67 #define _BCM_SP 0x80 /* hard space (0x20) */
68
69 extern const unsigned char bcm_ctype[];
70 #define bcm_ismask(x) (bcm_ctype[(int)(unsigned char)(x)])
71
72 #define bcm_isalnum(c) ((bcm_ismask(c)&(_BCM_U|_BCM_L|_BCM_D)) != 0)
73 #define bcm_isalpha(c) ((bcm_ismask(c)&(_BCM_U|_BCM_L)) != 0)
74 #define bcm_iscntrl(c) ((bcm_ismask(c)&(_BCM_C)) != 0)
75 #define bcm_isdigit(c) ((bcm_ismask(c)&(_BCM_D)) != 0)
76 #define bcm_isgraph(c) ((bcm_ismask(c)&(_BCM_P|_BCM_U|_BCM_L|_BCM_D)) != 0)
77 #define bcm_islower(c) ((bcm_ismask(c)&(_BCM_L)) != 0)
78 #define bcm_isprint(c) ((bcm_ismask(c)&(_BCM_P|_BCM_U|_BCM_L|_BCM_D|_BCM_SP)) != 0)
79 #define bcm_ispunct(c) ((bcm_ismask(c)&(_BCM_P)) != 0)
80 #define bcm_isspace(c) ((bcm_ismask(c)&(_BCM_S)) != 0)
81 #define bcm_isupper(c) ((bcm_ismask(c)&(_BCM_U)) != 0)
82 #define bcm_isxdigit(c) ((bcm_ismask(c)&(_BCM_D|_BCM_X)) != 0)
83 #define bcm_tolower(c) (bcm_isupper((c)) ? ((c) + 'a' - 'A') : (c))
84 #define bcm_toupper(c) (bcm_islower((c)) ? ((c) + 'A' - 'a') : (c))
85
86 #define CIRCULAR_ARRAY_FULL(rd_idx, wr_idx, max) ((wr_idx + 1)%max == rd_idx)
87
88 #define KB(bytes) (((bytes) + 1023) / 1024)
89
90 /* Buffer structure for collecting string-formatted data
91 * using bcm_bprintf() API.
92 * Use bcm_binit() to initialize before use
93 */
94
95 struct bcmstrbuf {
96 char *buf; /* pointer to current position in origbuf */
97 unsigned int size; /* current (residual) size in bytes */
98 char *origbuf; /* unmodified pointer to orignal buffer */
99 unsigned int origsize; /* unmodified orignal buffer size in bytes */
100 };
101
102 #define BCMSTRBUF_LEN(b) (b->size)
103 #define BCMSTRBUF_BUF(b) (b->buf)
104
105 /* ** driver-only section ** */
106 #ifdef BCMDRIVER
107 #include <osl.h>
108 #include <hnd_pktq.h>
109 #include <hnd_pktpool.h>
110
111 #define GPIO_PIN_NOTDEFINED 0x20 /* Pin not defined */
112
113 /*
114 * Spin at most 'us' microseconds while 'exp' is true.
115 * Caller should explicitly test 'exp' when this completes
116 * and take appropriate error action if 'exp' is still true.
117 */
118 #ifndef SPINWAIT_POLL_PERIOD
119 #define SPINWAIT_POLL_PERIOD 10U
120 #endif // endif
121
122 #define SPINWAIT(exp, us) { \
123 uint countdown = (us) + (SPINWAIT_POLL_PERIOD - 1U); \
124 while (((exp) != 0) && (uint)(countdown >= SPINWAIT_POLL_PERIOD)) { \
125 OSL_DELAY(SPINWAIT_POLL_PERIOD); \
126 countdown -= SPINWAIT_POLL_PERIOD; \
127 } \
128 }
129
130 /* forward definition of ether_addr structure used by some function prototypes */
131
132 struct ether_addr;
133
134 extern int ether_isbcast(const void *ea);
135 extern int ether_isnulladdr(const void *ea);
136
137 #define UP_TABLE_MAX ((IPV4_TOS_DSCP_MASK >> IPV4_TOS_DSCP_SHIFT) + 1) /* 64 max */
138 #define CORE_SLAVE_PORT_0 0
139 #define CORE_SLAVE_PORT_1 1
140 #define CORE_BASE_ADDR_0 0
141 #define CORE_BASE_ADDR_1 1
142
143 /* externs */
144 /* packet */
145 extern uint pktcopy(osl_t *osh, void *p, uint offset, int len, uchar *buf);
146 extern uint pktfrombuf(osl_t *osh, void *p, uint offset, int len, uchar *buf);
147 extern uint pkttotlen(osl_t *osh, void *p);
148 extern void *pktlast(osl_t *osh, void *p);
149 extern uint pktsegcnt(osl_t *osh, void *p);
150 extern uint8 *pktdataoffset(osl_t *osh, void *p, uint offset);
151 extern void *pktoffset(osl_t *osh, void *p, uint offset);
152
153 /* Get priority from a packet and pass it back in scb (or equiv) */
154 #define PKTPRIO_VDSCP 0x100 /* DSCP prio found after VLAN tag */
155 #define PKTPRIO_VLAN 0x200 /* VLAN prio found */
156 #define PKTPRIO_UPD 0x400 /* DSCP used to update VLAN prio */
157 #define PKTPRIO_DSCP 0x800 /* DSCP prio found */
158
159 /* DSCP type definitions (RFC4594) */
160 /* AF1x: High-Throughput Data (RFC2597) */
161 #define DSCP_AF11 0x0A
162 #define DSCP_AF12 0x0C
163 #define DSCP_AF13 0x0E
164 /* AF2x: Low-Latency Data (RFC2597) */
165 #define DSCP_AF21 0x12
166 #define DSCP_AF22 0x14
167 #define DSCP_AF23 0x16
168 /* CS2: OAM (RFC2474) */
169 #define DSCP_CS2 0x10
170 /* AF3x: Multimedia Streaming (RFC2597) */
171 #define DSCP_AF31 0x1A
172 #define DSCP_AF32 0x1C
173 #define DSCP_AF33 0x1E
174 /* CS3: Broadcast Video (RFC2474) */
175 #define DSCP_CS3 0x18
176 /* VA: VOCIE-ADMIT (RFC5865) */
177 #define DSCP_VA 0x2C
178 /* EF: Telephony (RFC3246) */
179 #define DSCP_EF 0x2E
180 /* CS6: Network Control (RFC2474) */
181 #define DSCP_CS6 0x30
182 /* CS7: Network Control (RFC2474) */
183 #define DSCP_CS7 0x38
184
185 extern uint pktsetprio(void *pkt, bool update_vtag);
186 extern uint pktsetprio_qms(void *pkt, uint8* up_table, bool update_vtag);
187 extern bool pktgetdscp(uint8 *pktdata, uint pktlen, uint8 *dscp);
188
189 /* ethernet address */
190 extern char *bcm_ether_ntoa(const struct ether_addr *ea, char *buf);
191 extern int bcm_ether_atoe(const char *p, struct ether_addr *ea);
192
193 /* ip address */
194 struct ipv4_addr;
195 extern char *bcm_ip_ntoa(struct ipv4_addr *ia, char *buf);
196 extern char *bcm_ipv6_ntoa(void *ipv6, char *buf);
197 extern int bcm_atoipv4(const char *p, struct ipv4_addr *ip);
198
199 /* delay */
200 extern void bcm_mdelay(uint ms);
201 /* variable access */
202 #if defined(BCM_RECLAIM)
203 extern bool _nvram_reclaim_enb;
204 #define NVRAM_RECLAIM_ENAB() (_nvram_reclaim_enb)
205 #define NVRAM_RECLAIM_CHECK(name) \
206 if (NVRAM_RECLAIM_ENAB() && (bcm_attach_part_reclaimed == TRUE)) { \
207 *(char*) 0 = 0; /* TRAP */ \
208 return NULL; \
209 }
210 #else /* BCM_RECLAIM */
211 #define NVRAM_RECLAIM_CHECK(name)
212 #endif /* BCM_RECLAIM */
213
214 extern char *getvar(char *vars, const char *name);
215 extern int getintvar(char *vars, const char *name);
216 extern int getintvararray(char *vars, const char *name, int index);
217 extern int getintvararraysize(char *vars, const char *name);
218
219 /* Read an array of values from a possibly slice-specific nvram string */
220 extern int get_uint8_vararray_slicespecific(osl_t *osh, char *vars, char *vars_table_accessor,
221 const char* name, uint8* dest_array, uint dest_size);
222 extern int get_int16_vararray_slicespecific(osl_t *osh, char *vars, char *vars_table_accessor,
223 const char* name, int16* dest_array, uint dest_size);
224 /* Prepend a slice-specific accessor to an nvram string name */
225 extern int get_slicespecific_var_name(osl_t *osh, char *vars_table_accessor,
226 const char *name, char **name_out);
227
228 extern uint getgpiopin(char *vars, char *pin_name, uint def_pin);
229 #define bcm_perf_enable()
230 #define bcmstats(fmt)
231 #define bcmlog(fmt, a1, a2)
232 #define bcmdumplog(buf, size) *buf = '\0'
233 #define bcmdumplogent(buf, idx) -1
234
235 #define TSF_TICKS_PER_MS 1000
236 #define TS_ENTER 0xdeadbeef /* Timestamp profiling enter */
237 #define TS_EXIT 0xbeefcafe /* Timestamp profiling exit */
238
239 #define bcmtslog(tstamp, fmt, a1, a2)
240 #define bcmprinttslogs()
241 #define bcmprinttstamp(us)
242 #define bcmdumptslog(b)
243
244 extern char *bcm_nvram_vars(uint *length);
245 extern int bcm_nvram_cache(void *sih);
246
247 /* Support for sharing code across in-driver iovar implementations.
248 * The intent is that a driver use this structure to map iovar names
249 * to its (private) iovar identifiers, and the lookup function to
250 * find the entry. Macros are provided to map ids and get/set actions
251 * into a single number space for a switch statement.
252 */
253
254 /* iovar structure */
255 typedef struct bcm_iovar {
256 const char *name; /* name for lookup and display */
257 uint16 varid; /* id for switch */
258 uint16 flags; /* driver-specific flag bits */
259 uint8 flags2; /* driver-specific flag bits */
260 uint8 type; /* base type of argument */
261 uint16 minlen; /* min length for buffer vars */
262 } bcm_iovar_t;
263
264 /* varid definitions are per-driver, may use these get/set bits */
265
266 /* IOVar action bits for id mapping */
267 #define IOV_GET 0 /* Get an iovar */
268 #define IOV_SET 1 /* Set an iovar */
269
270 /* Varid to actionid mapping */
271 #define IOV_GVAL(id) ((id) * 2)
272 #define IOV_SVAL(id) ((id) * 2 + IOV_SET)
273 #define IOV_ISSET(actionid) ((actionid & IOV_SET) == IOV_SET)
274 #define IOV_ID(actionid) (actionid >> 1)
275
276 /* flags are per-driver based on driver attributes */
277
278 extern const bcm_iovar_t *bcm_iovar_lookup(const bcm_iovar_t *table, const char *name);
279 extern int bcm_iovar_lencheck(const bcm_iovar_t *table, void *arg, int len, bool set);
280
281 /* ioctl structure */
282 typedef struct wlc_ioctl_cmd {
283 uint16 cmd; /**< IOCTL command */
284 uint16 flags; /**< IOCTL command flags */
285 int16 min_len; /**< IOCTL command minimum argument len (in bytes) */
286 } wlc_ioctl_cmd_t;
287
288 #if defined(WLTINYDUMP) || defined(WLMSG_INFORM) || defined(WLMSG_ASSOC) || \
289 defined(WLMSG_PRPKT) || defined(WLMSG_WSEC)
290 extern int bcm_format_ssid(char* buf, const uchar ssid[], uint ssid_len);
291 #endif // endif
292 #endif /* BCMDRIVER */
293
294 /* string */
295 extern int bcm_atoi(const char *s);
296 extern ulong bcm_strtoul(const char *cp, char **endp, uint base);
297 extern uint64 bcm_strtoull(const char *cp, char **endp, uint base);
298 extern char *bcmstrstr(const char *haystack, const char *needle);
299 extern char *bcmstrnstr(const char *s, uint s_len, const char *substr, uint substr_len);
300 extern char *bcmstrcat(char *dest, const char *src);
301 extern char *bcmstrncat(char *dest, const char *src, uint size);
302 extern ulong wchar2ascii(char *abuf, ushort *wbuf, ushort wbuflen, ulong abuflen);
303 char* bcmstrtok(char **string, const char *delimiters, char *tokdelim);
304 int bcmstricmp(const char *s1, const char *s2);
305 int bcmstrnicmp(const char* s1, const char* s2, int cnt);
306
307 /* Base type definitions */
308 #define IOVT_VOID 0 /* no value (implictly set only) */
309 #define IOVT_BOOL 1 /* any value ok (zero/nonzero) */
310 #define IOVT_INT8 2 /* integer values are range-checked */
311 #define IOVT_UINT8 3 /* unsigned int 8 bits */
312 #define IOVT_INT16 4 /* int 16 bits */
313 #define IOVT_UINT16 5 /* unsigned int 16 bits */
314 #define IOVT_INT32 6 /* int 32 bits */
315 #define IOVT_UINT32 7 /* unsigned int 32 bits */
316 #define IOVT_BUFFER 8 /* buffer is size-checked as per minlen */
317 #define BCM_IOVT_VALID(type) (((unsigned int)(type)) <= IOVT_BUFFER)
318
319 /* Initializer for IOV type strings */
320 #define BCM_IOV_TYPE_INIT { \
321 "void", \
322 "bool", \
323 "int8", \
324 "uint8", \
325 "int16", \
326 "uint16", \
327 "int32", \
328 "uint32", \
329 "buffer", \
330 "" }
331
332 #define BCM_IOVT_IS_INT(type) (\
333 (type == IOVT_BOOL) || \
334 (type == IOVT_INT8) || \
335 (type == IOVT_UINT8) || \
336 (type == IOVT_INT16) || \
337 (type == IOVT_UINT16) || \
338 (type == IOVT_INT32) || \
339 (type == IOVT_UINT32))
340
341 /* ** driver/apps-shared section ** */
342
343 #define BCME_STRLEN 64 /* Max string length for BCM errors */
344 #define VALID_BCMERROR(e) valid_bcmerror(e)
345
346 #ifdef DBG_BUS
347 /** tracks non typical execution paths, use gdb with arm sim + firmware dump to read counters */
348 #define DBG_BUS_INC(s, cnt) ((s)->dbg_bus->cnt++)
349 #else
350 #define DBG_BUS_INC(s, cnt)
351 #endif /* DBG_BUS */
352
353 /*
354 * error codes could be added but the defined ones shouldn't be changed/deleted
355 * these error codes are exposed to the user code
356 * when ever a new error code is added to this list
357 * please update errorstring table with the related error string and
358 * update osl files with os specific errorcode map
359 */
360
361 #define BCME_OK 0 /* Success */
362 #define BCME_ERROR -1 /* Error generic */
363 #define BCME_BADARG -2 /* Bad Argument */
364 #define BCME_BADOPTION -3 /* Bad option */
365 #define BCME_NOTUP -4 /* Not up */
366 #define BCME_NOTDOWN -5 /* Not down */
367 #define BCME_NOTAP -6 /* Not AP */
368 #define BCME_NOTSTA -7 /* Not STA */
369 #define BCME_BADKEYIDX -8 /* BAD Key Index */
370 #define BCME_RADIOOFF -9 /* Radio Off */
371 #define BCME_NOTBANDLOCKED -10 /* Not band locked */
372 #define BCME_NOCLK -11 /* No Clock */
373 #define BCME_BADRATESET -12 /* BAD Rate valueset */
374 #define BCME_BADBAND -13 /* BAD Band */
375 #define BCME_BUFTOOSHORT -14 /* Buffer too short */
376 #define BCME_BUFTOOLONG -15 /* Buffer too long */
377 #define BCME_BUSY -16 /* Busy */
378 #define BCME_NOTASSOCIATED -17 /* Not Associated */
379 #define BCME_BADSSIDLEN -18 /* Bad SSID len */
380 #define BCME_OUTOFRANGECHAN -19 /* Out of Range Channel */
381 #define BCME_BADCHAN -20 /* Bad Channel */
382 #define BCME_BADADDR -21 /* Bad Address */
383 #define BCME_NORESOURCE -22 /* Not Enough Resources */
384 #define BCME_UNSUPPORTED -23 /* Unsupported */
385 #define BCME_BADLEN -24 /* Bad length */
386 #define BCME_NOTREADY -25 /* Not Ready */
387 #define BCME_EPERM -26 /* Not Permitted */
388 #define BCME_NOMEM -27 /* No Memory */
389 #define BCME_ASSOCIATED -28 /* Associated */
390 #define BCME_RANGE -29 /* Not In Range */
391 #define BCME_NOTFOUND -30 /* Not Found */
392 #define BCME_WME_NOT_ENABLED -31 /* WME Not Enabled */
393 #define BCME_TSPEC_NOTFOUND -32 /* TSPEC Not Found */
394 #define BCME_ACM_NOTSUPPORTED -33 /* ACM Not Supported */
395 #define BCME_NOT_WME_ASSOCIATION -34 /* Not WME Association */
396 #define BCME_SDIO_ERROR -35 /* SDIO Bus Error */
397 #define BCME_DONGLE_DOWN -36 /* Dongle Not Accessible */
398 #define BCME_VERSION -37 /* Incorrect version */
399 #define BCME_TXFAIL -38 /* TX failure */
400 #define BCME_RXFAIL -39 /* RX failure */
401 #define BCME_NODEVICE -40 /* Device not present */
402 #define BCME_NMODE_DISABLED -41 /* NMODE disabled */
403 #define BCME_HOFFLOAD_RESIDENT -42 /* offload resident */
404 #define BCME_SCANREJECT -43 /* reject scan request */
405 #define BCME_USAGE_ERROR -44 /* WLCMD usage error */
406 #define BCME_IOCTL_ERROR -45 /* WLCMD ioctl error */
407 #define BCME_SERIAL_PORT_ERR -46 /* RWL serial port error */
408 #define BCME_DISABLED -47 /* Disabled in this build */
409 #define BCME_DECERR -48 /* Decrypt error */
410 #define BCME_ENCERR -49 /* Encrypt error */
411 #define BCME_MICERR -50 /* Integrity/MIC error */
412 #define BCME_REPLAY -51 /* Replay */
413 #define BCME_IE_NOTFOUND -52 /* IE not found */
414 #define BCME_DATA_NOTFOUND -53 /* Complete data not found in buffer */
415 #define BCME_NOT_GC -54 /* expecting a group client */
416 #define BCME_PRS_REQ_FAILED -55 /* GC presence req failed to sent */
417 #define BCME_NO_P2P_SE -56 /* Could not find P2P-Subelement */
418 #define BCME_NOA_PND -57 /* NoA pending, CB shuld be NULL */
419 #define BCME_FRAG_Q_FAILED -58 /* queueing 80211 frag failedi */
420 #define BCME_GET_AF_FAILED -59 /* Get p2p AF pkt failed */
421 #define BCME_MSCH_NOTREADY -60 /* scheduler not ready */
422 #define BCME_IOV_LAST_CMD -61 /* last batched iov sub-command */
423 #define BCME_MINIPMU_CAL_FAIL -62 /* MiniPMU cal failed */
424 #define BCME_RCAL_FAIL -63 /* Rcal failed */
425 #define BCME_LPF_RCCAL_FAIL -64 /* RCCAL failed */
426 #define BCME_DACBUF_RCCAL_FAIL -65 /* RCCAL failed */
427 #define BCME_VCOCAL_FAIL -66 /* VCOCAL failed */
428 #define BCME_BANDLOCKED -67 /* interface is restricted to a band */
429 #define BCME_DNGL_DEVRESET -68 /* dongle re-attach during DEVRESET */
430 #define BCME_LAST BCME_DNGL_DEVRESET
431
432 #define BCME_NOTENABLED BCME_DISABLED
433
434 /* This error code is *internal* to the driver, and is not propogated to users. It should
435 * only be used by IOCTL patch handlers as an indication that it did not handle the IOCTL.
436 * (Since the error code is internal, an entry in 'BCMERRSTRINGTABLE' is not required,
437 * nor does it need to be part of any OSL driver-to-OS error code mapping).
438 */
439 #define BCME_IOCTL_PATCH_UNSUPPORTED -9999
440 #if (BCME_LAST <= BCME_IOCTL_PATCH_UNSUPPORTED)
441 #error "BCME_LAST <= BCME_IOCTL_PATCH_UNSUPPORTED"
442 #endif // endif
443
444 /* These are collection of BCME Error strings */
445 #define BCMERRSTRINGTABLE { \
446 "OK", \
447 "Undefined error", \
448 "Bad Argument", \
449 "Bad Option", \
450 "Not up", \
451 "Not down", \
452 "Not AP", \
453 "Not STA", \
454 "Bad Key Index", \
455 "Radio Off", \
456 "Not band locked", \
457 "No clock", \
458 "Bad Rate valueset", \
459 "Bad Band", \
460 "Buffer too short", \
461 "Buffer too long", \
462 "Busy", \
463 "Not Associated", \
464 "Bad SSID len", \
465 "Out of Range Channel", \
466 "Bad Channel", \
467 "Bad Address", \
468 "Not Enough Resources", \
469 "Unsupported", \
470 "Bad length", \
471 "Not Ready", \
472 "Not Permitted", \
473 "No Memory", \
474 "Associated", \
475 "Not In Range", \
476 "Not Found", \
477 "WME Not Enabled", \
478 "TSPEC Not Found", \
479 "ACM Not Supported", \
480 "Not WME Association", \
481 "SDIO Bus Error", \
482 "Dongle Not Accessible", \
483 "Incorrect version", \
484 "TX Failure", \
485 "RX Failure", \
486 "Device Not Present", \
487 "NMODE Disabled", \
488 "Host Offload in device", \
489 "Scan Rejected", \
490 "WLCMD usage error", \
491 "WLCMD ioctl error", \
492 "RWL serial port error", \
493 "Disabled", \
494 "Decrypt error", \
495 "Encrypt error", \
496 "MIC error", \
497 "Replay", \
498 "IE not found", \
499 "Data not found", \
500 "NOT GC", \
501 "PRS REQ FAILED", \
502 "NO P2P SubElement", \
503 "NOA Pending", \
504 "FRAG Q FAILED", \
505 "GET ActionFrame failed", \
506 "scheduler not ready", \
507 "Last IOV batched sub-cmd", \
508 "Mini PMU Cal failed", \
509 "R-cal failed", \
510 "LPF RC Cal failed", \
511 "DAC buf RC Cal failed", \
512 "VCO Cal failed", \
513 "band locked", \
514 "Dongle Devreset", \
515 }
516
517 #ifndef ABS
518 #define ABS(a) (((a) < 0) ? -(a) : (a))
519 #endif /* ABS */
520
521 #ifndef MIN
522 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
523 #endif /* MIN */
524
525 #ifndef MAX
526 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
527 #endif /* MAX */
528
529 /* limit to [min, max] */
530 #ifndef LIMIT_TO_RANGE
531 #define LIMIT_TO_RANGE(x, min, max) \
532 ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))
533 #endif /* LIMIT_TO_RANGE */
534
535 /* limit to max */
536 #ifndef LIMIT_TO_MAX
537 #define LIMIT_TO_MAX(x, max) \
538 (((x) > (max) ? (max) : (x)))
539 #endif /* LIMIT_TO_MAX */
540
541 /* limit to min */
542 #ifndef LIMIT_TO_MIN
543 #define LIMIT_TO_MIN(x, min) \
544 (((x) < (min) ? (min) : (x)))
545 #endif /* LIMIT_TO_MIN */
546
547 #define DELTA(curr, prev) ((curr) > (prev) ? ((curr) - (prev)) : \
548 (0xffffffff - (prev) + (curr) + 1))
549 #define CEIL(x, y) (((x) + ((y) - 1)) / (y))
550 #define ROUNDUP(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
551 #define ROUNDDN(p, align) ((p) & ~((align) - 1))
552 #define ISALIGNED(a, x) (((uintptr)(a) & ((x) - 1)) == 0)
553 #define ALIGN_ADDR(addr, boundary) (void *)(((uintptr)(addr) + (boundary) - 1) \
554 & ~((boundary) - 1))
555 #define ALIGN_SIZE(size, boundary) (((size) + (boundary) - 1) \
556 & ~((boundary) - 1))
557 #define ISPOWEROF2(x) ((((x) - 1) & (x)) == 0)
558 #define VALID_MASK(mask) !((mask) & ((mask) + 1))
559
560 #ifndef OFFSETOF
561 #ifdef __ARMCC_VERSION
562 /*
563 * The ARM RVCT compiler complains when using OFFSETOF where a constant
564 * expression is expected, such as an initializer for a static object.
565 * offsetof from the runtime library doesn't have that problem.
566 */
567 #include <stddef.h>
568 #define OFFSETOF(type, member) offsetof(type, member)
569 #else
570 # if ((__GNUC__ >= 4) && (__GNUC_MINOR__ >= 8))
571 /* GCC 4.8+ complains when using our OFFSETOF macro in array length declarations. */
572 # define OFFSETOF(type, member) __builtin_offsetof(type, member)
573 # else
574 # define OFFSETOF(type, member) ((uint)(uintptr)&((type *)0)->member)
575 # endif /* GCC 4.8 or newer */
576 #endif /* __ARMCC_VERSION */
577 #endif /* OFFSETOF */
578
579 #ifndef CONTAINEROF
580 #define CONTAINEROF(ptr, type, member) ((type *)((char *)(ptr) - OFFSETOF(type, member)))
581 #endif /* CONTAINEROF */
582
583 /* substruct size up to and including a member of the struct */
584 #ifndef STRUCT_SIZE_THROUGH
585 #define STRUCT_SIZE_THROUGH(sptr, fname) \
586 (((uint8*)&((sptr)->fname) - (uint8*)(sptr)) + sizeof((sptr)->fname))
587 #endif // endif
588
589 /* Extracting the size of element in a structure */
590 #define SIZE_OF(type, field) sizeof(((type *)0)->field)
591
592 #ifndef ARRAYSIZE
593 #define ARRAYSIZE(a) (uint32)(sizeof(a) / sizeof(a[0]))
594 #endif // endif
595
596 #ifndef ARRAYLAST /* returns pointer to last array element */
597 #define ARRAYLAST(a) (&a[ARRAYSIZE(a)-1])
598 #endif // endif
599
600 /* Calculates the required pad size. This is mainly used in register structures */
601 #define PADSZ(start, end) ((((end) - (start)) / 4) + 1)
602
603 /* Reference a function; used to prevent a static function from being optimized out */
604 extern void *_bcmutils_dummy_fn;
605 #define REFERENCE_FUNCTION(f) (_bcmutils_dummy_fn = (void *)(f))
606
607 /* bit map related macros */
608 #ifndef setbit
609 #ifndef NBBY /* the BSD family defines NBBY */
610 #define NBBY 8 /* 8 bits per byte */
611 #endif /* #ifndef NBBY */
612 #ifdef BCMUTILS_BIT_MACROS_USE_FUNCS
613 extern void setbit(void *array, uint bit);
614 extern void clrbit(void *array, uint bit);
615 extern bool isset(const void *array, uint bit);
616 extern bool isclr(const void *array, uint bit);
617 #else
618 #define setbit(a, i) (((uint8 *)a)[(i) / NBBY] |= 1 << ((i) % NBBY))
619 #define clrbit(a, i) (((uint8 *)a)[(i) / NBBY] &= ~(1 << ((i) % NBBY)))
620 #define isset(a, i) (((const uint8 *)a)[(i) / NBBY] & (1 << ((i) % NBBY)))
621 #define isclr(a, i) ((((const uint8 *)a)[(i) / NBBY] & (1 << ((i) % NBBY))) == 0)
622 #endif // endif
623 #endif /* setbit */
624
625 /* read/write/clear field in a consecutive bits in an octet array.
626 * 'addr' is the octet array's start byte address
627 * 'size' is the octet array's byte size
628 * 'stbit' is the value's start bit offset
629 * 'nbits' is the value's bit size
630 * This set of utilities are for convenience. Don't use them
631 * in time critical/data path as there's a great overhead in them.
632 */
633 void setbits(uint8 *addr, uint size, uint stbit, uint nbits, uint32 val);
634 uint32 getbits(const uint8 *addr, uint size, uint stbit, uint nbits);
635 #define clrbits(addr, size, stbit, nbits) setbits(addr, size, stbit, nbits, 0)
636
637 extern void set_bitrange(void *array, uint start, uint end, uint maxbit);
638 extern int bcm_find_fsb(uint32 num);
639
640 #define isbitset(a, i) (((a) & (1 << (i))) != 0)
641
642 #define NBITS(type) (sizeof(type) * 8)
643 #define NBITVAL(nbits) (1 << (nbits))
644 #define MAXBITVAL(nbits) ((1 << (nbits)) - 1)
645 #define NBITMASK(nbits) MAXBITVAL(nbits)
646 #define MAXNBVAL(nbyte) MAXBITVAL((nbyte) * 8)
647
648 extern void bcm_bitprint32(const uint32 u32);
649
650 /*
651 * ----------------------------------------------------------------------------
652 * Multiword map of 2bits, nibbles
653 * setbit2 setbit4 (void *ptr, uint32 ix, uint32 val)
654 * getbit2 getbit4 (void *ptr, uint32 ix)
655 * ----------------------------------------------------------------------------
656 */
657
658 #define DECLARE_MAP_API(NB, RSH, LSH, OFF, MSK) \
659 static INLINE void setbit##NB(void *ptr, uint32 ix, uint32 val) \
660 { \
661 uint32 *addr = (uint32 *)ptr; \
662 uint32 *a = addr + (ix >> RSH); /* (ix / 2^RSH) */ \
663 uint32 pos = (ix & OFF) << LSH; /* (ix % 2^RSH) * 2^LSH */ \
664 uint32 mask = (MSK << pos); \
665 uint32 tmp = *a & ~mask; \
666 *a = tmp | (val << pos); \
667 } \
668 static INLINE uint32 getbit##NB(void *ptr, uint32 ix) \
669 { \
670 uint32 *addr = (uint32 *)ptr; \
671 uint32 *a = addr + (ix >> RSH); \
672 uint32 pos = (ix & OFF) << LSH; \
673 return ((*a >> pos) & MSK); \
674 }
675
676 DECLARE_MAP_API(2, 4, 1, 15U, 0x0003U) /* setbit2() and getbit2() */
677 DECLARE_MAP_API(4, 3, 2, 7U, 0x000FU) /* setbit4() and getbit4() */
678 DECLARE_MAP_API(8, 2, 3, 3U, 0x00FFU) /* setbit8() and getbit8() */
679
680 /* basic mux operation - can be optimized on several architectures */
681 #define MUX(pred, true, false) ((pred) ? (true) : (false))
682
683 /* modulo inc/dec - assumes x E [0, bound - 1] */
684 #define MODDEC(x, bound) MUX((x) == 0, (bound) - 1, (x) - 1)
685 #define MODINC(x, bound) MUX((x) == (bound) - 1, 0, (x) + 1)
686
687 /* modulo inc/dec, bound = 2^k */
688 #define MODDEC_POW2(x, bound) (((x) - 1) & ((bound) - 1))
689 #define MODINC_POW2(x, bound) (((x) + 1) & ((bound) - 1))
690
691 /* modulo add/sub - assumes x, y E [0, bound - 1] */
692 #define MODADD(x, y, bound) \
693 MUX((x) + (y) >= (bound), (x) + (y) - (bound), (x) + (y))
694 #define MODSUB(x, y, bound) \
695 MUX(((int)(x)) - ((int)(y)) < 0, (x) - (y) + (bound), (x) - (y))
696
697 /* module add/sub, bound = 2^k */
698 #define MODADD_POW2(x, y, bound) (((x) + (y)) & ((bound) - 1))
699 #define MODSUB_POW2(x, y, bound) (((x) - (y)) & ((bound) - 1))
700
701 /* crc defines */
702 #define CRC8_INIT_VALUE 0xff /* Initial CRC8 checksum value */
703 #define CRC8_GOOD_VALUE 0x9f /* Good final CRC8 checksum value */
704 #define CRC16_INIT_VALUE 0xffff /* Initial CRC16 checksum value */
705 #define CRC16_GOOD_VALUE 0xf0b8 /* Good final CRC16 checksum value */
706 #define CRC32_INIT_VALUE 0xffffffff /* Initial CRC32 checksum value */
707 #define CRC32_GOOD_VALUE 0xdebb20e3 /* Good final CRC32 checksum value */
708
709 /* use for direct output of MAC address in printf etc */
710 #define MACF "%02x:%02x:%02x:%02x:%02x:%02x"
711 #define ETHERP_TO_MACF(ea) ((struct ether_addr *) (ea))->octet[0], \
712 ((struct ether_addr *) (ea))->octet[1], \
713 ((struct ether_addr *) (ea))->octet[2], \
714 ((struct ether_addr *) (ea))->octet[3], \
715 ((struct ether_addr *) (ea))->octet[4], \
716 ((struct ether_addr *) (ea))->octet[5]
717
718 #define CONST_ETHERP_TO_MACF(ea) ((const struct ether_addr *) (ea))->octet[0], \
719 ((const struct ether_addr *) (ea))->octet[1], \
720 ((const struct ether_addr *) (ea))->octet[2], \
721 ((const struct ether_addr *) (ea))->octet[3], \
722 ((const struct ether_addr *) (ea))->octet[4], \
723 ((const struct ether_addr *) (ea))->octet[5]
724 #define ETHER_TO_MACF(ea) (ea).octet[0], \
725 (ea).octet[1], \
726 (ea).octet[2], \
727 (ea).octet[3], \
728 (ea).octet[4], \
729 (ea).octet[5]
730 #if !defined(SIMPLE_MAC_PRINT)
731 #define MACDBG "%02x:%02x:%02x:%02x:%02x:%02x"
732 #define MAC2STRDBG(ea) CONST_ETHERP_TO_MACF(ea)
733 #else
734 #define MACDBG "%02x:xx:xx:xx:x%x:%02x"
735 #define MAC2STRDBG(ea) ((uint8*)(ea))[0], (((uint8*)(ea))[4] & 0xf), ((uint8*)(ea))[5]
736 #endif /* SIMPLE_MAC_PRINT */
737
738 #define MACOUIDBG "%02x:%x:%02x"
739 #define MACOUI2STRDBG(ea) ((uint8*)(ea))[0], ((uint8*)(ea))[1] & 0xf, ((uint8*)(ea))[2]
740
741 #define MACOUI "%02x:%02x:%02x"
742 #define MACOUI2STR(ea) ((uint8*)(ea))[0], ((uint8*)(ea))[1], ((uint8*)(ea))[2]
743
744 /* bcm_format_flags() bit description structure */
745 typedef struct bcm_bit_desc {
746 uint32 bit;
747 const char* name;
748 } bcm_bit_desc_t;
749
750 /* bcm_format_field */
751 typedef struct bcm_bit_desc_ex {
752 uint32 mask;
753 const bcm_bit_desc_t *bitfield;
754 } bcm_bit_desc_ex_t;
755
756 /* buffer length for ethernet address from bcm_ether_ntoa() */
757 #define ETHER_ADDR_STR_LEN 18 /* 18-bytes of Ethernet address buffer length */
758
759 static INLINE uint32 /* 32bit word aligned xor-32 */
bcm_compute_xor32(volatile uint32 * u32_val,int num_u32)760 bcm_compute_xor32(volatile uint32 *u32_val, int num_u32)
761 {
762 int idx;
763 uint32 xor32 = 0;
764 for (idx = 0; idx < num_u32; idx++)
765 xor32 ^= *(u32_val + idx);
766 return xor32;
767 }
768
769 /* crypto utility function */
770 /* 128-bit xor: *dst = *src1 xor *src2. dst1, src1 and src2 may have any alignment */
771 static INLINE void
xor_128bit_block(const uint8 * src1,const uint8 * src2,uint8 * dst)772 xor_128bit_block(const uint8 *src1, const uint8 *src2, uint8 *dst)
773 {
774 if (
775 #ifdef __i386__
776 1 ||
777 #endif // endif
778 (((uintptr)src1 | (uintptr)src2 | (uintptr)dst) & 3) == 0) {
779 /* ARM CM3 rel time: 1229 (727 if alignment check could be omitted) */
780 /* x86 supports unaligned. This version runs 6x-9x faster on x86. */
781 ((uint32 *)dst)[0] = ((const uint32 *)src1)[0] ^ ((const uint32 *)src2)[0];
782 ((uint32 *)dst)[1] = ((const uint32 *)src1)[1] ^ ((const uint32 *)src2)[1];
783 ((uint32 *)dst)[2] = ((const uint32 *)src1)[2] ^ ((const uint32 *)src2)[2];
784 ((uint32 *)dst)[3] = ((const uint32 *)src1)[3] ^ ((const uint32 *)src2)[3];
785 } else {
786 /* ARM CM3 rel time: 4668 (4191 if alignment check could be omitted) */
787 int k;
788 for (k = 0; k < 16; k++)
789 dst[k] = src1[k] ^ src2[k];
790 }
791 }
792
793 /* externs */
794 /* crc */
795 uint8 hndcrc8(const uint8 *p, uint nbytes, uint8 crc);
796 uint16 hndcrc16(const uint8 *p, uint nbytes, uint16 crc);
797 uint32 hndcrc32(const uint8 *p, uint nbytes, uint32 crc);
798
799 /* format/print */
800 #if defined(DHD_DEBUG) || defined(WLMSG_PRHDRS) || defined(WLMSG_PRPKT) || \
801 defined(WLMSG_ASSOC)
802 /* print out the value a field has: fields may have 1-32 bits and may hold any value */
803 extern int bcm_format_field(const bcm_bit_desc_ex_t *bd, uint32 field, char* buf, int len);
804 /* print out which bits in flags are set */
805 extern int bcm_format_flags(const bcm_bit_desc_t *bd, uint32 flags, char* buf, int len);
806 /* print out whcih bits in octet array 'addr' are set. bcm_bit_desc_t:bit is a bit offset. */
807 int bcm_format_octets(const bcm_bit_desc_t *bd, uint bdsz,
808 const uint8 *addr, uint size, char *buf, int len);
809 #endif // endif
810
811 extern int bcm_format_hex(char *str, const void *bytes, int len);
812
813 extern const char *bcm_crypto_algo_name(uint algo);
814 extern char *bcm_chipname(uint chipid, char *buf, uint len);
815 extern char *bcm_brev_str(uint32 brev, char *buf);
816 extern void printbig(char *buf);
817 extern void prhex(const char *msg, const uchar *buf, uint len);
818
819 /* bcmerror */
820 extern const char *bcmerrorstr(int bcmerror);
821
822 extern int wl_set_up_table(uint8 *up_table, bcm_tlv_t *qos_map_ie);
823
824 /* multi-bool data type: set of bools, mbool is true if any is set */
825 typedef uint32 mbool;
826 #define mboolset(mb, bit) ((mb) |= (bit)) /* set one bool */
827 #define mboolclr(mb, bit) ((mb) &= ~(bit)) /* clear one bool */
828 #define mboolisset(mb, bit) (((mb) & (bit)) != 0) /* TRUE if one bool is set */
829 #define mboolmaskset(mb, mask, val) ((mb) = (((mb) & ~(mask)) | (val)))
830
831 /* generic datastruct to help dump routines */
832 struct fielddesc {
833 const char *nameandfmt;
834 uint32 offset;
835 uint32 len;
836 };
837
838 extern void bcm_binit(struct bcmstrbuf *b, char *buf, uint size);
839 extern void bcm_bprhex(struct bcmstrbuf *b, const char *msg, bool newline,
840 const uint8 *buf, int len);
841
842 extern void bcm_inc_bytes(uchar *num, int num_bytes, uint8 amount);
843 extern int bcm_cmp_bytes(const uchar *arg1, const uchar *arg2, uint8 nbytes);
844 extern void bcm_print_bytes(const char *name, const uchar *cdata, int len);
845
846 typedef uint32 (*bcmutl_rdreg_rtn)(void *arg0, uint arg1, uint32 offset);
847 extern uint bcmdumpfields(bcmutl_rdreg_rtn func_ptr, void *arg0, uint arg1, struct fielddesc *str,
848 char *buf, uint32 bufsize);
849 extern uint bcm_bitcount(uint8 *bitmap, uint bytelength);
850
851 extern int bcm_bprintf(struct bcmstrbuf *b, const char *fmt, ...)
852 __attribute__ ((format (__printf__, 2, 0)));
853
854 /* power conversion */
855 extern uint16 bcm_qdbm_to_mw(uint8 qdbm);
856 extern uint8 bcm_mw_to_qdbm(uint16 mw);
857 extern uint bcm_mkiovar(const char *name, const char *data, uint datalen, char *buf, uint len);
858
859 unsigned int process_nvram_vars(char *varbuf, unsigned int len);
860 extern bool replace_nvram_variable(char *varbuf, unsigned int buflen, const char *variable,
861 unsigned int *datalen);
862
863 /* trace any object allocation / free, with / without features (flags) set to the object */
864
865 #define BCM_OBJDBG_ADD 1
866 #define BCM_OBJDBG_REMOVE 2
867 #define BCM_OBJDBG_ADD_PKT 3
868
869 /* object feature: set or clear flags */
870 #define BCM_OBJECT_FEATURE_FLAG 1
871 #define BCM_OBJECT_FEATURE_PKT_STATE 2
872 /* object feature: flag bits */
873 #define BCM_OBJECT_FEATURE_0 (1 << 0)
874 #define BCM_OBJECT_FEATURE_1 (1 << 1)
875 #define BCM_OBJECT_FEATURE_2 (1 << 2)
876 /* object feature: clear flag bits field set with this flag */
877 #define BCM_OBJECT_FEATURE_CLEAR (1 << 31)
878 #ifdef BCM_OBJECT_TRACE
879 #define bcm_pkt_validate_chk(obj) do { \
880 void * pkttag; \
881 bcm_object_trace_chk(obj, 0, 0, \
882 __FUNCTION__, __LINE__); \
883 if ((pkttag = PKTTAG(obj))) { \
884 bcm_object_trace_chk(obj, 1, DHD_PKTTAG_SN(pkttag), \
885 __FUNCTION__, __LINE__); \
886 } \
887 } while (0)
888 extern void bcm_object_trace_opr(void *obj, uint32 opt, const char *caller, int line);
889 extern void bcm_object_trace_upd(void *obj, void *obj_new);
890 extern void bcm_object_trace_chk(void *obj, uint32 chksn, uint32 sn,
891 const char *caller, int line);
892 extern void bcm_object_feature_set(void *obj, uint32 type, uint32 value);
893 extern int bcm_object_feature_get(void *obj, uint32 type, uint32 value);
894 extern void bcm_object_trace_init(void);
895 extern void bcm_object_trace_deinit(void);
896 #else
897 #define bcm_pkt_validate_chk(obj)
898 #define bcm_object_trace_opr(a, b, c, d)
899 #define bcm_object_trace_upd(a, b)
900 #define bcm_object_trace_chk(a, b, c, d, e)
901 #define bcm_object_feature_set(a, b, c)
902 #define bcm_object_feature_get(a, b, c)
903 #define bcm_object_trace_init()
904 #define bcm_object_trace_deinit()
905 #endif /* BCM_OBJECT_TRACE */
906
907 /* Public domain bit twiddling hacks/utilities: Sean Eron Anderson */
908
909 /* Table driven count set bits. */
910 static const uint8 /* Table only for use by bcm_cntsetbits */
911 _CSBTBL[256] =
912 {
913 # define B2(n) n, n + 1, n + 1, n + 2
914 # define B4(n) B2(n), B2(n + 1), B2(n + 1), B2(n + 2)
915 # define B6(n) B4(n), B4(n + 1), B4(n + 1), B4(n + 2)
916 B6(0), B6(0 + 1), B6(0 + 1), B6(0 + 2)
917 };
918
919 static INLINE uint32 /* Uses table _CSBTBL for fast counting of 1's in a u32 */
bcm_cntsetbits(const uint32 u32arg)920 bcm_cntsetbits(const uint32 u32arg)
921 {
922 /* function local scope declaration of const _CSBTBL[] */
923 const uint8 * p = (const uint8 *)&u32arg;
924 return (_CSBTBL[p[0]] + _CSBTBL[p[1]] + _CSBTBL[p[2]] + _CSBTBL[p[3]]);
925 }
926
927 static INLINE int /* C equivalent count of leading 0's in a u32 */
C_bcm_count_leading_zeros(uint32 u32arg)928 C_bcm_count_leading_zeros(uint32 u32arg)
929 {
930 int shifts = 0;
931 while (u32arg) {
932 shifts++; u32arg >>= 1;
933 }
934 return (32 - shifts);
935 }
936
937 /* the format of current TCM layout during boot
938 *
939 * Code Unused memory Random numbers Random number Magic number NVRAM NVRAM
940 * byte Count 0xFEEDC0DE Size
941 * |<-----Variable---->|<---Variable--->|<-----4 bytes-->|<---4 bytes---->|<---V--->|<--4B--->|
942 * |<------------- BCM_ENTROPY_HOST_MAXSIZE --------->|
943 */
944
945 /* The HOST need to provided 64 bytes (512 bits) entropy for the bcm SW RNG */
946 #define BCM_ENTROPY_MAGIC_SIZE 4u
947 #define BCM_ENTROPY_COUNT_SIZE 4u
948 #define BCM_ENTROPY_MIN_NBYTES 64u
949 #define BCM_ENTROPY_MAX_NBYTES 512u
950 #define BCM_ENTROPY_HOST_NBYTES 128u
951 #define BCM_ENTROPY_HOST_MAXSIZE \
952 (BCM_ENTROPY_MAGIC_SIZE + BCM_ENTROPY_COUNT_SIZE + BCM_ENTROPY_MAX_NBYTES)
953
954 /* Keep BCM MAX_RAND NUMBERS definition for the current dongle image. It will be
955 * removed after the dongle image is updated to use the bcm RNG.
956 */
957 #define BCM_MAX_RAND_NUMBERS 2u
958
959 /* Constant for calculate the location of host entropy input */
960 #define BCM_NVRAM_OFFSET_TCM 4u
961 #define BCM_NVRAM_IMG_COMPRS_FACTOR 4u
962 #define BCM_NVRAM_RNG_SIGNATURE 0xFEEDC0DEu
963
964 typedef struct bcm_rand_metadata {
965 uint32 count; /* number of random numbers in bytes */
966 uint32 signature; /* host fills it in, FW verfies before reading rand */
967 } bcm_rand_metadata_t;
968
969 #ifdef BCMDRIVER
970 /*
971 * Assembly instructions: Count Leading Zeros
972 * "clz" : MIPS, ARM
973 * "cntlzw" : PowerPC
974 * "BSF" : x86
975 * "lzcnt" : AMD, SPARC
976 */
977
978 #if defined(__arm__)
979 #if defined(__ARM_ARCH_7M__) /* Cortex M3 */
980 #define __USE_ASM_CLZ__
981 #endif /* __ARM_ARCH_7M__ */
982 #if defined(__ARM_ARCH_7R__) /* Cortex R4 */
983 #define __USE_ASM_CLZ__
984 #endif /* __ARM_ARCH_7R__ */
985 #endif /* __arm__ */
986
987 static INLINE int
bcm_count_leading_zeros(uint32 u32arg)988 bcm_count_leading_zeros(uint32 u32arg)
989 {
990 #if defined(__USE_ASM_CLZ__)
991 int zeros;
992 __asm__ volatile("clz %0, %1 \n" : "=r" (zeros) : "r" (u32arg));
993 return zeros;
994 #else /* C equivalent */
995 return C_bcm_count_leading_zeros(u32arg);
996 #endif /* C equivalent */
997 }
998
999 /*
1000 * Macro to count leading zeroes
1001 *
1002 */
1003 #if defined(__GNUC__)
1004 #define CLZ(x) __builtin_clzl(x)
1005 #elif defined(__arm__)
1006 #define CLZ(x) __clz(x)
1007 #else
1008 #define CLZ(x) bcm_count_leading_zeros(x)
1009 #endif /* __GNUC__ */
1010
1011 /* INTERFACE: Multiword bitmap based small id allocator. */
1012 struct bcm_mwbmap; /* forward declaration for use as an opaque mwbmap handle */
1013
1014 #define BCM_MWBMAP_INVALID_HDL ((struct bcm_mwbmap *)NULL)
1015 #define BCM_MWBMAP_INVALID_IDX ((uint32)(~0U))
1016
1017 /* Incarnate a multiword bitmap based small index allocator */
1018 extern struct bcm_mwbmap * bcm_mwbmap_init(osl_t * osh, uint32 items_max);
1019
1020 /* Free up the multiword bitmap index allocator */
1021 extern void bcm_mwbmap_fini(osl_t * osh, struct bcm_mwbmap * mwbmap_hdl);
1022
1023 /* Allocate a unique small index using a multiword bitmap index allocator */
1024 extern uint32 bcm_mwbmap_alloc(struct bcm_mwbmap * mwbmap_hdl);
1025
1026 /* Force an index at a specified position to be in use */
1027 extern void bcm_mwbmap_force(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix);
1028
1029 /* Free a previously allocated index back into the multiword bitmap allocator */
1030 extern void bcm_mwbmap_free(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix);
1031
1032 /* Fetch the toal number of free indices in the multiword bitmap allocator */
1033 extern uint32 bcm_mwbmap_free_cnt(struct bcm_mwbmap * mwbmap_hdl);
1034
1035 /* Determine whether an index is inuse or free */
1036 extern bool bcm_mwbmap_isfree(struct bcm_mwbmap * mwbmap_hdl, uint32 bitix);
1037
1038 /* Debug dump a multiword bitmap allocator */
1039 extern void bcm_mwbmap_show(struct bcm_mwbmap * mwbmap_hdl);
1040
1041 extern void bcm_mwbmap_audit(struct bcm_mwbmap * mwbmap_hdl);
1042 /* End - Multiword bitmap based small Id allocator. */
1043
1044 /* INTERFACE: Simple unique 16bit Id Allocator using a stack implementation. */
1045
1046 #define ID8_INVALID 0xFFu
1047 #define ID16_INVALID 0xFFFFu
1048 #define ID32_INVALID 0xFFFFFFFFu
1049 #define ID16_UNDEFINED ID16_INVALID
1050
1051 /*
1052 * Construct a 16bit id allocator, managing 16bit ids in the range:
1053 * [start_val16 .. start_val16+total_ids)
1054 * Note: start_val16 is inclusive.
1055 * Returns an opaque handle to the 16bit id allocator.
1056 */
1057 extern void * id16_map_init(osl_t *osh, uint16 total_ids, uint16 start_val16);
1058 extern void * id16_map_fini(osl_t *osh, void * id16_map_hndl);
1059 extern void id16_map_clear(void * id16_map_hndl, uint16 total_ids, uint16 start_val16);
1060
1061 /* Allocate a unique 16bit id */
1062 extern uint16 id16_map_alloc(void * id16_map_hndl);
1063
1064 /* Free a 16bit id value into the id16 allocator */
1065 extern void id16_map_free(void * id16_map_hndl, uint16 val16);
1066
1067 /* Get the number of failures encountered during id allocation. */
1068 extern uint32 id16_map_failures(void * id16_map_hndl);
1069
1070 /* Audit the 16bit id allocator state. */
1071 extern bool id16_map_audit(void * id16_map_hndl);
1072 /* End - Simple 16bit Id Allocator. */
1073 #endif /* BCMDRIVER */
1074
1075 #define MASK_32_BITS (~0)
1076 #define MASK_8_BITS ((1 << 8) - 1)
1077
1078 #define EXTRACT_LOW32(num) (uint32)(num & MASK_32_BITS)
1079 #define EXTRACT_HIGH32(num) (uint32)(((uint64)num >> 32) & MASK_32_BITS)
1080
1081 #define MAXIMUM(a, b) ((a > b) ? a : b)
1082 #define MINIMUM(a, b) ((a < b) ? a : b)
1083 #define LIMIT(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))
1084
1085 /* calculate checksum for ip header, tcp / udp header / data */
1086 uint16 bcm_ip_cksum(uint8 *buf, uint32 len, uint32 sum);
1087
1088 #ifndef _dll_t_
1089 #define _dll_t_
1090 /*
1091 * -----------------------------------------------------------------------------
1092 * Double Linked List Macros
1093 * -----------------------------------------------------------------------------
1094 *
1095 * All dll operations must be performed on a pre-initialized node.
1096 * Inserting an uninitialized node into a list effectively initialized it.
1097 *
1098 * When a node is deleted from a list, you may initialize it to avoid corruption
1099 * incurred by double deletion. You may skip initialization if the node is
1100 * immediately inserted into another list.
1101 *
1102 * By placing a dll_t element at the start of a struct, you may cast a dll_t *
1103 * to the struct or vice versa.
1104 *
1105 * Example of declaring an initializing someList and inserting nodeA, nodeB
1106 *
1107 * typedef struct item {
1108 * dll_t node;
1109 * int someData;
1110 * } Item_t;
1111 * Item_t nodeA, nodeB, nodeC;
1112 * nodeA.someData = 11111, nodeB.someData = 22222, nodeC.someData = 33333;
1113 *
1114 * dll_t someList;
1115 * dll_init(&someList);
1116 *
1117 * dll_append(&someList, (dll_t *) &nodeA);
1118 * dll_prepend(&someList, &nodeB.node);
1119 * dll_insert((dll_t *)&nodeC, &nodeA.node);
1120 *
1121 * dll_delete((dll_t *) &nodeB);
1122 *
1123 * Example of a for loop to walk someList of node_p
1124 *
1125 * extern void mydisplay(Item_t * item_p);
1126 *
1127 * dll_t * item_p, * next_p;
1128 * for (item_p = dll_head_p(&someList); ! dll_end(&someList, item_p);
1129 * item_p = next_p)
1130 * {
1131 * next_p = dll_next_p(item_p);
1132 * ... use item_p at will, including removing it from list ...
1133 * mydisplay((PItem_t)item_p);
1134 * }
1135 *
1136 * -----------------------------------------------------------------------------
1137 */
1138 typedef struct dll {
1139 struct dll * next_p;
1140 struct dll * prev_p;
1141 } dll_t;
1142
1143 static INLINE void
dll_init(dll_t * node_p)1144 dll_init(dll_t *node_p)
1145 {
1146 node_p->next_p = node_p;
1147 node_p->prev_p = node_p;
1148 }
1149 /* dll macros returing a pointer to dll_t */
1150
1151 static INLINE dll_t *
dll_head_p(dll_t * list_p)1152 dll_head_p(dll_t *list_p)
1153 {
1154 return list_p->next_p;
1155 }
1156
1157 static INLINE dll_t *
dll_tail_p(dll_t * list_p)1158 dll_tail_p(dll_t *list_p)
1159 {
1160 return (list_p)->prev_p;
1161 }
1162
1163 static INLINE dll_t *
dll_next_p(dll_t * node_p)1164 dll_next_p(dll_t *node_p)
1165 {
1166 return (node_p)->next_p;
1167 }
1168
1169 static INLINE dll_t *
dll_prev_p(dll_t * node_p)1170 dll_prev_p(dll_t *node_p)
1171 {
1172 return (node_p)->prev_p;
1173 }
1174
1175 static INLINE bool
dll_empty(dll_t * list_p)1176 dll_empty(dll_t *list_p)
1177 {
1178 return ((list_p)->next_p == (list_p));
1179 }
1180
1181 static INLINE bool
dll_end(dll_t * list_p,dll_t * node_p)1182 dll_end(dll_t *list_p, dll_t * node_p)
1183 {
1184 return (list_p == node_p);
1185 }
1186
1187 /* inserts the node new_p "after" the node at_p */
1188 static INLINE void
dll_insert(dll_t * new_p,dll_t * at_p)1189 dll_insert(dll_t *new_p, dll_t * at_p)
1190 {
1191 new_p->next_p = at_p->next_p;
1192 new_p->prev_p = at_p;
1193 at_p->next_p = new_p;
1194 (new_p->next_p)->prev_p = new_p;
1195 }
1196
1197 static INLINE void
dll_append(dll_t * list_p,dll_t * node_p)1198 dll_append(dll_t *list_p, dll_t *node_p)
1199 {
1200 dll_insert(node_p, dll_tail_p(list_p));
1201 }
1202
1203 static INLINE void
dll_prepend(dll_t * list_p,dll_t * node_p)1204 dll_prepend(dll_t *list_p, dll_t *node_p)
1205 {
1206 dll_insert(node_p, list_p);
1207 }
1208
1209 /* deletes a node from any list that it "may" be in, if at all. */
1210 static INLINE void
dll_delete(dll_t * node_p)1211 dll_delete(dll_t *node_p)
1212 {
1213 node_p->prev_p->next_p = node_p->next_p;
1214 node_p->next_p->prev_p = node_p->prev_p;
1215 }
1216 #endif /* ! defined(_dll_t_) */
1217
1218 /* Elements managed in a double linked list */
1219
1220 typedef struct dll_pool {
1221 dll_t free_list;
1222 uint16 free_count;
1223 uint16 elems_max;
1224 uint16 elem_size;
1225 dll_t elements[1];
1226 } dll_pool_t;
1227
1228 dll_pool_t * dll_pool_init(void * osh, uint16 elems_max, uint16 elem_size);
1229 void * dll_pool_alloc(dll_pool_t * dll_pool_p);
1230 void dll_pool_free(dll_pool_t * dll_pool_p, void * elem_p);
1231 void dll_pool_free_tail(dll_pool_t * dll_pool_p, void * elem_p);
1232 typedef void (* dll_elem_dump)(void * elem_p);
1233 void dll_pool_detach(void * osh, dll_pool_t * pool, uint16 elems_max, uint16 elem_size);
1234
1235 int valid_bcmerror(int e);
1236
1237 /* calculate IPv4 header checksum
1238 * - input ip points to IP header in network order
1239 * - output cksum is in network order
1240 */
1241 uint16 ipv4_hdr_cksum(uint8 *ip, int ip_len);
1242
1243 /* calculate IPv4 TCP header checksum
1244 * - input ip and tcp points to IP and TCP header in network order
1245 * - output cksum is in network order
1246 */
1247 uint16 ipv4_tcp_hdr_cksum(uint8 *ip, uint8 *tcp, uint16 tcp_len);
1248
1249 /* calculate IPv6 TCP header checksum
1250 * - input ipv6 and tcp points to IPv6 and TCP header in network order
1251 * - output cksum is in network order
1252 */
1253 uint16 ipv6_tcp_hdr_cksum(uint8 *ipv6, uint8 *tcp, uint16 tcp_len);
1254
1255 #ifdef __cplusplus
1256 }
1257 #endif // endif
1258
1259 /* #define DEBUG_COUNTER */
1260 #ifdef DEBUG_COUNTER
1261 #define CNTR_TBL_MAX 10
1262 typedef struct _counter_tbl_t {
1263 char name[16]; /* name of this counter table */
1264 uint32 prev_log_print; /* Internal use. Timestamp of the previous log print */
1265 uint log_print_interval; /* Desired interval to print logs in ms */
1266 uint needed_cnt; /* How many counters need to be used */
1267 uint32 cnt[CNTR_TBL_MAX]; /* Counting entries to increase at desired places */
1268 bool enabled; /* Whether to enable printing log */
1269 } counter_tbl_t;
1270
1271 void counter_printlog(counter_tbl_t *ctr_tbl);
1272 #endif /* DEBUG_COUNTER */
1273
1274 #if defined(__GNUC__)
1275 #define CALL_SITE __builtin_return_address(0)
1276 #else
1277 #define CALL_SITE ((void*) 0)
1278 #endif // endif
1279 #ifdef SHOW_LOGTRACE
1280 #define TRACE_LOG_BUF_MAX_SIZE 1700
1281 #define RTT_LOG_BUF_MAX_SIZE 1700
1282 #define BUF_NOT_AVAILABLE 0
1283 #define NEXT_BUF_NOT_AVAIL 1
1284 #define NEXT_BUF_AVAIL 2
1285
1286 typedef struct trace_buf_info {
1287 int availability;
1288 int size;
1289 char buf[TRACE_LOG_BUF_MAX_SIZE];
1290 } trace_buf_info_t;
1291 #endif /* SHOW_LOGTRACE */
1292
1293 enum dump_dongle_e {
1294 DUMP_DONGLE_COREREG = 0,
1295 DUMP_DONGLE_D11MEM
1296 };
1297
1298 typedef struct {
1299 uint32 type; /**< specifies e.g dump of d11 memory, use enum dump_dongle_e */
1300 uint32 index; /**< iterator1, specifies core index or d11 memory index */
1301 uint32 offset; /**< iterator2, byte offset within register set or memory */
1302 } dump_dongle_in_t;
1303
1304 typedef struct {
1305 uint32 address; /**< e.g. backplane address of register */
1306 uint32 id; /**< id, e.g. core id */
1307 uint32 rev; /**< rev, e.g. core rev */
1308 uint32 n_bytes; /**< nbytes in array val[] */
1309 uint32 val[1]; /**< out: values that were read out of registers or memory */
1310 } dump_dongle_out_t;
1311
1312 extern uint32 sqrt_int(uint32 value);
1313
1314 #ifdef BCMDRIVER
1315 /* structures and routines to process variable sized data */
1316 typedef struct var_len_data {
1317 uint32 vlen;
1318 uint8 *vdata;
1319 } var_len_data_t;
1320
1321 int bcm_vdata_alloc(osl_t *osh, var_len_data_t *vld, uint32 size);
1322 int bcm_vdata_free(osl_t *osh, var_len_data_t *vld);
1323 #endif /* BCMDRIVER */
1324
1325 /* Count the number of elements in an array that do not match the given value */
1326 extern int array_value_mismatch_count(uint8 value, uint8 *array, int array_size);
1327 /* Count the number of non-zero elements in an uint8 array */
1328 extern int array_nonzero_count(uint8 *array, int array_size);
1329 /* Count the number of non-zero elements in an int16 array */
1330 extern int array_nonzero_count_int16(int16 *array, int array_size);
1331 /* Count the number of zero elements in an uint8 array */
1332 extern int array_zero_count(uint8 *array, int array_size);
1333 /* Validate a uint8 ordered array. Assert if invalid. */
1334 extern int verify_ordered_array_uint8(uint8 *array, int array_size, uint8 range_lo, uint8 range_hi);
1335 /* Validate a int16 configuration array that need not be zero-terminated. Assert if invalid. */
1336 extern int verify_ordered_array_int16(int16 *array, int array_size, int16 range_lo, int16 range_hi);
1337 /* Validate all values in an array are in range */
1338 extern int verify_array_values(uint8 *array, int array_size,
1339 int range_lo, int range_hi, bool zero_terminated);
1340
1341 #endif /* _bcmutils_h_ */
1342