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