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