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