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