xref: /freebsd/sys/dev/bxe/bxe.c (revision 2f513db72b034fd5ef7f080b11be5c711c15186a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  * THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #define BXE_DRIVER_VERSION "1.78.91"
33 
34 #include "bxe.h"
35 #include "ecore_sp.h"
36 #include "ecore_init.h"
37 #include "ecore_init_ops.h"
38 
39 #include "57710_int_offsets.h"
40 #include "57711_int_offsets.h"
41 #include "57712_int_offsets.h"
42 
43 /*
44  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
45  * explicitly here for older kernels that don't include this changeset.
46  */
47 #ifndef CTLTYPE_U64
48 #define CTLTYPE_U64      CTLTYPE_QUAD
49 #define sysctl_handle_64 sysctl_handle_quad
50 #endif
51 
52 /*
53  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
54  * here as zero(0) for older kernels that don't include this changeset
55  * thereby masking the functionality.
56  */
57 #ifndef CSUM_TCP_IPV6
58 #define CSUM_TCP_IPV6 0
59 #define CSUM_UDP_IPV6 0
60 #endif
61 
62 /*
63  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
64  * for older kernels that don't include this changeset.
65  */
66 #if __FreeBSD_version < 900035
67 #define pci_find_cap pci_find_extcap
68 #endif
69 
70 #define BXE_DEF_SB_ATT_IDX 0x0001
71 #define BXE_DEF_SB_IDX     0x0002
72 
73 /*
74  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
75  * function HW initialization.
76  */
77 #define FLR_WAIT_USEC     10000 /* 10 msecs */
78 #define FLR_WAIT_INTERVAL 50    /* usecs */
79 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
80 
81 struct pbf_pN_buf_regs {
82     int pN;
83     uint32_t init_crd;
84     uint32_t crd;
85     uint32_t crd_freed;
86 };
87 
88 struct pbf_pN_cmd_regs {
89     int pN;
90     uint32_t lines_occup;
91     uint32_t lines_freed;
92 };
93 
94 /*
95  * PCI Device ID Table used by bxe_probe().
96  */
97 #define BXE_DEVDESC_MAX 64
98 static struct bxe_device_type bxe_devs[] = {
99     {
100         BRCM_VENDORID,
101         CHIP_NUM_57710,
102         PCI_ANY_ID, PCI_ANY_ID,
103         "QLogic NetXtreme II BCM57710 10GbE"
104     },
105     {
106         BRCM_VENDORID,
107         CHIP_NUM_57711,
108         PCI_ANY_ID, PCI_ANY_ID,
109         "QLogic NetXtreme II BCM57711 10GbE"
110     },
111     {
112         BRCM_VENDORID,
113         CHIP_NUM_57711E,
114         PCI_ANY_ID, PCI_ANY_ID,
115         "QLogic NetXtreme II BCM57711E 10GbE"
116     },
117     {
118         BRCM_VENDORID,
119         CHIP_NUM_57712,
120         PCI_ANY_ID, PCI_ANY_ID,
121         "QLogic NetXtreme II BCM57712 10GbE"
122     },
123     {
124         BRCM_VENDORID,
125         CHIP_NUM_57712_MF,
126         PCI_ANY_ID, PCI_ANY_ID,
127         "QLogic NetXtreme II BCM57712 MF 10GbE"
128     },
129     {
130         BRCM_VENDORID,
131         CHIP_NUM_57800,
132         PCI_ANY_ID, PCI_ANY_ID,
133         "QLogic NetXtreme II BCM57800 10GbE"
134     },
135     {
136         BRCM_VENDORID,
137         CHIP_NUM_57800_MF,
138         PCI_ANY_ID, PCI_ANY_ID,
139         "QLogic NetXtreme II BCM57800 MF 10GbE"
140     },
141     {
142         BRCM_VENDORID,
143         CHIP_NUM_57810,
144         PCI_ANY_ID, PCI_ANY_ID,
145         "QLogic NetXtreme II BCM57810 10GbE"
146     },
147     {
148         BRCM_VENDORID,
149         CHIP_NUM_57810_MF,
150         PCI_ANY_ID, PCI_ANY_ID,
151         "QLogic NetXtreme II BCM57810 MF 10GbE"
152     },
153     {
154         BRCM_VENDORID,
155         CHIP_NUM_57811,
156         PCI_ANY_ID, PCI_ANY_ID,
157         "QLogic NetXtreme II BCM57811 10GbE"
158     },
159     {
160         BRCM_VENDORID,
161         CHIP_NUM_57811_MF,
162         PCI_ANY_ID, PCI_ANY_ID,
163         "QLogic NetXtreme II BCM57811 MF 10GbE"
164     },
165     {
166         BRCM_VENDORID,
167         CHIP_NUM_57840_4_10,
168         PCI_ANY_ID, PCI_ANY_ID,
169         "QLogic NetXtreme II BCM57840 4x10GbE"
170     },
171     {
172         QLOGIC_VENDORID,
173         CHIP_NUM_57840_4_10,
174         PCI_ANY_ID, PCI_ANY_ID,
175         "QLogic NetXtreme II BCM57840 4x10GbE"
176     },
177     {
178         BRCM_VENDORID,
179         CHIP_NUM_57840_2_20,
180         PCI_ANY_ID, PCI_ANY_ID,
181         "QLogic NetXtreme II BCM57840 2x20GbE"
182     },
183     {
184         BRCM_VENDORID,
185         CHIP_NUM_57840_MF,
186         PCI_ANY_ID, PCI_ANY_ID,
187         "QLogic NetXtreme II BCM57840 MF 10GbE"
188     },
189     {
190         0, 0, 0, 0, NULL
191     }
192 };
193 
194 MALLOC_DECLARE(M_BXE_ILT);
195 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
196 
197 /*
198  * FreeBSD device entry points.
199  */
200 static int bxe_probe(device_t);
201 static int bxe_attach(device_t);
202 static int bxe_detach(device_t);
203 static int bxe_shutdown(device_t);
204 
205 
206 /*
207  * FreeBSD KLD module/device interface event handler method.
208  */
209 static device_method_t bxe_methods[] = {
210     /* Device interface (device_if.h) */
211     DEVMETHOD(device_probe,     bxe_probe),
212     DEVMETHOD(device_attach,    bxe_attach),
213     DEVMETHOD(device_detach,    bxe_detach),
214     DEVMETHOD(device_shutdown,  bxe_shutdown),
215     /* Bus interface (bus_if.h) */
216     DEVMETHOD(bus_print_child,  bus_generic_print_child),
217     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
218     KOBJMETHOD_END
219 };
220 
221 /*
222  * FreeBSD KLD Module data declaration
223  */
224 static driver_t bxe_driver = {
225     "bxe",                   /* module name */
226     bxe_methods,             /* event handler */
227     sizeof(struct bxe_softc) /* extra data */
228 };
229 
230 /*
231  * FreeBSD dev class is needed to manage dev instances and
232  * to associate with a bus type
233  */
234 static devclass_t bxe_devclass;
235 
236 MODULE_DEPEND(bxe, pci, 1, 1, 1);
237 MODULE_DEPEND(bxe, ether, 1, 1, 1);
238 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
239 
240 DEBUGNET_DEFINE(bxe);
241 
242 /* resources needed for unloading a previously loaded device */
243 
244 #define BXE_PREV_WAIT_NEEDED 1
245 struct mtx bxe_prev_mtx;
246 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
247 struct bxe_prev_list_node {
248     LIST_ENTRY(bxe_prev_list_node) node;
249     uint8_t bus;
250     uint8_t slot;
251     uint8_t path;
252     uint8_t aer; /* XXX automatic error recovery */
253     uint8_t undi;
254 };
255 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
256 
257 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
258 
259 /* Tunable device values... */
260 
261 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
262 
263 /* Debug */
264 unsigned long bxe_debug = 0;
265 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
266              &bxe_debug, 0, "Debug logging mode");
267 
268 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
269 static int bxe_interrupt_mode = INTR_MODE_MSIX;
270 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
271            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
272 
273 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
274 static int bxe_queue_count = 4;
275 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
276            &bxe_queue_count, 0, "Multi-Queue queue count");
277 
278 /* max number of buffers per queue (default RX_BD_USABLE) */
279 static int bxe_max_rx_bufs = 0;
280 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
281            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
282 
283 /* Host interrupt coalescing RX tick timer (usecs) */
284 static int bxe_hc_rx_ticks = 25;
285 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
286            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
287 
288 /* Host interrupt coalescing TX tick timer (usecs) */
289 static int bxe_hc_tx_ticks = 50;
290 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
291            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
292 
293 /* Maximum number of Rx packets to process at a time */
294 static int bxe_rx_budget = 0xffffffff;
295 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
296            &bxe_rx_budget, 0, "Rx processing budget");
297 
298 /* Maximum LRO aggregation size */
299 static int bxe_max_aggregation_size = 0;
300 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
301            &bxe_max_aggregation_size, 0, "max aggregation size");
302 
303 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
304 static int bxe_mrrs = -1;
305 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
306            &bxe_mrrs, 0, "PCIe maximum read request size");
307 
308 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
309 static int bxe_autogreeen = 0;
310 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
311            &bxe_autogreeen, 0, "AutoGrEEEn support");
312 
313 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
314 static int bxe_udp_rss = 0;
315 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
316            &bxe_udp_rss, 0, "UDP RSS support");
317 
318 
319 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
320 
321 #define STATS_OFFSET32(stat_name)                   \
322     (offsetof(struct bxe_eth_stats, stat_name) / 4)
323 
324 #define Q_STATS_OFFSET32(stat_name)                   \
325     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
326 
327 static const struct {
328     uint32_t offset;
329     uint32_t size;
330     uint32_t flags;
331 #define STATS_FLAGS_PORT  1
332 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
333 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
334     char string[STAT_NAME_LEN];
335 } bxe_eth_stats_arr[] = {
336     { STATS_OFFSET32(total_bytes_received_hi),
337                 8, STATS_FLAGS_BOTH, "rx_bytes" },
338     { STATS_OFFSET32(error_bytes_received_hi),
339                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
340     { STATS_OFFSET32(total_unicast_packets_received_hi),
341                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
342     { STATS_OFFSET32(total_multicast_packets_received_hi),
343                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
344     { STATS_OFFSET32(total_broadcast_packets_received_hi),
345                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
346     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
347                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
348     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
349                 8, STATS_FLAGS_PORT, "rx_align_errors" },
350     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
351                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
352     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
353                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
354     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
355                 8, STATS_FLAGS_PORT, "rx_fragments" },
356     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
357                 8, STATS_FLAGS_PORT, "rx_jabbers" },
358     { STATS_OFFSET32(no_buff_discard_hi),
359                 8, STATS_FLAGS_BOTH, "rx_discards" },
360     { STATS_OFFSET32(mac_filter_discard),
361                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
362     { STATS_OFFSET32(mf_tag_discard),
363                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
364     { STATS_OFFSET32(pfc_frames_received_hi),
365                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
366     { STATS_OFFSET32(pfc_frames_sent_hi),
367                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
368     { STATS_OFFSET32(brb_drop_hi),
369                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
370     { STATS_OFFSET32(brb_truncate_hi),
371                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
372     { STATS_OFFSET32(pause_frames_received_hi),
373                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
374     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
375                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
376     { STATS_OFFSET32(nig_timer_max),
377                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
378     { STATS_OFFSET32(total_bytes_transmitted_hi),
379                 8, STATS_FLAGS_BOTH, "tx_bytes" },
380     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
381                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
382     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
383                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
384     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
385                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
386     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
387                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
388     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
389                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
390     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
391                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
392     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
393                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
394     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
395                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
396     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
397                 8, STATS_FLAGS_PORT, "tx_deferred" },
398     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
399                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
400     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
401                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
402     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
403                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
404     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
405                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
406     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
407                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
408     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
409                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
410     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
411                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
412     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
413                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
414     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
415                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
416     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
417                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
418     { STATS_OFFSET32(pause_frames_sent_hi),
419                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
420     { STATS_OFFSET32(total_tpa_aggregations_hi),
421                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
422     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
423                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
424     { STATS_OFFSET32(total_tpa_bytes_hi),
425                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
426     { STATS_OFFSET32(eee_tx_lpi),
427                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
428     { STATS_OFFSET32(rx_calls),
429                 4, STATS_FLAGS_FUNC, "rx_calls"},
430     { STATS_OFFSET32(rx_pkts),
431                 4, STATS_FLAGS_FUNC, "rx_pkts"},
432     { STATS_OFFSET32(rx_tpa_pkts),
433                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
434     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
435                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
436     { STATS_OFFSET32(rx_bxe_service_rxsgl),
437                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
438     { STATS_OFFSET32(rx_jumbo_sge_pkts),
439                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
440     { STATS_OFFSET32(rx_soft_errors),
441                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
442     { STATS_OFFSET32(rx_hw_csum_errors),
443                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
444     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
445                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
446     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
447                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
448     { STATS_OFFSET32(rx_budget_reached),
449                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
450     { STATS_OFFSET32(tx_pkts),
451                 4, STATS_FLAGS_FUNC, "tx_pkts"},
452     { STATS_OFFSET32(tx_soft_errors),
453                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
454     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
455                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
456     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
457                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
458     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
459                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
460     { STATS_OFFSET32(tx_ofld_frames_lso),
461                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
462     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
463                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
464     { STATS_OFFSET32(tx_encap_failures),
465                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
466     { STATS_OFFSET32(tx_hw_queue_full),
467                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
468     { STATS_OFFSET32(tx_hw_max_queue_depth),
469                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
470     { STATS_OFFSET32(tx_dma_mapping_failure),
471                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
472     { STATS_OFFSET32(tx_max_drbr_queue_depth),
473                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
474     { STATS_OFFSET32(tx_window_violation_std),
475                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
476     { STATS_OFFSET32(tx_window_violation_tso),
477                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
478     { STATS_OFFSET32(tx_chain_lost_mbuf),
479                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
480     { STATS_OFFSET32(tx_frames_deferred),
481                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
482     { STATS_OFFSET32(tx_queue_xoff),
483                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
484     { STATS_OFFSET32(mbuf_defrag_attempts),
485                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
486     { STATS_OFFSET32(mbuf_defrag_failures),
487                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
488     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
489                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
490     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
491                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
492     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
493                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
494     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
495                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
496     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
497                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
498     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
499                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
500     { STATS_OFFSET32(mbuf_alloc_tx),
501                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
502     { STATS_OFFSET32(mbuf_alloc_rx),
503                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
504     { STATS_OFFSET32(mbuf_alloc_sge),
505                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
506     { STATS_OFFSET32(mbuf_alloc_tpa),
507                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
508     { STATS_OFFSET32(tx_queue_full_return),
509                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
510     { STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
511                 4, STATS_FLAGS_FUNC, "bxe_tx_mq_sc_state_failures"},
512     { STATS_OFFSET32(tx_request_link_down_failures),
513                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
514     { STATS_OFFSET32(bd_avail_too_less_failures),
515                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
516     { STATS_OFFSET32(tx_mq_not_empty),
517                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"},
518     { STATS_OFFSET32(nsegs_path1_errors),
519                 4, STATS_FLAGS_FUNC, "nsegs_path1_errors"},
520     { STATS_OFFSET32(nsegs_path2_errors),
521                 4, STATS_FLAGS_FUNC, "nsegs_path2_errors"}
522 
523 
524 };
525 
526 static const struct {
527     uint32_t offset;
528     uint32_t size;
529     char string[STAT_NAME_LEN];
530 } bxe_eth_q_stats_arr[] = {
531     { Q_STATS_OFFSET32(total_bytes_received_hi),
532                 8, "rx_bytes" },
533     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
534                 8, "rx_ucast_packets" },
535     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
536                 8, "rx_mcast_packets" },
537     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
538                 8, "rx_bcast_packets" },
539     { Q_STATS_OFFSET32(no_buff_discard_hi),
540                 8, "rx_discards" },
541     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
542                 8, "tx_bytes" },
543     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
544                 8, "tx_ucast_packets" },
545     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
546                 8, "tx_mcast_packets" },
547     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
548                 8, "tx_bcast_packets" },
549     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
550                 8, "tpa_aggregations" },
551     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
552                 8, "tpa_aggregated_frames"},
553     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
554                 8, "tpa_bytes"},
555     { Q_STATS_OFFSET32(rx_calls),
556                 4, "rx_calls"},
557     { Q_STATS_OFFSET32(rx_pkts),
558                 4, "rx_pkts"},
559     { Q_STATS_OFFSET32(rx_tpa_pkts),
560                 4, "rx_tpa_pkts"},
561     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
562                 4, "rx_erroneous_jumbo_sge_pkts"},
563     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
564                 4, "rx_bxe_service_rxsgl"},
565     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
566                 4, "rx_jumbo_sge_pkts"},
567     { Q_STATS_OFFSET32(rx_soft_errors),
568                 4, "rx_soft_errors"},
569     { Q_STATS_OFFSET32(rx_hw_csum_errors),
570                 4, "rx_hw_csum_errors"},
571     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
572                 4, "rx_ofld_frames_csum_ip"},
573     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
574                 4, "rx_ofld_frames_csum_tcp_udp"},
575     { Q_STATS_OFFSET32(rx_budget_reached),
576                 4, "rx_budget_reached"},
577     { Q_STATS_OFFSET32(tx_pkts),
578                 4, "tx_pkts"},
579     { Q_STATS_OFFSET32(tx_soft_errors),
580                 4, "tx_soft_errors"},
581     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
582                 4, "tx_ofld_frames_csum_ip"},
583     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
584                 4, "tx_ofld_frames_csum_tcp"},
585     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
586                 4, "tx_ofld_frames_csum_udp"},
587     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
588                 4, "tx_ofld_frames_lso"},
589     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
590                 4, "tx_ofld_frames_lso_hdr_splits"},
591     { Q_STATS_OFFSET32(tx_encap_failures),
592                 4, "tx_encap_failures"},
593     { Q_STATS_OFFSET32(tx_hw_queue_full),
594                 4, "tx_hw_queue_full"},
595     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
596                 4, "tx_hw_max_queue_depth"},
597     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
598                 4, "tx_dma_mapping_failure"},
599     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
600                 4, "tx_max_drbr_queue_depth"},
601     { Q_STATS_OFFSET32(tx_window_violation_std),
602                 4, "tx_window_violation_std"},
603     { Q_STATS_OFFSET32(tx_window_violation_tso),
604                 4, "tx_window_violation_tso"},
605     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
606                 4, "tx_chain_lost_mbuf"},
607     { Q_STATS_OFFSET32(tx_frames_deferred),
608                 4, "tx_frames_deferred"},
609     { Q_STATS_OFFSET32(tx_queue_xoff),
610                 4, "tx_queue_xoff"},
611     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
612                 4, "mbuf_defrag_attempts"},
613     { Q_STATS_OFFSET32(mbuf_defrag_failures),
614                 4, "mbuf_defrag_failures"},
615     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
616                 4, "mbuf_rx_bd_alloc_failed"},
617     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
618                 4, "mbuf_rx_bd_mapping_failed"},
619     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
620                 4, "mbuf_rx_tpa_alloc_failed"},
621     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
622                 4, "mbuf_rx_tpa_mapping_failed"},
623     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
624                 4, "mbuf_rx_sge_alloc_failed"},
625     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
626                 4, "mbuf_rx_sge_mapping_failed"},
627     { Q_STATS_OFFSET32(mbuf_alloc_tx),
628                 4, "mbuf_alloc_tx"},
629     { Q_STATS_OFFSET32(mbuf_alloc_rx),
630                 4, "mbuf_alloc_rx"},
631     { Q_STATS_OFFSET32(mbuf_alloc_sge),
632                 4, "mbuf_alloc_sge"},
633     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
634                 4, "mbuf_alloc_tpa"},
635     { Q_STATS_OFFSET32(tx_queue_full_return),
636                 4, "tx_queue_full_return"},
637     { Q_STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
638                 4, "bxe_tx_mq_sc_state_failures"},
639     { Q_STATS_OFFSET32(tx_request_link_down_failures),
640                 4, "tx_request_link_down_failures"},
641     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
642                 4, "bd_avail_too_less_failures"},
643     { Q_STATS_OFFSET32(tx_mq_not_empty),
644                 4, "tx_mq_not_empty"},
645     { Q_STATS_OFFSET32(nsegs_path1_errors),
646                 4, "nsegs_path1_errors"},
647     { Q_STATS_OFFSET32(nsegs_path2_errors),
648                 4, "nsegs_path2_errors"}
649 
650 
651 };
652 
653 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
654 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
655 
656 
657 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
658                                  uint8_t          read_cfg,
659                                  uint8_t          cmng_type);
660 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
661 static void    storm_memset_cmng(struct bxe_softc *sc,
662                                  struct cmng_init *cmng,
663                                  uint8_t          port);
664 static void    bxe_set_reset_global(struct bxe_softc *sc);
665 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
666 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
667                                  int              engine);
668 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
669 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
670                                    uint8_t          *global,
671                                    uint8_t          print);
672 static void    bxe_int_disable(struct bxe_softc *sc);
673 static int     bxe_release_leader_lock(struct bxe_softc *sc);
674 static void    bxe_pf_disable(struct bxe_softc *sc);
675 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
676 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
677                                       struct bxe_fastpath *fp,
678                                       uint16_t            rx_bd_prod,
679                                       uint16_t            rx_cq_prod,
680                                       uint16_t            rx_sge_prod);
681 static void    bxe_link_report_locked(struct bxe_softc *sc);
682 static void    bxe_link_report(struct bxe_softc *sc);
683 static void    bxe_link_status_update(struct bxe_softc *sc);
684 static void    bxe_periodic_callout_func(void *xsc);
685 static void    bxe_periodic_start(struct bxe_softc *sc);
686 static void    bxe_periodic_stop(struct bxe_softc *sc);
687 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
688                                     uint16_t prev_index,
689                                     uint16_t index);
690 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
691                                      int                 queue);
692 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
693                                      uint16_t            index);
694 static uint8_t bxe_txeof(struct bxe_softc *sc,
695                          struct bxe_fastpath *fp);
696 static void    bxe_task_fp(struct bxe_fastpath *fp);
697 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
698                                      struct mbuf      *m,
699                                      uint8_t          contents);
700 static int     bxe_alloc_mem(struct bxe_softc *sc);
701 static void    bxe_free_mem(struct bxe_softc *sc);
702 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
703 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
704 static int     bxe_interrupt_attach(struct bxe_softc *sc);
705 static void    bxe_interrupt_detach(struct bxe_softc *sc);
706 static void    bxe_set_rx_mode(struct bxe_softc *sc);
707 static int     bxe_init_locked(struct bxe_softc *sc);
708 static int     bxe_stop_locked(struct bxe_softc *sc);
709 static void    bxe_sp_err_timeout_task(void *arg, int pending);
710 void           bxe_parity_recover(struct bxe_softc *sc);
711 void           bxe_handle_error(struct bxe_softc *sc);
712 static __noinline int bxe_nic_load(struct bxe_softc *sc,
713                                    int              load_mode);
714 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
715                                      uint32_t         unload_mode,
716                                      uint8_t          keep_link);
717 
718 static void bxe_handle_sp_tq(void *context, int pending);
719 static void bxe_handle_fp_tq(void *context, int pending);
720 
721 static int bxe_add_cdev(struct bxe_softc *sc);
722 static void bxe_del_cdev(struct bxe_softc *sc);
723 int bxe_grc_dump(struct bxe_softc *sc);
724 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
725 static void bxe_free_buf_rings(struct bxe_softc *sc);
726 
727 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
728 uint32_t
729 calc_crc32(uint8_t  *crc32_packet,
730            uint32_t crc32_length,
731            uint32_t crc32_seed,
732            uint8_t  complement)
733 {
734    uint32_t byte         = 0;
735    uint32_t bit          = 0;
736    uint8_t  msb          = 0;
737    uint32_t temp         = 0;
738    uint32_t shft         = 0;
739    uint8_t  current_byte = 0;
740    uint32_t crc32_result = crc32_seed;
741    const uint32_t CRC32_POLY = 0x1edc6f41;
742 
743    if ((crc32_packet == NULL) ||
744        (crc32_length == 0) ||
745        ((crc32_length % 8) != 0))
746     {
747         return (crc32_result);
748     }
749 
750     for (byte = 0; byte < crc32_length; byte = byte + 1)
751     {
752         current_byte = crc32_packet[byte];
753         for (bit = 0; bit < 8; bit = bit + 1)
754         {
755             /* msb = crc32_result[31]; */
756             msb = (uint8_t)(crc32_result >> 31);
757 
758             crc32_result = crc32_result << 1;
759 
760             /* it (msb != current_byte[bit]) */
761             if (msb != (0x1 & (current_byte >> bit)))
762             {
763                 crc32_result = crc32_result ^ CRC32_POLY;
764                 /* crc32_result[0] = 1 */
765                 crc32_result |= 1;
766             }
767         }
768     }
769 
770     /* Last step is to:
771      * 1. "mirror" every bit
772      * 2. swap the 4 bytes
773      * 3. complement each bit
774      */
775 
776     /* Mirror */
777     temp = crc32_result;
778     shft = sizeof(crc32_result) * 8 - 1;
779 
780     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
781     {
782         temp <<= 1;
783         temp |= crc32_result & 1;
784         shft-- ;
785     }
786 
787     /* temp[31-bit] = crc32_result[bit] */
788     temp <<= shft;
789 
790     /* Swap */
791     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
792     {
793         uint32_t t0, t1, t2, t3;
794         t0 = (0x000000ff & (temp >> 24));
795         t1 = (0x0000ff00 & (temp >> 8));
796         t2 = (0x00ff0000 & (temp << 8));
797         t3 = (0xff000000 & (temp << 24));
798         crc32_result = t0 | t1 | t2 | t3;
799     }
800 
801     /* Complement */
802     if (complement)
803     {
804         crc32_result = ~crc32_result;
805     }
806 
807     return (crc32_result);
808 }
809 
810 int
811 bxe_test_bit(int                    nr,
812              volatile unsigned long *addr)
813 {
814     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
815 }
816 
817 void
818 bxe_set_bit(unsigned int           nr,
819             volatile unsigned long *addr)
820 {
821     atomic_set_acq_long(addr, (1 << nr));
822 }
823 
824 void
825 bxe_clear_bit(int                    nr,
826               volatile unsigned long *addr)
827 {
828     atomic_clear_acq_long(addr, (1 << nr));
829 }
830 
831 int
832 bxe_test_and_set_bit(int                    nr,
833                        volatile unsigned long *addr)
834 {
835     unsigned long x;
836     nr = (1 << nr);
837     do {
838         x = *addr;
839     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
840     // if (x & nr) bit_was_set; else bit_was_not_set;
841     return (x & nr);
842 }
843 
844 int
845 bxe_test_and_clear_bit(int                    nr,
846                        volatile unsigned long *addr)
847 {
848     unsigned long x;
849     nr = (1 << nr);
850     do {
851         x = *addr;
852     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
853     // if (x & nr) bit_was_set; else bit_was_not_set;
854     return (x & nr);
855 }
856 
857 int
858 bxe_cmpxchg(volatile int *addr,
859             int          old,
860             int          new)
861 {
862     int x;
863     do {
864         x = *addr;
865     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
866     return (x);
867 }
868 
869 /*
870  * Get DMA memory from the OS.
871  *
872  * Validates that the OS has provided DMA buffers in response to a
873  * bus_dmamap_load call and saves the physical address of those buffers.
874  * When the callback is used the OS will return 0 for the mapping function
875  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
876  * failures back to the caller.
877  *
878  * Returns:
879  *   Nothing.
880  */
881 static void
882 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
883 {
884     struct bxe_dma *dma = arg;
885 
886     if (error) {
887         dma->paddr = 0;
888         dma->nseg  = 0;
889         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
890     } else {
891         dma->paddr = segs->ds_addr;
892         dma->nseg  = nseg;
893     }
894 }
895 
896 /*
897  * Allocate a block of memory and map it for DMA. No partial completions
898  * allowed and release any resources acquired if we can't acquire all
899  * resources.
900  *
901  * Returns:
902  *   0 = Success, !0 = Failure
903  */
904 int
905 bxe_dma_alloc(struct bxe_softc *sc,
906               bus_size_t       size,
907               struct bxe_dma   *dma,
908               const char       *msg)
909 {
910     int rc;
911 
912     if (dma->size > 0) {
913         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
914               (unsigned long)dma->size);
915         return (1);
916     }
917 
918     memset(dma, 0, sizeof(*dma)); /* sanity */
919     dma->sc   = sc;
920     dma->size = size;
921     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
922 
923     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
924                             BCM_PAGE_SIZE,      /* alignment */
925                             0,                  /* boundary limit */
926                             BUS_SPACE_MAXADDR,  /* restricted low */
927                             BUS_SPACE_MAXADDR,  /* restricted hi */
928                             NULL,               /* addr filter() */
929                             NULL,               /* addr filter() arg */
930                             size,               /* max map size */
931                             1,                  /* num discontinuous */
932                             size,               /* max seg size */
933                             BUS_DMA_ALLOCNOW,   /* flags */
934                             NULL,               /* lock() */
935                             NULL,               /* lock() arg */
936                             &dma->tag);         /* returned dma tag */
937     if (rc != 0) {
938         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
939         memset(dma, 0, sizeof(*dma));
940         return (1);
941     }
942 
943     rc = bus_dmamem_alloc(dma->tag,
944                           (void **)&dma->vaddr,
945                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
946                           &dma->map);
947     if (rc != 0) {
948         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
949         bus_dma_tag_destroy(dma->tag);
950         memset(dma, 0, sizeof(*dma));
951         return (1);
952     }
953 
954     rc = bus_dmamap_load(dma->tag,
955                          dma->map,
956                          dma->vaddr,
957                          size,
958                          bxe_dma_map_addr, /* BLOGD in here */
959                          dma,
960                          BUS_DMA_NOWAIT);
961     if (rc != 0) {
962         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
963         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
964         bus_dma_tag_destroy(dma->tag);
965         memset(dma, 0, sizeof(*dma));
966         return (1);
967     }
968 
969     return (0);
970 }
971 
972 void
973 bxe_dma_free(struct bxe_softc *sc,
974              struct bxe_dma   *dma)
975 {
976     if (dma->size > 0) {
977         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
978 
979         bus_dmamap_sync(dma->tag, dma->map,
980                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
981         bus_dmamap_unload(dma->tag, dma->map);
982         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
983         bus_dma_tag_destroy(dma->tag);
984     }
985 
986     memset(dma, 0, sizeof(*dma));
987 }
988 
989 /*
990  * These indirect read and write routines are only during init.
991  * The locking is handled by the MCP.
992  */
993 
994 void
995 bxe_reg_wr_ind(struct bxe_softc *sc,
996                uint32_t         addr,
997                uint32_t         val)
998 {
999     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1000     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
1001     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1002 }
1003 
1004 uint32_t
1005 bxe_reg_rd_ind(struct bxe_softc *sc,
1006                uint32_t         addr)
1007 {
1008     uint32_t val;
1009 
1010     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1011     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1012     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1013 
1014     return (val);
1015 }
1016 
1017 static int
1018 bxe_acquire_hw_lock(struct bxe_softc *sc,
1019                     uint32_t         resource)
1020 {
1021     uint32_t lock_status;
1022     uint32_t resource_bit = (1 << resource);
1023     int func = SC_FUNC(sc);
1024     uint32_t hw_lock_control_reg;
1025     int cnt;
1026 
1027     /* validate the resource is within range */
1028     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1029         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1030             " resource_bit 0x%x\n", resource, resource_bit);
1031         return (-1);
1032     }
1033 
1034     if (func <= 5) {
1035         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1036     } else {
1037         hw_lock_control_reg =
1038                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1039     }
1040 
1041     /* validate the resource is not already taken */
1042     lock_status = REG_RD(sc, hw_lock_control_reg);
1043     if (lock_status & resource_bit) {
1044         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1045               resource, lock_status, resource_bit);
1046         return (-1);
1047     }
1048 
1049     /* try every 5ms for 5 seconds */
1050     for (cnt = 0; cnt < 1000; cnt++) {
1051         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1052         lock_status = REG_RD(sc, hw_lock_control_reg);
1053         if (lock_status & resource_bit) {
1054             return (0);
1055         }
1056         DELAY(5000);
1057     }
1058 
1059     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1060         resource, resource_bit);
1061     return (-1);
1062 }
1063 
1064 static int
1065 bxe_release_hw_lock(struct bxe_softc *sc,
1066                     uint32_t         resource)
1067 {
1068     uint32_t lock_status;
1069     uint32_t resource_bit = (1 << resource);
1070     int func = SC_FUNC(sc);
1071     uint32_t hw_lock_control_reg;
1072 
1073     /* validate the resource is within range */
1074     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1075         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1076             " resource_bit 0x%x\n", resource, resource_bit);
1077         return (-1);
1078     }
1079 
1080     if (func <= 5) {
1081         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1082     } else {
1083         hw_lock_control_reg =
1084                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1085     }
1086 
1087     /* validate the resource is currently taken */
1088     lock_status = REG_RD(sc, hw_lock_control_reg);
1089     if (!(lock_status & resource_bit)) {
1090         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1091               resource, lock_status, resource_bit);
1092         return (-1);
1093     }
1094 
1095     REG_WR(sc, hw_lock_control_reg, resource_bit);
1096     return (0);
1097 }
1098 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1099 {
1100 	BXE_PHY_LOCK(sc);
1101 	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1102 }
1103 
1104 static void bxe_release_phy_lock(struct bxe_softc *sc)
1105 {
1106 	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1107 	BXE_PHY_UNLOCK(sc);
1108 }
1109 /*
1110  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1111  * had we done things the other way around, if two pfs from the same port
1112  * would attempt to access nvram at the same time, we could run into a
1113  * scenario such as:
1114  * pf A takes the port lock.
1115  * pf B succeeds in taking the same lock since they are from the same port.
1116  * pf A takes the per pf misc lock. Performs eeprom access.
1117  * pf A finishes. Unlocks the per pf misc lock.
1118  * Pf B takes the lock and proceeds to perform it's own access.
1119  * pf A unlocks the per port lock, while pf B is still working (!).
1120  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1121  * access corrupted by pf B).*
1122  */
1123 static int
1124 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1125 {
1126     int port = SC_PORT(sc);
1127     int count, i;
1128     uint32_t val = 0;
1129 
1130     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1131     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1132 
1133     /* adjust timeout for emulation/FPGA */
1134     count = NVRAM_TIMEOUT_COUNT;
1135     if (CHIP_REV_IS_SLOW(sc)) {
1136         count *= 100;
1137     }
1138 
1139     /* request access to nvram interface */
1140     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1141            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1142 
1143     for (i = 0; i < count*10; i++) {
1144         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1145         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1146             break;
1147         }
1148 
1149         DELAY(5);
1150     }
1151 
1152     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1153         BLOGE(sc, "Cannot get access to nvram interface "
1154             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1155             port, val);
1156         return (-1);
1157     }
1158 
1159     return (0);
1160 }
1161 
1162 static int
1163 bxe_release_nvram_lock(struct bxe_softc *sc)
1164 {
1165     int port = SC_PORT(sc);
1166     int count, i;
1167     uint32_t val = 0;
1168 
1169     /* adjust timeout for emulation/FPGA */
1170     count = NVRAM_TIMEOUT_COUNT;
1171     if (CHIP_REV_IS_SLOW(sc)) {
1172         count *= 100;
1173     }
1174 
1175     /* relinquish nvram interface */
1176     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1177            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1178 
1179     for (i = 0; i < count*10; i++) {
1180         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1181         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1182             break;
1183         }
1184 
1185         DELAY(5);
1186     }
1187 
1188     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1189         BLOGE(sc, "Cannot free access to nvram interface "
1190             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1191             port, val);
1192         return (-1);
1193     }
1194 
1195     /* release HW lock: protect against other PFs in PF Direct Assignment */
1196     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1197 
1198     return (0);
1199 }
1200 
1201 static void
1202 bxe_enable_nvram_access(struct bxe_softc *sc)
1203 {
1204     uint32_t val;
1205 
1206     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1207 
1208     /* enable both bits, even on read */
1209     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1210            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1211 }
1212 
1213 static void
1214 bxe_disable_nvram_access(struct bxe_softc *sc)
1215 {
1216     uint32_t val;
1217 
1218     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1219 
1220     /* disable both bits, even after read */
1221     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1222            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1223                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1224 }
1225 
1226 static int
1227 bxe_nvram_read_dword(struct bxe_softc *sc,
1228                      uint32_t         offset,
1229                      uint32_t         *ret_val,
1230                      uint32_t         cmd_flags)
1231 {
1232     int count, i, rc;
1233     uint32_t val;
1234 
1235     /* build the command word */
1236     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1237 
1238     /* need to clear DONE bit separately */
1239     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1240 
1241     /* address of the NVRAM to read from */
1242     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1243            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1244 
1245     /* issue a read command */
1246     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1247 
1248     /* adjust timeout for emulation/FPGA */
1249     count = NVRAM_TIMEOUT_COUNT;
1250     if (CHIP_REV_IS_SLOW(sc)) {
1251         count *= 100;
1252     }
1253 
1254     /* wait for completion */
1255     *ret_val = 0;
1256     rc = -1;
1257     for (i = 0; i < count; i++) {
1258         DELAY(5);
1259         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1260 
1261         if (val & MCPR_NVM_COMMAND_DONE) {
1262             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1263             /* we read nvram data in cpu order
1264              * but ethtool sees it as an array of bytes
1265              * converting to big-endian will do the work
1266              */
1267             *ret_val = htobe32(val);
1268             rc = 0;
1269             break;
1270         }
1271     }
1272 
1273     if (rc == -1) {
1274         BLOGE(sc, "nvram read timeout expired "
1275             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1276             offset, cmd_flags, val);
1277     }
1278 
1279     return (rc);
1280 }
1281 
1282 static int
1283 bxe_nvram_read(struct bxe_softc *sc,
1284                uint32_t         offset,
1285                uint8_t          *ret_buf,
1286                int              buf_size)
1287 {
1288     uint32_t cmd_flags;
1289     uint32_t val;
1290     int rc;
1291 
1292     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1293         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1294               offset, buf_size);
1295         return (-1);
1296     }
1297 
1298     if ((offset + buf_size) > sc->devinfo.flash_size) {
1299         BLOGE(sc, "Invalid parameter, "
1300                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1301               offset, buf_size, sc->devinfo.flash_size);
1302         return (-1);
1303     }
1304 
1305     /* request access to nvram interface */
1306     rc = bxe_acquire_nvram_lock(sc);
1307     if (rc) {
1308         return (rc);
1309     }
1310 
1311     /* enable access to nvram interface */
1312     bxe_enable_nvram_access(sc);
1313 
1314     /* read the first word(s) */
1315     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1316     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1317         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1318         memcpy(ret_buf, &val, 4);
1319 
1320         /* advance to the next dword */
1321         offset += sizeof(uint32_t);
1322         ret_buf += sizeof(uint32_t);
1323         buf_size -= sizeof(uint32_t);
1324         cmd_flags = 0;
1325     }
1326 
1327     if (rc == 0) {
1328         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1329         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1330         memcpy(ret_buf, &val, 4);
1331     }
1332 
1333     /* disable access to nvram interface */
1334     bxe_disable_nvram_access(sc);
1335     bxe_release_nvram_lock(sc);
1336 
1337     return (rc);
1338 }
1339 
1340 static int
1341 bxe_nvram_write_dword(struct bxe_softc *sc,
1342                       uint32_t         offset,
1343                       uint32_t         val,
1344                       uint32_t         cmd_flags)
1345 {
1346     int count, i, rc;
1347 
1348     /* build the command word */
1349     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1350 
1351     /* need to clear DONE bit separately */
1352     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1353 
1354     /* write the data */
1355     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1356 
1357     /* address of the NVRAM to write to */
1358     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1359            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1360 
1361     /* issue the write command */
1362     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1363 
1364     /* adjust timeout for emulation/FPGA */
1365     count = NVRAM_TIMEOUT_COUNT;
1366     if (CHIP_REV_IS_SLOW(sc)) {
1367         count *= 100;
1368     }
1369 
1370     /* wait for completion */
1371     rc = -1;
1372     for (i = 0; i < count; i++) {
1373         DELAY(5);
1374         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1375         if (val & MCPR_NVM_COMMAND_DONE) {
1376             rc = 0;
1377             break;
1378         }
1379     }
1380 
1381     if (rc == -1) {
1382         BLOGE(sc, "nvram write timeout expired "
1383             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1384             offset, cmd_flags, val);
1385     }
1386 
1387     return (rc);
1388 }
1389 
1390 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1391 
1392 static int
1393 bxe_nvram_write1(struct bxe_softc *sc,
1394                  uint32_t         offset,
1395                  uint8_t          *data_buf,
1396                  int              buf_size)
1397 {
1398     uint32_t cmd_flags;
1399     uint32_t align_offset;
1400     uint32_t val;
1401     int rc;
1402 
1403     if ((offset + buf_size) > sc->devinfo.flash_size) {
1404         BLOGE(sc, "Invalid parameter, "
1405                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1406               offset, buf_size, sc->devinfo.flash_size);
1407         return (-1);
1408     }
1409 
1410     /* request access to nvram interface */
1411     rc = bxe_acquire_nvram_lock(sc);
1412     if (rc) {
1413         return (rc);
1414     }
1415 
1416     /* enable access to nvram interface */
1417     bxe_enable_nvram_access(sc);
1418 
1419     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1420     align_offset = (offset & ~0x03);
1421     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1422 
1423     if (rc == 0) {
1424         val &= ~(0xff << BYTE_OFFSET(offset));
1425         val |= (*data_buf << BYTE_OFFSET(offset));
1426 
1427         /* nvram data is returned as an array of bytes
1428          * convert it back to cpu order
1429          */
1430         val = be32toh(val);
1431 
1432         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1433     }
1434 
1435     /* disable access to nvram interface */
1436     bxe_disable_nvram_access(sc);
1437     bxe_release_nvram_lock(sc);
1438 
1439     return (rc);
1440 }
1441 
1442 static int
1443 bxe_nvram_write(struct bxe_softc *sc,
1444                 uint32_t         offset,
1445                 uint8_t          *data_buf,
1446                 int              buf_size)
1447 {
1448     uint32_t cmd_flags;
1449     uint32_t val;
1450     uint32_t written_so_far;
1451     int rc;
1452 
1453     if (buf_size == 1) {
1454         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1455     }
1456 
1457     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1458         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1459               offset, buf_size);
1460         return (-1);
1461     }
1462 
1463     if (buf_size == 0) {
1464         return (0); /* nothing to do */
1465     }
1466 
1467     if ((offset + buf_size) > sc->devinfo.flash_size) {
1468         BLOGE(sc, "Invalid parameter, "
1469                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1470               offset, buf_size, sc->devinfo.flash_size);
1471         return (-1);
1472     }
1473 
1474     /* request access to nvram interface */
1475     rc = bxe_acquire_nvram_lock(sc);
1476     if (rc) {
1477         return (rc);
1478     }
1479 
1480     /* enable access to nvram interface */
1481     bxe_enable_nvram_access(sc);
1482 
1483     written_so_far = 0;
1484     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1485     while ((written_so_far < buf_size) && (rc == 0)) {
1486         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1487             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1488         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1489             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1490         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1491             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1492         }
1493 
1494         memcpy(&val, data_buf, 4);
1495 
1496         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1497 
1498         /* advance to the next dword */
1499         offset += sizeof(uint32_t);
1500         data_buf += sizeof(uint32_t);
1501         written_so_far += sizeof(uint32_t);
1502         cmd_flags = 0;
1503     }
1504 
1505     /* disable access to nvram interface */
1506     bxe_disable_nvram_access(sc);
1507     bxe_release_nvram_lock(sc);
1508 
1509     return (rc);
1510 }
1511 
1512 /* copy command into DMAE command memory and set DMAE command Go */
1513 void
1514 bxe_post_dmae(struct bxe_softc    *sc,
1515               struct dmae_cmd *dmae,
1516               int                 idx)
1517 {
1518     uint32_t cmd_offset;
1519     int i;
1520 
1521     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1522     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1523         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1524     }
1525 
1526     REG_WR(sc, dmae_reg_go_c[idx], 1);
1527 }
1528 
1529 uint32_t
1530 bxe_dmae_opcode_add_comp(uint32_t opcode,
1531                          uint8_t  comp_type)
1532 {
1533     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1534                       DMAE_CMD_C_TYPE_ENABLE));
1535 }
1536 
1537 uint32_t
1538 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1539 {
1540     return (opcode & ~DMAE_CMD_SRC_RESET);
1541 }
1542 
1543 uint32_t
1544 bxe_dmae_opcode(struct bxe_softc *sc,
1545                 uint8_t          src_type,
1546                 uint8_t          dst_type,
1547                 uint8_t          with_comp,
1548                 uint8_t          comp_type)
1549 {
1550     uint32_t opcode = 0;
1551 
1552     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1553                (dst_type << DMAE_CMD_DST_SHIFT));
1554 
1555     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1556 
1557     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1558 
1559     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1560                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1561 
1562     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1563 
1564 #ifdef __BIG_ENDIAN
1565     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1566 #else
1567     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1568 #endif
1569 
1570     if (with_comp) {
1571         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1572     }
1573 
1574     return (opcode);
1575 }
1576 
1577 static void
1578 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1579                         struct dmae_cmd *dmae,
1580                         uint8_t             src_type,
1581                         uint8_t             dst_type)
1582 {
1583     memset(dmae, 0, sizeof(struct dmae_cmd));
1584 
1585     /* set the opcode */
1586     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1587                                    TRUE, DMAE_COMP_PCI);
1588 
1589     /* fill in the completion parameters */
1590     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1591     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1592     dmae->comp_val     = DMAE_COMP_VAL;
1593 }
1594 
1595 /* issue a DMAE command over the init channel and wait for completion */
1596 static int
1597 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1598                          struct dmae_cmd *dmae)
1599 {
1600     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1601     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1602 
1603     BXE_DMAE_LOCK(sc);
1604 
1605     /* reset completion */
1606     *wb_comp = 0;
1607 
1608     /* post the command on the channel used for initializations */
1609     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1610 
1611     /* wait for completion */
1612     DELAY(5);
1613 
1614     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1615         if (!timeout ||
1616             (sc->recovery_state != BXE_RECOVERY_DONE &&
1617              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1618             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1619                 *wb_comp, sc->recovery_state);
1620             BXE_DMAE_UNLOCK(sc);
1621             return (DMAE_TIMEOUT);
1622         }
1623 
1624         timeout--;
1625         DELAY(50);
1626     }
1627 
1628     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1629         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1630                 *wb_comp, sc->recovery_state);
1631         BXE_DMAE_UNLOCK(sc);
1632         return (DMAE_PCI_ERROR);
1633     }
1634 
1635     BXE_DMAE_UNLOCK(sc);
1636     return (0);
1637 }
1638 
1639 void
1640 bxe_read_dmae(struct bxe_softc *sc,
1641               uint32_t         src_addr,
1642               uint32_t         len32)
1643 {
1644     struct dmae_cmd dmae;
1645     uint32_t *data;
1646     int i, rc;
1647 
1648     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1649 
1650     if (!sc->dmae_ready) {
1651         data = BXE_SP(sc, wb_data[0]);
1652 
1653         for (i = 0; i < len32; i++) {
1654             data[i] = (CHIP_IS_E1(sc)) ?
1655                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1656                           REG_RD(sc, (src_addr + (i * 4)));
1657         }
1658 
1659         return;
1660     }
1661 
1662     /* set opcode and fixed command fields */
1663     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1664 
1665     /* fill in addresses and len */
1666     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1667     dmae.src_addr_hi = 0;
1668     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1669     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1670     dmae.len         = len32;
1671 
1672     /* issue the command and wait for completion */
1673     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1674         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1675     }
1676 }
1677 
1678 void
1679 bxe_write_dmae(struct bxe_softc *sc,
1680                bus_addr_t       dma_addr,
1681                uint32_t         dst_addr,
1682                uint32_t         len32)
1683 {
1684     struct dmae_cmd dmae;
1685     int rc;
1686 
1687     if (!sc->dmae_ready) {
1688         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1689 
1690         if (CHIP_IS_E1(sc)) {
1691             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1692         } else {
1693             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1694         }
1695 
1696         return;
1697     }
1698 
1699     /* set opcode and fixed command fields */
1700     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1701 
1702     /* fill in addresses and len */
1703     dmae.src_addr_lo = U64_LO(dma_addr);
1704     dmae.src_addr_hi = U64_HI(dma_addr);
1705     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1706     dmae.dst_addr_hi = 0;
1707     dmae.len         = len32;
1708 
1709     /* issue the command and wait for completion */
1710     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1711         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1712     }
1713 }
1714 
1715 void
1716 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1717                         bus_addr_t       phys_addr,
1718                         uint32_t         addr,
1719                         uint32_t         len)
1720 {
1721     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1722     int offset = 0;
1723 
1724     while (len > dmae_wr_max) {
1725         bxe_write_dmae(sc,
1726                        (phys_addr + offset), /* src DMA address */
1727                        (addr + offset),      /* dst GRC address */
1728                        dmae_wr_max);
1729         offset += (dmae_wr_max * 4);
1730         len -= dmae_wr_max;
1731     }
1732 
1733     bxe_write_dmae(sc,
1734                    (phys_addr + offset), /* src DMA address */
1735                    (addr + offset),      /* dst GRC address */
1736                    len);
1737 }
1738 
1739 void
1740 bxe_set_ctx_validation(struct bxe_softc   *sc,
1741                        struct eth_context *cxt,
1742                        uint32_t           cid)
1743 {
1744     /* ustorm cxt validation */
1745     cxt->ustorm_ag_context.cdu_usage =
1746         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1747             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1748     /* xcontext validation */
1749     cxt->xstorm_ag_context.cdu_reserved =
1750         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1751             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1752 }
1753 
1754 static void
1755 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1756                             uint8_t          port,
1757                             uint8_t          fw_sb_id,
1758                             uint8_t          sb_index,
1759                             uint8_t          ticks)
1760 {
1761     uint32_t addr =
1762         (BAR_CSTRORM_INTMEM +
1763          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1764 
1765     REG_WR8(sc, addr, ticks);
1766 
1767     BLOGD(sc, DBG_LOAD,
1768           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1769           port, fw_sb_id, sb_index, ticks);
1770 }
1771 
1772 static void
1773 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1774                             uint8_t          port,
1775                             uint16_t         fw_sb_id,
1776                             uint8_t          sb_index,
1777                             uint8_t          disable)
1778 {
1779     uint32_t enable_flag =
1780         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1781     uint32_t addr =
1782         (BAR_CSTRORM_INTMEM +
1783          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1784     uint8_t flags;
1785 
1786     /* clear and set */
1787     flags = REG_RD8(sc, addr);
1788     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1789     flags |= enable_flag;
1790     REG_WR8(sc, addr, flags);
1791 
1792     BLOGD(sc, DBG_LOAD,
1793           "port %d fw_sb_id %d sb_index %d disable %d\n",
1794           port, fw_sb_id, sb_index, disable);
1795 }
1796 
1797 void
1798 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1799                              uint8_t          fw_sb_id,
1800                              uint8_t          sb_index,
1801                              uint8_t          disable,
1802                              uint16_t         usec)
1803 {
1804     int port = SC_PORT(sc);
1805     uint8_t ticks = (usec / 4); /* XXX ??? */
1806 
1807     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1808 
1809     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1810     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1811 }
1812 
1813 void
1814 elink_cb_udelay(struct bxe_softc *sc,
1815                 uint32_t         usecs)
1816 {
1817     DELAY(usecs);
1818 }
1819 
1820 uint32_t
1821 elink_cb_reg_read(struct bxe_softc *sc,
1822                   uint32_t         reg_addr)
1823 {
1824     return (REG_RD(sc, reg_addr));
1825 }
1826 
1827 void
1828 elink_cb_reg_write(struct bxe_softc *sc,
1829                    uint32_t         reg_addr,
1830                    uint32_t         val)
1831 {
1832     REG_WR(sc, reg_addr, val);
1833 }
1834 
1835 void
1836 elink_cb_reg_wb_write(struct bxe_softc *sc,
1837                       uint32_t         offset,
1838                       uint32_t         *wb_write,
1839                       uint16_t         len)
1840 {
1841     REG_WR_DMAE(sc, offset, wb_write, len);
1842 }
1843 
1844 void
1845 elink_cb_reg_wb_read(struct bxe_softc *sc,
1846                      uint32_t         offset,
1847                      uint32_t         *wb_write,
1848                      uint16_t         len)
1849 {
1850     REG_RD_DMAE(sc, offset, wb_write, len);
1851 }
1852 
1853 uint8_t
1854 elink_cb_path_id(struct bxe_softc *sc)
1855 {
1856     return (SC_PATH(sc));
1857 }
1858 
1859 void
1860 elink_cb_event_log(struct bxe_softc     *sc,
1861                    const elink_log_id_t elink_log_id,
1862                    ...)
1863 {
1864     /* XXX */
1865     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1866 }
1867 
1868 static int
1869 bxe_set_spio(struct bxe_softc *sc,
1870              int              spio,
1871              uint32_t         mode)
1872 {
1873     uint32_t spio_reg;
1874 
1875     /* Only 2 SPIOs are configurable */
1876     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1877         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1878         return (-1);
1879     }
1880 
1881     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1882 
1883     /* read SPIO and mask except the float bits */
1884     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1885 
1886     switch (mode) {
1887     case MISC_SPIO_OUTPUT_LOW:
1888         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1889         /* clear FLOAT and set CLR */
1890         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1891         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1892         break;
1893 
1894     case MISC_SPIO_OUTPUT_HIGH:
1895         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1896         /* clear FLOAT and set SET */
1897         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1898         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1899         break;
1900 
1901     case MISC_SPIO_INPUT_HI_Z:
1902         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1903         /* set FLOAT */
1904         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1905         break;
1906 
1907     default:
1908         break;
1909     }
1910 
1911     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1912     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1913 
1914     return (0);
1915 }
1916 
1917 static int
1918 bxe_gpio_read(struct bxe_softc *sc,
1919               int              gpio_num,
1920               uint8_t          port)
1921 {
1922     /* The GPIO should be swapped if swap register is set and active */
1923     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1924                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1925     int gpio_shift = (gpio_num +
1926                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1927     uint32_t gpio_mask = (1 << gpio_shift);
1928     uint32_t gpio_reg;
1929 
1930     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1931         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1932             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1933             gpio_mask);
1934         return (-1);
1935     }
1936 
1937     /* read GPIO value */
1938     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1939 
1940     /* get the requested pin value */
1941     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1942 }
1943 
1944 static int
1945 bxe_gpio_write(struct bxe_softc *sc,
1946                int              gpio_num,
1947                uint32_t         mode,
1948                uint8_t          port)
1949 {
1950     /* The GPIO should be swapped if swap register is set and active */
1951     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1952                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1953     int gpio_shift = (gpio_num +
1954                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1955     uint32_t gpio_mask = (1 << gpio_shift);
1956     uint32_t gpio_reg;
1957 
1958     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1959         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1960             " gpio_shift %d gpio_mask 0x%x\n",
1961             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1962         return (-1);
1963     }
1964 
1965     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1966 
1967     /* read GPIO and mask except the float bits */
1968     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1969 
1970     switch (mode) {
1971     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1972         BLOGD(sc, DBG_PHY,
1973               "Set GPIO %d (shift %d) -> output low\n",
1974               gpio_num, gpio_shift);
1975         /* clear FLOAT and set CLR */
1976         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1977         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1978         break;
1979 
1980     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1981         BLOGD(sc, DBG_PHY,
1982               "Set GPIO %d (shift %d) -> output high\n",
1983               gpio_num, gpio_shift);
1984         /* clear FLOAT and set SET */
1985         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1986         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1987         break;
1988 
1989     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1990         BLOGD(sc, DBG_PHY,
1991               "Set GPIO %d (shift %d) -> input\n",
1992               gpio_num, gpio_shift);
1993         /* set FLOAT */
1994         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1995         break;
1996 
1997     default:
1998         break;
1999     }
2000 
2001     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2002     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2003 
2004     return (0);
2005 }
2006 
2007 static int
2008 bxe_gpio_mult_write(struct bxe_softc *sc,
2009                     uint8_t          pins,
2010                     uint32_t         mode)
2011 {
2012     uint32_t gpio_reg;
2013 
2014     /* any port swapping should be handled by caller */
2015 
2016     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2017 
2018     /* read GPIO and mask except the float bits */
2019     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2020     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2021     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2022     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2023 
2024     switch (mode) {
2025     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2026         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2027         /* set CLR */
2028         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2029         break;
2030 
2031     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2032         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2033         /* set SET */
2034         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2035         break;
2036 
2037     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2038         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2039         /* set FLOAT */
2040         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2041         break;
2042 
2043     default:
2044         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2045             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2046         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2047         return (-1);
2048     }
2049 
2050     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2051     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2052 
2053     return (0);
2054 }
2055 
2056 static int
2057 bxe_gpio_int_write(struct bxe_softc *sc,
2058                    int              gpio_num,
2059                    uint32_t         mode,
2060                    uint8_t          port)
2061 {
2062     /* The GPIO should be swapped if swap register is set and active */
2063     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2064                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2065     int gpio_shift = (gpio_num +
2066                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2067     uint32_t gpio_mask = (1 << gpio_shift);
2068     uint32_t gpio_reg;
2069 
2070     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2071         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2072             " gpio_shift %d gpio_mask 0x%x\n",
2073             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2074         return (-1);
2075     }
2076 
2077     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2078 
2079     /* read GPIO int */
2080     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2081 
2082     switch (mode) {
2083     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2084         BLOGD(sc, DBG_PHY,
2085               "Clear GPIO INT %d (shift %d) -> output low\n",
2086               gpio_num, gpio_shift);
2087         /* clear SET and set CLR */
2088         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2089         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2090         break;
2091 
2092     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2093         BLOGD(sc, DBG_PHY,
2094               "Set GPIO INT %d (shift %d) -> output high\n",
2095               gpio_num, gpio_shift);
2096         /* clear CLR and set SET */
2097         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2098         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2099         break;
2100 
2101     default:
2102         break;
2103     }
2104 
2105     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2106     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2107 
2108     return (0);
2109 }
2110 
2111 uint32_t
2112 elink_cb_gpio_read(struct bxe_softc *sc,
2113                    uint16_t         gpio_num,
2114                    uint8_t          port)
2115 {
2116     return (bxe_gpio_read(sc, gpio_num, port));
2117 }
2118 
2119 uint8_t
2120 elink_cb_gpio_write(struct bxe_softc *sc,
2121                     uint16_t         gpio_num,
2122                     uint8_t          mode, /* 0=low 1=high */
2123                     uint8_t          port)
2124 {
2125     return (bxe_gpio_write(sc, gpio_num, mode, port));
2126 }
2127 
2128 uint8_t
2129 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2130                          uint8_t          pins,
2131                          uint8_t          mode) /* 0=low 1=high */
2132 {
2133     return (bxe_gpio_mult_write(sc, pins, mode));
2134 }
2135 
2136 uint8_t
2137 elink_cb_gpio_int_write(struct bxe_softc *sc,
2138                         uint16_t         gpio_num,
2139                         uint8_t          mode, /* 0=low 1=high */
2140                         uint8_t          port)
2141 {
2142     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2143 }
2144 
2145 void
2146 elink_cb_notify_link_changed(struct bxe_softc *sc)
2147 {
2148     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2149                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2150 }
2151 
2152 /* send the MCP a request, block until there is a reply */
2153 uint32_t
2154 elink_cb_fw_command(struct bxe_softc *sc,
2155                     uint32_t         command,
2156                     uint32_t         param)
2157 {
2158     int mb_idx = SC_FW_MB_IDX(sc);
2159     uint32_t seq;
2160     uint32_t rc = 0;
2161     uint32_t cnt = 1;
2162     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2163 
2164     BXE_FWMB_LOCK(sc);
2165 
2166     seq = ++sc->fw_seq;
2167     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2168     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2169 
2170     BLOGD(sc, DBG_PHY,
2171           "wrote command 0x%08x to FW MB param 0x%08x\n",
2172           (command | seq), param);
2173 
2174     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2175     do {
2176         DELAY(delay * 1000);
2177         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2178     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2179 
2180     BLOGD(sc, DBG_PHY,
2181           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2182           cnt*delay, rc, seq);
2183 
2184     /* is this a reply to our command? */
2185     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2186         rc &= FW_MSG_CODE_MASK;
2187     } else {
2188         /* Ruh-roh! */
2189         BLOGE(sc, "FW failed to respond!\n");
2190         // XXX bxe_fw_dump(sc);
2191         rc = 0;
2192     }
2193 
2194     BXE_FWMB_UNLOCK(sc);
2195     return (rc);
2196 }
2197 
2198 static uint32_t
2199 bxe_fw_command(struct bxe_softc *sc,
2200                uint32_t         command,
2201                uint32_t         param)
2202 {
2203     return (elink_cb_fw_command(sc, command, param));
2204 }
2205 
2206 static void
2207 __storm_memset_dma_mapping(struct bxe_softc *sc,
2208                            uint32_t         addr,
2209                            bus_addr_t       mapping)
2210 {
2211     REG_WR(sc, addr, U64_LO(mapping));
2212     REG_WR(sc, (addr + 4), U64_HI(mapping));
2213 }
2214 
2215 static void
2216 storm_memset_spq_addr(struct bxe_softc *sc,
2217                       bus_addr_t       mapping,
2218                       uint16_t         abs_fid)
2219 {
2220     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2221                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2222     __storm_memset_dma_mapping(sc, addr, mapping);
2223 }
2224 
2225 static void
2226 storm_memset_vf_to_pf(struct bxe_softc *sc,
2227                       uint16_t         abs_fid,
2228                       uint16_t         pf_id)
2229 {
2230     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2231     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2232     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2233     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2234 }
2235 
2236 static void
2237 storm_memset_func_en(struct bxe_softc *sc,
2238                      uint16_t         abs_fid,
2239                      uint8_t          enable)
2240 {
2241     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2242     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2243     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2244     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2245 }
2246 
2247 static void
2248 storm_memset_eq_data(struct bxe_softc       *sc,
2249                      struct event_ring_data *eq_data,
2250                      uint16_t               pfid)
2251 {
2252     uint32_t addr;
2253     size_t size;
2254 
2255     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2256     size = sizeof(struct event_ring_data);
2257     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2258 }
2259 
2260 static void
2261 storm_memset_eq_prod(struct bxe_softc *sc,
2262                      uint16_t         eq_prod,
2263                      uint16_t         pfid)
2264 {
2265     uint32_t addr = (BAR_CSTRORM_INTMEM +
2266                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2267     REG_WR16(sc, addr, eq_prod);
2268 }
2269 
2270 /*
2271  * Post a slowpath command.
2272  *
2273  * A slowpath command is used to propagate a configuration change through
2274  * the controller in a controlled manner, allowing each STORM processor and
2275  * other H/W blocks to phase in the change.  The commands sent on the
2276  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2277  * completion of the ramrod will occur in different ways.  Here's a
2278  * breakdown of ramrods and how they complete:
2279  *
2280  * RAMROD_CMD_ID_ETH_PORT_SETUP
2281  *   Used to setup the leading connection on a port.  Completes on the
2282  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2283  *
2284  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2285  *   Used to setup an additional connection on a port.  Completes on the
2286  *   RCQ of the multi-queue/RSS connection being initialized.
2287  *
2288  * RAMROD_CMD_ID_ETH_STAT_QUERY
2289  *   Used to force the storm processors to update the statistics database
2290  *   in host memory.  This ramrod is send on the leading connection CID and
2291  *   completes as an index increment of the CSTORM on the default status
2292  *   block.
2293  *
2294  * RAMROD_CMD_ID_ETH_UPDATE
2295  *   Used to update the state of the leading connection, usually to udpate
2296  *   the RSS indirection table.  Completes on the RCQ of the leading
2297  *   connection. (Not currently used under FreeBSD until OS support becomes
2298  *   available.)
2299  *
2300  * RAMROD_CMD_ID_ETH_HALT
2301  *   Used when tearing down a connection prior to driver unload.  Completes
2302  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2303  *   use this on the leading connection.
2304  *
2305  * RAMROD_CMD_ID_ETH_SET_MAC
2306  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2307  *   the RCQ of the leading connection.
2308  *
2309  * RAMROD_CMD_ID_ETH_CFC_DEL
2310  *   Used when tearing down a conneciton prior to driver unload.  Completes
2311  *   on the RCQ of the leading connection (since the current connection
2312  *   has been completely removed from controller memory).
2313  *
2314  * RAMROD_CMD_ID_ETH_PORT_DEL
2315  *   Used to tear down the leading connection prior to driver unload,
2316  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2317  *   default status block.
2318  *
2319  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2320  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2321  *   RSS connection that is being offloaded.  (Not currently used under
2322  *   FreeBSD.)
2323  *
2324  * There can only be one command pending per function.
2325  *
2326  * Returns:
2327  *   0 = Success, !0 = Failure.
2328  */
2329 
2330 /* must be called under the spq lock */
2331 static inline
2332 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2333 {
2334     struct eth_spe *next_spe = sc->spq_prod_bd;
2335 
2336     if (sc->spq_prod_bd == sc->spq_last_bd) {
2337         /* wrap back to the first eth_spq */
2338         sc->spq_prod_bd = sc->spq;
2339         sc->spq_prod_idx = 0;
2340     } else {
2341         sc->spq_prod_bd++;
2342         sc->spq_prod_idx++;
2343     }
2344 
2345     return (next_spe);
2346 }
2347 
2348 /* must be called under the spq lock */
2349 static inline
2350 void bxe_sp_prod_update(struct bxe_softc *sc)
2351 {
2352     int func = SC_FUNC(sc);
2353 
2354     /*
2355      * Make sure that BD data is updated before writing the producer.
2356      * BD data is written to the memory, the producer is read from the
2357      * memory, thus we need a full memory barrier to ensure the ordering.
2358      */
2359     mb();
2360 
2361     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2362              sc->spq_prod_idx);
2363 
2364     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2365                       BUS_SPACE_BARRIER_WRITE);
2366 }
2367 
2368 /**
2369  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2370  *
2371  * @cmd:      command to check
2372  * @cmd_type: command type
2373  */
2374 static inline
2375 int bxe_is_contextless_ramrod(int cmd,
2376                               int cmd_type)
2377 {
2378     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2379         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2380         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2381         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2382         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2383         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2384         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2385         return (TRUE);
2386     } else {
2387         return (FALSE);
2388     }
2389 }
2390 
2391 /**
2392  * bxe_sp_post - place a single command on an SP ring
2393  *
2394  * @sc:         driver handle
2395  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2396  * @cid:        SW CID the command is related to
2397  * @data_hi:    command private data address (high 32 bits)
2398  * @data_lo:    command private data address (low 32 bits)
2399  * @cmd_type:   command type (e.g. NONE, ETH)
2400  *
2401  * SP data is handled as if it's always an address pair, thus data fields are
2402  * not swapped to little endian in upper functions. Instead this function swaps
2403  * data as if it's two uint32 fields.
2404  */
2405 int
2406 bxe_sp_post(struct bxe_softc *sc,
2407             int              command,
2408             int              cid,
2409             uint32_t         data_hi,
2410             uint32_t         data_lo,
2411             int              cmd_type)
2412 {
2413     struct eth_spe *spe;
2414     uint16_t type;
2415     int common;
2416 
2417     common = bxe_is_contextless_ramrod(command, cmd_type);
2418 
2419     BXE_SP_LOCK(sc);
2420 
2421     if (common) {
2422         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2423             BLOGE(sc, "EQ ring is full!\n");
2424             BXE_SP_UNLOCK(sc);
2425             return (-1);
2426         }
2427     } else {
2428         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2429             BLOGE(sc, "SPQ ring is full!\n");
2430             BXE_SP_UNLOCK(sc);
2431             return (-1);
2432         }
2433     }
2434 
2435     spe = bxe_sp_get_next(sc);
2436 
2437     /* CID needs port number to be encoded int it */
2438     spe->hdr.conn_and_cmd_data =
2439         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2440 
2441     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2442 
2443     /* TBD: Check if it works for VFs */
2444     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2445              SPE_HDR_T_FUNCTION_ID);
2446 
2447     spe->hdr.type = htole16(type);
2448 
2449     spe->data.update_data_addr.hi = htole32(data_hi);
2450     spe->data.update_data_addr.lo = htole32(data_lo);
2451 
2452     /*
2453      * It's ok if the actual decrement is issued towards the memory
2454      * somewhere between the lock and unlock. Thus no more explict
2455      * memory barrier is needed.
2456      */
2457     if (common) {
2458         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2459     } else {
2460         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2461     }
2462 
2463     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2464     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2465           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2466     BLOGD(sc, DBG_SP,
2467           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2468           sc->spq_prod_idx,
2469           (uint32_t)U64_HI(sc->spq_dma.paddr),
2470           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2471           command,
2472           common,
2473           HW_CID(sc, cid),
2474           data_hi,
2475           data_lo,
2476           type,
2477           atomic_load_acq_long(&sc->cq_spq_left),
2478           atomic_load_acq_long(&sc->eq_spq_left));
2479 
2480     bxe_sp_prod_update(sc);
2481 
2482     BXE_SP_UNLOCK(sc);
2483     return (0);
2484 }
2485 
2486 /**
2487  * bxe_debug_print_ind_table - prints the indirection table configuration.
2488  *
2489  * @sc: driver hanlde
2490  * @p:  pointer to rss configuration
2491  */
2492 
2493 /*
2494  * FreeBSD Device probe function.
2495  *
2496  * Compares the device found to the driver's list of supported devices and
2497  * reports back to the bsd loader whether this is the right driver for the device.
2498  * This is the driver entry function called from the "kldload" command.
2499  *
2500  * Returns:
2501  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2502  */
2503 static int
2504 bxe_probe(device_t dev)
2505 {
2506     struct bxe_device_type *t;
2507     char *descbuf;
2508     uint16_t did, sdid, svid, vid;
2509 
2510     /* Find our device structure */
2511     t = bxe_devs;
2512 
2513     /* Get the data for the device to be probed. */
2514     vid  = pci_get_vendor(dev);
2515     did  = pci_get_device(dev);
2516     svid = pci_get_subvendor(dev);
2517     sdid = pci_get_subdevice(dev);
2518 
2519     /* Look through the list of known devices for a match. */
2520     while (t->bxe_name != NULL) {
2521         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2522             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2523             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2524             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2525             if (descbuf == NULL)
2526                 return (ENOMEM);
2527 
2528             /* Print out the device identity. */
2529             snprintf(descbuf, BXE_DEVDESC_MAX,
2530                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2531                      (((pci_read_config(dev, PCIR_REVID, 4) &
2532                         0xf0) >> 4) + 'A'),
2533                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2534                      BXE_DRIVER_VERSION);
2535 
2536             device_set_desc_copy(dev, descbuf);
2537             free(descbuf, M_TEMP);
2538             return (BUS_PROBE_DEFAULT);
2539         }
2540         t++;
2541     }
2542 
2543     return (ENXIO);
2544 }
2545 
2546 static void
2547 bxe_init_mutexes(struct bxe_softc *sc)
2548 {
2549 #ifdef BXE_CORE_LOCK_SX
2550     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2551              "bxe%d_core_lock", sc->unit);
2552     sx_init(&sc->core_sx, sc->core_sx_name);
2553 #else
2554     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2555              "bxe%d_core_lock", sc->unit);
2556     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2557 #endif
2558 
2559     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2560              "bxe%d_sp_lock", sc->unit);
2561     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2562 
2563     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2564              "bxe%d_dmae_lock", sc->unit);
2565     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2566 
2567     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2568              "bxe%d_phy_lock", sc->unit);
2569     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2570 
2571     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2572              "bxe%d_fwmb_lock", sc->unit);
2573     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2574 
2575     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2576              "bxe%d_print_lock", sc->unit);
2577     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2578 
2579     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2580              "bxe%d_stats_lock", sc->unit);
2581     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2582 
2583     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2584              "bxe%d_mcast_lock", sc->unit);
2585     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2586 }
2587 
2588 static void
2589 bxe_release_mutexes(struct bxe_softc *sc)
2590 {
2591 #ifdef BXE_CORE_LOCK_SX
2592     sx_destroy(&sc->core_sx);
2593 #else
2594     if (mtx_initialized(&sc->core_mtx)) {
2595         mtx_destroy(&sc->core_mtx);
2596     }
2597 #endif
2598 
2599     if (mtx_initialized(&sc->sp_mtx)) {
2600         mtx_destroy(&sc->sp_mtx);
2601     }
2602 
2603     if (mtx_initialized(&sc->dmae_mtx)) {
2604         mtx_destroy(&sc->dmae_mtx);
2605     }
2606 
2607     if (mtx_initialized(&sc->port.phy_mtx)) {
2608         mtx_destroy(&sc->port.phy_mtx);
2609     }
2610 
2611     if (mtx_initialized(&sc->fwmb_mtx)) {
2612         mtx_destroy(&sc->fwmb_mtx);
2613     }
2614 
2615     if (mtx_initialized(&sc->print_mtx)) {
2616         mtx_destroy(&sc->print_mtx);
2617     }
2618 
2619     if (mtx_initialized(&sc->stats_mtx)) {
2620         mtx_destroy(&sc->stats_mtx);
2621     }
2622 
2623     if (mtx_initialized(&sc->mcast_mtx)) {
2624         mtx_destroy(&sc->mcast_mtx);
2625     }
2626 }
2627 
2628 static void
2629 bxe_tx_disable(struct bxe_softc* sc)
2630 {
2631     if_t ifp = sc->ifp;
2632 
2633     /* tell the stack the driver is stopped and TX queue is full */
2634     if (ifp !=  NULL) {
2635         if_setdrvflags(ifp, 0);
2636     }
2637 }
2638 
2639 static void
2640 bxe_drv_pulse(struct bxe_softc *sc)
2641 {
2642     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2643              sc->fw_drv_pulse_wr_seq);
2644 }
2645 
2646 static inline uint16_t
2647 bxe_tx_avail(struct bxe_softc *sc,
2648              struct bxe_fastpath *fp)
2649 {
2650     int16_t  used;
2651     uint16_t prod;
2652     uint16_t cons;
2653 
2654     prod = fp->tx_bd_prod;
2655     cons = fp->tx_bd_cons;
2656 
2657     used = SUB_S16(prod, cons);
2658 
2659     return (int16_t)(sc->tx_ring_size) - used;
2660 }
2661 
2662 static inline int
2663 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2664 {
2665     uint16_t hw_cons;
2666 
2667     mb(); /* status block fields can change */
2668     hw_cons = le16toh(*fp->tx_cons_sb);
2669     return (hw_cons != fp->tx_pkt_cons);
2670 }
2671 
2672 static inline uint8_t
2673 bxe_has_tx_work(struct bxe_fastpath *fp)
2674 {
2675     /* expand this for multi-cos if ever supported */
2676     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2677 }
2678 
2679 static inline int
2680 bxe_has_rx_work(struct bxe_fastpath *fp)
2681 {
2682     uint16_t rx_cq_cons_sb;
2683 
2684     mb(); /* status block fields can change */
2685     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2686     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2687         rx_cq_cons_sb++;
2688     return (fp->rx_cq_cons != rx_cq_cons_sb);
2689 }
2690 
2691 static void
2692 bxe_sp_event(struct bxe_softc    *sc,
2693              struct bxe_fastpath *fp,
2694              union eth_rx_cqe    *rr_cqe)
2695 {
2696     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2697     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2698     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2699     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2700 
2701     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2702           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2703 
2704     switch (command) {
2705     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2706         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2707         drv_cmd = ECORE_Q_CMD_UPDATE;
2708         break;
2709 
2710     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2711         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2712         drv_cmd = ECORE_Q_CMD_SETUP;
2713         break;
2714 
2715     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2716         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2717         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2718         break;
2719 
2720     case (RAMROD_CMD_ID_ETH_HALT):
2721         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2722         drv_cmd = ECORE_Q_CMD_HALT;
2723         break;
2724 
2725     case (RAMROD_CMD_ID_ETH_TERMINATE):
2726         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2727         drv_cmd = ECORE_Q_CMD_TERMINATE;
2728         break;
2729 
2730     case (RAMROD_CMD_ID_ETH_EMPTY):
2731         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2732         drv_cmd = ECORE_Q_CMD_EMPTY;
2733         break;
2734 
2735     default:
2736         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2737               command, fp->index);
2738         return;
2739     }
2740 
2741     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2742         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2743         /*
2744          * q_obj->complete_cmd() failure means that this was
2745          * an unexpected completion.
2746          *
2747          * In this case we don't want to increase the sc->spq_left
2748          * because apparently we haven't sent this command the first
2749          * place.
2750          */
2751         // bxe_panic(sc, ("Unexpected SP completion\n"));
2752         return;
2753     }
2754 
2755     atomic_add_acq_long(&sc->cq_spq_left, 1);
2756 
2757     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2758           atomic_load_acq_long(&sc->cq_spq_left));
2759 }
2760 
2761 /*
2762  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2763  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2764  * the current aggregation queue as in-progress.
2765  */
2766 static void
2767 bxe_tpa_start(struct bxe_softc            *sc,
2768               struct bxe_fastpath         *fp,
2769               uint16_t                    queue,
2770               uint16_t                    cons,
2771               uint16_t                    prod,
2772               struct eth_fast_path_rx_cqe *cqe)
2773 {
2774     struct bxe_sw_rx_bd tmp_bd;
2775     struct bxe_sw_rx_bd *rx_buf;
2776     struct eth_rx_bd *rx_bd;
2777     int max_agg_queues;
2778     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2779     uint16_t index;
2780 
2781     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2782                        "cons=%d prod=%d\n",
2783           fp->index, queue, cons, prod);
2784 
2785     max_agg_queues = MAX_AGG_QS(sc);
2786 
2787     KASSERT((queue < max_agg_queues),
2788             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2789              fp->index, queue, max_agg_queues));
2790 
2791     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2792             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2793              fp->index, queue));
2794 
2795     /* copy the existing mbuf and mapping from the TPA pool */
2796     tmp_bd = tpa_info->bd;
2797 
2798     if (tmp_bd.m == NULL) {
2799         uint32_t *tmp;
2800 
2801         tmp = (uint32_t *)cqe;
2802 
2803         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2804               fp->index, queue, cons, prod);
2805         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2806             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2807 
2808         /* XXX Error handling? */
2809         return;
2810     }
2811 
2812     /* change the TPA queue to the start state */
2813     tpa_info->state            = BXE_TPA_STATE_START;
2814     tpa_info->placement_offset = cqe->placement_offset;
2815     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2816     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2817     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2818 
2819     fp->rx_tpa_queue_used |= (1 << queue);
2820 
2821     /*
2822      * If all the buffer descriptors are filled with mbufs then fill in
2823      * the current consumer index with a new BD. Else if a maximum Rx
2824      * buffer limit is imposed then fill in the next producer index.
2825      */
2826     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2827                 prod : cons;
2828 
2829     /* move the received mbuf and mapping to TPA pool */
2830     tpa_info->bd = fp->rx_mbuf_chain[cons];
2831 
2832     /* release any existing RX BD mbuf mappings */
2833     if (cons != index) {
2834         rx_buf = &fp->rx_mbuf_chain[cons];
2835 
2836         if (rx_buf->m_map != NULL) {
2837             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2838                             BUS_DMASYNC_POSTREAD);
2839             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2840         }
2841 
2842         /*
2843          * We get here when the maximum number of rx buffers is less than
2844          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2845          * it out here without concern of a memory leak.
2846          */
2847         fp->rx_mbuf_chain[cons].m = NULL;
2848     }
2849 
2850     /* update the Rx SW BD with the mbuf info from the TPA pool */
2851     fp->rx_mbuf_chain[index] = tmp_bd;
2852 
2853     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2854     rx_bd = &fp->rx_chain[index];
2855     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2856     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2857 }
2858 
2859 /*
2860  * When a TPA aggregation is completed, loop through the individual mbufs
2861  * of the aggregation, combining them into a single mbuf which will be sent
2862  * up the stack. Refill all freed SGEs with mbufs as we go along.
2863  */
2864 static int
2865 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2866                    struct bxe_fastpath       *fp,
2867                    struct bxe_sw_tpa_info    *tpa_info,
2868                    uint16_t                  queue,
2869                    uint16_t                  pages,
2870                    struct mbuf               *m,
2871 			       struct eth_end_agg_rx_cqe *cqe,
2872                    uint16_t                  cqe_idx)
2873 {
2874     struct mbuf *m_frag;
2875     uint32_t frag_len, frag_size, i;
2876     uint16_t sge_idx;
2877     int rc = 0;
2878     int j;
2879 
2880     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2881 
2882     BLOGD(sc, DBG_LRO,
2883           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2884           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2885 
2886     /* make sure the aggregated frame is not too big to handle */
2887     if (pages > 8 * PAGES_PER_SGE) {
2888 
2889         uint32_t *tmp = (uint32_t *)cqe;
2890 
2891         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2892                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2893               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2894               tpa_info->len_on_bd, frag_size);
2895 
2896         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2897             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2898 
2899         bxe_panic(sc, ("sge page count error\n"));
2900         return (EINVAL);
2901     }
2902 
2903     /*
2904      * Scan through the scatter gather list pulling individual mbufs into a
2905      * single mbuf for the host stack.
2906      */
2907     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2908         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2909 
2910         /*
2911          * Firmware gives the indices of the SGE as if the ring is an array
2912          * (meaning that the "next" element will consume 2 indices).
2913          */
2914         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2915 
2916         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2917                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2918               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2919 
2920         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2921 
2922         /* allocate a new mbuf for the SGE */
2923         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2924         if (rc) {
2925             /* Leave all remaining SGEs in the ring! */
2926             return (rc);
2927         }
2928 
2929         /* update the fragment length */
2930         m_frag->m_len = frag_len;
2931 
2932         /* concatenate the fragment to the head mbuf */
2933         m_cat(m, m_frag);
2934         fp->eth_q_stats.mbuf_alloc_sge--;
2935 
2936         /* update the TPA mbuf size and remaining fragment size */
2937         m->m_pkthdr.len += frag_len;
2938         frag_size -= frag_len;
2939     }
2940 
2941     BLOGD(sc, DBG_LRO,
2942           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2943           fp->index, queue, frag_size);
2944 
2945     return (rc);
2946 }
2947 
2948 static inline void
2949 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2950 {
2951     int i, j;
2952 
2953     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2954         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2955 
2956         for (j = 0; j < 2; j++) {
2957             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2958             idx--;
2959         }
2960     }
2961 }
2962 
2963 static inline void
2964 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2965 {
2966     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2967     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2968 
2969     /*
2970      * Clear the two last indices in the page to 1. These are the indices that
2971      * correspond to the "next" element, hence will never be indicated and
2972      * should be removed from the calculations.
2973      */
2974     bxe_clear_sge_mask_next_elems(fp);
2975 }
2976 
2977 static inline void
2978 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2979                         uint16_t            idx)
2980 {
2981     uint16_t last_max = fp->last_max_sge;
2982 
2983     if (SUB_S16(idx, last_max) > 0) {
2984         fp->last_max_sge = idx;
2985     }
2986 }
2987 
2988 static inline void
2989 bxe_update_sge_prod(struct bxe_softc          *sc,
2990                     struct bxe_fastpath       *fp,
2991                     uint16_t                  sge_len,
2992                     union eth_sgl_or_raw_data *cqe)
2993 {
2994     uint16_t last_max, last_elem, first_elem;
2995     uint16_t delta = 0;
2996     uint16_t i;
2997 
2998     if (!sge_len) {
2999         return;
3000     }
3001 
3002     /* first mark all used pages */
3003     for (i = 0; i < sge_len; i++) {
3004         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3005                             RX_SGE(le16toh(cqe->sgl[i])));
3006     }
3007 
3008     BLOGD(sc, DBG_LRO,
3009           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3010           fp->index, sge_len - 1,
3011           le16toh(cqe->sgl[sge_len - 1]));
3012 
3013     /* assume that the last SGE index is the biggest */
3014     bxe_update_last_max_sge(fp,
3015                             le16toh(cqe->sgl[sge_len - 1]));
3016 
3017     last_max = RX_SGE(fp->last_max_sge);
3018     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3019     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3020 
3021     /* if ring is not full */
3022     if (last_elem + 1 != first_elem) {
3023         last_elem++;
3024     }
3025 
3026     /* now update the prod */
3027     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3028         if (__predict_true(fp->sge_mask[i])) {
3029             break;
3030         }
3031 
3032         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3033         delta += BIT_VEC64_ELEM_SZ;
3034     }
3035 
3036     if (delta > 0) {
3037         fp->rx_sge_prod += delta;
3038         /* clear page-end entries */
3039         bxe_clear_sge_mask_next_elems(fp);
3040     }
3041 
3042     BLOGD(sc, DBG_LRO,
3043           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3044           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3045 }
3046 
3047 /*
3048  * The aggregation on the current TPA queue has completed. Pull the individual
3049  * mbuf fragments together into a single mbuf, perform all necessary checksum
3050  * calculations, and send the resuting mbuf to the stack.
3051  */
3052 static void
3053 bxe_tpa_stop(struct bxe_softc          *sc,
3054              struct bxe_fastpath       *fp,
3055              struct bxe_sw_tpa_info    *tpa_info,
3056              uint16_t                  queue,
3057              uint16_t                  pages,
3058 			 struct eth_end_agg_rx_cqe *cqe,
3059              uint16_t                  cqe_idx)
3060 {
3061     if_t ifp = sc->ifp;
3062     struct mbuf *m;
3063     int rc = 0;
3064 
3065     BLOGD(sc, DBG_LRO,
3066           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3067           fp->index, queue, tpa_info->placement_offset,
3068           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3069 
3070     m = tpa_info->bd.m;
3071 
3072     /* allocate a replacement before modifying existing mbuf */
3073     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3074     if (rc) {
3075         /* drop the frame and log an error */
3076         fp->eth_q_stats.rx_soft_errors++;
3077         goto bxe_tpa_stop_exit;
3078     }
3079 
3080     /* we have a replacement, fixup the current mbuf */
3081     m_adj(m, tpa_info->placement_offset);
3082     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3083 
3084     /* mark the checksums valid (taken care of by the firmware) */
3085     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3086     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3087     m->m_pkthdr.csum_data = 0xffff;
3088     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3089                                CSUM_IP_VALID   |
3090                                CSUM_DATA_VALID |
3091                                CSUM_PSEUDO_HDR);
3092 
3093     /* aggregate all of the SGEs into a single mbuf */
3094     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3095     if (rc) {
3096         /* drop the packet and log an error */
3097         fp->eth_q_stats.rx_soft_errors++;
3098         m_freem(m);
3099     } else {
3100         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3101             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3102             m->m_flags |= M_VLANTAG;
3103         }
3104 
3105         /* assign packet to this interface interface */
3106         if_setrcvif(m, ifp);
3107 
3108 #if __FreeBSD_version >= 800000
3109         /* specify what RSS queue was used for this flow */
3110         m->m_pkthdr.flowid = fp->index;
3111         BXE_SET_FLOWID(m);
3112 #endif
3113 
3114         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3115         fp->eth_q_stats.rx_tpa_pkts++;
3116 
3117         /* pass the frame to the stack */
3118         if_input(ifp, m);
3119     }
3120 
3121     /* we passed an mbuf up the stack or dropped the frame */
3122     fp->eth_q_stats.mbuf_alloc_tpa--;
3123 
3124 bxe_tpa_stop_exit:
3125 
3126     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3127     fp->rx_tpa_queue_used &= ~(1 << queue);
3128 }
3129 
3130 static uint8_t
3131 bxe_service_rxsgl(
3132                  struct bxe_fastpath *fp,
3133                  uint16_t len,
3134                  uint16_t lenonbd,
3135                  struct mbuf *m,
3136                  struct eth_fast_path_rx_cqe *cqe_fp)
3137 {
3138     struct mbuf *m_frag;
3139     uint16_t frags, frag_len;
3140     uint16_t sge_idx = 0;
3141     uint16_t j;
3142     uint8_t i, rc = 0;
3143     uint32_t frag_size;
3144 
3145     /* adjust the mbuf */
3146     m->m_len = lenonbd;
3147 
3148     frag_size =  len - lenonbd;
3149     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3150 
3151     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3152         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3153 
3154         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3155         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3156         m_frag->m_len = frag_len;
3157 
3158        /* allocate a new mbuf for the SGE */
3159         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3160         if (rc) {
3161             /* Leave all remaining SGEs in the ring! */
3162             return (rc);
3163         }
3164         fp->eth_q_stats.mbuf_alloc_sge--;
3165 
3166         /* concatenate the fragment to the head mbuf */
3167         m_cat(m, m_frag);
3168 
3169         frag_size -= frag_len;
3170     }
3171 
3172     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3173 
3174     return rc;
3175 }
3176 
3177 static uint8_t
3178 bxe_rxeof(struct bxe_softc    *sc,
3179           struct bxe_fastpath *fp)
3180 {
3181     if_t ifp = sc->ifp;
3182     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3183     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3184     int rx_pkts = 0;
3185     int rc = 0;
3186 
3187     BXE_FP_RX_LOCK(fp);
3188 
3189     /* CQ "next element" is of the size of the regular element */
3190     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3191     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3192         hw_cq_cons++;
3193     }
3194 
3195     bd_cons = fp->rx_bd_cons;
3196     bd_prod = fp->rx_bd_prod;
3197     bd_prod_fw = bd_prod;
3198     sw_cq_cons = fp->rx_cq_cons;
3199     sw_cq_prod = fp->rx_cq_prod;
3200 
3201     /*
3202      * Memory barrier necessary as speculative reads of the rx
3203      * buffer can be ahead of the index in the status block
3204      */
3205     rmb();
3206 
3207     BLOGD(sc, DBG_RX,
3208           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3209           fp->index, hw_cq_cons, sw_cq_cons);
3210 
3211     while (sw_cq_cons != hw_cq_cons) {
3212         struct bxe_sw_rx_bd *rx_buf = NULL;
3213         union eth_rx_cqe *cqe;
3214         struct eth_fast_path_rx_cqe *cqe_fp;
3215         uint8_t cqe_fp_flags;
3216         enum eth_rx_cqe_type cqe_fp_type;
3217         uint16_t len, lenonbd,  pad;
3218         struct mbuf *m = NULL;
3219 
3220         comp_ring_cons = RCQ(sw_cq_cons);
3221         bd_prod = RX_BD(bd_prod);
3222         bd_cons = RX_BD(bd_cons);
3223 
3224         cqe          = &fp->rcq_chain[comp_ring_cons];
3225         cqe_fp       = &cqe->fast_path_cqe;
3226         cqe_fp_flags = cqe_fp->type_error_flags;
3227         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3228 
3229         BLOGD(sc, DBG_RX,
3230               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3231               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3232               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3233               fp->index,
3234               hw_cq_cons,
3235               sw_cq_cons,
3236               bd_prod,
3237               bd_cons,
3238               CQE_TYPE(cqe_fp_flags),
3239               cqe_fp_flags,
3240               cqe_fp->status_flags,
3241               le32toh(cqe_fp->rss_hash_result),
3242               le16toh(cqe_fp->vlan_tag),
3243               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3244               le16toh(cqe_fp->len_on_bd));
3245 
3246         /* is this a slowpath msg? */
3247         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3248             bxe_sp_event(sc, fp, cqe);
3249             goto next_cqe;
3250         }
3251 
3252         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3253 
3254         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3255             struct bxe_sw_tpa_info *tpa_info;
3256             uint16_t frag_size, pages;
3257             uint8_t queue;
3258 
3259             if (CQE_TYPE_START(cqe_fp_type)) {
3260                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3261                               bd_cons, bd_prod, cqe_fp);
3262                 m = NULL; /* packet not ready yet */
3263                 goto next_rx;
3264             }
3265 
3266             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3267                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3268 
3269             queue = cqe->end_agg_cqe.queue_index;
3270             tpa_info = &fp->rx_tpa_info[queue];
3271 
3272             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3273                   fp->index, queue);
3274 
3275             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3276                          tpa_info->len_on_bd);
3277             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3278 
3279             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3280                          &cqe->end_agg_cqe, comp_ring_cons);
3281 
3282             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3283 
3284             goto next_cqe;
3285         }
3286 
3287         /* non TPA */
3288 
3289         /* is this an error packet? */
3290         if (__predict_false(cqe_fp_flags &
3291                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3292             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3293             fp->eth_q_stats.rx_soft_errors++;
3294             goto next_rx;
3295         }
3296 
3297         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3298         lenonbd = le16toh(cqe_fp->len_on_bd);
3299         pad = cqe_fp->placement_offset;
3300 
3301         m = rx_buf->m;
3302 
3303         if (__predict_false(m == NULL)) {
3304             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3305                   bd_cons, fp->index);
3306             goto next_rx;
3307         }
3308 
3309         /* XXX double copy if packet length under a threshold */
3310 
3311         /*
3312          * If all the buffer descriptors are filled with mbufs then fill in
3313          * the current consumer index with a new BD. Else if a maximum Rx
3314          * buffer limit is imposed then fill in the next producer index.
3315          */
3316         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3317                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3318                                       bd_prod : bd_cons);
3319         if (rc != 0) {
3320 
3321             /* we simply reuse the received mbuf and don't post it to the stack */
3322             m = NULL;
3323 
3324             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3325                   fp->index, rc);
3326             fp->eth_q_stats.rx_soft_errors++;
3327 
3328             if (sc->max_rx_bufs != RX_BD_USABLE) {
3329                 /* copy this consumer index to the producer index */
3330                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3331                        sizeof(struct bxe_sw_rx_bd));
3332                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3333             }
3334 
3335             goto next_rx;
3336         }
3337 
3338         /* current mbuf was detached from the bd */
3339         fp->eth_q_stats.mbuf_alloc_rx--;
3340 
3341         /* we allocated a replacement mbuf, fixup the current one */
3342         m_adj(m, pad);
3343         m->m_pkthdr.len = m->m_len = len;
3344 
3345         if ((len > 60) && (len > lenonbd)) {
3346             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3347             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3348             if (rc)
3349                 break;
3350             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3351         } else if (lenonbd < len) {
3352             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3353         }
3354 
3355         /* assign packet to this interface interface */
3356 	if_setrcvif(m, ifp);
3357 
3358         /* assume no hardware checksum has complated */
3359         m->m_pkthdr.csum_flags = 0;
3360 
3361         /* validate checksum if offload enabled */
3362         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3363             /* check for a valid IP frame */
3364             if (!(cqe->fast_path_cqe.status_flags &
3365                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3366                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3367                 if (__predict_false(cqe_fp_flags &
3368                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3369                     fp->eth_q_stats.rx_hw_csum_errors++;
3370                 } else {
3371                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3372                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3373                 }
3374             }
3375 
3376             /* check for a valid TCP/UDP frame */
3377             if (!(cqe->fast_path_cqe.status_flags &
3378                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3379                 if (__predict_false(cqe_fp_flags &
3380                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3381                     fp->eth_q_stats.rx_hw_csum_errors++;
3382                 } else {
3383                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3384                     m->m_pkthdr.csum_data = 0xFFFF;
3385                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3386                                                CSUM_PSEUDO_HDR);
3387                 }
3388             }
3389         }
3390 
3391         /* if there is a VLAN tag then flag that info */
3392         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3393             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3394             m->m_flags |= M_VLANTAG;
3395         }
3396 
3397 #if __FreeBSD_version >= 800000
3398         /* specify what RSS queue was used for this flow */
3399         m->m_pkthdr.flowid = fp->index;
3400         BXE_SET_FLOWID(m);
3401 #endif
3402 
3403 next_rx:
3404 
3405         bd_cons    = RX_BD_NEXT(bd_cons);
3406         bd_prod    = RX_BD_NEXT(bd_prod);
3407         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3408 
3409         /* pass the frame to the stack */
3410         if (__predict_true(m != NULL)) {
3411             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3412             rx_pkts++;
3413             if_input(ifp, m);
3414         }
3415 
3416 next_cqe:
3417 
3418         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3419         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3420 
3421         /* limit spinning on the queue */
3422         if (rc != 0)
3423             break;
3424 
3425         if (rx_pkts == sc->rx_budget) {
3426             fp->eth_q_stats.rx_budget_reached++;
3427             break;
3428         }
3429     } /* while work to do */
3430 
3431     fp->rx_bd_cons = bd_cons;
3432     fp->rx_bd_prod = bd_prod_fw;
3433     fp->rx_cq_cons = sw_cq_cons;
3434     fp->rx_cq_prod = sw_cq_prod;
3435 
3436     /* Update producers */
3437     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3438 
3439     fp->eth_q_stats.rx_pkts += rx_pkts;
3440     fp->eth_q_stats.rx_calls++;
3441 
3442     BXE_FP_RX_UNLOCK(fp);
3443 
3444     return (sw_cq_cons != hw_cq_cons);
3445 }
3446 
3447 static uint16_t
3448 bxe_free_tx_pkt(struct bxe_softc    *sc,
3449                 struct bxe_fastpath *fp,
3450                 uint16_t            idx)
3451 {
3452     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3453     struct eth_tx_start_bd *tx_start_bd;
3454     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3455     uint16_t new_cons;
3456     int nbd;
3457 
3458     /* unmap the mbuf from non-paged memory */
3459     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3460 
3461     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3462     nbd = le16toh(tx_start_bd->nbd) - 1;
3463 
3464     new_cons = (tx_buf->first_bd + nbd);
3465 
3466     /* free the mbuf */
3467     if (__predict_true(tx_buf->m != NULL)) {
3468         m_freem(tx_buf->m);
3469         fp->eth_q_stats.mbuf_alloc_tx--;
3470     } else {
3471         fp->eth_q_stats.tx_chain_lost_mbuf++;
3472     }
3473 
3474     tx_buf->m = NULL;
3475     tx_buf->first_bd = 0;
3476 
3477     return (new_cons);
3478 }
3479 
3480 /* transmit timeout watchdog */
3481 static int
3482 bxe_watchdog(struct bxe_softc    *sc,
3483              struct bxe_fastpath *fp)
3484 {
3485     BXE_FP_TX_LOCK(fp);
3486 
3487     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3488         BXE_FP_TX_UNLOCK(fp);
3489         return (0);
3490     }
3491 
3492     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3493 
3494     BXE_FP_TX_UNLOCK(fp);
3495     BXE_SET_ERROR_BIT(sc, BXE_ERR_TXQ_STUCK);
3496     taskqueue_enqueue_timeout(taskqueue_thread,
3497         &sc->sp_err_timeout_task, hz/10);
3498 
3499     return (-1);
3500 }
3501 
3502 /* processes transmit completions */
3503 static uint8_t
3504 bxe_txeof(struct bxe_softc    *sc,
3505           struct bxe_fastpath *fp)
3506 {
3507     if_t ifp = sc->ifp;
3508     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3509     uint16_t tx_bd_avail;
3510 
3511     BXE_FP_TX_LOCK_ASSERT(fp);
3512 
3513     bd_cons = fp->tx_bd_cons;
3514     hw_cons = le16toh(*fp->tx_cons_sb);
3515     sw_cons = fp->tx_pkt_cons;
3516 
3517     while (sw_cons != hw_cons) {
3518         pkt_cons = TX_BD(sw_cons);
3519 
3520         BLOGD(sc, DBG_TX,
3521               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3522               fp->index, hw_cons, sw_cons, pkt_cons);
3523 
3524         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3525 
3526         sw_cons++;
3527     }
3528 
3529     fp->tx_pkt_cons = sw_cons;
3530     fp->tx_bd_cons  = bd_cons;
3531 
3532     BLOGD(sc, DBG_TX,
3533           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3534           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3535 
3536     mb();
3537 
3538     tx_bd_avail = bxe_tx_avail(sc, fp);
3539 
3540     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3541         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3542     } else {
3543         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3544     }
3545 
3546     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3547         /* reset the watchdog timer if there are pending transmits */
3548         fp->watchdog_timer = BXE_TX_TIMEOUT;
3549         return (TRUE);
3550     } else {
3551         /* clear watchdog when there are no pending transmits */
3552         fp->watchdog_timer = 0;
3553         return (FALSE);
3554     }
3555 }
3556 
3557 static void
3558 bxe_drain_tx_queues(struct bxe_softc *sc)
3559 {
3560     struct bxe_fastpath *fp;
3561     int i, count;
3562 
3563     /* wait until all TX fastpath tasks have completed */
3564     for (i = 0; i < sc->num_queues; i++) {
3565         fp = &sc->fp[i];
3566 
3567         count = 1000;
3568 
3569         while (bxe_has_tx_work(fp)) {
3570 
3571             BXE_FP_TX_LOCK(fp);
3572             bxe_txeof(sc, fp);
3573             BXE_FP_TX_UNLOCK(fp);
3574 
3575             if (count == 0) {
3576                 BLOGE(sc, "Timeout waiting for fp[%d] "
3577                           "transmits to complete!\n", i);
3578                 bxe_panic(sc, ("tx drain failure\n"));
3579                 return;
3580             }
3581 
3582             count--;
3583             DELAY(1000);
3584             rmb();
3585         }
3586     }
3587 
3588     return;
3589 }
3590 
3591 static int
3592 bxe_del_all_macs(struct bxe_softc          *sc,
3593                  struct ecore_vlan_mac_obj *mac_obj,
3594                  int                       mac_type,
3595                  uint8_t                   wait_for_comp)
3596 {
3597     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3598     int rc;
3599 
3600     /* wait for completion of requested */
3601     if (wait_for_comp) {
3602         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3603     }
3604 
3605     /* Set the mac type of addresses we want to clear */
3606     bxe_set_bit(mac_type, &vlan_mac_flags);
3607 
3608     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3609     if (rc < 0) {
3610         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3611             rc, mac_type, wait_for_comp);
3612     }
3613 
3614     return (rc);
3615 }
3616 
3617 static int
3618 bxe_fill_accept_flags(struct bxe_softc *sc,
3619                       uint32_t         rx_mode,
3620                       unsigned long    *rx_accept_flags,
3621                       unsigned long    *tx_accept_flags)
3622 {
3623     /* Clear the flags first */
3624     *rx_accept_flags = 0;
3625     *tx_accept_flags = 0;
3626 
3627     switch (rx_mode) {
3628     case BXE_RX_MODE_NONE:
3629         /*
3630          * 'drop all' supersedes any accept flags that may have been
3631          * passed to the function.
3632          */
3633         break;
3634 
3635     case BXE_RX_MODE_NORMAL:
3636         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3637         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3638         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3639 
3640         /* internal switching mode */
3641         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3642         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3643         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3644 
3645         break;
3646 
3647     case BXE_RX_MODE_ALLMULTI:
3648         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3649         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3650         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3651 
3652         /* internal switching mode */
3653         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3654         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3655         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3656 
3657         break;
3658 
3659     case BXE_RX_MODE_PROMISC:
3660         /*
3661          * According to deffinition of SI mode, iface in promisc mode
3662          * should receive matched and unmatched (in resolution of port)
3663          * unicast packets.
3664          */
3665         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3666         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3667         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3668         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3669 
3670         /* internal switching mode */
3671         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3672         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3673 
3674         if (IS_MF_SI(sc)) {
3675             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3676         } else {
3677             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3678         }
3679 
3680         break;
3681 
3682     default:
3683         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3684         return (-1);
3685     }
3686 
3687     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3688     if (rx_mode != BXE_RX_MODE_NONE) {
3689         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3690         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3691     }
3692 
3693     return (0);
3694 }
3695 
3696 static int
3697 bxe_set_q_rx_mode(struct bxe_softc *sc,
3698                   uint8_t          cl_id,
3699                   unsigned long    rx_mode_flags,
3700                   unsigned long    rx_accept_flags,
3701                   unsigned long    tx_accept_flags,
3702                   unsigned long    ramrod_flags)
3703 {
3704     struct ecore_rx_mode_ramrod_params ramrod_param;
3705     int rc;
3706 
3707     memset(&ramrod_param, 0, sizeof(ramrod_param));
3708 
3709     /* Prepare ramrod parameters */
3710     ramrod_param.cid = 0;
3711     ramrod_param.cl_id = cl_id;
3712     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3713     ramrod_param.func_id = SC_FUNC(sc);
3714 
3715     ramrod_param.pstate = &sc->sp_state;
3716     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3717 
3718     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3719     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3720 
3721     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3722 
3723     ramrod_param.ramrod_flags = ramrod_flags;
3724     ramrod_param.rx_mode_flags = rx_mode_flags;
3725 
3726     ramrod_param.rx_accept_flags = rx_accept_flags;
3727     ramrod_param.tx_accept_flags = tx_accept_flags;
3728 
3729     rc = ecore_config_rx_mode(sc, &ramrod_param);
3730     if (rc < 0) {
3731         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3732             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3733             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3734             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3735             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3736         return (rc);
3737     }
3738 
3739     return (0);
3740 }
3741 
3742 static int
3743 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3744 {
3745     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3746     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3747     int rc;
3748 
3749     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3750                                &tx_accept_flags);
3751     if (rc) {
3752         return (rc);
3753     }
3754 
3755     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3756     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3757 
3758     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3759     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3760                               rx_accept_flags, tx_accept_flags,
3761                               ramrod_flags));
3762 }
3763 
3764 /* returns the "mcp load_code" according to global load_count array */
3765 static int
3766 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3767 {
3768     int path = SC_PATH(sc);
3769     int port = SC_PORT(sc);
3770 
3771     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3772           path, load_count[path][0], load_count[path][1],
3773           load_count[path][2]);
3774     load_count[path][0]++;
3775     load_count[path][1 + port]++;
3776     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3777           path, load_count[path][0], load_count[path][1],
3778           load_count[path][2]);
3779     if (load_count[path][0] == 1) {
3780         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3781     } else if (load_count[path][1 + port] == 1) {
3782         return (FW_MSG_CODE_DRV_LOAD_PORT);
3783     } else {
3784         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3785     }
3786 }
3787 
3788 /* returns the "mcp load_code" according to global load_count array */
3789 static int
3790 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3791 {
3792     int port = SC_PORT(sc);
3793     int path = SC_PATH(sc);
3794 
3795     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3796           path, load_count[path][0], load_count[path][1],
3797           load_count[path][2]);
3798     load_count[path][0]--;
3799     load_count[path][1 + port]--;
3800     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3801           path, load_count[path][0], load_count[path][1],
3802           load_count[path][2]);
3803     if (load_count[path][0] == 0) {
3804         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3805     } else if (load_count[path][1 + port] == 0) {
3806         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3807     } else {
3808         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3809     }
3810 }
3811 
3812 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3813 static uint32_t
3814 bxe_send_unload_req(struct bxe_softc *sc,
3815                     int              unload_mode)
3816 {
3817     uint32_t reset_code = 0;
3818 
3819     /* Select the UNLOAD request mode */
3820     if (unload_mode == UNLOAD_NORMAL) {
3821         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3822     } else {
3823         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3824     }
3825 
3826     /* Send the request to the MCP */
3827     if (!BXE_NOMCP(sc)) {
3828         reset_code = bxe_fw_command(sc, reset_code, 0);
3829     } else {
3830         reset_code = bxe_nic_unload_no_mcp(sc);
3831     }
3832 
3833     return (reset_code);
3834 }
3835 
3836 /* send UNLOAD_DONE command to the MCP */
3837 static void
3838 bxe_send_unload_done(struct bxe_softc *sc,
3839                      uint8_t          keep_link)
3840 {
3841     uint32_t reset_param =
3842         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3843 
3844     /* Report UNLOAD_DONE to MCP */
3845     if (!BXE_NOMCP(sc)) {
3846         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3847     }
3848 }
3849 
3850 static int
3851 bxe_func_wait_started(struct bxe_softc *sc)
3852 {
3853     int tout = 50;
3854 
3855     if (!sc->port.pmf) {
3856         return (0);
3857     }
3858 
3859     /*
3860      * (assumption: No Attention from MCP at this stage)
3861      * PMF probably in the middle of TX disable/enable transaction
3862      * 1. Sync IRS for default SB
3863      * 2. Sync SP queue - this guarantees us that attention handling started
3864      * 3. Wait, that TX disable/enable transaction completes
3865      *
3866      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3867      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3868      * received completion for the transaction the state is TX_STOPPED.
3869      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3870      * transaction.
3871      */
3872 
3873     /* XXX make sure default SB ISR is done */
3874     /* need a way to synchronize an irq (intr_mtx?) */
3875 
3876     /* XXX flush any work queues */
3877 
3878     while (ecore_func_get_state(sc, &sc->func_obj) !=
3879            ECORE_F_STATE_STARTED && tout--) {
3880         DELAY(20000);
3881     }
3882 
3883     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3884         /*
3885          * Failed to complete the transaction in a "good way"
3886          * Force both transactions with CLR bit.
3887          */
3888         struct ecore_func_state_params func_params = { NULL };
3889 
3890         BLOGE(sc, "Unexpected function state! "
3891                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3892 
3893         func_params.f_obj = &sc->func_obj;
3894         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3895 
3896         /* STARTED-->TX_STOPPED */
3897         func_params.cmd = ECORE_F_CMD_TX_STOP;
3898         ecore_func_state_change(sc, &func_params);
3899 
3900         /* TX_STOPPED-->STARTED */
3901         func_params.cmd = ECORE_F_CMD_TX_START;
3902         return (ecore_func_state_change(sc, &func_params));
3903     }
3904 
3905     return (0);
3906 }
3907 
3908 static int
3909 bxe_stop_queue(struct bxe_softc *sc,
3910                int              index)
3911 {
3912     struct bxe_fastpath *fp = &sc->fp[index];
3913     struct ecore_queue_state_params q_params = { NULL };
3914     int rc;
3915 
3916     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3917 
3918     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3919     /* We want to wait for completion in this context */
3920     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3921 
3922     /* Stop the primary connection: */
3923 
3924     /* ...halt the connection */
3925     q_params.cmd = ECORE_Q_CMD_HALT;
3926     rc = ecore_queue_state_change(sc, &q_params);
3927     if (rc) {
3928         return (rc);
3929     }
3930 
3931     /* ...terminate the connection */
3932     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3933     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3934     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3935     rc = ecore_queue_state_change(sc, &q_params);
3936     if (rc) {
3937         return (rc);
3938     }
3939 
3940     /* ...delete cfc entry */
3941     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3942     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3943     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3944     return (ecore_queue_state_change(sc, &q_params));
3945 }
3946 
3947 /* wait for the outstanding SP commands */
3948 static inline uint8_t
3949 bxe_wait_sp_comp(struct bxe_softc *sc,
3950                  unsigned long    mask)
3951 {
3952     unsigned long tmp;
3953     int tout = 5000; /* wait for 5 secs tops */
3954 
3955     while (tout--) {
3956         mb();
3957         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3958             return (TRUE);
3959         }
3960 
3961         DELAY(1000);
3962     }
3963 
3964     mb();
3965 
3966     tmp = atomic_load_acq_long(&sc->sp_state);
3967     if (tmp & mask) {
3968         BLOGE(sc, "Filtering completion timed out: "
3969                   "sp_state 0x%lx, mask 0x%lx\n",
3970               tmp, mask);
3971         return (FALSE);
3972     }
3973 
3974     return (FALSE);
3975 }
3976 
3977 static int
3978 bxe_func_stop(struct bxe_softc *sc)
3979 {
3980     struct ecore_func_state_params func_params = { NULL };
3981     int rc;
3982 
3983     /* prepare parameters for function state transitions */
3984     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3985     func_params.f_obj = &sc->func_obj;
3986     func_params.cmd = ECORE_F_CMD_STOP;
3987 
3988     /*
3989      * Try to stop the function the 'good way'. If it fails (in case
3990      * of a parity error during bxe_chip_cleanup()) and we are
3991      * not in a debug mode, perform a state transaction in order to
3992      * enable further HW_RESET transaction.
3993      */
3994     rc = ecore_func_state_change(sc, &func_params);
3995     if (rc) {
3996         BLOGE(sc, "FUNC_STOP ramrod failed. "
3997                   "Running a dry transaction (%d)\n", rc);
3998         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3999         return (ecore_func_state_change(sc, &func_params));
4000     }
4001 
4002     return (0);
4003 }
4004 
4005 static int
4006 bxe_reset_hw(struct bxe_softc *sc,
4007              uint32_t         load_code)
4008 {
4009     struct ecore_func_state_params func_params = { NULL };
4010 
4011     /* Prepare parameters for function state transitions */
4012     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4013 
4014     func_params.f_obj = &sc->func_obj;
4015     func_params.cmd = ECORE_F_CMD_HW_RESET;
4016 
4017     func_params.params.hw_init.load_phase = load_code;
4018 
4019     return (ecore_func_state_change(sc, &func_params));
4020 }
4021 
4022 static void
4023 bxe_int_disable_sync(struct bxe_softc *sc,
4024                      int              disable_hw)
4025 {
4026     if (disable_hw) {
4027         /* prevent the HW from sending interrupts */
4028         bxe_int_disable(sc);
4029     }
4030 
4031     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4032     /* make sure all ISRs are done */
4033 
4034     /* XXX make sure sp_task is not running */
4035     /* cancel and flush work queues */
4036 }
4037 
4038 static void
4039 bxe_chip_cleanup(struct bxe_softc *sc,
4040                  uint32_t         unload_mode,
4041                  uint8_t          keep_link)
4042 {
4043     int port = SC_PORT(sc);
4044     struct ecore_mcast_ramrod_params rparam = { NULL };
4045     uint32_t reset_code;
4046     int i, rc = 0;
4047 
4048     bxe_drain_tx_queues(sc);
4049 
4050     /* give HW time to discard old tx messages */
4051     DELAY(1000);
4052 
4053     /* Clean all ETH MACs */
4054     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4055     if (rc < 0) {
4056         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4057     }
4058 
4059     /* Clean up UC list  */
4060     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4061     if (rc < 0) {
4062         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4063     }
4064 
4065     /* Disable LLH */
4066     if (!CHIP_IS_E1(sc)) {
4067         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4068     }
4069 
4070     /* Set "drop all" to stop Rx */
4071 
4072     /*
4073      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4074      * a race between the completion code and this code.
4075      */
4076     BXE_MCAST_LOCK(sc);
4077 
4078     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4079         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4080     } else {
4081         bxe_set_storm_rx_mode(sc);
4082     }
4083 
4084     /* Clean up multicast configuration */
4085     rparam.mcast_obj = &sc->mcast_obj;
4086     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4087     if (rc < 0) {
4088         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4089     }
4090 
4091     BXE_MCAST_UNLOCK(sc);
4092 
4093     // XXX bxe_iov_chip_cleanup(sc);
4094 
4095     /*
4096      * Send the UNLOAD_REQUEST to the MCP. This will return if
4097      * this function should perform FUNCTION, PORT, or COMMON HW
4098      * reset.
4099      */
4100     reset_code = bxe_send_unload_req(sc, unload_mode);
4101 
4102     /*
4103      * (assumption: No Attention from MCP at this stage)
4104      * PMF probably in the middle of TX disable/enable transaction
4105      */
4106     rc = bxe_func_wait_started(sc);
4107     if (rc) {
4108         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4109     }
4110 
4111     /*
4112      * Close multi and leading connections
4113      * Completions for ramrods are collected in a synchronous way
4114      */
4115     for (i = 0; i < sc->num_queues; i++) {
4116         if (bxe_stop_queue(sc, i)) {
4117             goto unload_error;
4118         }
4119     }
4120 
4121     /*
4122      * If SP settings didn't get completed so far - something
4123      * very wrong has happen.
4124      */
4125     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4126         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4127     }
4128 
4129 unload_error:
4130 
4131     rc = bxe_func_stop(sc);
4132     if (rc) {
4133         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4134     }
4135 
4136     /* disable HW interrupts */
4137     bxe_int_disable_sync(sc, TRUE);
4138 
4139     /* detach interrupts */
4140     bxe_interrupt_detach(sc);
4141 
4142     /* Reset the chip */
4143     rc = bxe_reset_hw(sc, reset_code);
4144     if (rc) {
4145         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4146     }
4147 
4148     /* Report UNLOAD_DONE to MCP */
4149     bxe_send_unload_done(sc, keep_link);
4150 }
4151 
4152 static void
4153 bxe_disable_close_the_gate(struct bxe_softc *sc)
4154 {
4155     uint32_t val;
4156     int port = SC_PORT(sc);
4157 
4158     BLOGD(sc, DBG_LOAD,
4159           "Disabling 'close the gates'\n");
4160 
4161     if (CHIP_IS_E1(sc)) {
4162         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4163                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4164         val = REG_RD(sc, addr);
4165         val &= ~(0x300);
4166         REG_WR(sc, addr, val);
4167     } else {
4168         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4169         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4170                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4171         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4172     }
4173 }
4174 
4175 /*
4176  * Cleans the object that have internal lists without sending
4177  * ramrods. Should be run when interrutps are disabled.
4178  */
4179 static void
4180 bxe_squeeze_objects(struct bxe_softc *sc)
4181 {
4182     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4183     struct ecore_mcast_ramrod_params rparam = { NULL };
4184     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4185     int rc;
4186 
4187     /* Cleanup MACs' object first... */
4188 
4189     /* Wait for completion of requested */
4190     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4191     /* Perform a dry cleanup */
4192     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4193 
4194     /* Clean ETH primary MAC */
4195     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4196     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4197                              &ramrod_flags);
4198     if (rc != 0) {
4199         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4200     }
4201 
4202     /* Cleanup UC list */
4203     vlan_mac_flags = 0;
4204     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4205     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4206                              &ramrod_flags);
4207     if (rc != 0) {
4208         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4209     }
4210 
4211     /* Now clean mcast object... */
4212 
4213     rparam.mcast_obj = &sc->mcast_obj;
4214     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4215 
4216     /* Add a DEL command... */
4217     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4218     if (rc < 0) {
4219         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4220     }
4221 
4222     /* now wait until all pending commands are cleared */
4223 
4224     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4225     while (rc != 0) {
4226         if (rc < 0) {
4227             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4228             return;
4229         }
4230 
4231         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4232     }
4233 }
4234 
4235 /* stop the controller */
4236 static __noinline int
4237 bxe_nic_unload(struct bxe_softc *sc,
4238                uint32_t         unload_mode,
4239                uint8_t          keep_link)
4240 {
4241     uint8_t global = FALSE;
4242     uint32_t val;
4243     int i;
4244 
4245     BXE_CORE_LOCK_ASSERT(sc);
4246 
4247     if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4248 
4249     for (i = 0; i < sc->num_queues; i++) {
4250         struct bxe_fastpath *fp;
4251 
4252         fp = &sc->fp[i];
4253 	fp->watchdog_timer = 0;
4254         BXE_FP_TX_LOCK(fp);
4255         BXE_FP_TX_UNLOCK(fp);
4256     }
4257 
4258     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4259 
4260     /* mark driver as unloaded in shmem2 */
4261     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4262         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4263         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4264                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4265     }
4266 
4267     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4268         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4269 
4270 	if(CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
4271             /*
4272              * We can get here if the driver has been unloaded
4273              * during parity error recovery and is either waiting for a
4274              * leader to complete or for other functions to unload and
4275              * then ifconfig down has been issued. In this case we want to
4276              * unload and let other functions to complete a recovery
4277              * process.
4278              */
4279             sc->recovery_state = BXE_RECOVERY_DONE;
4280             sc->is_leader = 0;
4281             bxe_release_leader_lock(sc);
4282             mb();
4283             BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4284 	}
4285         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4286             " state = 0x%x\n", sc->recovery_state, sc->state);
4287         return (-1);
4288     }
4289 
4290     /*
4291      * Nothing to do during unload if previous bxe_nic_load()
4292      * did not completed successfully - all resourses are released.
4293      */
4294     if ((sc->state == BXE_STATE_CLOSED) ||
4295         (sc->state == BXE_STATE_ERROR)) {
4296         return (0);
4297     }
4298 
4299     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4300     mb();
4301 
4302     /* stop tx */
4303     bxe_tx_disable(sc);
4304 
4305     sc->rx_mode = BXE_RX_MODE_NONE;
4306     /* XXX set rx mode ??? */
4307 
4308     if (IS_PF(sc) && !sc->grcdump_done) {
4309         /* set ALWAYS_ALIVE bit in shmem */
4310         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4311 
4312         bxe_drv_pulse(sc);
4313 
4314         bxe_stats_handle(sc, STATS_EVENT_STOP);
4315         bxe_save_statistics(sc);
4316     }
4317 
4318     /* wait till consumers catch up with producers in all queues */
4319     bxe_drain_tx_queues(sc);
4320 
4321     /* if VF indicate to PF this function is going down (PF will delete sp
4322      * elements and clear initializations
4323      */
4324     if (IS_VF(sc)) {
4325         ; /* bxe_vfpf_close_vf(sc); */
4326     } else if (unload_mode != UNLOAD_RECOVERY) {
4327         /* if this is a normal/close unload need to clean up chip */
4328         if (!sc->grcdump_done)
4329             bxe_chip_cleanup(sc, unload_mode, keep_link);
4330     } else {
4331         /* Send the UNLOAD_REQUEST to the MCP */
4332         bxe_send_unload_req(sc, unload_mode);
4333 
4334         /*
4335          * Prevent transactions to host from the functions on the
4336          * engine that doesn't reset global blocks in case of global
4337          * attention once gloabl blocks are reset and gates are opened
4338          * (the engine which leader will perform the recovery
4339          * last).
4340          */
4341         if (!CHIP_IS_E1x(sc)) {
4342             bxe_pf_disable(sc);
4343         }
4344 
4345         /* disable HW interrupts */
4346         bxe_int_disable_sync(sc, TRUE);
4347 
4348         /* detach interrupts */
4349         bxe_interrupt_detach(sc);
4350 
4351         /* Report UNLOAD_DONE to MCP */
4352         bxe_send_unload_done(sc, FALSE);
4353     }
4354 
4355     /*
4356      * At this stage no more interrupts will arrive so we may safely clean
4357      * the queue'able objects here in case they failed to get cleaned so far.
4358      */
4359     if (IS_PF(sc)) {
4360         bxe_squeeze_objects(sc);
4361     }
4362 
4363     /* There should be no more pending SP commands at this stage */
4364     sc->sp_state = 0;
4365 
4366     sc->port.pmf = 0;
4367 
4368     bxe_free_fp_buffers(sc);
4369 
4370     if (IS_PF(sc)) {
4371         bxe_free_mem(sc);
4372     }
4373 
4374     bxe_free_fw_stats_mem(sc);
4375 
4376     sc->state = BXE_STATE_CLOSED;
4377 
4378     /*
4379      * Check if there are pending parity attentions. If there are - set
4380      * RECOVERY_IN_PROGRESS.
4381      */
4382     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4383         bxe_set_reset_in_progress(sc);
4384 
4385         /* Set RESET_IS_GLOBAL if needed */
4386         if (global) {
4387             bxe_set_reset_global(sc);
4388         }
4389     }
4390 
4391     /*
4392      * The last driver must disable a "close the gate" if there is no
4393      * parity attention or "process kill" pending.
4394      */
4395     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4396         bxe_reset_is_done(sc, SC_PATH(sc))) {
4397         bxe_disable_close_the_gate(sc);
4398     }
4399 
4400     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4401 
4402     bxe_link_report(sc);
4403 
4404     return (0);
4405 }
4406 
4407 /*
4408  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4409  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4410  */
4411 static int
4412 bxe_ifmedia_update(struct ifnet  *ifp)
4413 {
4414     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4415     struct ifmedia *ifm;
4416 
4417     ifm = &sc->ifmedia;
4418 
4419     /* We only support Ethernet media type. */
4420     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4421         return (EINVAL);
4422     }
4423 
4424     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4425     case IFM_AUTO:
4426          break;
4427     case IFM_10G_CX4:
4428     case IFM_10G_SR:
4429     case IFM_10G_T:
4430     case IFM_10G_TWINAX:
4431     default:
4432         /* We don't support changing the media type. */
4433         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4434               IFM_SUBTYPE(ifm->ifm_media));
4435         return (EINVAL);
4436     }
4437 
4438     return (0);
4439 }
4440 
4441 /*
4442  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4443  */
4444 static void
4445 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4446 {
4447     struct bxe_softc *sc = if_getsoftc(ifp);
4448 
4449     /* Bug 165447: the 'ifconfig' tool skips printing of the "status: ..."
4450        line if the IFM_AVALID flag is *NOT* set. So we need to set this
4451        flag unconditionally (irrespective of the admininistrative
4452        'up/down' state of the interface) to ensure that that line is always
4453        displayed.
4454     */
4455     ifmr->ifm_status = IFM_AVALID;
4456 
4457     /* Setup the default interface info. */
4458     ifmr->ifm_active = IFM_ETHER;
4459 
4460     /* Report link down if the driver isn't running. */
4461     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4462         ifmr->ifm_active |= IFM_NONE;
4463         BLOGD(sc, DBG_PHY, "in %s : nic still not loaded fully\n", __func__);
4464         BLOGD(sc, DBG_PHY, "in %s : link_up (1) : %d\n",
4465                 __func__, sc->link_vars.link_up);
4466         return;
4467     }
4468 
4469 
4470     if (sc->link_vars.link_up) {
4471         ifmr->ifm_status |= IFM_ACTIVE;
4472         ifmr->ifm_active |= IFM_FDX;
4473     } else {
4474         ifmr->ifm_active |= IFM_NONE;
4475         BLOGD(sc, DBG_PHY, "in %s : setting IFM_NONE\n",
4476                 __func__);
4477         return;
4478     }
4479 
4480     ifmr->ifm_active |= sc->media;
4481     return;
4482 }
4483 
4484 static void
4485 bxe_handle_chip_tq(void *context,
4486                    int  pending)
4487 {
4488     struct bxe_softc *sc = (struct bxe_softc *)context;
4489     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4490 
4491     switch (work)
4492     {
4493 
4494     case CHIP_TQ_REINIT:
4495         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4496             /* restart the interface */
4497             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4498             bxe_periodic_stop(sc);
4499             BXE_CORE_LOCK(sc);
4500             bxe_stop_locked(sc);
4501             bxe_init_locked(sc);
4502             BXE_CORE_UNLOCK(sc);
4503         }
4504         break;
4505 
4506     default:
4507         break;
4508     }
4509 }
4510 
4511 /*
4512  * Handles any IOCTL calls from the operating system.
4513  *
4514  * Returns:
4515  *   0 = Success, >0 Failure
4516  */
4517 static int
4518 bxe_ioctl(if_t ifp,
4519           u_long       command,
4520           caddr_t      data)
4521 {
4522     struct bxe_softc *sc = if_getsoftc(ifp);
4523     struct ifreq *ifr = (struct ifreq *)data;
4524     int mask = 0;
4525     int reinit = 0;
4526     int error = 0;
4527 
4528     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4529     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4530 
4531     switch (command)
4532     {
4533     case SIOCSIFMTU:
4534         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4535               ifr->ifr_mtu);
4536 
4537         if (sc->mtu == ifr->ifr_mtu) {
4538             /* nothing to change */
4539             break;
4540         }
4541 
4542         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4543             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4544                   ifr->ifr_mtu, mtu_min, mtu_max);
4545             error = EINVAL;
4546             break;
4547         }
4548 
4549         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4550                              (unsigned long)ifr->ifr_mtu);
4551 	/*
4552         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4553                               (unsigned long)ifr->ifr_mtu);
4554 	XXX - Not sure why it needs to be atomic
4555 	*/
4556 	if_setmtu(ifp, ifr->ifr_mtu);
4557         reinit = 1;
4558         break;
4559 
4560     case SIOCSIFFLAGS:
4561         /* toggle the interface state up or down */
4562         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4563 
4564 	BXE_CORE_LOCK(sc);
4565         /* check if the interface is up */
4566         if (if_getflags(ifp) & IFF_UP) {
4567             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4568                 /* set the receive mode flags */
4569                 bxe_set_rx_mode(sc);
4570             } else if(sc->state != BXE_STATE_DISABLED) {
4571 		bxe_init_locked(sc);
4572             }
4573         } else {
4574             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4575 		bxe_periodic_stop(sc);
4576 		bxe_stop_locked(sc);
4577             }
4578         }
4579 	BXE_CORE_UNLOCK(sc);
4580 
4581         break;
4582 
4583     case SIOCADDMULTI:
4584     case SIOCDELMULTI:
4585         /* add/delete multicast addresses */
4586         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4587 
4588         /* check if the interface is up */
4589         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4590             /* set the receive mode flags */
4591 	    BXE_CORE_LOCK(sc);
4592             bxe_set_rx_mode(sc);
4593 	    BXE_CORE_UNLOCK(sc);
4594         }
4595 
4596         break;
4597 
4598     case SIOCSIFCAP:
4599         /* find out which capabilities have changed */
4600         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4601 
4602         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4603               mask);
4604 
4605         /* toggle the LRO capabilites enable flag */
4606         if (mask & IFCAP_LRO) {
4607 	    if_togglecapenable(ifp, IFCAP_LRO);
4608             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4609                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4610             reinit = 1;
4611         }
4612 
4613         /* toggle the TXCSUM checksum capabilites enable flag */
4614         if (mask & IFCAP_TXCSUM) {
4615 	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4616             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4617                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4618             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4619                 if_sethwassistbits(ifp, (CSUM_IP      |
4620                                     CSUM_TCP      |
4621                                     CSUM_UDP      |
4622                                     CSUM_TSO      |
4623                                     CSUM_TCP_IPV6 |
4624                                     CSUM_UDP_IPV6), 0);
4625             } else {
4626 		if_clearhwassist(ifp); /* XXX */
4627             }
4628         }
4629 
4630         /* toggle the RXCSUM checksum capabilities enable flag */
4631         if (mask & IFCAP_RXCSUM) {
4632 	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4633             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4634                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4635             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4636                 if_sethwassistbits(ifp, (CSUM_IP      |
4637                                     CSUM_TCP      |
4638                                     CSUM_UDP      |
4639                                     CSUM_TSO      |
4640                                     CSUM_TCP_IPV6 |
4641                                     CSUM_UDP_IPV6), 0);
4642             } else {
4643 		if_clearhwassist(ifp); /* XXX */
4644             }
4645         }
4646 
4647         /* toggle TSO4 capabilities enabled flag */
4648         if (mask & IFCAP_TSO4) {
4649             if_togglecapenable(ifp, IFCAP_TSO4);
4650             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4651                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4652         }
4653 
4654         /* toggle TSO6 capabilities enabled flag */
4655         if (mask & IFCAP_TSO6) {
4656 	    if_togglecapenable(ifp, IFCAP_TSO6);
4657             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4658                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4659         }
4660 
4661         /* toggle VLAN_HWTSO capabilities enabled flag */
4662         if (mask & IFCAP_VLAN_HWTSO) {
4663 
4664 	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4665             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4666                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4667         }
4668 
4669         /* toggle VLAN_HWCSUM capabilities enabled flag */
4670         if (mask & IFCAP_VLAN_HWCSUM) {
4671             /* XXX investigate this... */
4672             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4673             error = EINVAL;
4674         }
4675 
4676         /* toggle VLAN_MTU capabilities enable flag */
4677         if (mask & IFCAP_VLAN_MTU) {
4678             /* XXX investigate this... */
4679             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4680             error = EINVAL;
4681         }
4682 
4683         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4684         if (mask & IFCAP_VLAN_HWTAGGING) {
4685             /* XXX investigate this... */
4686             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4687             error = EINVAL;
4688         }
4689 
4690         /* toggle VLAN_HWFILTER capabilities enabled flag */
4691         if (mask & IFCAP_VLAN_HWFILTER) {
4692             /* XXX investigate this... */
4693             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4694             error = EINVAL;
4695         }
4696 
4697         /* XXX not yet...
4698          * IFCAP_WOL_MAGIC
4699          */
4700 
4701         break;
4702 
4703     case SIOCSIFMEDIA:
4704     case SIOCGIFMEDIA:
4705         /* set/get interface media */
4706         BLOGD(sc, DBG_IOCTL,
4707               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4708               (command & 0xff));
4709         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4710         break;
4711 
4712     default:
4713         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4714               (command & 0xff));
4715         error = ether_ioctl(ifp, command, data);
4716         break;
4717     }
4718 
4719     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4720         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4721               "Re-initializing hardware from IOCTL change\n");
4722 	bxe_periodic_stop(sc);
4723 	BXE_CORE_LOCK(sc);
4724 	bxe_stop_locked(sc);
4725 	bxe_init_locked(sc);
4726 	BXE_CORE_UNLOCK(sc);
4727     }
4728 
4729     return (error);
4730 }
4731 
4732 static __noinline void
4733 bxe_dump_mbuf(struct bxe_softc *sc,
4734               struct mbuf      *m,
4735               uint8_t          contents)
4736 {
4737     char * type;
4738     int i = 0;
4739 
4740     if (!(sc->debug & DBG_MBUF)) {
4741         return;
4742     }
4743 
4744     if (m == NULL) {
4745         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4746         return;
4747     }
4748 
4749     while (m) {
4750 
4751 #if __FreeBSD_version >= 1000000
4752         BLOGD(sc, DBG_MBUF,
4753               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4754               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4755 
4756         if (m->m_flags & M_PKTHDR) {
4757              BLOGD(sc, DBG_MBUF,
4758                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4759                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4760                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4761         }
4762 #else
4763         BLOGD(sc, DBG_MBUF,
4764               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4765               i, m, m->m_len, m->m_flags,
4766               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4767 
4768         if (m->m_flags & M_PKTHDR) {
4769              BLOGD(sc, DBG_MBUF,
4770                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4771                    i, m->m_pkthdr.len, m->m_flags,
4772                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4773                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4774                    "\22M_PROMISC\23M_NOFREE",
4775                    (int)m->m_pkthdr.csum_flags,
4776                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4777                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4778                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4779                    "\14CSUM_PSEUDO_HDR");
4780         }
4781 #endif /* #if __FreeBSD_version >= 1000000 */
4782 
4783         if (m->m_flags & M_EXT) {
4784             switch (m->m_ext.ext_type) {
4785             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4786             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4787             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4788             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4789             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4790             case EXT_PACKET:     type = "EXT_PACKET";     break;
4791             case EXT_MBUF:       type = "EXT_MBUF";       break;
4792             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4793             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4794             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4795             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4796             default:             type = "UNKNOWN";        break;
4797             }
4798 
4799             BLOGD(sc, DBG_MBUF,
4800                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4801                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4802         }
4803 
4804         if (contents) {
4805             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4806         }
4807 
4808         m = m->m_next;
4809         i++;
4810     }
4811 }
4812 
4813 /*
4814  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4815  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4816  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4817  * The headers comes in a separate bd in FreeBSD so 13-3=10.
4818  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4819  */
4820 static int
4821 bxe_chktso_window(struct bxe_softc  *sc,
4822                   int               nsegs,
4823                   bus_dma_segment_t *segs,
4824                   struct mbuf       *m)
4825 {
4826     uint32_t num_wnds, wnd_size, wnd_sum;
4827     int32_t frag_idx, wnd_idx;
4828     unsigned short lso_mss;
4829     int defrag;
4830 
4831     defrag = 0;
4832     wnd_sum = 0;
4833     wnd_size = 10;
4834     num_wnds = nsegs - wnd_size;
4835     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4836 
4837     /*
4838      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4839      * first window sum of data while skipping the first assuming it is the
4840      * header in FreeBSD.
4841      */
4842     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4843         wnd_sum += htole16(segs[frag_idx].ds_len);
4844     }
4845 
4846     /* check the first 10 bd window size */
4847     if (wnd_sum < lso_mss) {
4848         return (1);
4849     }
4850 
4851     /* run through the windows */
4852     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4853         /* subtract the first mbuf->m_len of the last wndw(-header) */
4854         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4855         /* add the next mbuf len to the len of our new window */
4856         wnd_sum += htole16(segs[frag_idx].ds_len);
4857         if (wnd_sum < lso_mss) {
4858             return (1);
4859         }
4860     }
4861 
4862     return (0);
4863 }
4864 
4865 static uint8_t
4866 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4867                     struct mbuf         *m,
4868                     uint32_t            *parsing_data)
4869 {
4870     struct ether_vlan_header *eh = NULL;
4871     struct ip *ip4 = NULL;
4872     struct ip6_hdr *ip6 = NULL;
4873     caddr_t ip = NULL;
4874     struct tcphdr *th = NULL;
4875     int e_hlen, ip_hlen, l4_off;
4876     uint16_t proto;
4877 
4878     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4879         /* no L4 checksum offload needed */
4880         return (0);
4881     }
4882 
4883     /* get the Ethernet header */
4884     eh = mtod(m, struct ether_vlan_header *);
4885 
4886     /* handle VLAN encapsulation if present */
4887     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4888         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4889         proto  = ntohs(eh->evl_proto);
4890     } else {
4891         e_hlen = ETHER_HDR_LEN;
4892         proto  = ntohs(eh->evl_encap_proto);
4893     }
4894 
4895     switch (proto) {
4896     case ETHERTYPE_IP:
4897         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4898         ip4 = (m->m_len < sizeof(struct ip)) ?
4899                   (struct ip *)m->m_next->m_data :
4900                   (struct ip *)(m->m_data + e_hlen);
4901         /* ip_hl is number of 32-bit words */
4902         ip_hlen = (ip4->ip_hl << 2);
4903         ip = (caddr_t)ip4;
4904         break;
4905     case ETHERTYPE_IPV6:
4906         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4907         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4908                   (struct ip6_hdr *)m->m_next->m_data :
4909                   (struct ip6_hdr *)(m->m_data + e_hlen);
4910         /* XXX cannot support offload with IPv6 extensions */
4911         ip_hlen = sizeof(struct ip6_hdr);
4912         ip = (caddr_t)ip6;
4913         break;
4914     default:
4915         /* We can't offload in this case... */
4916         /* XXX error stat ??? */
4917         return (0);
4918     }
4919 
4920     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4921     l4_off = (e_hlen + ip_hlen);
4922 
4923     *parsing_data |=
4924         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4925          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4926 
4927     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4928                                   CSUM_TSO |
4929                                   CSUM_TCP_IPV6)) {
4930         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4931         th = (struct tcphdr *)(ip + ip_hlen);
4932         /* th_off is number of 32-bit words */
4933         *parsing_data |= ((th->th_off <<
4934                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4935                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4936         return (l4_off + (th->th_off << 2)); /* entire header length */
4937     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4938                                          CSUM_UDP_IPV6)) {
4939         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4940         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4941     } else {
4942         /* XXX error stat ??? */
4943         return (0);
4944     }
4945 }
4946 
4947 static uint8_t
4948 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4949                  struct mbuf                *m,
4950                  struct eth_tx_parse_bd_e1x *pbd)
4951 {
4952     struct ether_vlan_header *eh = NULL;
4953     struct ip *ip4 = NULL;
4954     struct ip6_hdr *ip6 = NULL;
4955     caddr_t ip = NULL;
4956     struct tcphdr *th = NULL;
4957     struct udphdr *uh = NULL;
4958     int e_hlen, ip_hlen;
4959     uint16_t proto;
4960     uint8_t hlen;
4961     uint16_t tmp_csum;
4962     uint32_t *tmp_uh;
4963 
4964     /* get the Ethernet header */
4965     eh = mtod(m, struct ether_vlan_header *);
4966 
4967     /* handle VLAN encapsulation if present */
4968     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4969         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4970         proto  = ntohs(eh->evl_proto);
4971     } else {
4972         e_hlen = ETHER_HDR_LEN;
4973         proto  = ntohs(eh->evl_encap_proto);
4974     }
4975 
4976     switch (proto) {
4977     case ETHERTYPE_IP:
4978         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4979         ip4 = (m->m_len < sizeof(struct ip)) ?
4980                   (struct ip *)m->m_next->m_data :
4981                   (struct ip *)(m->m_data + e_hlen);
4982         /* ip_hl is number of 32-bit words */
4983         ip_hlen = (ip4->ip_hl << 1);
4984         ip = (caddr_t)ip4;
4985         break;
4986     case ETHERTYPE_IPV6:
4987         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4988         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4989                   (struct ip6_hdr *)m->m_next->m_data :
4990                   (struct ip6_hdr *)(m->m_data + e_hlen);
4991         /* XXX cannot support offload with IPv6 extensions */
4992         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4993         ip = (caddr_t)ip6;
4994         break;
4995     default:
4996         /* We can't offload in this case... */
4997         /* XXX error stat ??? */
4998         return (0);
4999     }
5000 
5001     hlen = (e_hlen >> 1);
5002 
5003     /* note that rest of global_data is indirectly zeroed here */
5004     if (m->m_flags & M_VLANTAG) {
5005         pbd->global_data =
5006             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5007     } else {
5008         pbd->global_data = htole16(hlen);
5009     }
5010 
5011     pbd->ip_hlen_w = ip_hlen;
5012 
5013     hlen += pbd->ip_hlen_w;
5014 
5015     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5016 
5017     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5018                                   CSUM_TSO |
5019                                   CSUM_TCP_IPV6)) {
5020         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5021         /* th_off is number of 32-bit words */
5022         hlen += (uint16_t)(th->th_off << 1);
5023     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5024                                          CSUM_UDP_IPV6)) {
5025         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5026         hlen += (sizeof(struct udphdr) / 2);
5027     } else {
5028         /* valid case as only CSUM_IP was set */
5029         return (0);
5030     }
5031 
5032     pbd->total_hlen_w = htole16(hlen);
5033 
5034     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5035                                   CSUM_TSO |
5036                                   CSUM_TCP_IPV6)) {
5037         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5038         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5039     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5040                                          CSUM_UDP_IPV6)) {
5041         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5042 
5043         /*
5044          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5045          * checksums and does not know anything about the UDP header and where
5046          * the checksum field is located. It only knows about TCP. Therefore
5047          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5048          * offload. Since the checksum field offset for TCP is 16 bytes and
5049          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5050          * bytes less than the start of the UDP header. This allows the
5051          * hardware to write the checksum in the correct spot. But the
5052          * hardware will compute a checksum which includes the last 10 bytes
5053          * of the IP header. To correct this we tweak the stack computed
5054          * pseudo checksum by folding in the calculation of the inverse
5055          * checksum for those final 10 bytes of the IP header. This allows
5056          * the correct checksum to be computed by the hardware.
5057          */
5058 
5059         /* set pointer 10 bytes before UDP header */
5060         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5061 
5062         /* calculate a pseudo header checksum over the first 10 bytes */
5063         tmp_csum = in_pseudo(*tmp_uh,
5064                              *(tmp_uh + 1),
5065                              *(uint16_t *)(tmp_uh + 2));
5066 
5067         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5068     }
5069 
5070     return (hlen * 2); /* entire header length, number of bytes */
5071 }
5072 
5073 static void
5074 bxe_set_pbd_lso_e2(struct mbuf *m,
5075                    uint32_t    *parsing_data)
5076 {
5077     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5078                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5079                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5080 
5081     /* XXX test for IPv6 with extension header... */
5082 }
5083 
5084 static void
5085 bxe_set_pbd_lso(struct mbuf                *m,
5086                 struct eth_tx_parse_bd_e1x *pbd)
5087 {
5088     struct ether_vlan_header *eh = NULL;
5089     struct ip *ip = NULL;
5090     struct tcphdr *th = NULL;
5091     int e_hlen;
5092 
5093     /* get the Ethernet header */
5094     eh = mtod(m, struct ether_vlan_header *);
5095 
5096     /* handle VLAN encapsulation if present */
5097     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5098                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5099 
5100     /* get the IP and TCP header, with LSO entire header in first mbuf */
5101     /* XXX assuming IPv4 */
5102     ip = (struct ip *)(m->m_data + e_hlen);
5103     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5104 
5105     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5106     pbd->tcp_send_seq = ntohl(th->th_seq);
5107     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5108 
5109 #if 1
5110         /* XXX IPv4 */
5111         pbd->ip_id = ntohs(ip->ip_id);
5112         pbd->tcp_pseudo_csum =
5113             ntohs(in_pseudo(ip->ip_src.s_addr,
5114                             ip->ip_dst.s_addr,
5115                             htons(IPPROTO_TCP)));
5116 #else
5117         /* XXX IPv6 */
5118         pbd->tcp_pseudo_csum =
5119             ntohs(in_pseudo(&ip6->ip6_src,
5120                             &ip6->ip6_dst,
5121                             htons(IPPROTO_TCP)));
5122 #endif
5123 
5124     pbd->global_data |=
5125         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5126 }
5127 
5128 /*
5129  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5130  * visible to the controller.
5131  *
5132  * If an mbuf is submitted to this routine and cannot be given to the
5133  * controller (e.g. it has too many fragments) then the function may free
5134  * the mbuf and return to the caller.
5135  *
5136  * Returns:
5137  *   0 = Success, !0 = Failure
5138  *   Note the side effect that an mbuf may be freed if it causes a problem.
5139  */
5140 static int
5141 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5142 {
5143     bus_dma_segment_t segs[32];
5144     struct mbuf *m0;
5145     struct bxe_sw_tx_bd *tx_buf;
5146     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5147     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5148     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5149     struct eth_tx_bd *tx_data_bd;
5150     struct eth_tx_bd *tx_total_pkt_size_bd;
5151     struct eth_tx_start_bd *tx_start_bd;
5152     uint16_t bd_prod, pkt_prod, total_pkt_size;
5153     uint8_t mac_type;
5154     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5155     struct bxe_softc *sc;
5156     uint16_t tx_bd_avail;
5157     struct ether_vlan_header *eh;
5158     uint32_t pbd_e2_parsing_data = 0;
5159     uint8_t hlen = 0;
5160     int tmp_bd;
5161     int i;
5162 
5163     sc = fp->sc;
5164 
5165 #if __FreeBSD_version >= 800000
5166     M_ASSERTPKTHDR(*m_head);
5167 #endif /* #if __FreeBSD_version >= 800000 */
5168 
5169     m0 = *m_head;
5170     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5171     tx_start_bd = NULL;
5172     tx_data_bd = NULL;
5173     tx_total_pkt_size_bd = NULL;
5174 
5175     /* get the H/W pointer for packets and BDs */
5176     pkt_prod = fp->tx_pkt_prod;
5177     bd_prod = fp->tx_bd_prod;
5178 
5179     mac_type = UNICAST_ADDRESS;
5180 
5181     /* map the mbuf into the next open DMAable memory */
5182     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5183     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5184                                     tx_buf->m_map, m0,
5185                                     segs, &nsegs, BUS_DMA_NOWAIT);
5186 
5187     /* mapping errors */
5188     if(__predict_false(error != 0)) {
5189         fp->eth_q_stats.tx_dma_mapping_failure++;
5190         if (error == ENOMEM) {
5191             /* resource issue, try again later */
5192             rc = ENOMEM;
5193         } else if (error == EFBIG) {
5194             /* possibly recoverable with defragmentation */
5195             fp->eth_q_stats.mbuf_defrag_attempts++;
5196             m0 = m_defrag(*m_head, M_NOWAIT);
5197             if (m0 == NULL) {
5198                 fp->eth_q_stats.mbuf_defrag_failures++;
5199                 rc = ENOBUFS;
5200             } else {
5201                 /* defrag successful, try mapping again */
5202                 *m_head = m0;
5203                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5204                                                 tx_buf->m_map, m0,
5205                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5206                 if (error) {
5207                     fp->eth_q_stats.tx_dma_mapping_failure++;
5208                     rc = error;
5209                 }
5210             }
5211         } else {
5212             /* unknown, unrecoverable mapping error */
5213             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5214             bxe_dump_mbuf(sc, m0, FALSE);
5215             rc = error;
5216         }
5217 
5218         goto bxe_tx_encap_continue;
5219     }
5220 
5221     tx_bd_avail = bxe_tx_avail(sc, fp);
5222 
5223     /* make sure there is enough room in the send queue */
5224     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5225         /* Recoverable, try again later. */
5226         fp->eth_q_stats.tx_hw_queue_full++;
5227         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5228         rc = ENOMEM;
5229         goto bxe_tx_encap_continue;
5230     }
5231 
5232     /* capture the current H/W TX chain high watermark */
5233     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5234                         (TX_BD_USABLE - tx_bd_avail))) {
5235         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5236     }
5237 
5238     /* make sure it fits in the packet window */
5239     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5240         /*
5241          * The mbuf may be to big for the controller to handle. If the frame
5242          * is a TSO frame we'll need to do an additional check.
5243          */
5244         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5245             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5246                 goto bxe_tx_encap_continue; /* OK to send */
5247             } else {
5248                 fp->eth_q_stats.tx_window_violation_tso++;
5249             }
5250         } else {
5251             fp->eth_q_stats.tx_window_violation_std++;
5252         }
5253 
5254         /* lets try to defragment this mbuf and remap it */
5255         fp->eth_q_stats.mbuf_defrag_attempts++;
5256         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5257 
5258         m0 = m_defrag(*m_head, M_NOWAIT);
5259         if (m0 == NULL) {
5260             fp->eth_q_stats.mbuf_defrag_failures++;
5261             /* Ugh, just drop the frame... :( */
5262             rc = ENOBUFS;
5263         } else {
5264             /* defrag successful, try mapping again */
5265             *m_head = m0;
5266             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5267                                             tx_buf->m_map, m0,
5268                                             segs, &nsegs, BUS_DMA_NOWAIT);
5269             if (error) {
5270                 fp->eth_q_stats.tx_dma_mapping_failure++;
5271                 /* No sense in trying to defrag/copy chain, drop it. :( */
5272                 rc = error;
5273             } else {
5274                /* if the chain is still too long then drop it */
5275                 if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5276                     /*
5277                      * in case TSO is enabled nsegs should be checked against
5278                      * BXE_TSO_MAX_SEGMENTS
5279                      */
5280                     if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5281                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5282                         fp->eth_q_stats.nsegs_path1_errors++;
5283                         rc = ENODEV;
5284                     }
5285                 } else {
5286                     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5287                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5288                         fp->eth_q_stats.nsegs_path2_errors++;
5289                         rc = ENODEV;
5290                     }
5291                 }
5292             }
5293         }
5294     }
5295 
5296 bxe_tx_encap_continue:
5297 
5298     /* Check for errors */
5299     if (rc) {
5300         if (rc == ENOMEM) {
5301             /* recoverable try again later  */
5302         } else {
5303             fp->eth_q_stats.tx_soft_errors++;
5304             fp->eth_q_stats.mbuf_alloc_tx--;
5305             m_freem(*m_head);
5306             *m_head = NULL;
5307         }
5308 
5309         return (rc);
5310     }
5311 
5312     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5313     if (m0->m_flags & M_BCAST) {
5314         mac_type = BROADCAST_ADDRESS;
5315     } else if (m0->m_flags & M_MCAST) {
5316         mac_type = MULTICAST_ADDRESS;
5317     }
5318 
5319     /* store the mbuf into the mbuf ring */
5320     tx_buf->m        = m0;
5321     tx_buf->first_bd = fp->tx_bd_prod;
5322     tx_buf->flags    = 0;
5323 
5324     /* prepare the first transmit (start) BD for the mbuf */
5325     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5326 
5327     BLOGD(sc, DBG_TX,
5328           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5329           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5330 
5331     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5332     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5333     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5334     total_pkt_size += tx_start_bd->nbytes;
5335     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5336 
5337     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5338 
5339     /* all frames have at least Start BD + Parsing BD */
5340     nbds = nsegs + 1;
5341     tx_start_bd->nbd = htole16(nbds);
5342 
5343     if (m0->m_flags & M_VLANTAG) {
5344         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5345         tx_start_bd->bd_flags.as_bitfield |=
5346             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5347     } else {
5348         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5349         if (IS_VF(sc)) {
5350             /* map ethernet header to find type and header length */
5351             eh = mtod(m0, struct ether_vlan_header *);
5352             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5353         } else {
5354             /* used by FW for packet accounting */
5355             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5356         }
5357     }
5358 
5359     /*
5360      * add a parsing BD from the chain. The parsing BD is always added
5361      * though it is only used for TSO and chksum
5362      */
5363     bd_prod = TX_BD_NEXT(bd_prod);
5364 
5365     if (m0->m_pkthdr.csum_flags) {
5366         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5367             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5368             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5369         }
5370 
5371         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5372             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5373                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5374         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5375             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5376                                                   ETH_TX_BD_FLAGS_IS_UDP |
5377                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5378         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5379                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5380             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5381         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5382             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5383                                                   ETH_TX_BD_FLAGS_IS_UDP);
5384         }
5385     }
5386 
5387     if (!CHIP_IS_E1x(sc)) {
5388         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5389         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5390 
5391         if (m0->m_pkthdr.csum_flags) {
5392             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5393         }
5394 
5395         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5396                  mac_type);
5397     } else {
5398         uint16_t global_data = 0;
5399 
5400         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5401         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5402 
5403         if (m0->m_pkthdr.csum_flags) {
5404             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5405         }
5406 
5407         SET_FLAG(global_data,
5408                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5409         pbd_e1x->global_data |= htole16(global_data);
5410     }
5411 
5412     /* setup the parsing BD with TSO specific info */
5413     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5414         fp->eth_q_stats.tx_ofld_frames_lso++;
5415         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5416 
5417         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5418             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5419 
5420             /* split the first BD into header/data making the fw job easy */
5421             nbds++;
5422             tx_start_bd->nbd = htole16(nbds);
5423             tx_start_bd->nbytes = htole16(hlen);
5424 
5425             bd_prod = TX_BD_NEXT(bd_prod);
5426 
5427             /* new transmit BD after the tx_parse_bd */
5428             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5429             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5430             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5431             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5432             if (tx_total_pkt_size_bd == NULL) {
5433                 tx_total_pkt_size_bd = tx_data_bd;
5434             }
5435 
5436             BLOGD(sc, DBG_TX,
5437                   "TSO split header size is %d (%x:%x) nbds %d\n",
5438                   le16toh(tx_start_bd->nbytes),
5439                   le32toh(tx_start_bd->addr_hi),
5440                   le32toh(tx_start_bd->addr_lo),
5441                   nbds);
5442         }
5443 
5444         if (!CHIP_IS_E1x(sc)) {
5445             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5446         } else {
5447             bxe_set_pbd_lso(m0, pbd_e1x);
5448         }
5449     }
5450 
5451     if (pbd_e2_parsing_data) {
5452         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5453     }
5454 
5455     /* prepare remaining BDs, start tx bd contains first seg/frag */
5456     for (i = 1; i < nsegs ; i++) {
5457         bd_prod = TX_BD_NEXT(bd_prod);
5458         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5459         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5460         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5461         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5462         if (tx_total_pkt_size_bd == NULL) {
5463             tx_total_pkt_size_bd = tx_data_bd;
5464         }
5465         total_pkt_size += tx_data_bd->nbytes;
5466     }
5467 
5468     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5469 
5470     if (tx_total_pkt_size_bd != NULL) {
5471         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5472     }
5473 
5474     if (__predict_false(sc->debug & DBG_TX)) {
5475         tmp_bd = tx_buf->first_bd;
5476         for (i = 0; i < nbds; i++)
5477         {
5478             if (i == 0) {
5479                 BLOGD(sc, DBG_TX,
5480                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5481                       "bd_flags=0x%x hdr_nbds=%d\n",
5482                       tx_start_bd,
5483                       tmp_bd,
5484                       le16toh(tx_start_bd->nbd),
5485                       le16toh(tx_start_bd->vlan_or_ethertype),
5486                       tx_start_bd->bd_flags.as_bitfield,
5487                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5488             } else if (i == 1) {
5489                 if (pbd_e1x) {
5490                     BLOGD(sc, DBG_TX,
5491                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5492                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5493                           "tcp_seq=%u total_hlen_w=%u\n",
5494                           pbd_e1x,
5495                           tmp_bd,
5496                           pbd_e1x->global_data,
5497                           pbd_e1x->ip_hlen_w,
5498                           pbd_e1x->ip_id,
5499                           pbd_e1x->lso_mss,
5500                           pbd_e1x->tcp_flags,
5501                           pbd_e1x->tcp_pseudo_csum,
5502                           pbd_e1x->tcp_send_seq,
5503                           le16toh(pbd_e1x->total_hlen_w));
5504                 } else { /* if (pbd_e2) */
5505                     BLOGD(sc, DBG_TX,
5506                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5507                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5508                           pbd_e2,
5509                           tmp_bd,
5510                           pbd_e2->data.mac_addr.dst_hi,
5511                           pbd_e2->data.mac_addr.dst_mid,
5512                           pbd_e2->data.mac_addr.dst_lo,
5513                           pbd_e2->data.mac_addr.src_hi,
5514                           pbd_e2->data.mac_addr.src_mid,
5515                           pbd_e2->data.mac_addr.src_lo,
5516                           pbd_e2->parsing_data);
5517                 }
5518             }
5519 
5520             if (i != 1) { /* skip parse db as it doesn't hold data */
5521                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5522                 BLOGD(sc, DBG_TX,
5523                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5524                       tx_data_bd,
5525                       tmp_bd,
5526                       le16toh(tx_data_bd->nbytes),
5527                       le32toh(tx_data_bd->addr_hi),
5528                       le32toh(tx_data_bd->addr_lo));
5529             }
5530 
5531             tmp_bd = TX_BD_NEXT(tmp_bd);
5532         }
5533     }
5534 
5535     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5536 
5537     /* update TX BD producer index value for next TX */
5538     bd_prod = TX_BD_NEXT(bd_prod);
5539 
5540     /*
5541      * If the chain of tx_bd's describing this frame is adjacent to or spans
5542      * an eth_tx_next_bd element then we need to increment the nbds value.
5543      */
5544     if (TX_BD_IDX(bd_prod) < nbds) {
5545         nbds++;
5546     }
5547 
5548     /* don't allow reordering of writes for nbd and packets */
5549     mb();
5550 
5551     fp->tx_db.data.prod += nbds;
5552 
5553     /* producer points to the next free tx_bd at this point */
5554     fp->tx_pkt_prod++;
5555     fp->tx_bd_prod = bd_prod;
5556 
5557     DOORBELL(sc, fp->index, fp->tx_db.raw);
5558 
5559     fp->eth_q_stats.tx_pkts++;
5560 
5561     /* Prevent speculative reads from getting ahead of the status block. */
5562     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5563                       0, 0, BUS_SPACE_BARRIER_READ);
5564 
5565     /* Prevent speculative reads from getting ahead of the doorbell. */
5566     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5567                       0, 0, BUS_SPACE_BARRIER_READ);
5568 
5569     return (0);
5570 }
5571 
5572 static void
5573 bxe_tx_start_locked(struct bxe_softc *sc,
5574                     if_t ifp,
5575                     struct bxe_fastpath *fp)
5576 {
5577     struct mbuf *m = NULL;
5578     int tx_count = 0;
5579     uint16_t tx_bd_avail;
5580 
5581     BXE_FP_TX_LOCK_ASSERT(fp);
5582 
5583     /* keep adding entries while there are frames to send */
5584     while (!if_sendq_empty(ifp)) {
5585 
5586         /*
5587          * check for any frames to send
5588          * dequeue can still be NULL even if queue is not empty
5589          */
5590         m = if_dequeue(ifp);
5591         if (__predict_false(m == NULL)) {
5592             break;
5593         }
5594 
5595         /* the mbuf now belongs to us */
5596         fp->eth_q_stats.mbuf_alloc_tx++;
5597 
5598         /*
5599          * Put the frame into the transmit ring. If we don't have room,
5600          * place the mbuf back at the head of the TX queue, set the
5601          * OACTIVE flag, and wait for the NIC to drain the chain.
5602          */
5603         if (__predict_false(bxe_tx_encap(fp, &m))) {
5604             fp->eth_q_stats.tx_encap_failures++;
5605             if (m != NULL) {
5606                 /* mark the TX queue as full and return the frame */
5607                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5608 		if_sendq_prepend(ifp, m);
5609                 fp->eth_q_stats.mbuf_alloc_tx--;
5610                 fp->eth_q_stats.tx_queue_xoff++;
5611             }
5612 
5613             /* stop looking for more work */
5614             break;
5615         }
5616 
5617         /* the frame was enqueued successfully */
5618         tx_count++;
5619 
5620         /* send a copy of the frame to any BPF listeners. */
5621         if_etherbpfmtap(ifp, m);
5622 
5623         tx_bd_avail = bxe_tx_avail(sc, fp);
5624 
5625         /* handle any completions if we're running low */
5626         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5627             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5628             bxe_txeof(sc, fp);
5629             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5630                 break;
5631             }
5632         }
5633     }
5634 
5635     /* all TX packets were dequeued and/or the tx ring is full */
5636     if (tx_count > 0) {
5637         /* reset the TX watchdog timeout timer */
5638         fp->watchdog_timer = BXE_TX_TIMEOUT;
5639     }
5640 }
5641 
5642 /* Legacy (non-RSS) dispatch routine */
5643 static void
5644 bxe_tx_start(if_t ifp)
5645 {
5646     struct bxe_softc *sc;
5647     struct bxe_fastpath *fp;
5648 
5649     sc = if_getsoftc(ifp);
5650 
5651     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5652         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5653         return;
5654     }
5655 
5656     if (!sc->link_vars.link_up) {
5657         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5658         return;
5659     }
5660 
5661     fp = &sc->fp[0];
5662 
5663     if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5664         fp->eth_q_stats.tx_queue_full_return++;
5665         return;
5666     }
5667 
5668     BXE_FP_TX_LOCK(fp);
5669     bxe_tx_start_locked(sc, ifp, fp);
5670     BXE_FP_TX_UNLOCK(fp);
5671 }
5672 
5673 #if __FreeBSD_version >= 901504
5674 
5675 static int
5676 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5677                        if_t                ifp,
5678                        struct bxe_fastpath *fp,
5679                        struct mbuf         *m)
5680 {
5681     struct buf_ring *tx_br = fp->tx_br;
5682     struct mbuf *next;
5683     int depth, rc, tx_count;
5684     uint16_t tx_bd_avail;
5685 
5686     rc = tx_count = 0;
5687 
5688     BXE_FP_TX_LOCK_ASSERT(fp);
5689 
5690     if (sc->state != BXE_STATE_OPEN)  {
5691         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5692         return ENETDOWN;
5693     }
5694 
5695     if (!tx_br) {
5696         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5697         return (EINVAL);
5698     }
5699 
5700     if (m != NULL) {
5701         rc = drbr_enqueue(ifp, tx_br, m);
5702         if (rc != 0) {
5703             fp->eth_q_stats.tx_soft_errors++;
5704             goto bxe_tx_mq_start_locked_exit;
5705         }
5706     }
5707 
5708     if (!sc->link_vars.link_up || !(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5709         fp->eth_q_stats.tx_request_link_down_failures++;
5710         goto bxe_tx_mq_start_locked_exit;
5711     }
5712 
5713     /* fetch the depth of the driver queue */
5714     depth = drbr_inuse_drv(ifp, tx_br);
5715     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5716         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5717     }
5718 
5719     /* keep adding entries while there are frames to send */
5720     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5721         /* handle any completions if we're running low */
5722         tx_bd_avail = bxe_tx_avail(sc, fp);
5723         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5724             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5725             bxe_txeof(sc, fp);
5726             tx_bd_avail = bxe_tx_avail(sc, fp);
5727             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5728                 fp->eth_q_stats.bd_avail_too_less_failures++;
5729                 m_freem(next);
5730                 drbr_advance(ifp, tx_br);
5731                 rc = ENOBUFS;
5732                 break;
5733             }
5734         }
5735 
5736         /* the mbuf now belongs to us */
5737         fp->eth_q_stats.mbuf_alloc_tx++;
5738 
5739         /*
5740          * Put the frame into the transmit ring. If we don't have room,
5741          * place the mbuf back at the head of the TX queue, set the
5742          * OACTIVE flag, and wait for the NIC to drain the chain.
5743          */
5744         rc = bxe_tx_encap(fp, &next);
5745         if (__predict_false(rc != 0)) {
5746             fp->eth_q_stats.tx_encap_failures++;
5747             if (next != NULL) {
5748                 /* mark the TX queue as full and save the frame */
5749                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5750                 drbr_putback(ifp, tx_br, next);
5751                 fp->eth_q_stats.mbuf_alloc_tx--;
5752                 fp->eth_q_stats.tx_frames_deferred++;
5753             } else
5754                 drbr_advance(ifp, tx_br);
5755 
5756             /* stop looking for more work */
5757             break;
5758         }
5759 
5760         /* the transmit frame was enqueued successfully */
5761         tx_count++;
5762 
5763         /* send a copy of the frame to any BPF listeners */
5764 	if_etherbpfmtap(ifp, next);
5765 
5766         drbr_advance(ifp, tx_br);
5767     }
5768 
5769     /* all TX packets were dequeued and/or the tx ring is full */
5770     if (tx_count > 0) {
5771         /* reset the TX watchdog timeout timer */
5772         fp->watchdog_timer = BXE_TX_TIMEOUT;
5773     }
5774 
5775 bxe_tx_mq_start_locked_exit:
5776     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5777     if (!drbr_empty(ifp, tx_br)) {
5778         fp->eth_q_stats.tx_mq_not_empty++;
5779         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5780     }
5781 
5782     return (rc);
5783 }
5784 
5785 static void
5786 bxe_tx_mq_start_deferred(void *arg,
5787                          int pending)
5788 {
5789     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5790     struct bxe_softc *sc = fp->sc;
5791     if_t ifp = sc->ifp;
5792 
5793     BXE_FP_TX_LOCK(fp);
5794     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5795     BXE_FP_TX_UNLOCK(fp);
5796 }
5797 
5798 /* Multiqueue (TSS) dispatch routine. */
5799 static int
5800 bxe_tx_mq_start(struct ifnet *ifp,
5801                 struct mbuf  *m)
5802 {
5803     struct bxe_softc *sc = if_getsoftc(ifp);
5804     struct bxe_fastpath *fp;
5805     int fp_index, rc;
5806 
5807     fp_index = 0; /* default is the first queue */
5808 
5809     /* check if flowid is set */
5810 
5811     if (BXE_VALID_FLOWID(m))
5812         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5813 
5814     fp = &sc->fp[fp_index];
5815 
5816     if (sc->state != BXE_STATE_OPEN)  {
5817         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5818         return ENETDOWN;
5819     }
5820 
5821     if (BXE_FP_TX_TRYLOCK(fp)) {
5822         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5823         BXE_FP_TX_UNLOCK(fp);
5824     } else {
5825         rc = drbr_enqueue(ifp, fp->tx_br, m);
5826         taskqueue_enqueue(fp->tq, &fp->tx_task);
5827     }
5828 
5829     return (rc);
5830 }
5831 
5832 static void
5833 bxe_mq_flush(struct ifnet *ifp)
5834 {
5835     struct bxe_softc *sc = if_getsoftc(ifp);
5836     struct bxe_fastpath *fp;
5837     struct mbuf *m;
5838     int i;
5839 
5840     for (i = 0; i < sc->num_queues; i++) {
5841         fp = &sc->fp[i];
5842 
5843         if (fp->state != BXE_FP_STATE_IRQ) {
5844             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5845                   fp->index, fp->state);
5846             continue;
5847         }
5848 
5849         if (fp->tx_br != NULL) {
5850             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5851             BXE_FP_TX_LOCK(fp);
5852             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5853                 m_freem(m);
5854             }
5855             BXE_FP_TX_UNLOCK(fp);
5856         }
5857     }
5858 
5859     if_qflush(ifp);
5860 }
5861 
5862 #endif /* FreeBSD_version >= 901504 */
5863 
5864 static uint16_t
5865 bxe_cid_ilt_lines(struct bxe_softc *sc)
5866 {
5867     if (IS_SRIOV(sc)) {
5868         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5869     }
5870     return (L2_ILT_LINES(sc));
5871 }
5872 
5873 static void
5874 bxe_ilt_set_info(struct bxe_softc *sc)
5875 {
5876     struct ilt_client_info *ilt_client;
5877     struct ecore_ilt *ilt = sc->ilt;
5878     uint16_t line = 0;
5879 
5880     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5881     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5882 
5883     /* CDU */
5884     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5885     ilt_client->client_num = ILT_CLIENT_CDU;
5886     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5887     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5888     ilt_client->start = line;
5889     line += bxe_cid_ilt_lines(sc);
5890 
5891     if (CNIC_SUPPORT(sc)) {
5892         line += CNIC_ILT_LINES;
5893     }
5894 
5895     ilt_client->end = (line - 1);
5896 
5897     BLOGD(sc, DBG_LOAD,
5898           "ilt client[CDU]: start %d, end %d, "
5899           "psz 0x%x, flags 0x%x, hw psz %d\n",
5900           ilt_client->start, ilt_client->end,
5901           ilt_client->page_size,
5902           ilt_client->flags,
5903           ilog2(ilt_client->page_size >> 12));
5904 
5905     /* QM */
5906     if (QM_INIT(sc->qm_cid_count)) {
5907         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5908         ilt_client->client_num = ILT_CLIENT_QM;
5909         ilt_client->page_size = QM_ILT_PAGE_SZ;
5910         ilt_client->flags = 0;
5911         ilt_client->start = line;
5912 
5913         /* 4 bytes for each cid */
5914         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5915                              QM_ILT_PAGE_SZ);
5916 
5917         ilt_client->end = (line - 1);
5918 
5919         BLOGD(sc, DBG_LOAD,
5920               "ilt client[QM]: start %d, end %d, "
5921               "psz 0x%x, flags 0x%x, hw psz %d\n",
5922               ilt_client->start, ilt_client->end,
5923               ilt_client->page_size, ilt_client->flags,
5924               ilog2(ilt_client->page_size >> 12));
5925     }
5926 
5927     if (CNIC_SUPPORT(sc)) {
5928         /* SRC */
5929         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5930         ilt_client->client_num = ILT_CLIENT_SRC;
5931         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5932         ilt_client->flags = 0;
5933         ilt_client->start = line;
5934         line += SRC_ILT_LINES;
5935         ilt_client->end = (line - 1);
5936 
5937         BLOGD(sc, DBG_LOAD,
5938               "ilt client[SRC]: start %d, end %d, "
5939               "psz 0x%x, flags 0x%x, hw psz %d\n",
5940               ilt_client->start, ilt_client->end,
5941               ilt_client->page_size, ilt_client->flags,
5942               ilog2(ilt_client->page_size >> 12));
5943 
5944         /* TM */
5945         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5946         ilt_client->client_num = ILT_CLIENT_TM;
5947         ilt_client->page_size = TM_ILT_PAGE_SZ;
5948         ilt_client->flags = 0;
5949         ilt_client->start = line;
5950         line += TM_ILT_LINES;
5951         ilt_client->end = (line - 1);
5952 
5953         BLOGD(sc, DBG_LOAD,
5954               "ilt client[TM]: start %d, end %d, "
5955               "psz 0x%x, flags 0x%x, hw psz %d\n",
5956               ilt_client->start, ilt_client->end,
5957               ilt_client->page_size, ilt_client->flags,
5958               ilog2(ilt_client->page_size >> 12));
5959     }
5960 
5961     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5962 }
5963 
5964 static void
5965 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5966 {
5967     int i;
5968     uint32_t rx_buf_size;
5969 
5970     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5971 
5972     for (i = 0; i < sc->num_queues; i++) {
5973         if(rx_buf_size <= MCLBYTES){
5974             sc->fp[i].rx_buf_size = rx_buf_size;
5975             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5976         }else if (rx_buf_size <= MJUMPAGESIZE){
5977             sc->fp[i].rx_buf_size = rx_buf_size;
5978             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5979         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5980             sc->fp[i].rx_buf_size = MCLBYTES;
5981             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5982         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5983             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5984             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5985         }else {
5986             sc->fp[i].rx_buf_size = MCLBYTES;
5987             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5988         }
5989     }
5990 }
5991 
5992 static int
5993 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5994 {
5995     int rc = 0;
5996 
5997     if ((sc->ilt =
5998          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5999                                     M_BXE_ILT,
6000                                     (M_NOWAIT | M_ZERO))) == NULL) {
6001         rc = 1;
6002     }
6003 
6004     return (rc);
6005 }
6006 
6007 static int
6008 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6009 {
6010     int rc = 0;
6011 
6012     if ((sc->ilt->lines =
6013          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6014                                     M_BXE_ILT,
6015                                     (M_NOWAIT | M_ZERO))) == NULL) {
6016         rc = 1;
6017     }
6018 
6019     return (rc);
6020 }
6021 
6022 static void
6023 bxe_free_ilt_mem(struct bxe_softc *sc)
6024 {
6025     if (sc->ilt != NULL) {
6026         free(sc->ilt, M_BXE_ILT);
6027         sc->ilt = NULL;
6028     }
6029 }
6030 
6031 static void
6032 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6033 {
6034     if (sc->ilt->lines != NULL) {
6035         free(sc->ilt->lines, M_BXE_ILT);
6036         sc->ilt->lines = NULL;
6037     }
6038 }
6039 
6040 static void
6041 bxe_free_mem(struct bxe_softc *sc)
6042 {
6043     int i;
6044 
6045     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6046         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6047         sc->context[i].vcxt = NULL;
6048         sc->context[i].size = 0;
6049     }
6050 
6051     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6052 
6053     bxe_free_ilt_lines_mem(sc);
6054 
6055 }
6056 
6057 static int
6058 bxe_alloc_mem(struct bxe_softc *sc)
6059 {
6060 
6061     int context_size;
6062     int allocated;
6063     int i;
6064 
6065     /*
6066      * Allocate memory for CDU context:
6067      * This memory is allocated separately and not in the generic ILT
6068      * functions because CDU differs in few aspects:
6069      * 1. There can be multiple entities allocating memory for context -
6070      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6071      * its own ILT lines.
6072      * 2. Since CDU page-size is not a single 4KB page (which is the case
6073      * for the other ILT clients), to be efficient we want to support
6074      * allocation of sub-page-size in the last entry.
6075      * 3. Context pointers are used by the driver to pass to FW / update
6076      * the context (for the other ILT clients the pointers are used just to
6077      * free the memory during unload).
6078      */
6079     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6080     for (i = 0, allocated = 0; allocated < context_size; i++) {
6081         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6082                                   (context_size - allocated));
6083 
6084         if (bxe_dma_alloc(sc, sc->context[i].size,
6085                           &sc->context[i].vcxt_dma,
6086                           "cdu context") != 0) {
6087             bxe_free_mem(sc);
6088             return (-1);
6089         }
6090 
6091         sc->context[i].vcxt =
6092             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6093 
6094         allocated += sc->context[i].size;
6095     }
6096 
6097     bxe_alloc_ilt_lines_mem(sc);
6098 
6099     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6100           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6101     {
6102         for (i = 0; i < 4; i++) {
6103             BLOGD(sc, DBG_LOAD,
6104                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6105                   i,
6106                   sc->ilt->clients[i].page_size,
6107                   sc->ilt->clients[i].start,
6108                   sc->ilt->clients[i].end,
6109                   sc->ilt->clients[i].client_num,
6110                   sc->ilt->clients[i].flags);
6111         }
6112     }
6113     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6114         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6115         bxe_free_mem(sc);
6116         return (-1);
6117     }
6118 
6119     return (0);
6120 }
6121 
6122 static void
6123 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6124 {
6125     struct bxe_softc *sc;
6126     int i;
6127 
6128     sc = fp->sc;
6129 
6130     if (fp->rx_mbuf_tag == NULL) {
6131         return;
6132     }
6133 
6134     /* free all mbufs and unload all maps */
6135     for (i = 0; i < RX_BD_TOTAL; i++) {
6136         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6137             bus_dmamap_sync(fp->rx_mbuf_tag,
6138                             fp->rx_mbuf_chain[i].m_map,
6139                             BUS_DMASYNC_POSTREAD);
6140             bus_dmamap_unload(fp->rx_mbuf_tag,
6141                               fp->rx_mbuf_chain[i].m_map);
6142         }
6143 
6144         if (fp->rx_mbuf_chain[i].m != NULL) {
6145             m_freem(fp->rx_mbuf_chain[i].m);
6146             fp->rx_mbuf_chain[i].m = NULL;
6147             fp->eth_q_stats.mbuf_alloc_rx--;
6148         }
6149     }
6150 }
6151 
6152 static void
6153 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6154 {
6155     struct bxe_softc *sc;
6156     int i, max_agg_queues;
6157 
6158     sc = fp->sc;
6159 
6160     if (fp->rx_mbuf_tag == NULL) {
6161         return;
6162     }
6163 
6164     max_agg_queues = MAX_AGG_QS(sc);
6165 
6166     /* release all mbufs and unload all DMA maps in the TPA pool */
6167     for (i = 0; i < max_agg_queues; i++) {
6168         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6169             bus_dmamap_sync(fp->rx_mbuf_tag,
6170                             fp->rx_tpa_info[i].bd.m_map,
6171                             BUS_DMASYNC_POSTREAD);
6172             bus_dmamap_unload(fp->rx_mbuf_tag,
6173                               fp->rx_tpa_info[i].bd.m_map);
6174         }
6175 
6176         if (fp->rx_tpa_info[i].bd.m != NULL) {
6177             m_freem(fp->rx_tpa_info[i].bd.m);
6178             fp->rx_tpa_info[i].bd.m = NULL;
6179             fp->eth_q_stats.mbuf_alloc_tpa--;
6180         }
6181     }
6182 }
6183 
6184 static void
6185 bxe_free_sge_chain(struct bxe_fastpath *fp)
6186 {
6187     struct bxe_softc *sc;
6188     int i;
6189 
6190     sc = fp->sc;
6191 
6192     if (fp->rx_sge_mbuf_tag == NULL) {
6193         return;
6194     }
6195 
6196     /* rree all mbufs and unload all maps */
6197     for (i = 0; i < RX_SGE_TOTAL; i++) {
6198         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6199             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6200                             fp->rx_sge_mbuf_chain[i].m_map,
6201                             BUS_DMASYNC_POSTREAD);
6202             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6203                               fp->rx_sge_mbuf_chain[i].m_map);
6204         }
6205 
6206         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6207             m_freem(fp->rx_sge_mbuf_chain[i].m);
6208             fp->rx_sge_mbuf_chain[i].m = NULL;
6209             fp->eth_q_stats.mbuf_alloc_sge--;
6210         }
6211     }
6212 }
6213 
6214 static void
6215 bxe_free_fp_buffers(struct bxe_softc *sc)
6216 {
6217     struct bxe_fastpath *fp;
6218     int i;
6219 
6220     for (i = 0; i < sc->num_queues; i++) {
6221         fp = &sc->fp[i];
6222 
6223 #if __FreeBSD_version >= 901504
6224         if (fp->tx_br != NULL) {
6225             /* just in case bxe_mq_flush() wasn't called */
6226             if (mtx_initialized(&fp->tx_mtx)) {
6227                 struct mbuf *m;
6228 
6229                 BXE_FP_TX_LOCK(fp);
6230                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6231                     m_freem(m);
6232                 BXE_FP_TX_UNLOCK(fp);
6233             }
6234         }
6235 #endif
6236 
6237         /* free all RX buffers */
6238         bxe_free_rx_bd_chain(fp);
6239         bxe_free_tpa_pool(fp);
6240         bxe_free_sge_chain(fp);
6241 
6242         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6243             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6244                   fp->eth_q_stats.mbuf_alloc_rx);
6245         }
6246 
6247         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6248             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6249                   fp->eth_q_stats.mbuf_alloc_sge);
6250         }
6251 
6252         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6253             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6254                   fp->eth_q_stats.mbuf_alloc_tpa);
6255         }
6256 
6257         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6258             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6259                   fp->eth_q_stats.mbuf_alloc_tx);
6260         }
6261 
6262         /* XXX verify all mbufs were reclaimed */
6263     }
6264 }
6265 
6266 static int
6267 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6268                      uint16_t            prev_index,
6269                      uint16_t            index)
6270 {
6271     struct bxe_sw_rx_bd *rx_buf;
6272     struct eth_rx_bd *rx_bd;
6273     bus_dma_segment_t segs[1];
6274     bus_dmamap_t map;
6275     struct mbuf *m;
6276     int nsegs, rc;
6277 
6278     rc = 0;
6279 
6280     /* allocate the new RX BD mbuf */
6281     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6282     if (__predict_false(m == NULL)) {
6283         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6284         return (ENOBUFS);
6285     }
6286 
6287     fp->eth_q_stats.mbuf_alloc_rx++;
6288 
6289     /* initialize the mbuf buffer length */
6290     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6291 
6292     /* map the mbuf into non-paged pool */
6293     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6294                                  fp->rx_mbuf_spare_map,
6295                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6296     if (__predict_false(rc != 0)) {
6297         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6298         m_freem(m);
6299         fp->eth_q_stats.mbuf_alloc_rx--;
6300         return (rc);
6301     }
6302 
6303     /* all mbufs must map to a single segment */
6304     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6305 
6306     /* release any existing RX BD mbuf mappings */
6307 
6308     if (prev_index != index) {
6309         rx_buf = &fp->rx_mbuf_chain[prev_index];
6310 
6311         if (rx_buf->m_map != NULL) {
6312             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6313                             BUS_DMASYNC_POSTREAD);
6314             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6315         }
6316 
6317         /*
6318          * We only get here from bxe_rxeof() when the maximum number
6319          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6320          * holds the mbuf in the prev_index so it's OK to NULL it out
6321          * here without concern of a memory leak.
6322          */
6323         fp->rx_mbuf_chain[prev_index].m = NULL;
6324     }
6325 
6326     rx_buf = &fp->rx_mbuf_chain[index];
6327 
6328     if (rx_buf->m_map != NULL) {
6329         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6330                         BUS_DMASYNC_POSTREAD);
6331         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6332     }
6333 
6334     /* save the mbuf and mapping info for a future packet */
6335     map = (prev_index != index) ?
6336               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6337     rx_buf->m_map = fp->rx_mbuf_spare_map;
6338     fp->rx_mbuf_spare_map = map;
6339     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6340                     BUS_DMASYNC_PREREAD);
6341     rx_buf->m = m;
6342 
6343     rx_bd = &fp->rx_chain[index];
6344     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6345     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6346 
6347     return (rc);
6348 }
6349 
6350 static int
6351 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6352                       int                 queue)
6353 {
6354     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6355     bus_dma_segment_t segs[1];
6356     bus_dmamap_t map;
6357     struct mbuf *m;
6358     int nsegs;
6359     int rc = 0;
6360 
6361     /* allocate the new TPA mbuf */
6362     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6363     if (__predict_false(m == NULL)) {
6364         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6365         return (ENOBUFS);
6366     }
6367 
6368     fp->eth_q_stats.mbuf_alloc_tpa++;
6369 
6370     /* initialize the mbuf buffer length */
6371     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6372 
6373     /* map the mbuf into non-paged pool */
6374     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6375                                  fp->rx_tpa_info_mbuf_spare_map,
6376                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6377     if (__predict_false(rc != 0)) {
6378         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6379         m_free(m);
6380         fp->eth_q_stats.mbuf_alloc_tpa--;
6381         return (rc);
6382     }
6383 
6384     /* all mbufs must map to a single segment */
6385     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6386 
6387     /* release any existing TPA mbuf mapping */
6388     if (tpa_info->bd.m_map != NULL) {
6389         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6390                         BUS_DMASYNC_POSTREAD);
6391         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6392     }
6393 
6394     /* save the mbuf and mapping info for the TPA mbuf */
6395     map = tpa_info->bd.m_map;
6396     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6397     fp->rx_tpa_info_mbuf_spare_map = map;
6398     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6399                     BUS_DMASYNC_PREREAD);
6400     tpa_info->bd.m = m;
6401     tpa_info->seg = segs[0];
6402 
6403     return (rc);
6404 }
6405 
6406 /*
6407  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6408  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6409  * chain.
6410  */
6411 static int
6412 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6413                       uint16_t            index)
6414 {
6415     struct bxe_sw_rx_bd *sge_buf;
6416     struct eth_rx_sge *sge;
6417     bus_dma_segment_t segs[1];
6418     bus_dmamap_t map;
6419     struct mbuf *m;
6420     int nsegs;
6421     int rc = 0;
6422 
6423     /* allocate a new SGE mbuf */
6424     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6425     if (__predict_false(m == NULL)) {
6426         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6427         return (ENOMEM);
6428     }
6429 
6430     fp->eth_q_stats.mbuf_alloc_sge++;
6431 
6432     /* initialize the mbuf buffer length */
6433     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6434 
6435     /* map the SGE mbuf into non-paged pool */
6436     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6437                                  fp->rx_sge_mbuf_spare_map,
6438                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6439     if (__predict_false(rc != 0)) {
6440         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6441         m_freem(m);
6442         fp->eth_q_stats.mbuf_alloc_sge--;
6443         return (rc);
6444     }
6445 
6446     /* all mbufs must map to a single segment */
6447     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6448 
6449     sge_buf = &fp->rx_sge_mbuf_chain[index];
6450 
6451     /* release any existing SGE mbuf mapping */
6452     if (sge_buf->m_map != NULL) {
6453         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6454                         BUS_DMASYNC_POSTREAD);
6455         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6456     }
6457 
6458     /* save the mbuf and mapping info for a future packet */
6459     map = sge_buf->m_map;
6460     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6461     fp->rx_sge_mbuf_spare_map = map;
6462     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6463                     BUS_DMASYNC_PREREAD);
6464     sge_buf->m = m;
6465 
6466     sge = &fp->rx_sge_chain[index];
6467     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6468     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6469 
6470     return (rc);
6471 }
6472 
6473 static __noinline int
6474 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6475 {
6476     struct bxe_fastpath *fp;
6477     int i, j, rc = 0;
6478     int ring_prod, cqe_ring_prod;
6479     int max_agg_queues;
6480 
6481     for (i = 0; i < sc->num_queues; i++) {
6482         fp = &sc->fp[i];
6483 
6484         ring_prod = cqe_ring_prod = 0;
6485         fp->rx_bd_cons = 0;
6486         fp->rx_cq_cons = 0;
6487 
6488         /* allocate buffers for the RX BDs in RX BD chain */
6489         for (j = 0; j < sc->max_rx_bufs; j++) {
6490             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6491             if (rc != 0) {
6492                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6493                       i, rc);
6494                 goto bxe_alloc_fp_buffers_error;
6495             }
6496 
6497             ring_prod     = RX_BD_NEXT(ring_prod);
6498             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6499         }
6500 
6501         fp->rx_bd_prod = ring_prod;
6502         fp->rx_cq_prod = cqe_ring_prod;
6503         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6504 
6505         max_agg_queues = MAX_AGG_QS(sc);
6506 
6507         fp->tpa_enable = TRUE;
6508 
6509         /* fill the TPA pool */
6510         for (j = 0; j < max_agg_queues; j++) {
6511             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6512             if (rc != 0) {
6513                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6514                           i, j);
6515                 fp->tpa_enable = FALSE;
6516                 goto bxe_alloc_fp_buffers_error;
6517             }
6518 
6519             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6520         }
6521 
6522         if (fp->tpa_enable) {
6523             /* fill the RX SGE chain */
6524             ring_prod = 0;
6525             for (j = 0; j < RX_SGE_USABLE; j++) {
6526                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6527                 if (rc != 0) {
6528                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6529                               i, ring_prod);
6530                     fp->tpa_enable = FALSE;
6531                     ring_prod = 0;
6532                     goto bxe_alloc_fp_buffers_error;
6533                 }
6534 
6535                 ring_prod = RX_SGE_NEXT(ring_prod);
6536             }
6537 
6538             fp->rx_sge_prod = ring_prod;
6539         }
6540     }
6541 
6542     return (0);
6543 
6544 bxe_alloc_fp_buffers_error:
6545 
6546     /* unwind what was already allocated */
6547     bxe_free_rx_bd_chain(fp);
6548     bxe_free_tpa_pool(fp);
6549     bxe_free_sge_chain(fp);
6550 
6551     return (ENOBUFS);
6552 }
6553 
6554 static void
6555 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6556 {
6557     bxe_dma_free(sc, &sc->fw_stats_dma);
6558 
6559     sc->fw_stats_num = 0;
6560 
6561     sc->fw_stats_req_size = 0;
6562     sc->fw_stats_req = NULL;
6563     sc->fw_stats_req_mapping = 0;
6564 
6565     sc->fw_stats_data_size = 0;
6566     sc->fw_stats_data = NULL;
6567     sc->fw_stats_data_mapping = 0;
6568 }
6569 
6570 static int
6571 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6572 {
6573     uint8_t num_queue_stats;
6574     int num_groups;
6575 
6576     /* number of queues for statistics is number of eth queues */
6577     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6578 
6579     /*
6580      * Total number of FW statistics requests =
6581      *   1 for port stats + 1 for PF stats + num of queues
6582      */
6583     sc->fw_stats_num = (2 + num_queue_stats);
6584 
6585     /*
6586      * Request is built from stats_query_header and an array of
6587      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6588      * rules. The real number or requests is configured in the
6589      * stats_query_header.
6590      */
6591     num_groups =
6592         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6593          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6594 
6595     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6596           sc->fw_stats_num, num_groups);
6597 
6598     sc->fw_stats_req_size =
6599         (sizeof(struct stats_query_header) +
6600          (num_groups * sizeof(struct stats_query_cmd_group)));
6601 
6602     /*
6603      * Data for statistics requests + stats_counter.
6604      * stats_counter holds per-STORM counters that are incremented when
6605      * STORM has finished with the current request. Memory for FCoE
6606      * offloaded statistics are counted anyway, even if they will not be sent.
6607      * VF stats are not accounted for here as the data of VF stats is stored
6608      * in memory allocated by the VF, not here.
6609      */
6610     sc->fw_stats_data_size =
6611         (sizeof(struct stats_counter) +
6612          sizeof(struct per_port_stats) +
6613          sizeof(struct per_pf_stats) +
6614          /* sizeof(struct fcoe_statistics_params) + */
6615          (sizeof(struct per_queue_stats) * num_queue_stats));
6616 
6617     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6618                       &sc->fw_stats_dma, "fw stats") != 0) {
6619         bxe_free_fw_stats_mem(sc);
6620         return (-1);
6621     }
6622 
6623     /* set up the shortcuts */
6624 
6625     sc->fw_stats_req =
6626         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6627     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6628 
6629     sc->fw_stats_data =
6630         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6631                                      sc->fw_stats_req_size);
6632     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6633                                  sc->fw_stats_req_size);
6634 
6635     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6636           (uintmax_t)sc->fw_stats_req_mapping);
6637 
6638     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6639           (uintmax_t)sc->fw_stats_data_mapping);
6640 
6641     return (0);
6642 }
6643 
6644 /*
6645  * Bits map:
6646  * 0-7  - Engine0 load counter.
6647  * 8-15 - Engine1 load counter.
6648  * 16   - Engine0 RESET_IN_PROGRESS bit.
6649  * 17   - Engine1 RESET_IN_PROGRESS bit.
6650  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6651  *        function on the engine
6652  * 19   - Engine1 ONE_IS_LOADED.
6653  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6654  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6655  *        for just the one belonging to its engine).
6656  */
6657 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6658 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6659 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6660 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6661 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6662 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6663 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6664 #define BXE_GLOBAL_RESET_BIT      0x00040000
6665 
6666 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6667 static void
6668 bxe_set_reset_global(struct bxe_softc *sc)
6669 {
6670     uint32_t val;
6671     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6672     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6673     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6674     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6675 }
6676 
6677 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6678 static void
6679 bxe_clear_reset_global(struct bxe_softc *sc)
6680 {
6681     uint32_t val;
6682     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6683     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6684     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6685     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6686 }
6687 
6688 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6689 static uint8_t
6690 bxe_reset_is_global(struct bxe_softc *sc)
6691 {
6692     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6693     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6694     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6695 }
6696 
6697 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6698 static void
6699 bxe_set_reset_done(struct bxe_softc *sc)
6700 {
6701     uint32_t val;
6702     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6703                                  BXE_PATH0_RST_IN_PROG_BIT;
6704 
6705     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6706 
6707     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6708     /* Clear the bit */
6709     val &= ~bit;
6710     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6711 
6712     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6713 }
6714 
6715 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6716 static void
6717 bxe_set_reset_in_progress(struct bxe_softc *sc)
6718 {
6719     uint32_t val;
6720     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6721                                  BXE_PATH0_RST_IN_PROG_BIT;
6722 
6723     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6724 
6725     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6726     /* Set the bit */
6727     val |= bit;
6728     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6729 
6730     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6731 }
6732 
6733 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6734 static uint8_t
6735 bxe_reset_is_done(struct bxe_softc *sc,
6736                   int              engine)
6737 {
6738     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6739     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6740                             BXE_PATH0_RST_IN_PROG_BIT;
6741 
6742     /* return false if bit is set */
6743     return (val & bit) ? FALSE : TRUE;
6744 }
6745 
6746 /* get the load status for an engine, should be run under rtnl lock */
6747 static uint8_t
6748 bxe_get_load_status(struct bxe_softc *sc,
6749                     int              engine)
6750 {
6751     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6752                              BXE_PATH0_LOAD_CNT_MASK;
6753     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6754                               BXE_PATH0_LOAD_CNT_SHIFT;
6755     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6756 
6757     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6758 
6759     val = ((val & mask) >> shift);
6760 
6761     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6762 
6763     return (val != 0);
6764 }
6765 
6766 /* set pf load mark */
6767 /* XXX needs to be under rtnl lock */
6768 static void
6769 bxe_set_pf_load(struct bxe_softc *sc)
6770 {
6771     uint32_t val;
6772     uint32_t val1;
6773     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6774                                   BXE_PATH0_LOAD_CNT_MASK;
6775     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6776                                    BXE_PATH0_LOAD_CNT_SHIFT;
6777 
6778     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6779 
6780     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6781     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6782 
6783     /* get the current counter value */
6784     val1 = ((val & mask) >> shift);
6785 
6786     /* set bit of this PF */
6787     val1 |= (1 << SC_ABS_FUNC(sc));
6788 
6789     /* clear the old value */
6790     val &= ~mask;
6791 
6792     /* set the new one */
6793     val |= ((val1 << shift) & mask);
6794 
6795     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6796 
6797     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6798 }
6799 
6800 /* clear pf load mark */
6801 /* XXX needs to be under rtnl lock */
6802 static uint8_t
6803 bxe_clear_pf_load(struct bxe_softc *sc)
6804 {
6805     uint32_t val1, val;
6806     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6807                                   BXE_PATH0_LOAD_CNT_MASK;
6808     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6809                                    BXE_PATH0_LOAD_CNT_SHIFT;
6810 
6811     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6812     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6813     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6814 
6815     /* get the current counter value */
6816     val1 = (val & mask) >> shift;
6817 
6818     /* clear bit of that PF */
6819     val1 &= ~(1 << SC_ABS_FUNC(sc));
6820 
6821     /* clear the old value */
6822     val &= ~mask;
6823 
6824     /* set the new one */
6825     val |= ((val1 << shift) & mask);
6826 
6827     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6828     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6829     return (val1 != 0);
6830 }
6831 
6832 /* send load requrest to mcp and analyze response */
6833 static int
6834 bxe_nic_load_request(struct bxe_softc *sc,
6835                      uint32_t         *load_code)
6836 {
6837     /* init fw_seq */
6838     sc->fw_seq =
6839         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6840          DRV_MSG_SEQ_NUMBER_MASK);
6841 
6842     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6843 
6844     /* get the current FW pulse sequence */
6845     sc->fw_drv_pulse_wr_seq =
6846         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6847          DRV_PULSE_SEQ_MASK);
6848 
6849     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6850           sc->fw_drv_pulse_wr_seq);
6851 
6852     /* load request */
6853     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6854                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6855 
6856     /* if the MCP fails to respond we must abort */
6857     if (!(*load_code)) {
6858         BLOGE(sc, "MCP response failure!\n");
6859         return (-1);
6860     }
6861 
6862     /* if MCP refused then must abort */
6863     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6864         BLOGE(sc, "MCP refused load request\n");
6865         return (-1);
6866     }
6867 
6868     return (0);
6869 }
6870 
6871 /*
6872  * Check whether another PF has already loaded FW to chip. In virtualized
6873  * environments a pf from anoth VM may have already initialized the device
6874  * including loading FW.
6875  */
6876 static int
6877 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6878                          uint32_t         load_code)
6879 {
6880     uint32_t my_fw, loaded_fw;
6881 
6882     /* is another pf loaded on this engine? */
6883     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6884         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6885         /* build my FW version dword */
6886         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6887                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6888                  (BCM_5710_FW_REVISION_VERSION << 16) +
6889                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6890 
6891         /* read loaded FW from chip */
6892         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6893         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6894               loaded_fw, my_fw);
6895 
6896         /* abort nic load if version mismatch */
6897         if (my_fw != loaded_fw) {
6898             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6899                   loaded_fw, my_fw);
6900             return (-1);
6901         }
6902     }
6903 
6904     return (0);
6905 }
6906 
6907 /* mark PMF if applicable */
6908 static void
6909 bxe_nic_load_pmf(struct bxe_softc *sc,
6910                  uint32_t         load_code)
6911 {
6912     uint32_t ncsi_oem_data_addr;
6913 
6914     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6915         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6916         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6917         /*
6918          * Barrier here for ordering between the writing to sc->port.pmf here
6919          * and reading it from the periodic task.
6920          */
6921         sc->port.pmf = 1;
6922         mb();
6923     } else {
6924         sc->port.pmf = 0;
6925     }
6926 
6927     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6928 
6929     /* XXX needed? */
6930     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6931         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6932             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6933             if (ncsi_oem_data_addr) {
6934                 REG_WR(sc,
6935                        (ncsi_oem_data_addr +
6936                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6937                        0);
6938             }
6939         }
6940     }
6941 }
6942 
6943 static void
6944 bxe_read_mf_cfg(struct bxe_softc *sc)
6945 {
6946     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6947     int abs_func;
6948     int vn;
6949 
6950     if (BXE_NOMCP(sc)) {
6951         return; /* what should be the default bvalue in this case */
6952     }
6953 
6954     /*
6955      * The formula for computing the absolute function number is...
6956      * For 2 port configuration (4 functions per port):
6957      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6958      * For 4 port configuration (2 functions per port):
6959      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6960      */
6961     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6962         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6963         if (abs_func >= E1H_FUNC_MAX) {
6964             break;
6965         }
6966         sc->devinfo.mf_info.mf_config[vn] =
6967             MFCFG_RD(sc, func_mf_config[abs_func].config);
6968     }
6969 
6970     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6971         FUNC_MF_CFG_FUNC_DISABLED) {
6972         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6973         sc->flags |= BXE_MF_FUNC_DIS;
6974     } else {
6975         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6976         sc->flags &= ~BXE_MF_FUNC_DIS;
6977     }
6978 }
6979 
6980 /* acquire split MCP access lock register */
6981 static int bxe_acquire_alr(struct bxe_softc *sc)
6982 {
6983     uint32_t j, val;
6984 
6985     for (j = 0; j < 1000; j++) {
6986         val = (1UL << 31);
6987         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6988         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6989         if (val & (1L << 31))
6990             break;
6991 
6992         DELAY(5000);
6993     }
6994 
6995     if (!(val & (1L << 31))) {
6996         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6997         return (-1);
6998     }
6999 
7000     return (0);
7001 }
7002 
7003 /* release split MCP access lock register */
7004 static void bxe_release_alr(struct bxe_softc *sc)
7005 {
7006     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7007 }
7008 
7009 static void
7010 bxe_fan_failure(struct bxe_softc *sc)
7011 {
7012     int port = SC_PORT(sc);
7013     uint32_t ext_phy_config;
7014 
7015     /* mark the failure */
7016     ext_phy_config =
7017         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7018 
7019     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7020     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7021     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7022              ext_phy_config);
7023 
7024     /* log the failure */
7025     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7026               "the card to prevent permanent damage. "
7027               "Please contact OEM Support for assistance\n");
7028 
7029     /* XXX */
7030 #if 1
7031     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7032 #else
7033     /*
7034      * Schedule device reset (unload)
7035      * This is due to some boards consuming sufficient power when driver is
7036      * up to overheat if fan fails.
7037      */
7038     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7039     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7040 #endif
7041 }
7042 
7043 /* this function is called upon a link interrupt */
7044 static void
7045 bxe_link_attn(struct bxe_softc *sc)
7046 {
7047     uint32_t pause_enabled = 0;
7048     struct host_port_stats *pstats;
7049     int cmng_fns;
7050     struct bxe_fastpath *fp;
7051     int i;
7052 
7053     /* Make sure that we are synced with the current statistics */
7054     bxe_stats_handle(sc, STATS_EVENT_STOP);
7055     BLOGD(sc, DBG_LOAD, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7056     elink_link_update(&sc->link_params, &sc->link_vars);
7057 
7058     if (sc->link_vars.link_up) {
7059 
7060         /* dropless flow control */
7061         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7062             pause_enabled = 0;
7063 
7064             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7065                 pause_enabled = 1;
7066             }
7067 
7068             REG_WR(sc,
7069                    (BAR_USTRORM_INTMEM +
7070                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7071                    pause_enabled);
7072         }
7073 
7074         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7075             pstats = BXE_SP(sc, port_stats);
7076             /* reset old mac stats */
7077             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7078         }
7079 
7080         if (sc->state == BXE_STATE_OPEN) {
7081             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7082 	    /* Restart tx when the link comes back. */
7083 	    FOR_EACH_ETH_QUEUE(sc, i) {
7084 		fp = &sc->fp[i];
7085 		taskqueue_enqueue(fp->tq, &fp->tx_task);
7086 	    }
7087         }
7088 
7089     }
7090 
7091     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7092         cmng_fns = bxe_get_cmng_fns_mode(sc);
7093 
7094         if (cmng_fns != CMNG_FNS_NONE) {
7095             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7096             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7097         } else {
7098             /* rate shaping and fairness are disabled */
7099             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7100         }
7101     }
7102 
7103     bxe_link_report_locked(sc);
7104 
7105     if (IS_MF(sc)) {
7106         ; // XXX bxe_link_sync_notify(sc);
7107     }
7108 }
7109 
7110 static void
7111 bxe_attn_int_asserted(struct bxe_softc *sc,
7112                       uint32_t         asserted)
7113 {
7114     int port = SC_PORT(sc);
7115     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7116                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7117     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7118                                         NIG_REG_MASK_INTERRUPT_PORT0;
7119     uint32_t aeu_mask;
7120     uint32_t nig_mask = 0;
7121     uint32_t reg_addr;
7122     uint32_t igu_acked;
7123     uint32_t cnt;
7124 
7125     if (sc->attn_state & asserted) {
7126         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7127     }
7128 
7129     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7130 
7131     aeu_mask = REG_RD(sc, aeu_addr);
7132 
7133     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7134           aeu_mask, asserted);
7135 
7136     aeu_mask &= ~(asserted & 0x3ff);
7137 
7138     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7139 
7140     REG_WR(sc, aeu_addr, aeu_mask);
7141 
7142     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7143 
7144     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7145     sc->attn_state |= asserted;
7146     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7147 
7148     if (asserted & ATTN_HARD_WIRED_MASK) {
7149         if (asserted & ATTN_NIG_FOR_FUNC) {
7150 
7151 	    bxe_acquire_phy_lock(sc);
7152             /* save nig interrupt mask */
7153             nig_mask = REG_RD(sc, nig_int_mask_addr);
7154 
7155             /* If nig_mask is not set, no need to call the update function */
7156             if (nig_mask) {
7157                 REG_WR(sc, nig_int_mask_addr, 0);
7158 
7159                 bxe_link_attn(sc);
7160             }
7161 
7162             /* handle unicore attn? */
7163         }
7164 
7165         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7166             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7167         }
7168 
7169         if (asserted & GPIO_2_FUNC) {
7170             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7171         }
7172 
7173         if (asserted & GPIO_3_FUNC) {
7174             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7175         }
7176 
7177         if (asserted & GPIO_4_FUNC) {
7178             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7179         }
7180 
7181         if (port == 0) {
7182             if (asserted & ATTN_GENERAL_ATTN_1) {
7183                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7184                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7185             }
7186             if (asserted & ATTN_GENERAL_ATTN_2) {
7187                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7188                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7189             }
7190             if (asserted & ATTN_GENERAL_ATTN_3) {
7191                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7192                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7193             }
7194         } else {
7195             if (asserted & ATTN_GENERAL_ATTN_4) {
7196                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7197                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7198             }
7199             if (asserted & ATTN_GENERAL_ATTN_5) {
7200                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7201                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7202             }
7203             if (asserted & ATTN_GENERAL_ATTN_6) {
7204                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7205                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7206             }
7207         }
7208     } /* hardwired */
7209 
7210     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7211         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7212     } else {
7213         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7214     }
7215 
7216     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7217           asserted,
7218           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7219     REG_WR(sc, reg_addr, asserted);
7220 
7221     /* now set back the mask */
7222     if (asserted & ATTN_NIG_FOR_FUNC) {
7223         /*
7224          * Verify that IGU ack through BAR was written before restoring
7225          * NIG mask. This loop should exit after 2-3 iterations max.
7226          */
7227         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7228             cnt = 0;
7229 
7230             do {
7231                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7232             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7233                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7234 
7235             if (!igu_acked) {
7236                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7237             }
7238 
7239             mb();
7240         }
7241 
7242         REG_WR(sc, nig_int_mask_addr, nig_mask);
7243 
7244 	bxe_release_phy_lock(sc);
7245     }
7246 }
7247 
7248 static void
7249 bxe_print_next_block(struct bxe_softc *sc,
7250                      int              idx,
7251                      const char       *blk)
7252 {
7253     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7254 }
7255 
7256 static int
7257 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7258                               uint32_t         sig,
7259                               int              par_num,
7260                               uint8_t          print)
7261 {
7262     uint32_t cur_bit = 0;
7263     int i = 0;
7264 
7265     for (i = 0; sig; i++) {
7266         cur_bit = ((uint32_t)0x1 << i);
7267         if (sig & cur_bit) {
7268             switch (cur_bit) {
7269             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7270                 if (print)
7271                     bxe_print_next_block(sc, par_num++, "BRB");
7272                 break;
7273             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7274                 if (print)
7275                     bxe_print_next_block(sc, par_num++, "PARSER");
7276                 break;
7277             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7278                 if (print)
7279                     bxe_print_next_block(sc, par_num++, "TSDM");
7280                 break;
7281             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7282                 if (print)
7283                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7284                 break;
7285             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7286                 if (print)
7287                     bxe_print_next_block(sc, par_num++, "TCM");
7288                 break;
7289             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7290                 if (print)
7291                     bxe_print_next_block(sc, par_num++, "TSEMI");
7292                 break;
7293             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7294                 if (print)
7295                     bxe_print_next_block(sc, par_num++, "XPB");
7296                 break;
7297             }
7298 
7299             /* Clear the bit */
7300             sig &= ~cur_bit;
7301         }
7302     }
7303 
7304     return (par_num);
7305 }
7306 
7307 static int
7308 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7309                               uint32_t         sig,
7310                               int              par_num,
7311                               uint8_t          *global,
7312                               uint8_t          print)
7313 {
7314     int i = 0;
7315     uint32_t cur_bit = 0;
7316     for (i = 0; sig; i++) {
7317         cur_bit = ((uint32_t)0x1 << i);
7318         if (sig & cur_bit) {
7319             switch (cur_bit) {
7320             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7321                 if (print)
7322                     bxe_print_next_block(sc, par_num++, "PBF");
7323                 break;
7324             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7325                 if (print)
7326                     bxe_print_next_block(sc, par_num++, "QM");
7327                 break;
7328             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7329                 if (print)
7330                     bxe_print_next_block(sc, par_num++, "TM");
7331                 break;
7332             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7333                 if (print)
7334                     bxe_print_next_block(sc, par_num++, "XSDM");
7335                 break;
7336             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7337                 if (print)
7338                     bxe_print_next_block(sc, par_num++, "XCM");
7339                 break;
7340             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7341                 if (print)
7342                     bxe_print_next_block(sc, par_num++, "XSEMI");
7343                 break;
7344             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7345                 if (print)
7346                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7347                 break;
7348             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7349                 if (print)
7350                     bxe_print_next_block(sc, par_num++, "NIG");
7351                 break;
7352             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7353                 if (print)
7354                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7355                 *global = TRUE;
7356                 break;
7357             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7358                 if (print)
7359                     bxe_print_next_block(sc, par_num++, "DEBUG");
7360                 break;
7361             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7362                 if (print)
7363                     bxe_print_next_block(sc, par_num++, "USDM");
7364                 break;
7365             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7366                 if (print)
7367                     bxe_print_next_block(sc, par_num++, "UCM");
7368                 break;
7369             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7370                 if (print)
7371                     bxe_print_next_block(sc, par_num++, "USEMI");
7372                 break;
7373             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7374                 if (print)
7375                     bxe_print_next_block(sc, par_num++, "UPB");
7376                 break;
7377             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7378                 if (print)
7379                     bxe_print_next_block(sc, par_num++, "CSDM");
7380                 break;
7381             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7382                 if (print)
7383                     bxe_print_next_block(sc, par_num++, "CCM");
7384                 break;
7385             }
7386 
7387             /* Clear the bit */
7388             sig &= ~cur_bit;
7389         }
7390     }
7391 
7392     return (par_num);
7393 }
7394 
7395 static int
7396 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7397                               uint32_t         sig,
7398                               int              par_num,
7399                               uint8_t          print)
7400 {
7401     uint32_t cur_bit = 0;
7402     int i = 0;
7403 
7404     for (i = 0; sig; i++) {
7405         cur_bit = ((uint32_t)0x1 << i);
7406         if (sig & cur_bit) {
7407             switch (cur_bit) {
7408             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7409                 if (print)
7410                     bxe_print_next_block(sc, par_num++, "CSEMI");
7411                 break;
7412             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7413                 if (print)
7414                     bxe_print_next_block(sc, par_num++, "PXP");
7415                 break;
7416             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7417                 if (print)
7418                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7419                 break;
7420             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7421                 if (print)
7422                     bxe_print_next_block(sc, par_num++, "CFC");
7423                 break;
7424             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7425                 if (print)
7426                     bxe_print_next_block(sc, par_num++, "CDU");
7427                 break;
7428             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7429                 if (print)
7430                     bxe_print_next_block(sc, par_num++, "DMAE");
7431                 break;
7432             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7433                 if (print)
7434                     bxe_print_next_block(sc, par_num++, "IGU");
7435                 break;
7436             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7437                 if (print)
7438                     bxe_print_next_block(sc, par_num++, "MISC");
7439                 break;
7440             }
7441 
7442             /* Clear the bit */
7443             sig &= ~cur_bit;
7444         }
7445     }
7446 
7447     return (par_num);
7448 }
7449 
7450 static int
7451 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7452                               uint32_t         sig,
7453                               int              par_num,
7454                               uint8_t          *global,
7455                               uint8_t          print)
7456 {
7457     uint32_t cur_bit = 0;
7458     int i = 0;
7459 
7460     for (i = 0; sig; i++) {
7461         cur_bit = ((uint32_t)0x1 << i);
7462         if (sig & cur_bit) {
7463             switch (cur_bit) {
7464             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7465                 if (print)
7466                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7467                 *global = TRUE;
7468                 break;
7469             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7470                 if (print)
7471                     bxe_print_next_block(sc, par_num++,
7472                               "MCP UMP RX");
7473                 *global = TRUE;
7474                 break;
7475             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7476                 if (print)
7477                     bxe_print_next_block(sc, par_num++,
7478                               "MCP UMP TX");
7479                 *global = TRUE;
7480                 break;
7481             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7482                 if (print)
7483                     bxe_print_next_block(sc, par_num++,
7484                               "MCP SCPAD");
7485                 *global = TRUE;
7486                 break;
7487             }
7488 
7489             /* Clear the bit */
7490             sig &= ~cur_bit;
7491         }
7492     }
7493 
7494     return (par_num);
7495 }
7496 
7497 static int
7498 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7499                               uint32_t         sig,
7500                               int              par_num,
7501                               uint8_t          print)
7502 {
7503     uint32_t cur_bit = 0;
7504     int i = 0;
7505 
7506     for (i = 0; sig; i++) {
7507         cur_bit = ((uint32_t)0x1 << i);
7508         if (sig & cur_bit) {
7509             switch (cur_bit) {
7510             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7511                 if (print)
7512                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7513                 break;
7514             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7515                 if (print)
7516                     bxe_print_next_block(sc, par_num++, "ATC");
7517                 break;
7518             }
7519 
7520             /* Clear the bit */
7521             sig &= ~cur_bit;
7522         }
7523     }
7524 
7525     return (par_num);
7526 }
7527 
7528 static uint8_t
7529 bxe_parity_attn(struct bxe_softc *sc,
7530                 uint8_t          *global,
7531                 uint8_t          print,
7532                 uint32_t         *sig)
7533 {
7534     int par_num = 0;
7535 
7536     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7537         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7538         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7539         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7540         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7541         BLOGE(sc, "Parity error: HW block parity attention:\n"
7542                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7543               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7544               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7545               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7546               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7547               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7548 
7549         if (print)
7550             BLOGI(sc, "Parity errors detected in blocks: ");
7551 
7552         par_num =
7553             bxe_check_blocks_with_parity0(sc, sig[0] &
7554                                           HW_PRTY_ASSERT_SET_0,
7555                                           par_num, print);
7556         par_num =
7557             bxe_check_blocks_with_parity1(sc, sig[1] &
7558                                           HW_PRTY_ASSERT_SET_1,
7559                                           par_num, global, print);
7560         par_num =
7561             bxe_check_blocks_with_parity2(sc, sig[2] &
7562                                           HW_PRTY_ASSERT_SET_2,
7563                                           par_num, print);
7564         par_num =
7565             bxe_check_blocks_with_parity3(sc, sig[3] &
7566                                           HW_PRTY_ASSERT_SET_3,
7567                                           par_num, global, print);
7568         par_num =
7569             bxe_check_blocks_with_parity4(sc, sig[4] &
7570                                           HW_PRTY_ASSERT_SET_4,
7571                                           par_num, print);
7572 
7573         if (print)
7574             BLOGI(sc, "\n");
7575 
7576 	if( *global == TRUE ) {
7577                 BXE_SET_ERROR_BIT(sc, BXE_ERR_GLOBAL);
7578         }
7579 
7580         return (TRUE);
7581     }
7582 
7583     return (FALSE);
7584 }
7585 
7586 static uint8_t
7587 bxe_chk_parity_attn(struct bxe_softc *sc,
7588                     uint8_t          *global,
7589                     uint8_t          print)
7590 {
7591     struct attn_route attn = { {0} };
7592     int port = SC_PORT(sc);
7593 
7594     if(sc->state != BXE_STATE_OPEN)
7595         return FALSE;
7596 
7597     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7598     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7599     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7600     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7601 
7602     /*
7603      * Since MCP attentions can't be disabled inside the block, we need to
7604      * read AEU registers to see whether they're currently disabled
7605      */
7606     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7607                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7608                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7609                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7610 
7611 
7612     if (!CHIP_IS_E1x(sc))
7613         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7614 
7615     return (bxe_parity_attn(sc, global, print, attn.sig));
7616 }
7617 
7618 static void
7619 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7620                          uint32_t         attn)
7621 {
7622     uint32_t val;
7623     boolean_t err_flg = FALSE;
7624 
7625     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7626         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7627         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7628         err_flg = TRUE;
7629         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7630             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7631         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7632             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7633         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7634             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7635         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7636             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7637         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7638             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7639         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7640             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7641         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7642             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7643         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7644             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7645         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7646             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7647     }
7648 
7649     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7650         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7651         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7652 	err_flg = TRUE;
7653         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7654             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7655         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7656             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7657         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7658             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7659         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7660             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7661         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7662             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7663         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7664             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7665     }
7666 
7667     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7668                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7669         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7670               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7671                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7672 	err_flg = TRUE;
7673     }
7674     if (err_flg) {
7675 	BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
7676 	taskqueue_enqueue_timeout(taskqueue_thread,
7677 	    &sc->sp_err_timeout_task, hz/10);
7678     }
7679 
7680 }
7681 
7682 static void
7683 bxe_e1h_disable(struct bxe_softc *sc)
7684 {
7685     int port = SC_PORT(sc);
7686 
7687     bxe_tx_disable(sc);
7688 
7689     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7690 }
7691 
7692 static void
7693 bxe_e1h_enable(struct bxe_softc *sc)
7694 {
7695     int port = SC_PORT(sc);
7696 
7697     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7698 
7699     // XXX bxe_tx_enable(sc);
7700 }
7701 
7702 /*
7703  * called due to MCP event (on pmf):
7704  *   reread new bandwidth configuration
7705  *   configure FW
7706  *   notify others function about the change
7707  */
7708 static void
7709 bxe_config_mf_bw(struct bxe_softc *sc)
7710 {
7711     if (sc->link_vars.link_up) {
7712         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7713         // XXX bxe_link_sync_notify(sc);
7714     }
7715 
7716     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7717 }
7718 
7719 static void
7720 bxe_set_mf_bw(struct bxe_softc *sc)
7721 {
7722     bxe_config_mf_bw(sc);
7723     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7724 }
7725 
7726 static void
7727 bxe_handle_eee_event(struct bxe_softc *sc)
7728 {
7729     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7730     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7731 }
7732 
7733 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7734 
7735 static void
7736 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7737 {
7738     struct eth_stats_info *ether_stat =
7739         &sc->sp->drv_info_to_mcp.ether_stat;
7740 
7741     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7742             ETH_STAT_INFO_VERSION_LEN);
7743 
7744     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7745     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7746                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7747                                           ether_stat->mac_local + MAC_PAD,
7748                                           MAC_PAD, ETH_ALEN);
7749 
7750     ether_stat->mtu_size = sc->mtu;
7751 
7752     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7753     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7754         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7755     }
7756 
7757     // XXX ether_stat->feature_flags |= ???;
7758 
7759     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7760 
7761     ether_stat->txq_size = sc->tx_ring_size;
7762     ether_stat->rxq_size = sc->rx_ring_size;
7763 }
7764 
7765 static void
7766 bxe_handle_drv_info_req(struct bxe_softc *sc)
7767 {
7768     enum drv_info_opcode op_code;
7769     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7770 
7771     /* if drv_info version supported by MFW doesn't match - send NACK */
7772     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7773         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7774         return;
7775     }
7776 
7777     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7778                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7779 
7780     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7781 
7782     switch (op_code) {
7783     case ETH_STATS_OPCODE:
7784         bxe_drv_info_ether_stat(sc);
7785         break;
7786     case FCOE_STATS_OPCODE:
7787     case ISCSI_STATS_OPCODE:
7788     default:
7789         /* if op code isn't supported - send NACK */
7790         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7791         return;
7792     }
7793 
7794     /*
7795      * If we got drv_info attn from MFW then these fields are defined in
7796      * shmem2 for sure
7797      */
7798     SHMEM2_WR(sc, drv_info_host_addr_lo,
7799               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7800     SHMEM2_WR(sc, drv_info_host_addr_hi,
7801               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7802 
7803     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7804 }
7805 
7806 static void
7807 bxe_dcc_event(struct bxe_softc *sc,
7808               uint32_t         dcc_event)
7809 {
7810     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7811 
7812     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7813         /*
7814          * This is the only place besides the function initialization
7815          * where the sc->flags can change so it is done without any
7816          * locks
7817          */
7818         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7819             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7820             sc->flags |= BXE_MF_FUNC_DIS;
7821             bxe_e1h_disable(sc);
7822         } else {
7823             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7824             sc->flags &= ~BXE_MF_FUNC_DIS;
7825             bxe_e1h_enable(sc);
7826         }
7827         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7828     }
7829 
7830     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7831         bxe_config_mf_bw(sc);
7832         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7833     }
7834 
7835     /* Report results to MCP */
7836     if (dcc_event)
7837         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7838     else
7839         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7840 }
7841 
7842 static void
7843 bxe_pmf_update(struct bxe_softc *sc)
7844 {
7845     int port = SC_PORT(sc);
7846     uint32_t val;
7847 
7848     sc->port.pmf = 1;
7849     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7850 
7851     /*
7852      * We need the mb() to ensure the ordering between the writing to
7853      * sc->port.pmf here and reading it from the bxe_periodic_task().
7854      */
7855     mb();
7856 
7857     /* queue a periodic task */
7858     // XXX schedule task...
7859 
7860     // XXX bxe_dcbx_pmf_update(sc);
7861 
7862     /* enable nig attention */
7863     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7864     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7865         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7866         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7867     } else if (!CHIP_IS_E1x(sc)) {
7868         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7869         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7870     }
7871 
7872     bxe_stats_handle(sc, STATS_EVENT_PMF);
7873 }
7874 
7875 static int
7876 bxe_mc_assert(struct bxe_softc *sc)
7877 {
7878     char last_idx;
7879     int i, rc = 0;
7880     uint32_t row0, row1, row2, row3;
7881 
7882     /* XSTORM */
7883     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7884     if (last_idx)
7885         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7886 
7887     /* print the asserts */
7888     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7889 
7890         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7891         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7892         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7893         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7894 
7895         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7896             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7897                   i, row3, row2, row1, row0);
7898             rc++;
7899         } else {
7900             break;
7901         }
7902     }
7903 
7904     /* TSTORM */
7905     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7906     if (last_idx) {
7907         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7908     }
7909 
7910     /* print the asserts */
7911     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7912 
7913         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7914         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7915         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7916         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7917 
7918         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7919             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7920                   i, row3, row2, row1, row0);
7921             rc++;
7922         } else {
7923             break;
7924         }
7925     }
7926 
7927     /* CSTORM */
7928     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7929     if (last_idx) {
7930         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7931     }
7932 
7933     /* print the asserts */
7934     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7935 
7936         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7937         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7938         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7939         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7940 
7941         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7942             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7943                   i, row3, row2, row1, row0);
7944             rc++;
7945         } else {
7946             break;
7947         }
7948     }
7949 
7950     /* USTORM */
7951     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7952     if (last_idx) {
7953         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7954     }
7955 
7956     /* print the asserts */
7957     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7958 
7959         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7960         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7961         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7962         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7963 
7964         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7965             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7966                   i, row3, row2, row1, row0);
7967             rc++;
7968         } else {
7969             break;
7970         }
7971     }
7972 
7973     return (rc);
7974 }
7975 
7976 static void
7977 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7978                          uint32_t         attn)
7979 {
7980     int func = SC_FUNC(sc);
7981     uint32_t val;
7982 
7983     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7984 
7985         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7986 
7987             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7988             bxe_read_mf_cfg(sc);
7989             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7990                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7991             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7992 
7993             if (val & DRV_STATUS_DCC_EVENT_MASK)
7994                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7995 
7996             if (val & DRV_STATUS_SET_MF_BW)
7997                 bxe_set_mf_bw(sc);
7998 
7999             if (val & DRV_STATUS_DRV_INFO_REQ)
8000                 bxe_handle_drv_info_req(sc);
8001 
8002             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8003                 bxe_pmf_update(sc);
8004 
8005             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8006                 bxe_handle_eee_event(sc);
8007 
8008             if (sc->link_vars.periodic_flags &
8009                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8010                 /* sync with link */
8011 		bxe_acquire_phy_lock(sc);
8012                 sc->link_vars.periodic_flags &=
8013                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8014 		bxe_release_phy_lock(sc);
8015                 if (IS_MF(sc))
8016                     ; // XXX bxe_link_sync_notify(sc);
8017                 bxe_link_report(sc);
8018             }
8019 
8020             /*
8021              * Always call it here: bxe_link_report() will
8022              * prevent the link indication duplication.
8023              */
8024             bxe_link_status_update(sc);
8025 
8026         } else if (attn & BXE_MC_ASSERT_BITS) {
8027 
8028             BLOGE(sc, "MC assert!\n");
8029             bxe_mc_assert(sc);
8030             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8031             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8032             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8033             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8034             bxe_int_disable(sc);
8035             BXE_SET_ERROR_BIT(sc, BXE_ERR_MC_ASSERT);
8036             taskqueue_enqueue_timeout(taskqueue_thread,
8037                 &sc->sp_err_timeout_task, hz/10);
8038 
8039         } else if (attn & BXE_MCP_ASSERT) {
8040 
8041             BLOGE(sc, "MCP assert!\n");
8042             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8043             BXE_SET_ERROR_BIT(sc, BXE_ERR_MCP_ASSERT);
8044             taskqueue_enqueue_timeout(taskqueue_thread,
8045                 &sc->sp_err_timeout_task, hz/10);
8046             bxe_int_disable(sc);  /*avoid repetive assert alert */
8047 
8048 
8049         } else {
8050             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8051         }
8052     }
8053 
8054     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8055         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8056         if (attn & BXE_GRC_TIMEOUT) {
8057             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8058             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8059         }
8060         if (attn & BXE_GRC_RSV) {
8061             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8062             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8063         }
8064         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8065     }
8066 }
8067 
8068 static void
8069 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8070                          uint32_t         attn)
8071 {
8072     int port = SC_PORT(sc);
8073     int reg_offset;
8074     uint32_t val0, mask0, val1, mask1;
8075     uint32_t val;
8076     boolean_t err_flg = FALSE;
8077 
8078     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8079         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8080         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8081         /* CFC error attention */
8082         if (val & 0x2) {
8083             BLOGE(sc, "FATAL error from CFC\n");
8084 	    err_flg = TRUE;
8085         }
8086     }
8087 
8088     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8089         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8090         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8091         /* RQ_USDMDP_FIFO_OVERFLOW */
8092         if (val & 0x18000) {
8093             BLOGE(sc, "FATAL error from PXP\n");
8094 	    err_flg = TRUE;
8095         }
8096 
8097         if (!CHIP_IS_E1x(sc)) {
8098             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8099             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8100 	    err_flg = TRUE;
8101         }
8102     }
8103 
8104 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8105 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8106 
8107     if (attn & AEU_PXP2_HW_INT_BIT) {
8108         /*  CQ47854 workaround do not panic on
8109          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8110          */
8111         if (!CHIP_IS_E1x(sc)) {
8112             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8113             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8114             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8115             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8116             /*
8117              * If the only PXP2_EOP_ERROR_BIT is set in
8118              * STS0 and STS1 - clear it
8119              *
8120              * probably we lose additional attentions between
8121              * STS0 and STS_CLR0, in this case user will not
8122              * be notified about them
8123              */
8124             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8125                 !(val1 & mask1))
8126                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8127 
8128             /* print the register, since no one can restore it */
8129             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8130 
8131             /*
8132              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8133              * then notify
8134              */
8135             if (val0 & PXP2_EOP_ERROR_BIT) {
8136                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8137 		err_flg = TRUE;
8138 
8139                 /*
8140                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8141                  * set then clear attention from PXP2 block without panic
8142                  */
8143                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8144                     ((val1 & mask1) == 0))
8145                     attn &= ~AEU_PXP2_HW_INT_BIT;
8146             }
8147         }
8148     }
8149 
8150     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8151         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8152                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8153 
8154         val = REG_RD(sc, reg_offset);
8155         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8156         REG_WR(sc, reg_offset, val);
8157 
8158         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8159               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8160 	err_flg = TRUE;
8161         bxe_panic(sc, ("HW block attention set2\n"));
8162     }
8163     if(err_flg) {
8164         BXE_SET_ERROR_BIT(sc, BXE_ERR_GLOBAL);
8165         taskqueue_enqueue_timeout(taskqueue_thread,
8166            &sc->sp_err_timeout_task, hz/10);
8167     }
8168 
8169 }
8170 
8171 static void
8172 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8173                          uint32_t         attn)
8174 {
8175     int port = SC_PORT(sc);
8176     int reg_offset;
8177     uint32_t val;
8178     boolean_t err_flg = FALSE;
8179 
8180     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8181         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8182         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8183         /* DORQ discard attention */
8184         if (val & 0x2) {
8185             BLOGE(sc, "FATAL error from DORQ\n");
8186 	    err_flg = TRUE;
8187         }
8188     }
8189 
8190     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8191         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8192                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8193 
8194         val = REG_RD(sc, reg_offset);
8195         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8196         REG_WR(sc, reg_offset, val);
8197 
8198         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8199               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8200         err_flg = TRUE;
8201         bxe_panic(sc, ("HW block attention set1\n"));
8202     }
8203     if(err_flg) {
8204         BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
8205         taskqueue_enqueue_timeout(taskqueue_thread,
8206            &sc->sp_err_timeout_task, hz/10);
8207     }
8208 
8209 }
8210 
8211 static void
8212 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8213                          uint32_t         attn)
8214 {
8215     int port = SC_PORT(sc);
8216     int reg_offset;
8217     uint32_t val;
8218 
8219     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8220                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8221 
8222     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8223         val = REG_RD(sc, reg_offset);
8224         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8225         REG_WR(sc, reg_offset, val);
8226 
8227         BLOGW(sc, "SPIO5 hw attention\n");
8228 
8229         /* Fan failure attention */
8230         elink_hw_reset_phy(&sc->link_params);
8231         bxe_fan_failure(sc);
8232     }
8233 
8234     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8235 	bxe_acquire_phy_lock(sc);
8236         elink_handle_module_detect_int(&sc->link_params);
8237 	bxe_release_phy_lock(sc);
8238     }
8239 
8240     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8241         val = REG_RD(sc, reg_offset);
8242         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8243         REG_WR(sc, reg_offset, val);
8244 
8245 
8246         BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
8247         taskqueue_enqueue_timeout(taskqueue_thread,
8248            &sc->sp_err_timeout_task, hz/10);
8249 
8250         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8251                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8252     }
8253 }
8254 
8255 static void
8256 bxe_attn_int_deasserted(struct bxe_softc *sc,
8257                         uint32_t         deasserted)
8258 {
8259     struct attn_route attn;
8260     struct attn_route *group_mask;
8261     int port = SC_PORT(sc);
8262     int index;
8263     uint32_t reg_addr;
8264     uint32_t val;
8265     uint32_t aeu_mask;
8266     uint8_t global = FALSE;
8267 
8268     /*
8269      * Need to take HW lock because MCP or other port might also
8270      * try to handle this event.
8271      */
8272     bxe_acquire_alr(sc);
8273 
8274     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8275         /* XXX
8276          * In case of parity errors don't handle attentions so that
8277          * other function would "see" parity errors.
8278          */
8279         // XXX schedule a recovery task...
8280         /* disable HW interrupts */
8281         bxe_int_disable(sc);
8282         BXE_SET_ERROR_BIT(sc, BXE_ERR_PARITY);
8283         taskqueue_enqueue_timeout(taskqueue_thread,
8284            &sc->sp_err_timeout_task, hz/10);
8285         bxe_release_alr(sc);
8286         return;
8287     }
8288 
8289     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8290     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8291     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8292     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8293     if (!CHIP_IS_E1x(sc)) {
8294         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8295     } else {
8296         attn.sig[4] = 0;
8297     }
8298 
8299     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8300           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8301 
8302     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8303         if (deasserted & (1 << index)) {
8304             group_mask = &sc->attn_group[index];
8305 
8306             BLOGD(sc, DBG_INTR,
8307                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8308                   group_mask->sig[0], group_mask->sig[1],
8309                   group_mask->sig[2], group_mask->sig[3],
8310                   group_mask->sig[4]);
8311 
8312             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8313             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8314             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8315             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8316             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8317         }
8318     }
8319 
8320     bxe_release_alr(sc);
8321 
8322     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8323         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8324                     COMMAND_REG_ATTN_BITS_CLR);
8325     } else {
8326         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8327     }
8328 
8329     val = ~deasserted;
8330     BLOGD(sc, DBG_INTR,
8331           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8332           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8333     REG_WR(sc, reg_addr, val);
8334 
8335     if (~sc->attn_state & deasserted) {
8336         BLOGE(sc, "IGU error\n");
8337     }
8338 
8339     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8340                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8341 
8342     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8343 
8344     aeu_mask = REG_RD(sc, reg_addr);
8345 
8346     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8347           aeu_mask, deasserted);
8348     aeu_mask |= (deasserted & 0x3ff);
8349     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8350 
8351     REG_WR(sc, reg_addr, aeu_mask);
8352     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8353 
8354     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8355     sc->attn_state &= ~deasserted;
8356     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8357 }
8358 
8359 static void
8360 bxe_attn_int(struct bxe_softc *sc)
8361 {
8362     /* read local copy of bits */
8363     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8364     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8365     uint32_t attn_state = sc->attn_state;
8366 
8367     /* look for changed bits */
8368     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8369     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8370 
8371     BLOGD(sc, DBG_INTR,
8372           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8373           attn_bits, attn_ack, asserted, deasserted);
8374 
8375     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8376         BLOGE(sc, "BAD attention state\n");
8377     }
8378 
8379     /* handle bits that were raised */
8380     if (asserted) {
8381         bxe_attn_int_asserted(sc, asserted);
8382     }
8383 
8384     if (deasserted) {
8385         bxe_attn_int_deasserted(sc, deasserted);
8386     }
8387 }
8388 
8389 static uint16_t
8390 bxe_update_dsb_idx(struct bxe_softc *sc)
8391 {
8392     struct host_sp_status_block *def_sb = sc->def_sb;
8393     uint16_t rc = 0;
8394 
8395     mb(); /* status block is written to by the chip */
8396 
8397     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8398         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8399         rc |= BXE_DEF_SB_ATT_IDX;
8400     }
8401 
8402     if (sc->def_idx != def_sb->sp_sb.running_index) {
8403         sc->def_idx = def_sb->sp_sb.running_index;
8404         rc |= BXE_DEF_SB_IDX;
8405     }
8406 
8407     mb();
8408 
8409     return (rc);
8410 }
8411 
8412 static inline struct ecore_queue_sp_obj *
8413 bxe_cid_to_q_obj(struct bxe_softc *sc,
8414                  uint32_t         cid)
8415 {
8416     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8417     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8418 }
8419 
8420 static void
8421 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8422 {
8423     struct ecore_mcast_ramrod_params rparam;
8424     int rc;
8425 
8426     memset(&rparam, 0, sizeof(rparam));
8427 
8428     rparam.mcast_obj = &sc->mcast_obj;
8429 
8430     BXE_MCAST_LOCK(sc);
8431 
8432     /* clear pending state for the last command */
8433     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8434 
8435     /* if there are pending mcast commands - send them */
8436     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8437         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8438         if (rc < 0) {
8439             BLOGD(sc, DBG_SP,
8440                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8441         }
8442     }
8443 
8444     BXE_MCAST_UNLOCK(sc);
8445 }
8446 
8447 static void
8448 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8449                               union event_ring_elem *elem)
8450 {
8451     unsigned long ramrod_flags = 0;
8452     int rc = 0;
8453     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8454     struct ecore_vlan_mac_obj *vlan_mac_obj;
8455 
8456     /* always push next commands out, don't wait here */
8457     bit_set(&ramrod_flags, RAMROD_CONT);
8458 
8459     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8460     case ECORE_FILTER_MAC_PENDING:
8461         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8462         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8463         break;
8464 
8465     case ECORE_FILTER_MCAST_PENDING:
8466         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8467         /*
8468          * This is only relevant for 57710 where multicast MACs are
8469          * configured as unicast MACs using the same ramrod.
8470          */
8471         bxe_handle_mcast_eqe(sc);
8472         return;
8473 
8474     default:
8475         BLOGE(sc, "Unsupported classification command: %d\n",
8476               elem->message.data.eth_event.echo);
8477         return;
8478     }
8479 
8480     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8481 
8482     if (rc < 0) {
8483         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8484     } else if (rc > 0) {
8485         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8486     }
8487 }
8488 
8489 static void
8490 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8491                        union event_ring_elem *elem)
8492 {
8493     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8494 
8495     /* send rx_mode command again if was requested */
8496     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8497                                &sc->sp_state)) {
8498         bxe_set_storm_rx_mode(sc);
8499     }
8500 }
8501 
8502 static void
8503 bxe_update_eq_prod(struct bxe_softc *sc,
8504                    uint16_t         prod)
8505 {
8506     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8507     wmb(); /* keep prod updates ordered */
8508 }
8509 
8510 static void
8511 bxe_eq_int(struct bxe_softc *sc)
8512 {
8513     uint16_t hw_cons, sw_cons, sw_prod;
8514     union event_ring_elem *elem;
8515     uint8_t echo;
8516     uint32_t cid;
8517     uint8_t opcode;
8518     int spqe_cnt = 0;
8519     struct ecore_queue_sp_obj *q_obj;
8520     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8521     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8522 
8523     hw_cons = le16toh(*sc->eq_cons_sb);
8524 
8525     /*
8526      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8527      * when we get to the next-page we need to adjust so the loop
8528      * condition below will be met. The next element is the size of a
8529      * regular element and hence incrementing by 1
8530      */
8531     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8532         hw_cons++;
8533     }
8534 
8535     /*
8536      * This function may never run in parallel with itself for a
8537      * specific sc and no need for a read memory barrier here.
8538      */
8539     sw_cons = sc->eq_cons;
8540     sw_prod = sc->eq_prod;
8541 
8542     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8543           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8544 
8545     for (;
8546          sw_cons != hw_cons;
8547          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8548 
8549         elem = &sc->eq[EQ_DESC(sw_cons)];
8550 
8551         /* elem CID originates from FW, actually LE */
8552         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8553         opcode = elem->message.opcode;
8554 
8555         /* handle eq element */
8556         switch (opcode) {
8557 
8558         case EVENT_RING_OPCODE_STAT_QUERY:
8559             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8560                   sc->stats_comp++);
8561             /* nothing to do with stats comp */
8562             goto next_spqe;
8563 
8564         case EVENT_RING_OPCODE_CFC_DEL:
8565             /* handle according to cid range */
8566             /* we may want to verify here that the sc state is HALTING */
8567             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8568             q_obj = bxe_cid_to_q_obj(sc, cid);
8569             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8570                 break;
8571             }
8572             goto next_spqe;
8573 
8574         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8575             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8576             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8577                 break;
8578             }
8579             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8580             goto next_spqe;
8581 
8582         case EVENT_RING_OPCODE_START_TRAFFIC:
8583             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8584             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8585                 break;
8586             }
8587             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8588             goto next_spqe;
8589 
8590         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8591             echo = elem->message.data.function_update_event.echo;
8592             if (echo == SWITCH_UPDATE) {
8593                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8594                 if (f_obj->complete_cmd(sc, f_obj,
8595                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8596                     break;
8597                 }
8598             }
8599             else {
8600                 BLOGD(sc, DBG_SP,
8601                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8602             }
8603             goto next_spqe;
8604 
8605         case EVENT_RING_OPCODE_FORWARD_SETUP:
8606             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8607             if (q_obj->complete_cmd(sc, q_obj,
8608                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8609                 break;
8610             }
8611             goto next_spqe;
8612 
8613         case EVENT_RING_OPCODE_FUNCTION_START:
8614             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8615             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8616                 break;
8617             }
8618             goto next_spqe;
8619 
8620         case EVENT_RING_OPCODE_FUNCTION_STOP:
8621             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8622             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8623                 break;
8624             }
8625             goto next_spqe;
8626         }
8627 
8628         switch (opcode | sc->state) {
8629         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8630         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8631             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8632             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8633             rss_raw->clear_pending(rss_raw);
8634             break;
8635 
8636         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8637         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8638         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8639         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8640         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8641         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8642             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8643             bxe_handle_classification_eqe(sc, elem);
8644             break;
8645 
8646         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8647         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8648         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8649             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8650             bxe_handle_mcast_eqe(sc);
8651             break;
8652 
8653         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8654         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8655         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8656             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8657             bxe_handle_rx_mode_eqe(sc, elem);
8658             break;
8659 
8660         default:
8661             /* unknown event log error and continue */
8662             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8663                   elem->message.opcode, sc->state);
8664         }
8665 
8666 next_spqe:
8667         spqe_cnt++;
8668     } /* for */
8669 
8670     mb();
8671     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8672 
8673     sc->eq_cons = sw_cons;
8674     sc->eq_prod = sw_prod;
8675 
8676     /* make sure that above mem writes were issued towards the memory */
8677     wmb();
8678 
8679     /* update producer */
8680     bxe_update_eq_prod(sc, sc->eq_prod);
8681 }
8682 
8683 static void
8684 bxe_handle_sp_tq(void *context,
8685                  int  pending)
8686 {
8687     struct bxe_softc *sc = (struct bxe_softc *)context;
8688     uint16_t status;
8689 
8690     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8691 
8692     /* what work needs to be performed? */
8693     status = bxe_update_dsb_idx(sc);
8694 
8695     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8696 
8697     /* HW attentions */
8698     if (status & BXE_DEF_SB_ATT_IDX) {
8699         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8700         bxe_attn_int(sc);
8701         status &= ~BXE_DEF_SB_ATT_IDX;
8702     }
8703 
8704     /* SP events: STAT_QUERY and others */
8705     if (status & BXE_DEF_SB_IDX) {
8706         /* handle EQ completions */
8707         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8708         bxe_eq_int(sc);
8709         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8710                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8711         status &= ~BXE_DEF_SB_IDX;
8712     }
8713 
8714     /* if status is non zero then something went wrong */
8715     if (__predict_false(status)) {
8716         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8717     }
8718 
8719     /* ack status block only if something was actually handled */
8720     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8721                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8722 
8723     /*
8724      * Must be called after the EQ processing (since eq leads to sriov
8725      * ramrod completion flows).
8726      * This flow may have been scheduled by the arrival of a ramrod
8727      * completion, or by the sriov code rescheduling itself.
8728      */
8729     // XXX bxe_iov_sp_task(sc);
8730 
8731 }
8732 
8733 static void
8734 bxe_handle_fp_tq(void *context,
8735                  int  pending)
8736 {
8737     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8738     struct bxe_softc *sc = fp->sc;
8739     uint8_t more_tx = FALSE;
8740     uint8_t more_rx = FALSE;
8741 
8742     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8743 
8744     /* XXX
8745      * IFF_DRV_RUNNING state can't be checked here since we process
8746      * slowpath events on a client queue during setup. Instead
8747      * we need to add a "process/continue" flag here that the driver
8748      * can use to tell the task here not to do anything.
8749      */
8750 #if 0
8751     if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8752         return;
8753     }
8754 #endif
8755 
8756     /* update the fastpath index */
8757     bxe_update_fp_sb_idx(fp);
8758 
8759     /* XXX add loop here if ever support multiple tx CoS */
8760     /* fp->txdata[cos] */
8761     if (bxe_has_tx_work(fp)) {
8762         BXE_FP_TX_LOCK(fp);
8763         more_tx = bxe_txeof(sc, fp);
8764         BXE_FP_TX_UNLOCK(fp);
8765     }
8766 
8767     if (bxe_has_rx_work(fp)) {
8768         more_rx = bxe_rxeof(sc, fp);
8769     }
8770 
8771     if (more_rx /*|| more_tx*/) {
8772         /* still more work to do */
8773         taskqueue_enqueue(fp->tq, &fp->tq_task);
8774         return;
8775     }
8776 
8777     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8778                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8779 }
8780 
8781 static void
8782 bxe_task_fp(struct bxe_fastpath *fp)
8783 {
8784     struct bxe_softc *sc = fp->sc;
8785     uint8_t more_tx = FALSE;
8786     uint8_t more_rx = FALSE;
8787 
8788     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8789 
8790     /* update the fastpath index */
8791     bxe_update_fp_sb_idx(fp);
8792 
8793     /* XXX add loop here if ever support multiple tx CoS */
8794     /* fp->txdata[cos] */
8795     if (bxe_has_tx_work(fp)) {
8796         BXE_FP_TX_LOCK(fp);
8797         more_tx = bxe_txeof(sc, fp);
8798         BXE_FP_TX_UNLOCK(fp);
8799     }
8800 
8801     if (bxe_has_rx_work(fp)) {
8802         more_rx = bxe_rxeof(sc, fp);
8803     }
8804 
8805     if (more_rx /*|| more_tx*/) {
8806         /* still more work to do, bail out if this ISR and process later */
8807         taskqueue_enqueue(fp->tq, &fp->tq_task);
8808         return;
8809     }
8810 
8811     /*
8812      * Here we write the fastpath index taken before doing any tx or rx work.
8813      * It is very well possible other hw events occurred up to this point and
8814      * they were actually processed accordingly above. Since we're going to
8815      * write an older fastpath index, an interrupt is coming which we might
8816      * not do any work in.
8817      */
8818     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8819                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8820 }
8821 
8822 /*
8823  * Legacy interrupt entry point.
8824  *
8825  * Verifies that the controller generated the interrupt and
8826  * then calls a separate routine to handle the various
8827  * interrupt causes: link, RX, and TX.
8828  */
8829 static void
8830 bxe_intr_legacy(void *xsc)
8831 {
8832     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8833     struct bxe_fastpath *fp;
8834     uint16_t status, mask;
8835     int i;
8836 
8837     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8838 
8839     /*
8840      * 0 for ustorm, 1 for cstorm
8841      * the bits returned from ack_int() are 0-15
8842      * bit 0 = attention status block
8843      * bit 1 = fast path status block
8844      * a mask of 0x2 or more = tx/rx event
8845      * a mask of 1 = slow path event
8846      */
8847 
8848     status = bxe_ack_int(sc);
8849 
8850     /* the interrupt is not for us */
8851     if (__predict_false(status == 0)) {
8852         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8853         return;
8854     }
8855 
8856     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8857 
8858     FOR_EACH_ETH_QUEUE(sc, i) {
8859         fp = &sc->fp[i];
8860         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8861         if (status & mask) {
8862             /* acknowledge and disable further fastpath interrupts */
8863             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8864             bxe_task_fp(fp);
8865             status &= ~mask;
8866         }
8867     }
8868 
8869     if (__predict_false(status & 0x1)) {
8870         /* acknowledge and disable further slowpath interrupts */
8871         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8872 
8873         /* schedule slowpath handler */
8874         taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8875 
8876         status &= ~0x1;
8877     }
8878 
8879     if (__predict_false(status)) {
8880         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8881     }
8882 }
8883 
8884 /* slowpath interrupt entry point */
8885 static void
8886 bxe_intr_sp(void *xsc)
8887 {
8888     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8889 
8890     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8891 
8892     /* acknowledge and disable further slowpath interrupts */
8893     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8894 
8895     /* schedule slowpath handler */
8896     taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8897 }
8898 
8899 /* fastpath interrupt entry point */
8900 static void
8901 bxe_intr_fp(void *xfp)
8902 {
8903     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8904     struct bxe_softc *sc = fp->sc;
8905 
8906     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8907 
8908     BLOGD(sc, DBG_INTR,
8909           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8910           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8911 
8912     /* acknowledge and disable further fastpath interrupts */
8913     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8914 
8915     bxe_task_fp(fp);
8916 }
8917 
8918 /* Release all interrupts allocated by the driver. */
8919 static void
8920 bxe_interrupt_free(struct bxe_softc *sc)
8921 {
8922     int i;
8923 
8924     switch (sc->interrupt_mode) {
8925     case INTR_MODE_INTX:
8926         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8927         if (sc->intr[0].resource != NULL) {
8928             bus_release_resource(sc->dev,
8929                                  SYS_RES_IRQ,
8930                                  sc->intr[0].rid,
8931                                  sc->intr[0].resource);
8932         }
8933         break;
8934     case INTR_MODE_MSI:
8935         for (i = 0; i < sc->intr_count; i++) {
8936             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8937             if (sc->intr[i].resource && sc->intr[i].rid) {
8938                 bus_release_resource(sc->dev,
8939                                      SYS_RES_IRQ,
8940                                      sc->intr[i].rid,
8941                                      sc->intr[i].resource);
8942             }
8943         }
8944         pci_release_msi(sc->dev);
8945         break;
8946     case INTR_MODE_MSIX:
8947         for (i = 0; i < sc->intr_count; i++) {
8948             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8949             if (sc->intr[i].resource && sc->intr[i].rid) {
8950                 bus_release_resource(sc->dev,
8951                                      SYS_RES_IRQ,
8952                                      sc->intr[i].rid,
8953                                      sc->intr[i].resource);
8954             }
8955         }
8956         pci_release_msi(sc->dev);
8957         break;
8958     default:
8959         /* nothing to do as initial allocation failed */
8960         break;
8961     }
8962 }
8963 
8964 /*
8965  * This function determines and allocates the appropriate
8966  * interrupt based on system capabilites and user request.
8967  *
8968  * The user may force a particular interrupt mode, specify
8969  * the number of receive queues, specify the method for
8970  * distribuitng received frames to receive queues, or use
8971  * the default settings which will automatically select the
8972  * best supported combination.  In addition, the OS may or
8973  * may not support certain combinations of these settings.
8974  * This routine attempts to reconcile the settings requested
8975  * by the user with the capabilites available from the system
8976  * to select the optimal combination of features.
8977  *
8978  * Returns:
8979  *   0 = Success, !0 = Failure.
8980  */
8981 static int
8982 bxe_interrupt_alloc(struct bxe_softc *sc)
8983 {
8984     int msix_count = 0;
8985     int msi_count = 0;
8986     int num_requested = 0;
8987     int num_allocated = 0;
8988     int rid, i, j;
8989     int rc;
8990 
8991     /* get the number of available MSI/MSI-X interrupts from the OS */
8992     if (sc->interrupt_mode > 0) {
8993         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8994             msix_count = pci_msix_count(sc->dev);
8995         }
8996 
8997         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8998             msi_count = pci_msi_count(sc->dev);
8999         }
9000 
9001         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
9002               msi_count, msix_count);
9003     }
9004 
9005     do { /* try allocating MSI-X interrupt resources (at least 2) */
9006         if (sc->interrupt_mode != INTR_MODE_MSIX) {
9007             break;
9008         }
9009 
9010         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9011             (msix_count < 2)) {
9012             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9013             break;
9014         }
9015 
9016         /* ask for the necessary number of MSI-X vectors */
9017         num_requested = min((sc->num_queues + 1), msix_count);
9018 
9019         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9020 
9021         num_allocated = num_requested;
9022         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9023             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9024             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9025             break;
9026         }
9027 
9028         if (num_allocated < 2) { /* possible? */
9029             BLOGE(sc, "MSI-X allocation less than 2!\n");
9030             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9031             pci_release_msi(sc->dev);
9032             break;
9033         }
9034 
9035         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9036               num_requested, num_allocated);
9037 
9038         /* best effort so use the number of vectors allocated to us */
9039         sc->intr_count = num_allocated;
9040         sc->num_queues = num_allocated - 1;
9041 
9042         rid = 1; /* initial resource identifier */
9043 
9044         /* allocate the MSI-X vectors */
9045         for (i = 0; i < num_allocated; i++) {
9046             sc->intr[i].rid = (rid + i);
9047 
9048             if ((sc->intr[i].resource =
9049                  bus_alloc_resource_any(sc->dev,
9050                                         SYS_RES_IRQ,
9051                                         &sc->intr[i].rid,
9052                                         RF_ACTIVE)) == NULL) {
9053                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9054                       i, (rid + i));
9055 
9056                 for (j = (i - 1); j >= 0; j--) {
9057                     bus_release_resource(sc->dev,
9058                                          SYS_RES_IRQ,
9059                                          sc->intr[j].rid,
9060                                          sc->intr[j].resource);
9061                 }
9062 
9063                 sc->intr_count = 0;
9064                 sc->num_queues = 0;
9065                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9066                 pci_release_msi(sc->dev);
9067                 break;
9068             }
9069 
9070             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9071         }
9072     } while (0);
9073 
9074     do { /* try allocating MSI vector resources (at least 2) */
9075         if (sc->interrupt_mode != INTR_MODE_MSI) {
9076             break;
9077         }
9078 
9079         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9080             (msi_count < 1)) {
9081             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9082             break;
9083         }
9084 
9085         /* ask for a single MSI vector */
9086         num_requested = 1;
9087 
9088         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9089 
9090         num_allocated = num_requested;
9091         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9092             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9093             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9094             break;
9095         }
9096 
9097         if (num_allocated != 1) { /* possible? */
9098             BLOGE(sc, "MSI allocation is not 1!\n");
9099             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9100             pci_release_msi(sc->dev);
9101             break;
9102         }
9103 
9104         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9105               num_requested, num_allocated);
9106 
9107         /* best effort so use the number of vectors allocated to us */
9108         sc->intr_count = num_allocated;
9109         sc->num_queues = num_allocated;
9110 
9111         rid = 1; /* initial resource identifier */
9112 
9113         sc->intr[0].rid = rid;
9114 
9115         if ((sc->intr[0].resource =
9116              bus_alloc_resource_any(sc->dev,
9117                                     SYS_RES_IRQ,
9118                                     &sc->intr[0].rid,
9119                                     RF_ACTIVE)) == NULL) {
9120             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9121             sc->intr_count = 0;
9122             sc->num_queues = 0;
9123             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9124             pci_release_msi(sc->dev);
9125             break;
9126         }
9127 
9128         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9129     } while (0);
9130 
9131     do { /* try allocating INTx vector resources */
9132         if (sc->interrupt_mode != INTR_MODE_INTX) {
9133             break;
9134         }
9135 
9136         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9137 
9138         /* only one vector for INTx */
9139         sc->intr_count = 1;
9140         sc->num_queues = 1;
9141 
9142         rid = 0; /* initial resource identifier */
9143 
9144         sc->intr[0].rid = rid;
9145 
9146         if ((sc->intr[0].resource =
9147              bus_alloc_resource_any(sc->dev,
9148                                     SYS_RES_IRQ,
9149                                     &sc->intr[0].rid,
9150                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9151             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9152             sc->intr_count = 0;
9153             sc->num_queues = 0;
9154             sc->interrupt_mode = -1; /* Failed! */
9155             break;
9156         }
9157 
9158         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9159     } while (0);
9160 
9161     if (sc->interrupt_mode == -1) {
9162         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9163         rc = 1;
9164     } else {
9165         BLOGD(sc, DBG_LOAD,
9166               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9167               sc->interrupt_mode, sc->num_queues);
9168         rc = 0;
9169     }
9170 
9171     return (rc);
9172 }
9173 
9174 static void
9175 bxe_interrupt_detach(struct bxe_softc *sc)
9176 {
9177     struct bxe_fastpath *fp;
9178     int i;
9179 
9180     /* release interrupt resources */
9181     for (i = 0; i < sc->intr_count; i++) {
9182         if (sc->intr[i].resource && sc->intr[i].tag) {
9183             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9184             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9185         }
9186     }
9187 
9188     for (i = 0; i < sc->num_queues; i++) {
9189         fp = &sc->fp[i];
9190         if (fp->tq) {
9191             taskqueue_drain(fp->tq, &fp->tq_task);
9192             taskqueue_drain(fp->tq, &fp->tx_task);
9193             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9194                 NULL))
9195                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9196         }
9197 
9198         for (i = 0; i < sc->num_queues; i++) {
9199             fp = &sc->fp[i];
9200             if (fp->tq != NULL) {
9201                 taskqueue_free(fp->tq);
9202                 fp->tq = NULL;
9203             }
9204         }
9205     }
9206 
9207     if (sc->sp_tq) {
9208         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9209         taskqueue_free(sc->sp_tq);
9210         sc->sp_tq = NULL;
9211     }
9212 }
9213 
9214 /*
9215  * Enables interrupts and attach to the ISR.
9216  *
9217  * When using multiple MSI/MSI-X vectors the first vector
9218  * is used for slowpath operations while all remaining
9219  * vectors are used for fastpath operations.  If only a
9220  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9221  * ISR must look for both slowpath and fastpath completions.
9222  */
9223 static int
9224 bxe_interrupt_attach(struct bxe_softc *sc)
9225 {
9226     struct bxe_fastpath *fp;
9227     int rc = 0;
9228     int i;
9229 
9230     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9231              "bxe%d_sp_tq", sc->unit);
9232     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9233     sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9234                                  taskqueue_thread_enqueue,
9235                                  &sc->sp_tq);
9236     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9237                             "%s", sc->sp_tq_name);
9238 
9239 
9240     for (i = 0; i < sc->num_queues; i++) {
9241         fp = &sc->fp[i];
9242         snprintf(fp->tq_name, sizeof(fp->tq_name),
9243                  "bxe%d_fp%d_tq", sc->unit, i);
9244         NET_TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9245         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9246         fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9247                                   taskqueue_thread_enqueue,
9248                                   &fp->tq);
9249         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9250                           bxe_tx_mq_start_deferred, fp);
9251         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9252                                 "%s", fp->tq_name);
9253     }
9254 
9255     /* setup interrupt handlers */
9256     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9257         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9258 
9259         /*
9260          * Setup the interrupt handler. Note that we pass the driver instance
9261          * to the interrupt handler for the slowpath.
9262          */
9263         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9264                                  (INTR_TYPE_NET | INTR_MPSAFE),
9265                                  NULL, bxe_intr_sp, sc,
9266                                  &sc->intr[0].tag)) != 0) {
9267             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9268             goto bxe_interrupt_attach_exit;
9269         }
9270 
9271         bus_describe_intr(sc->dev, sc->intr[0].resource,
9272                           sc->intr[0].tag, "sp");
9273 
9274         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9275 
9276         /* initialize the fastpath vectors (note the first was used for sp) */
9277         for (i = 0; i < sc->num_queues; i++) {
9278             fp = &sc->fp[i];
9279             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9280 
9281             /*
9282              * Setup the interrupt handler. Note that we pass the
9283              * fastpath context to the interrupt handler in this
9284              * case.
9285              */
9286             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9287                                      (INTR_TYPE_NET | INTR_MPSAFE),
9288                                      NULL, bxe_intr_fp, fp,
9289                                      &sc->intr[i + 1].tag)) != 0) {
9290                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9291                       (i + 1), rc);
9292                 goto bxe_interrupt_attach_exit;
9293             }
9294 
9295             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9296                               sc->intr[i + 1].tag, "fp%02d", i);
9297 
9298             /* bind the fastpath instance to a cpu */
9299             if (sc->num_queues > 1) {
9300                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9301             }
9302 
9303             fp->state = BXE_FP_STATE_IRQ;
9304         }
9305     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9306         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9307 
9308         /*
9309          * Setup the interrupt handler. Note that we pass the
9310          * driver instance to the interrupt handler which
9311          * will handle both the slowpath and fastpath.
9312          */
9313         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9314                                  (INTR_TYPE_NET | INTR_MPSAFE),
9315                                  NULL, bxe_intr_legacy, sc,
9316                                  &sc->intr[0].tag)) != 0) {
9317             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9318             goto bxe_interrupt_attach_exit;
9319         }
9320 
9321     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9322         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9323 
9324         /*
9325          * Setup the interrupt handler. Note that we pass the
9326          * driver instance to the interrupt handler which
9327          * will handle both the slowpath and fastpath.
9328          */
9329         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9330                                  (INTR_TYPE_NET | INTR_MPSAFE),
9331                                  NULL, bxe_intr_legacy, sc,
9332                                  &sc->intr[0].tag)) != 0) {
9333             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9334             goto bxe_interrupt_attach_exit;
9335         }
9336     }
9337 
9338 bxe_interrupt_attach_exit:
9339 
9340     return (rc);
9341 }
9342 
9343 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9344 static int  bxe_init_hw_common(struct bxe_softc *sc);
9345 static int  bxe_init_hw_port(struct bxe_softc *sc);
9346 static int  bxe_init_hw_func(struct bxe_softc *sc);
9347 static void bxe_reset_common(struct bxe_softc *sc);
9348 static void bxe_reset_port(struct bxe_softc *sc);
9349 static void bxe_reset_func(struct bxe_softc *sc);
9350 static int  bxe_gunzip_init(struct bxe_softc *sc);
9351 static void bxe_gunzip_end(struct bxe_softc *sc);
9352 static int  bxe_init_firmware(struct bxe_softc *sc);
9353 static void bxe_release_firmware(struct bxe_softc *sc);
9354 
9355 static struct
9356 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9357     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9358     .init_hw_cmn      = bxe_init_hw_common,
9359     .init_hw_port     = bxe_init_hw_port,
9360     .init_hw_func     = bxe_init_hw_func,
9361 
9362     .reset_hw_cmn     = bxe_reset_common,
9363     .reset_hw_port    = bxe_reset_port,
9364     .reset_hw_func    = bxe_reset_func,
9365 
9366     .gunzip_init      = bxe_gunzip_init,
9367     .gunzip_end       = bxe_gunzip_end,
9368 
9369     .init_fw          = bxe_init_firmware,
9370     .release_fw       = bxe_release_firmware,
9371 };
9372 
9373 static void
9374 bxe_init_func_obj(struct bxe_softc *sc)
9375 {
9376     sc->dmae_ready = 0;
9377 
9378     ecore_init_func_obj(sc,
9379                         &sc->func_obj,
9380                         BXE_SP(sc, func_rdata),
9381                         BXE_SP_MAPPING(sc, func_rdata),
9382                         BXE_SP(sc, func_afex_rdata),
9383                         BXE_SP_MAPPING(sc, func_afex_rdata),
9384                         &bxe_func_sp_drv);
9385 }
9386 
9387 static int
9388 bxe_init_hw(struct bxe_softc *sc,
9389             uint32_t         load_code)
9390 {
9391     struct ecore_func_state_params func_params = { NULL };
9392     int rc;
9393 
9394     /* prepare the parameters for function state transitions */
9395     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9396 
9397     func_params.f_obj = &sc->func_obj;
9398     func_params.cmd = ECORE_F_CMD_HW_INIT;
9399 
9400     func_params.params.hw_init.load_phase = load_code;
9401 
9402     /*
9403      * Via a plethora of function pointers, we will eventually reach
9404      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9405      */
9406     rc = ecore_func_state_change(sc, &func_params);
9407 
9408     return (rc);
9409 }
9410 
9411 static void
9412 bxe_fill(struct bxe_softc *sc,
9413          uint32_t         addr,
9414          int              fill,
9415          uint32_t         len)
9416 {
9417     uint32_t i;
9418 
9419     if (!(len % 4) && !(addr % 4)) {
9420         for (i = 0; i < len; i += 4) {
9421             REG_WR(sc, (addr + i), fill);
9422         }
9423     } else {
9424         for (i = 0; i < len; i++) {
9425             REG_WR8(sc, (addr + i), fill);
9426         }
9427     }
9428 }
9429 
9430 /* writes FP SP data to FW - data_size in dwords */
9431 static void
9432 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9433                   int              fw_sb_id,
9434                   uint32_t         *sb_data_p,
9435                   uint32_t         data_size)
9436 {
9437     int index;
9438 
9439     for (index = 0; index < data_size; index++) {
9440         REG_WR(sc,
9441                (BAR_CSTRORM_INTMEM +
9442                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9443                 (sizeof(uint32_t) * index)),
9444                *(sb_data_p + index));
9445     }
9446 }
9447 
9448 static void
9449 bxe_zero_fp_sb(struct bxe_softc *sc,
9450                int              fw_sb_id)
9451 {
9452     struct hc_status_block_data_e2 sb_data_e2;
9453     struct hc_status_block_data_e1x sb_data_e1x;
9454     uint32_t *sb_data_p;
9455     uint32_t data_size = 0;
9456 
9457     if (!CHIP_IS_E1x(sc)) {
9458         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9459         sb_data_e2.common.state = SB_DISABLED;
9460         sb_data_e2.common.p_func.vf_valid = FALSE;
9461         sb_data_p = (uint32_t *)&sb_data_e2;
9462         data_size = (sizeof(struct hc_status_block_data_e2) /
9463                      sizeof(uint32_t));
9464     } else {
9465         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9466         sb_data_e1x.common.state = SB_DISABLED;
9467         sb_data_e1x.common.p_func.vf_valid = FALSE;
9468         sb_data_p = (uint32_t *)&sb_data_e1x;
9469         data_size = (sizeof(struct hc_status_block_data_e1x) /
9470                      sizeof(uint32_t));
9471     }
9472 
9473     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9474 
9475     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9476              0, CSTORM_STATUS_BLOCK_SIZE);
9477     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9478              0, CSTORM_SYNC_BLOCK_SIZE);
9479 }
9480 
9481 static void
9482 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9483                   struct hc_sp_status_block_data *sp_sb_data)
9484 {
9485     int i;
9486 
9487     for (i = 0;
9488          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9489          i++) {
9490         REG_WR(sc,
9491                (BAR_CSTRORM_INTMEM +
9492                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9493                 (i * sizeof(uint32_t))),
9494                *((uint32_t *)sp_sb_data + i));
9495     }
9496 }
9497 
9498 static void
9499 bxe_zero_sp_sb(struct bxe_softc *sc)
9500 {
9501     struct hc_sp_status_block_data sp_sb_data;
9502 
9503     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9504 
9505     sp_sb_data.state           = SB_DISABLED;
9506     sp_sb_data.p_func.vf_valid = FALSE;
9507 
9508     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9509 
9510     bxe_fill(sc,
9511              (BAR_CSTRORM_INTMEM +
9512               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9513               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9514     bxe_fill(sc,
9515              (BAR_CSTRORM_INTMEM +
9516               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9517               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9518 }
9519 
9520 static void
9521 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9522                              int                       igu_sb_id,
9523                              int                       igu_seg_id)
9524 {
9525     hc_sm->igu_sb_id      = igu_sb_id;
9526     hc_sm->igu_seg_id     = igu_seg_id;
9527     hc_sm->timer_value    = 0xFF;
9528     hc_sm->time_to_expire = 0xFFFFFFFF;
9529 }
9530 
9531 static void
9532 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9533 {
9534     /* zero out state machine indices */
9535 
9536     /* rx indices */
9537     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9538 
9539     /* tx indices */
9540     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9541     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9542     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9543     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9544 
9545     /* map indices */
9546 
9547     /* rx indices */
9548     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9549         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9550 
9551     /* tx indices */
9552     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9553         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9554     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9555         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9556     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9557         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9558     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9559         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9560 }
9561 
9562 static void
9563 bxe_init_sb(struct bxe_softc *sc,
9564             bus_addr_t       busaddr,
9565             int              vfid,
9566             uint8_t          vf_valid,
9567             int              fw_sb_id,
9568             int              igu_sb_id)
9569 {
9570     struct hc_status_block_data_e2  sb_data_e2;
9571     struct hc_status_block_data_e1x sb_data_e1x;
9572     struct hc_status_block_sm       *hc_sm_p;
9573     uint32_t *sb_data_p;
9574     int igu_seg_id;
9575     int data_size;
9576 
9577     if (CHIP_INT_MODE_IS_BC(sc)) {
9578         igu_seg_id = HC_SEG_ACCESS_NORM;
9579     } else {
9580         igu_seg_id = IGU_SEG_ACCESS_NORM;
9581     }
9582 
9583     bxe_zero_fp_sb(sc, fw_sb_id);
9584 
9585     if (!CHIP_IS_E1x(sc)) {
9586         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9587         sb_data_e2.common.state = SB_ENABLED;
9588         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9589         sb_data_e2.common.p_func.vf_id = vfid;
9590         sb_data_e2.common.p_func.vf_valid = vf_valid;
9591         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9592         sb_data_e2.common.same_igu_sb_1b = TRUE;
9593         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9594         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9595         hc_sm_p = sb_data_e2.common.state_machine;
9596         sb_data_p = (uint32_t *)&sb_data_e2;
9597         data_size = (sizeof(struct hc_status_block_data_e2) /
9598                      sizeof(uint32_t));
9599         bxe_map_sb_state_machines(sb_data_e2.index_data);
9600     } else {
9601         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9602         sb_data_e1x.common.state = SB_ENABLED;
9603         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9604         sb_data_e1x.common.p_func.vf_id = 0xff;
9605         sb_data_e1x.common.p_func.vf_valid = FALSE;
9606         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9607         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9608         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9609         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9610         hc_sm_p = sb_data_e1x.common.state_machine;
9611         sb_data_p = (uint32_t *)&sb_data_e1x;
9612         data_size = (sizeof(struct hc_status_block_data_e1x) /
9613                      sizeof(uint32_t));
9614         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9615     }
9616 
9617     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9618     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9619 
9620     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9621 
9622     /* write indices to HW - PCI guarantees endianity of regpairs */
9623     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9624 }
9625 
9626 static inline uint8_t
9627 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9628 {
9629     if (CHIP_IS_E1x(fp->sc)) {
9630         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9631     } else {
9632         return (fp->cl_id);
9633     }
9634 }
9635 
9636 static inline uint32_t
9637 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9638                            struct bxe_fastpath *fp)
9639 {
9640     uint32_t offset = BAR_USTRORM_INTMEM;
9641 
9642     if (!CHIP_IS_E1x(sc)) {
9643         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9644     } else {
9645         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9646     }
9647 
9648     return (offset);
9649 }
9650 
9651 static void
9652 bxe_init_eth_fp(struct bxe_softc *sc,
9653                 int              idx)
9654 {
9655     struct bxe_fastpath *fp = &sc->fp[idx];
9656     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9657     unsigned long q_type = 0;
9658     int cos;
9659 
9660     fp->sc    = sc;
9661     fp->index = idx;
9662 
9663     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9664     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9665 
9666     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9667                     (SC_L_ID(sc) + idx) :
9668                     /* want client ID same as IGU SB ID for non-E1 */
9669                     fp->igu_sb_id;
9670     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9671 
9672     /* setup sb indices */
9673     if (!CHIP_IS_E1x(sc)) {
9674         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9675         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9676     } else {
9677         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9678         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9679     }
9680 
9681     /* init shortcut */
9682     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9683 
9684     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9685 
9686     /*
9687      * XXX If multiple CoS is ever supported then each fastpath structure
9688      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9689      */
9690     for (cos = 0; cos < sc->max_cos; cos++) {
9691         cids[cos] = idx;
9692     }
9693     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9694 
9695     /* nothing more for a VF to do */
9696     if (IS_VF(sc)) {
9697         return;
9698     }
9699 
9700     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9701                 fp->fw_sb_id, fp->igu_sb_id);
9702 
9703     bxe_update_fp_sb_idx(fp);
9704 
9705     /* Configure Queue State object */
9706     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9707     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9708 
9709     ecore_init_queue_obj(sc,
9710                          &sc->sp_objs[idx].q_obj,
9711                          fp->cl_id,
9712                          cids,
9713                          sc->max_cos,
9714                          SC_FUNC(sc),
9715                          BXE_SP(sc, q_rdata),
9716                          BXE_SP_MAPPING(sc, q_rdata),
9717                          q_type);
9718 
9719     /* configure classification DBs */
9720     ecore_init_mac_obj(sc,
9721                        &sc->sp_objs[idx].mac_obj,
9722                        fp->cl_id,
9723                        idx,
9724                        SC_FUNC(sc),
9725                        BXE_SP(sc, mac_rdata),
9726                        BXE_SP_MAPPING(sc, mac_rdata),
9727                        ECORE_FILTER_MAC_PENDING,
9728                        &sc->sp_state,
9729                        ECORE_OBJ_TYPE_RX_TX,
9730                        &sc->macs_pool);
9731 
9732     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9733           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9734 }
9735 
9736 static inline void
9737 bxe_update_rx_prod(struct bxe_softc    *sc,
9738                    struct bxe_fastpath *fp,
9739                    uint16_t            rx_bd_prod,
9740                    uint16_t            rx_cq_prod,
9741                    uint16_t            rx_sge_prod)
9742 {
9743     struct ustorm_eth_rx_producers rx_prods = { 0 };
9744     uint32_t i;
9745 
9746     /* update producers */
9747     rx_prods.bd_prod  = rx_bd_prod;
9748     rx_prods.cqe_prod = rx_cq_prod;
9749     rx_prods.sge_prod = rx_sge_prod;
9750 
9751     /*
9752      * Make sure that the BD and SGE data is updated before updating the
9753      * producers since FW might read the BD/SGE right after the producer
9754      * is updated.
9755      * This is only applicable for weak-ordered memory model archs such
9756      * as IA-64. The following barrier is also mandatory since FW will
9757      * assumes BDs must have buffers.
9758      */
9759     wmb();
9760 
9761     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9762         REG_WR(sc,
9763                (fp->ustorm_rx_prods_offset + (i * 4)),
9764                ((uint32_t *)&rx_prods)[i]);
9765     }
9766 
9767     wmb(); /* keep prod updates ordered */
9768 
9769     BLOGD(sc, DBG_RX,
9770           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9771           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9772 }
9773 
9774 static void
9775 bxe_init_rx_rings(struct bxe_softc *sc)
9776 {
9777     struct bxe_fastpath *fp;
9778     int i;
9779 
9780     for (i = 0; i < sc->num_queues; i++) {
9781         fp = &sc->fp[i];
9782 
9783         fp->rx_bd_cons = 0;
9784 
9785         /*
9786          * Activate the BD ring...
9787          * Warning, this will generate an interrupt (to the TSTORM)
9788          * so this can only be done after the chip is initialized
9789          */
9790         bxe_update_rx_prod(sc, fp,
9791                            fp->rx_bd_prod,
9792                            fp->rx_cq_prod,
9793                            fp->rx_sge_prod);
9794 
9795         if (i != 0) {
9796             continue;
9797         }
9798 
9799         if (CHIP_IS_E1(sc)) {
9800             REG_WR(sc,
9801                    (BAR_USTRORM_INTMEM +
9802                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9803                    U64_LO(fp->rcq_dma.paddr));
9804             REG_WR(sc,
9805                    (BAR_USTRORM_INTMEM +
9806                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9807                    U64_HI(fp->rcq_dma.paddr));
9808         }
9809     }
9810 }
9811 
9812 static void
9813 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9814 {
9815     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9816     fp->tx_db.data.zero_fill1 = 0;
9817     fp->tx_db.data.prod = 0;
9818 
9819     fp->tx_pkt_prod = 0;
9820     fp->tx_pkt_cons = 0;
9821     fp->tx_bd_prod = 0;
9822     fp->tx_bd_cons = 0;
9823     fp->eth_q_stats.tx_pkts = 0;
9824 }
9825 
9826 static inline void
9827 bxe_init_tx_rings(struct bxe_softc *sc)
9828 {
9829     int i;
9830 
9831     for (i = 0; i < sc->num_queues; i++) {
9832         bxe_init_tx_ring_one(&sc->fp[i]);
9833     }
9834 }
9835 
9836 static void
9837 bxe_init_def_sb(struct bxe_softc *sc)
9838 {
9839     struct host_sp_status_block *def_sb = sc->def_sb;
9840     bus_addr_t mapping = sc->def_sb_dma.paddr;
9841     int igu_sp_sb_index;
9842     int igu_seg_id;
9843     int port = SC_PORT(sc);
9844     int func = SC_FUNC(sc);
9845     int reg_offset, reg_offset_en5;
9846     uint64_t section;
9847     int index, sindex;
9848     struct hc_sp_status_block_data sp_sb_data;
9849 
9850     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9851 
9852     if (CHIP_INT_MODE_IS_BC(sc)) {
9853         igu_sp_sb_index = DEF_SB_IGU_ID;
9854         igu_seg_id = HC_SEG_ACCESS_DEF;
9855     } else {
9856         igu_sp_sb_index = sc->igu_dsb_id;
9857         igu_seg_id = IGU_SEG_ACCESS_DEF;
9858     }
9859 
9860     /* attentions */
9861     section = ((uint64_t)mapping +
9862                offsetof(struct host_sp_status_block, atten_status_block));
9863     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9864     sc->attn_state = 0;
9865 
9866     reg_offset = (port) ?
9867                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9868                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9869     reg_offset_en5 = (port) ?
9870                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9871                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9872 
9873     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9874         /* take care of sig[0]..sig[4] */
9875         for (sindex = 0; sindex < 4; sindex++) {
9876             sc->attn_group[index].sig[sindex] =
9877                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9878         }
9879 
9880         if (!CHIP_IS_E1x(sc)) {
9881             /*
9882              * enable5 is separate from the rest of the registers,
9883              * and the address skip is 4 and not 16 between the
9884              * different groups
9885              */
9886             sc->attn_group[index].sig[4] =
9887                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9888         } else {
9889             sc->attn_group[index].sig[4] = 0;
9890         }
9891     }
9892 
9893     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9894         reg_offset = (port) ?
9895                          HC_REG_ATTN_MSG1_ADDR_L :
9896                          HC_REG_ATTN_MSG0_ADDR_L;
9897         REG_WR(sc, reg_offset, U64_LO(section));
9898         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9899     } else if (!CHIP_IS_E1x(sc)) {
9900         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9901         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9902     }
9903 
9904     section = ((uint64_t)mapping +
9905                offsetof(struct host_sp_status_block, sp_sb));
9906 
9907     bxe_zero_sp_sb(sc);
9908 
9909     /* PCI guarantees endianity of regpair */
9910     sp_sb_data.state           = SB_ENABLED;
9911     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9912     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9913     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9914     sp_sb_data.igu_seg_id      = igu_seg_id;
9915     sp_sb_data.p_func.pf_id    = func;
9916     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9917     sp_sb_data.p_func.vf_id    = 0xff;
9918 
9919     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9920 
9921     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9922 }
9923 
9924 static void
9925 bxe_init_sp_ring(struct bxe_softc *sc)
9926 {
9927     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9928     sc->spq_prod_idx = 0;
9929     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9930     sc->spq_prod_bd = sc->spq;
9931     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9932 }
9933 
9934 static void
9935 bxe_init_eq_ring(struct bxe_softc *sc)
9936 {
9937     union event_ring_elem *elem;
9938     int i;
9939 
9940     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9941         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9942 
9943         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9944                                                  BCM_PAGE_SIZE *
9945                                                  (i % NUM_EQ_PAGES)));
9946         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9947                                                  BCM_PAGE_SIZE *
9948                                                  (i % NUM_EQ_PAGES)));
9949     }
9950 
9951     sc->eq_cons    = 0;
9952     sc->eq_prod    = NUM_EQ_DESC;
9953     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9954 
9955     atomic_store_rel_long(&sc->eq_spq_left,
9956                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9957                                NUM_EQ_DESC) - 1));
9958 }
9959 
9960 static void
9961 bxe_init_internal_common(struct bxe_softc *sc)
9962 {
9963     int i;
9964 
9965     /*
9966      * Zero this manually as its initialization is currently missing
9967      * in the initTool.
9968      */
9969     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9970         REG_WR(sc,
9971                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9972                0);
9973     }
9974 
9975     if (!CHIP_IS_E1x(sc)) {
9976         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9977                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9978     }
9979 }
9980 
9981 static void
9982 bxe_init_internal(struct bxe_softc *sc,
9983                   uint32_t         load_code)
9984 {
9985     switch (load_code) {
9986     case FW_MSG_CODE_DRV_LOAD_COMMON:
9987     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9988         bxe_init_internal_common(sc);
9989         /* no break */
9990 
9991     case FW_MSG_CODE_DRV_LOAD_PORT:
9992         /* nothing to do */
9993         /* no break */
9994 
9995     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9996         /* internal memory per function is initialized inside bxe_pf_init */
9997         break;
9998 
9999     default:
10000         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
10001         break;
10002     }
10003 }
10004 
10005 static void
10006 storm_memset_func_cfg(struct bxe_softc                         *sc,
10007                       struct tstorm_eth_function_common_config *tcfg,
10008                       uint16_t                                  abs_fid)
10009 {
10010     uint32_t addr;
10011     size_t size;
10012 
10013     addr = (BAR_TSTRORM_INTMEM +
10014             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10015     size = sizeof(struct tstorm_eth_function_common_config);
10016     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10017 }
10018 
10019 static void
10020 bxe_func_init(struct bxe_softc            *sc,
10021               struct bxe_func_init_params *p)
10022 {
10023     struct tstorm_eth_function_common_config tcfg = { 0 };
10024 
10025     if (CHIP_IS_E1x(sc)) {
10026         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10027     }
10028 
10029     /* Enable the function in the FW */
10030     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10031     storm_memset_func_en(sc, p->func_id, 1);
10032 
10033     /* spq */
10034     if (p->func_flgs & FUNC_FLG_SPQ) {
10035         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10036         REG_WR(sc,
10037                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10038                p->spq_prod);
10039     }
10040 }
10041 
10042 /*
10043  * Calculates the sum of vn_min_rates.
10044  * It's needed for further normalizing of the min_rates.
10045  * Returns:
10046  *   sum of vn_min_rates.
10047  *     or
10048  *   0 - if all the min_rates are 0.
10049  * In the later case fainess algorithm should be deactivated.
10050  * If all min rates are not zero then those that are zeroes will be set to 1.
10051  */
10052 static void
10053 bxe_calc_vn_min(struct bxe_softc       *sc,
10054                 struct cmng_init_input *input)
10055 {
10056     uint32_t vn_cfg;
10057     uint32_t vn_min_rate;
10058     int all_zero = 1;
10059     int vn;
10060 
10061     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10062         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10063         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10064                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10065 
10066         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10067             /* skip hidden VNs */
10068             vn_min_rate = 0;
10069         } else if (!vn_min_rate) {
10070             /* If min rate is zero - set it to 100 */
10071             vn_min_rate = DEF_MIN_RATE;
10072         } else {
10073             all_zero = 0;
10074         }
10075 
10076         input->vnic_min_rate[vn] = vn_min_rate;
10077     }
10078 
10079     /* if ETS or all min rates are zeros - disable fairness */
10080     if (BXE_IS_ETS_ENABLED(sc)) {
10081         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10082         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10083     } else if (all_zero) {
10084         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10085         BLOGD(sc, DBG_LOAD,
10086               "Fariness disabled (all MIN values are zeroes)\n");
10087     } else {
10088         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10089     }
10090 }
10091 
10092 static inline uint16_t
10093 bxe_extract_max_cfg(struct bxe_softc *sc,
10094                     uint32_t         mf_cfg)
10095 {
10096     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10097                         FUNC_MF_CFG_MAX_BW_SHIFT);
10098 
10099     if (!max_cfg) {
10100         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10101         max_cfg = 100;
10102     }
10103 
10104     return (max_cfg);
10105 }
10106 
10107 static void
10108 bxe_calc_vn_max(struct bxe_softc       *sc,
10109                 int                    vn,
10110                 struct cmng_init_input *input)
10111 {
10112     uint16_t vn_max_rate;
10113     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10114     uint32_t max_cfg;
10115 
10116     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10117         vn_max_rate = 0;
10118     } else {
10119         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10120 
10121         if (IS_MF_SI(sc)) {
10122             /* max_cfg in percents of linkspeed */
10123             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10124         } else { /* SD modes */
10125             /* max_cfg is absolute in 100Mb units */
10126             vn_max_rate = (max_cfg * 100);
10127         }
10128     }
10129 
10130     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10131 
10132     input->vnic_max_rate[vn] = vn_max_rate;
10133 }
10134 
10135 static void
10136 bxe_cmng_fns_init(struct bxe_softc *sc,
10137                   uint8_t          read_cfg,
10138                   uint8_t          cmng_type)
10139 {
10140     struct cmng_init_input input;
10141     int vn;
10142 
10143     memset(&input, 0, sizeof(struct cmng_init_input));
10144 
10145     input.port_rate = sc->link_vars.line_speed;
10146 
10147     if (cmng_type == CMNG_FNS_MINMAX) {
10148         /* read mf conf from shmem */
10149         if (read_cfg) {
10150             bxe_read_mf_cfg(sc);
10151         }
10152 
10153         /* get VN min rate and enable fairness if not 0 */
10154         bxe_calc_vn_min(sc, &input);
10155 
10156         /* get VN max rate */
10157         if (sc->port.pmf) {
10158             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10159                 bxe_calc_vn_max(sc, vn, &input);
10160             }
10161         }
10162 
10163         /* always enable rate shaping and fairness */
10164         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10165 
10166         ecore_init_cmng(&input, &sc->cmng);
10167         return;
10168     }
10169 
10170     /* rate shaping and fairness are disabled */
10171     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10172 }
10173 
10174 static int
10175 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10176 {
10177     if (CHIP_REV_IS_SLOW(sc)) {
10178         return (CMNG_FNS_NONE);
10179     }
10180 
10181     if (IS_MF(sc)) {
10182         return (CMNG_FNS_MINMAX);
10183     }
10184 
10185     return (CMNG_FNS_NONE);
10186 }
10187 
10188 static void
10189 storm_memset_cmng(struct bxe_softc *sc,
10190                   struct cmng_init *cmng,
10191                   uint8_t          port)
10192 {
10193     int vn;
10194     int func;
10195     uint32_t addr;
10196     size_t size;
10197 
10198     addr = (BAR_XSTRORM_INTMEM +
10199             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10200     size = sizeof(struct cmng_struct_per_port);
10201     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10202 
10203     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10204         func = func_by_vn(sc, vn);
10205 
10206         addr = (BAR_XSTRORM_INTMEM +
10207                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10208         size = sizeof(struct rate_shaping_vars_per_vn);
10209         ecore_storm_memset_struct(sc, addr, size,
10210                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10211 
10212         addr = (BAR_XSTRORM_INTMEM +
10213                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10214         size = sizeof(struct fairness_vars_per_vn);
10215         ecore_storm_memset_struct(sc, addr, size,
10216                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10217     }
10218 }
10219 
10220 static void
10221 bxe_pf_init(struct bxe_softc *sc)
10222 {
10223     struct bxe_func_init_params func_init = { 0 };
10224     struct event_ring_data eq_data = { { 0 } };
10225     uint16_t flags;
10226 
10227     if (!CHIP_IS_E1x(sc)) {
10228         /* reset IGU PF statistics: MSIX + ATTN */
10229         /* PF */
10230         REG_WR(sc,
10231                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10232                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10233                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10234                0);
10235         /* ATTN */
10236         REG_WR(sc,
10237                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10238                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10239                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10240                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10241                0);
10242     }
10243 
10244     /* function setup flags */
10245     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10246 
10247     /*
10248      * This flag is relevant for E1x only.
10249      * E2 doesn't have a TPA configuration in a function level.
10250      */
10251     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10252 
10253     func_init.func_flgs = flags;
10254     func_init.pf_id     = SC_FUNC(sc);
10255     func_init.func_id   = SC_FUNC(sc);
10256     func_init.spq_map   = sc->spq_dma.paddr;
10257     func_init.spq_prod  = sc->spq_prod_idx;
10258 
10259     bxe_func_init(sc, &func_init);
10260 
10261     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10262 
10263     /*
10264      * Congestion management values depend on the link rate.
10265      * There is no active link so initial link rate is set to 10Gbps.
10266      * When the link comes up the congestion management values are
10267      * re-calculated according to the actual link rate.
10268      */
10269     sc->link_vars.line_speed = SPEED_10000;
10270     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10271 
10272     /* Only the PMF sets the HW */
10273     if (sc->port.pmf) {
10274         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10275     }
10276 
10277     /* init Event Queue - PCI bus guarantees correct endainity */
10278     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10279     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10280     eq_data.producer     = sc->eq_prod;
10281     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10282     eq_data.sb_id        = DEF_SB_ID;
10283     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10284 }
10285 
10286 static void
10287 bxe_hc_int_enable(struct bxe_softc *sc)
10288 {
10289     int port = SC_PORT(sc);
10290     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10291     uint32_t val = REG_RD(sc, addr);
10292     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10293     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10294                            (sc->intr_count == 1)) ? TRUE : FALSE;
10295     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10296 
10297     if (msix) {
10298         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10299                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10300         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10301                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10302         if (single_msix) {
10303             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10304         }
10305     } else if (msi) {
10306         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10307         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10308                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10309                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10310     } else {
10311         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10312                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10313                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10314                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10315 
10316         if (!CHIP_IS_E1(sc)) {
10317             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10318                   val, port, addr);
10319 
10320             REG_WR(sc, addr, val);
10321 
10322             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10323         }
10324     }
10325 
10326     if (CHIP_IS_E1(sc)) {
10327         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10328     }
10329 
10330     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10331           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10332 
10333     REG_WR(sc, addr, val);
10334 
10335     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10336     mb();
10337 
10338     if (!CHIP_IS_E1(sc)) {
10339         /* init leading/trailing edge */
10340         if (IS_MF(sc)) {
10341             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10342             if (sc->port.pmf) {
10343                 /* enable nig and gpio3 attention */
10344                 val |= 0x1100;
10345             }
10346         } else {
10347             val = 0xffff;
10348         }
10349 
10350         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10351         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10352     }
10353 
10354     /* make sure that interrupts are indeed enabled from here on */
10355     mb();
10356 }
10357 
10358 static void
10359 bxe_igu_int_enable(struct bxe_softc *sc)
10360 {
10361     uint32_t val;
10362     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10363     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10364                            (sc->intr_count == 1)) ? TRUE : FALSE;
10365     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10366 
10367     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10368 
10369     if (msix) {
10370         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10371                  IGU_PF_CONF_SINGLE_ISR_EN);
10372         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10373                 IGU_PF_CONF_ATTN_BIT_EN);
10374         if (single_msix) {
10375             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10376         }
10377     } else if (msi) {
10378         val &= ~IGU_PF_CONF_INT_LINE_EN;
10379         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10380                 IGU_PF_CONF_ATTN_BIT_EN |
10381                 IGU_PF_CONF_SINGLE_ISR_EN);
10382     } else {
10383         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10384         val |= (IGU_PF_CONF_INT_LINE_EN |
10385                 IGU_PF_CONF_ATTN_BIT_EN |
10386                 IGU_PF_CONF_SINGLE_ISR_EN);
10387     }
10388 
10389     /* clean previous status - need to configure igu prior to ack*/
10390     if ((!msix) || single_msix) {
10391         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10392         bxe_ack_int(sc);
10393     }
10394 
10395     val |= IGU_PF_CONF_FUNC_EN;
10396 
10397     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10398           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10399 
10400     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10401 
10402     mb();
10403 
10404     /* init leading/trailing edge */
10405     if (IS_MF(sc)) {
10406         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10407         if (sc->port.pmf) {
10408             /* enable nig and gpio3 attention */
10409             val |= 0x1100;
10410         }
10411     } else {
10412         val = 0xffff;
10413     }
10414 
10415     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10416     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10417 
10418     /* make sure that interrupts are indeed enabled from here on */
10419     mb();
10420 }
10421 
10422 static void
10423 bxe_int_enable(struct bxe_softc *sc)
10424 {
10425     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10426         bxe_hc_int_enable(sc);
10427     } else {
10428         bxe_igu_int_enable(sc);
10429     }
10430 }
10431 
10432 static void
10433 bxe_hc_int_disable(struct bxe_softc *sc)
10434 {
10435     int port = SC_PORT(sc);
10436     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10437     uint32_t val = REG_RD(sc, addr);
10438 
10439     /*
10440      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10441      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10442      * block
10443      */
10444     if (CHIP_IS_E1(sc)) {
10445         /*
10446          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10447          * to prevent from HC sending interrupts after we exit the function
10448          */
10449         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10450 
10451         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10452                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10453                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10454     } else {
10455         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10456                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10457                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10458                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10459     }
10460 
10461     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10462 
10463     /* flush all outstanding writes */
10464     mb();
10465 
10466     REG_WR(sc, addr, val);
10467     if (REG_RD(sc, addr) != val) {
10468         BLOGE(sc, "proper val not read from HC IGU!\n");
10469     }
10470 }
10471 
10472 static void
10473 bxe_igu_int_disable(struct bxe_softc *sc)
10474 {
10475     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10476 
10477     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10478              IGU_PF_CONF_INT_LINE_EN |
10479              IGU_PF_CONF_ATTN_BIT_EN);
10480 
10481     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10482 
10483     /* flush all outstanding writes */
10484     mb();
10485 
10486     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10487     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10488         BLOGE(sc, "proper val not read from IGU!\n");
10489     }
10490 }
10491 
10492 static void
10493 bxe_int_disable(struct bxe_softc *sc)
10494 {
10495     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10496         bxe_hc_int_disable(sc);
10497     } else {
10498         bxe_igu_int_disable(sc);
10499     }
10500 }
10501 
10502 static void
10503 bxe_nic_init(struct bxe_softc *sc,
10504              int              load_code)
10505 {
10506     int i;
10507 
10508     for (i = 0; i < sc->num_queues; i++) {
10509         bxe_init_eth_fp(sc, i);
10510     }
10511 
10512     rmb(); /* ensure status block indices were read */
10513 
10514     bxe_init_rx_rings(sc);
10515     bxe_init_tx_rings(sc);
10516 
10517     if (IS_VF(sc)) {
10518         return;
10519     }
10520 
10521     /* initialize MOD_ABS interrupts */
10522     elink_init_mod_abs_int(sc, &sc->link_vars,
10523                            sc->devinfo.chip_id,
10524                            sc->devinfo.shmem_base,
10525                            sc->devinfo.shmem2_base,
10526                            SC_PORT(sc));
10527 
10528     bxe_init_def_sb(sc);
10529     bxe_update_dsb_idx(sc);
10530     bxe_init_sp_ring(sc);
10531     bxe_init_eq_ring(sc);
10532     bxe_init_internal(sc, load_code);
10533     bxe_pf_init(sc);
10534     bxe_stats_init(sc);
10535 
10536     /* flush all before enabling interrupts */
10537     mb();
10538 
10539     bxe_int_enable(sc);
10540 
10541     /* check for SPIO5 */
10542     bxe_attn_int_deasserted0(sc,
10543                              REG_RD(sc,
10544                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10545                                      SC_PORT(sc)*4)) &
10546                              AEU_INPUTS_ATTN_BITS_SPIO5);
10547 }
10548 
10549 static inline void
10550 bxe_init_objs(struct bxe_softc *sc)
10551 {
10552     /* mcast rules must be added to tx if tx switching is enabled */
10553     ecore_obj_type o_type =
10554         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10555                                          ECORE_OBJ_TYPE_RX;
10556 
10557     /* RX_MODE controlling object */
10558     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10559 
10560     /* multicast configuration controlling object */
10561     ecore_init_mcast_obj(sc,
10562                          &sc->mcast_obj,
10563                          sc->fp[0].cl_id,
10564                          sc->fp[0].index,
10565                          SC_FUNC(sc),
10566                          SC_FUNC(sc),
10567                          BXE_SP(sc, mcast_rdata),
10568                          BXE_SP_MAPPING(sc, mcast_rdata),
10569                          ECORE_FILTER_MCAST_PENDING,
10570                          &sc->sp_state,
10571                          o_type);
10572 
10573     /* Setup CAM credit pools */
10574     ecore_init_mac_credit_pool(sc,
10575                                &sc->macs_pool,
10576                                SC_FUNC(sc),
10577                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10578                                                  VNICS_PER_PATH(sc));
10579 
10580     ecore_init_vlan_credit_pool(sc,
10581                                 &sc->vlans_pool,
10582                                 SC_ABS_FUNC(sc) >> 1,
10583                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10584                                                   VNICS_PER_PATH(sc));
10585 
10586     /* RSS configuration object */
10587     ecore_init_rss_config_obj(sc,
10588                               &sc->rss_conf_obj,
10589                               sc->fp[0].cl_id,
10590                               sc->fp[0].index,
10591                               SC_FUNC(sc),
10592                               SC_FUNC(sc),
10593                               BXE_SP(sc, rss_rdata),
10594                               BXE_SP_MAPPING(sc, rss_rdata),
10595                               ECORE_FILTER_RSS_CONF_PENDING,
10596                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10597 }
10598 
10599 /*
10600  * Initialize the function. This must be called before sending CLIENT_SETUP
10601  * for the first client.
10602  */
10603 static inline int
10604 bxe_func_start(struct bxe_softc *sc)
10605 {
10606     struct ecore_func_state_params func_params = { NULL };
10607     struct ecore_func_start_params *start_params = &func_params.params.start;
10608 
10609     /* Prepare parameters for function state transitions */
10610     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10611 
10612     func_params.f_obj = &sc->func_obj;
10613     func_params.cmd = ECORE_F_CMD_START;
10614 
10615     /* Function parameters */
10616     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10617     start_params->sd_vlan_tag = OVLAN(sc);
10618 
10619     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10620         start_params->network_cos_mode = STATIC_COS;
10621     } else { /* CHIP_IS_E1X */
10622         start_params->network_cos_mode = FW_WRR;
10623     }
10624 
10625     //start_params->gre_tunnel_mode = 0;
10626     //start_params->gre_tunnel_rss  = 0;
10627 
10628     return (ecore_func_state_change(sc, &func_params));
10629 }
10630 
10631 static int
10632 bxe_set_power_state(struct bxe_softc *sc,
10633                     uint8_t          state)
10634 {
10635     uint16_t pmcsr;
10636 
10637     /* If there is no power capability, silently succeed */
10638     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10639         BLOGW(sc, "No power capability\n");
10640         return (0);
10641     }
10642 
10643     pmcsr = pci_read_config(sc->dev,
10644                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10645                             2);
10646 
10647     switch (state) {
10648     case PCI_PM_D0:
10649         pci_write_config(sc->dev,
10650                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10651                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10652 
10653         if (pmcsr & PCIM_PSTAT_DMASK) {
10654             /* delay required during transition out of D3hot */
10655             DELAY(20000);
10656         }
10657 
10658         break;
10659 
10660     case PCI_PM_D3hot:
10661         /* XXX if there are other clients above don't shut down the power */
10662 
10663         /* don't shut down the power for emulation and FPGA */
10664         if (CHIP_REV_IS_SLOW(sc)) {
10665             return (0);
10666         }
10667 
10668         pmcsr &= ~PCIM_PSTAT_DMASK;
10669         pmcsr |= PCIM_PSTAT_D3;
10670 
10671         if (sc->wol) {
10672             pmcsr |= PCIM_PSTAT_PMEENABLE;
10673         }
10674 
10675         pci_write_config(sc->dev,
10676                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10677                          pmcsr, 4);
10678 
10679         /*
10680          * No more memory access after this point until device is brought back
10681          * to D0 state.
10682          */
10683         break;
10684 
10685     default:
10686         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10687             state, pmcsr);
10688         return (-1);
10689     }
10690 
10691     return (0);
10692 }
10693 
10694 
10695 /* return true if succeeded to acquire the lock */
10696 static uint8_t
10697 bxe_trylock_hw_lock(struct bxe_softc *sc,
10698                     uint32_t         resource)
10699 {
10700     uint32_t lock_status;
10701     uint32_t resource_bit = (1 << resource);
10702     int func = SC_FUNC(sc);
10703     uint32_t hw_lock_control_reg;
10704 
10705     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10706 
10707     /* Validating that the resource is within range */
10708     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10709         BLOGD(sc, DBG_LOAD,
10710               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10711               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10712         return (FALSE);
10713     }
10714 
10715     if (func <= 5) {
10716         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10717     } else {
10718         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10719     }
10720 
10721     /* try to acquire the lock */
10722     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10723     lock_status = REG_RD(sc, hw_lock_control_reg);
10724     if (lock_status & resource_bit) {
10725         return (TRUE);
10726     }
10727 
10728     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10729         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10730         lock_status, resource_bit);
10731 
10732     return (FALSE);
10733 }
10734 
10735 /*
10736  * Get the recovery leader resource id according to the engine this function
10737  * belongs to. Currently only only 2 engines is supported.
10738  */
10739 static int
10740 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10741 {
10742     if (SC_PATH(sc)) {
10743         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10744     } else {
10745         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10746     }
10747 }
10748 
10749 /* try to acquire a leader lock for current engine */
10750 static uint8_t
10751 bxe_trylock_leader_lock(struct bxe_softc *sc)
10752 {
10753     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10754 }
10755 
10756 static int
10757 bxe_release_leader_lock(struct bxe_softc *sc)
10758 {
10759     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10760 }
10761 
10762 /* close gates #2, #3 and #4 */
10763 static void
10764 bxe_set_234_gates(struct bxe_softc *sc,
10765                   uint8_t          close)
10766 {
10767     uint32_t val;
10768 
10769     /* gates #2 and #4a are closed/opened for "not E1" only */
10770     if (!CHIP_IS_E1(sc)) {
10771         /* #4 */
10772         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10773         /* #2 */
10774         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10775     }
10776 
10777     /* #3 */
10778     if (CHIP_IS_E1x(sc)) {
10779         /* prevent interrupts from HC on both ports */
10780         val = REG_RD(sc, HC_REG_CONFIG_1);
10781         REG_WR(sc, HC_REG_CONFIG_1,
10782                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10783                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10784 
10785         val = REG_RD(sc, HC_REG_CONFIG_0);
10786         REG_WR(sc, HC_REG_CONFIG_0,
10787                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10788                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10789     } else {
10790         /* Prevent incoming interrupts in IGU */
10791         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10792 
10793         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10794                (!close) ?
10795                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10796                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10797     }
10798 
10799     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10800           close ? "closing" : "opening");
10801 
10802     wmb();
10803 }
10804 
10805 /* poll for pending writes bit, it should get cleared in no more than 1s */
10806 static int
10807 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10808 {
10809     uint32_t cnt = 1000;
10810     uint32_t pend_bits = 0;
10811 
10812     do {
10813         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10814 
10815         if (pend_bits == 0) {
10816             break;
10817         }
10818 
10819         DELAY(1000);
10820     } while (--cnt > 0);
10821 
10822     if (cnt == 0) {
10823         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10824         return (-1);
10825     }
10826 
10827     return (0);
10828 }
10829 
10830 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10831 
10832 static void
10833 bxe_clp_reset_prep(struct bxe_softc *sc,
10834                    uint32_t         *magic_val)
10835 {
10836     /* Do some magic... */
10837     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10838     *magic_val = val & SHARED_MF_CLP_MAGIC;
10839     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10840 }
10841 
10842 /* restore the value of the 'magic' bit */
10843 static void
10844 bxe_clp_reset_done(struct bxe_softc *sc,
10845                    uint32_t         magic_val)
10846 {
10847     /* Restore the 'magic' bit value... */
10848     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10849     MFCFG_WR(sc, shared_mf_config.clp_mb,
10850               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10851 }
10852 
10853 /* prepare for MCP reset, takes care of CLP configurations */
10854 static void
10855 bxe_reset_mcp_prep(struct bxe_softc *sc,
10856                    uint32_t         *magic_val)
10857 {
10858     uint32_t shmem;
10859     uint32_t validity_offset;
10860 
10861     /* set `magic' bit in order to save MF config */
10862     if (!CHIP_IS_E1(sc)) {
10863         bxe_clp_reset_prep(sc, magic_val);
10864     }
10865 
10866     /* get shmem offset */
10867     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10868     validity_offset =
10869         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10870 
10871     /* Clear validity map flags */
10872     if (shmem > 0) {
10873         REG_WR(sc, shmem + validity_offset, 0);
10874     }
10875 }
10876 
10877 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10878 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10879 
10880 static void
10881 bxe_mcp_wait_one(struct bxe_softc *sc)
10882 {
10883     /* special handling for emulation and FPGA (10 times longer) */
10884     if (CHIP_REV_IS_SLOW(sc)) {
10885         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10886     } else {
10887         DELAY((MCP_ONE_TIMEOUT) * 1000);
10888     }
10889 }
10890 
10891 /* initialize shmem_base and waits for validity signature to appear */
10892 static int
10893 bxe_init_shmem(struct bxe_softc *sc)
10894 {
10895     int cnt = 0;
10896     uint32_t val = 0;
10897 
10898     do {
10899         sc->devinfo.shmem_base     =
10900         sc->link_params.shmem_base =
10901             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10902 
10903         if (sc->devinfo.shmem_base) {
10904             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10905             if (val & SHR_MEM_VALIDITY_MB)
10906                 return (0);
10907         }
10908 
10909         bxe_mcp_wait_one(sc);
10910 
10911     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10912 
10913     BLOGE(sc, "BAD MCP validity signature\n");
10914 
10915     return (-1);
10916 }
10917 
10918 static int
10919 bxe_reset_mcp_comp(struct bxe_softc *sc,
10920                    uint32_t         magic_val)
10921 {
10922     int rc = bxe_init_shmem(sc);
10923 
10924     /* Restore the `magic' bit value */
10925     if (!CHIP_IS_E1(sc)) {
10926         bxe_clp_reset_done(sc, magic_val);
10927     }
10928 
10929     return (rc);
10930 }
10931 
10932 static void
10933 bxe_pxp_prep(struct bxe_softc *sc)
10934 {
10935     if (!CHIP_IS_E1(sc)) {
10936         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10937         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10938         wmb();
10939     }
10940 }
10941 
10942 /*
10943  * Reset the whole chip except for:
10944  *      - PCIE core
10945  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10946  *      - IGU
10947  *      - MISC (including AEU)
10948  *      - GRC
10949  *      - RBCN, RBCP
10950  */
10951 static void
10952 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10953                             uint8_t          global)
10954 {
10955     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10956     uint32_t global_bits2, stay_reset2;
10957 
10958     /*
10959      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10960      * (per chip) blocks.
10961      */
10962     global_bits2 =
10963         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10964         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10965 
10966     /*
10967      * Don't reset the following blocks.
10968      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10969      *            reset, as in 4 port device they might still be owned
10970      *            by the MCP (there is only one leader per path).
10971      */
10972     not_reset_mask1 =
10973         MISC_REGISTERS_RESET_REG_1_RST_HC |
10974         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10975         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10976 
10977     not_reset_mask2 =
10978         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10979         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10980         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10981         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10982         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10983         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10984         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10985         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10986         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10987         MISC_REGISTERS_RESET_REG_2_PGLC |
10988         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10989         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10990         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10991         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10992         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10993         MISC_REGISTERS_RESET_REG_2_UMAC1;
10994 
10995     /*
10996      * Keep the following blocks in reset:
10997      *  - all xxMACs are handled by the elink code.
10998      */
10999     stay_reset2 =
11000         MISC_REGISTERS_RESET_REG_2_XMAC |
11001         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
11002 
11003     /* Full reset masks according to the chip */
11004     reset_mask1 = 0xffffffff;
11005 
11006     if (CHIP_IS_E1(sc))
11007         reset_mask2 = 0xffff;
11008     else if (CHIP_IS_E1H(sc))
11009         reset_mask2 = 0x1ffff;
11010     else if (CHIP_IS_E2(sc))
11011         reset_mask2 = 0xfffff;
11012     else /* CHIP_IS_E3 */
11013         reset_mask2 = 0x3ffffff;
11014 
11015     /* Don't reset global blocks unless we need to */
11016     if (!global)
11017         reset_mask2 &= ~global_bits2;
11018 
11019     /*
11020      * In case of attention in the QM, we need to reset PXP
11021      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11022      * because otherwise QM reset would release 'close the gates' shortly
11023      * before resetting the PXP, then the PSWRQ would send a write
11024      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11025      * read the payload data from PSWWR, but PSWWR would not
11026      * respond. The write queue in PGLUE would stuck, dmae commands
11027      * would not return. Therefore it's important to reset the second
11028      * reset register (containing the
11029      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11030      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11031      * bit).
11032      */
11033     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11034            reset_mask2 & (~not_reset_mask2));
11035 
11036     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11037            reset_mask1 & (~not_reset_mask1));
11038 
11039     mb();
11040     wmb();
11041 
11042     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11043            reset_mask2 & (~stay_reset2));
11044 
11045     mb();
11046     wmb();
11047 
11048     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11049     wmb();
11050 }
11051 
11052 static int
11053 bxe_process_kill(struct bxe_softc *sc,
11054                  uint8_t          global)
11055 {
11056     int cnt = 1000;
11057     uint32_t val = 0;
11058     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11059     uint32_t tags_63_32 = 0;
11060 
11061     /* Empty the Tetris buffer, wait for 1s */
11062     do {
11063         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11064         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11065         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11066         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11067         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11068         if (CHIP_IS_E3(sc)) {
11069             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11070         }
11071 
11072         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11073             ((port_is_idle_0 & 0x1) == 0x1) &&
11074             ((port_is_idle_1 & 0x1) == 0x1) &&
11075             (pgl_exp_rom2 == 0xffffffff) &&
11076             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11077             break;
11078         DELAY(1000);
11079     } while (cnt-- > 0);
11080 
11081     if (cnt <= 0) {
11082         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11083                   "are still outstanding read requests after 1s! "
11084                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11085                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11086               sr_cnt, blk_cnt, port_is_idle_0,
11087               port_is_idle_1, pgl_exp_rom2);
11088         return (-1);
11089     }
11090 
11091     mb();
11092 
11093     /* Close gates #2, #3 and #4 */
11094     bxe_set_234_gates(sc, TRUE);
11095 
11096     /* Poll for IGU VQs for 57712 and newer chips */
11097     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11098         return (-1);
11099     }
11100 
11101     /* XXX indicate that "process kill" is in progress to MCP */
11102 
11103     /* clear "unprepared" bit */
11104     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11105     mb();
11106 
11107     /* Make sure all is written to the chip before the reset */
11108     wmb();
11109 
11110     /*
11111      * Wait for 1ms to empty GLUE and PCI-E core queues,
11112      * PSWHST, GRC and PSWRD Tetris buffer.
11113      */
11114     DELAY(1000);
11115 
11116     /* Prepare to chip reset: */
11117     /* MCP */
11118     if (global) {
11119         bxe_reset_mcp_prep(sc, &val);
11120     }
11121 
11122     /* PXP */
11123     bxe_pxp_prep(sc);
11124     mb();
11125 
11126     /* reset the chip */
11127     bxe_process_kill_chip_reset(sc, global);
11128     mb();
11129 
11130     /* clear errors in PGB */
11131     if (!CHIP_IS_E1(sc))
11132         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11133 
11134     /* Recover after reset: */
11135     /* MCP */
11136     if (global && bxe_reset_mcp_comp(sc, val)) {
11137         return (-1);
11138     }
11139 
11140     /* XXX add resetting the NO_MCP mode DB here */
11141 
11142     /* Open the gates #2, #3 and #4 */
11143     bxe_set_234_gates(sc, FALSE);
11144 
11145     /* XXX
11146      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11147      * re-enable attentions
11148      */
11149 
11150     return (0);
11151 }
11152 
11153 static int
11154 bxe_leader_reset(struct bxe_softc *sc)
11155 {
11156     int rc = 0;
11157     uint8_t global = bxe_reset_is_global(sc);
11158     uint32_t load_code;
11159 
11160     /*
11161      * If not going to reset MCP, load "fake" driver to reset HW while
11162      * driver is owner of the HW.
11163      */
11164     if (!global && !BXE_NOMCP(sc)) {
11165         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11166                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11167         if (!load_code) {
11168             BLOGE(sc, "MCP response failure, aborting\n");
11169             rc = -1;
11170             goto exit_leader_reset;
11171         }
11172 
11173         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11174             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11175             BLOGE(sc, "MCP unexpected response, aborting\n");
11176             rc = -1;
11177             goto exit_leader_reset2;
11178         }
11179 
11180         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11181         if (!load_code) {
11182             BLOGE(sc, "MCP response failure, aborting\n");
11183             rc = -1;
11184             goto exit_leader_reset2;
11185         }
11186     }
11187 
11188     /* try to recover after the failure */
11189     if (bxe_process_kill(sc, global)) {
11190         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11191         rc = -1;
11192         goto exit_leader_reset2;
11193     }
11194 
11195     /*
11196      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11197      * state.
11198      */
11199     bxe_set_reset_done(sc);
11200     if (global) {
11201         bxe_clear_reset_global(sc);
11202     }
11203 
11204 exit_leader_reset2:
11205 
11206     /* unload "fake driver" if it was loaded */
11207     if (!global && !BXE_NOMCP(sc)) {
11208         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11209         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11210     }
11211 
11212 exit_leader_reset:
11213 
11214     sc->is_leader = 0;
11215     bxe_release_leader_lock(sc);
11216 
11217     mb();
11218     return (rc);
11219 }
11220 
11221 /*
11222  * prepare INIT transition, parameters configured:
11223  *   - HC configuration
11224  *   - Queue's CDU context
11225  */
11226 static void
11227 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11228                    struct bxe_fastpath            *fp,
11229                    struct ecore_queue_init_params *init_params)
11230 {
11231     uint8_t cos;
11232     int cxt_index, cxt_offset;
11233 
11234     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11235     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11236 
11237     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11238     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11239 
11240     /* HC rate */
11241     init_params->rx.hc_rate =
11242         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11243     init_params->tx.hc_rate =
11244         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11245 
11246     /* FW SB ID */
11247     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11248 
11249     /* CQ index among the SB indices */
11250     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11251     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11252 
11253     /* set maximum number of COSs supported by this queue */
11254     init_params->max_cos = sc->max_cos;
11255 
11256     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11257           fp->index, init_params->max_cos);
11258 
11259     /* set the context pointers queue object */
11260     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11261         /* XXX change index/cid here if ever support multiple tx CoS */
11262         /* fp->txdata[cos]->cid */
11263         cxt_index = fp->index / ILT_PAGE_CIDS;
11264         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11265         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11266     }
11267 }
11268 
11269 /* set flags that are common for the Tx-only and not normal connections */
11270 static unsigned long
11271 bxe_get_common_flags(struct bxe_softc    *sc,
11272                      struct bxe_fastpath *fp,
11273                      uint8_t             zero_stats)
11274 {
11275     unsigned long flags = 0;
11276 
11277     /* PF driver will always initialize the Queue to an ACTIVE state */
11278     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11279 
11280     /*
11281      * tx only connections collect statistics (on the same index as the
11282      * parent connection). The statistics are zeroed when the parent
11283      * connection is initialized.
11284      */
11285 
11286     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11287     if (zero_stats) {
11288         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11289     }
11290 
11291     /*
11292      * tx only connections can support tx-switching, though their
11293      * CoS-ness doesn't survive the loopback
11294      */
11295     if (sc->flags & BXE_TX_SWITCHING) {
11296         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11297     }
11298 
11299     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11300 
11301     return (flags);
11302 }
11303 
11304 static unsigned long
11305 bxe_get_q_flags(struct bxe_softc    *sc,
11306                 struct bxe_fastpath *fp,
11307                 uint8_t             leading)
11308 {
11309     unsigned long flags = 0;
11310 
11311     if (IS_MF_SD(sc)) {
11312         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11313     }
11314 
11315     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11316         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11317 #if __FreeBSD_version >= 800000
11318         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11319 #endif
11320     }
11321 
11322     if (leading) {
11323         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11324         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11325     }
11326 
11327     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11328 
11329     /* merge with common flags */
11330     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11331 }
11332 
11333 static void
11334 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11335                       struct bxe_fastpath               *fp,
11336                       struct ecore_general_setup_params *gen_init,
11337                       uint8_t                           cos)
11338 {
11339     gen_init->stat_id = bxe_stats_id(fp);
11340     gen_init->spcl_id = fp->cl_id;
11341     gen_init->mtu = sc->mtu;
11342     gen_init->cos = cos;
11343 }
11344 
11345 static void
11346 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11347                  struct bxe_fastpath           *fp,
11348                  struct rxq_pause_params       *pause,
11349                  struct ecore_rxq_setup_params *rxq_init)
11350 {
11351     uint8_t max_sge = 0;
11352     uint16_t sge_sz = 0;
11353     uint16_t tpa_agg_size = 0;
11354 
11355     pause->sge_th_lo = SGE_TH_LO(sc);
11356     pause->sge_th_hi = SGE_TH_HI(sc);
11357 
11358     /* validate SGE ring has enough to cross high threshold */
11359     if (sc->dropless_fc &&
11360             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11361             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11362         BLOGW(sc, "sge ring threshold limit\n");
11363     }
11364 
11365     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11366     tpa_agg_size = (2 * sc->mtu);
11367     if (tpa_agg_size < sc->max_aggregation_size) {
11368         tpa_agg_size = sc->max_aggregation_size;
11369     }
11370 
11371     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11372     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11373                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11374     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11375 
11376     /* pause - not for e1 */
11377     if (!CHIP_IS_E1(sc)) {
11378         pause->bd_th_lo = BD_TH_LO(sc);
11379         pause->bd_th_hi = BD_TH_HI(sc);
11380 
11381         pause->rcq_th_lo = RCQ_TH_LO(sc);
11382         pause->rcq_th_hi = RCQ_TH_HI(sc);
11383 
11384         /* validate rings have enough entries to cross high thresholds */
11385         if (sc->dropless_fc &&
11386             pause->bd_th_hi + FW_PREFETCH_CNT >
11387             sc->rx_ring_size) {
11388             BLOGW(sc, "rx bd ring threshold limit\n");
11389         }
11390 
11391         if (sc->dropless_fc &&
11392             pause->rcq_th_hi + FW_PREFETCH_CNT >
11393             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11394             BLOGW(sc, "rcq ring threshold limit\n");
11395         }
11396 
11397         pause->pri_map = 1;
11398     }
11399 
11400     /* rxq setup */
11401     rxq_init->dscr_map   = fp->rx_dma.paddr;
11402     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11403     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11404     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11405 
11406     /*
11407      * This should be a maximum number of data bytes that may be
11408      * placed on the BD (not including paddings).
11409      */
11410     rxq_init->buf_sz = (fp->rx_buf_size -
11411                         IP_HEADER_ALIGNMENT_PADDING);
11412 
11413     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11414     rxq_init->tpa_agg_sz      = tpa_agg_size;
11415     rxq_init->sge_buf_sz      = sge_sz;
11416     rxq_init->max_sges_pkt    = max_sge;
11417     rxq_init->rss_engine_id   = SC_FUNC(sc);
11418     rxq_init->mcast_engine_id = SC_FUNC(sc);
11419 
11420     /*
11421      * Maximum number or simultaneous TPA aggregation for this Queue.
11422      * For PF Clients it should be the maximum available number.
11423      * VF driver(s) may want to define it to a smaller value.
11424      */
11425     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11426 
11427     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11428     rxq_init->fw_sb_id = fp->fw_sb_id;
11429 
11430     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11431 
11432     /*
11433      * configure silent vlan removal
11434      * if multi function mode is afex, then mask default vlan
11435      */
11436     if (IS_MF_AFEX(sc)) {
11437         rxq_init->silent_removal_value =
11438             sc->devinfo.mf_info.afex_def_vlan_tag;
11439         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11440     }
11441 }
11442 
11443 static void
11444 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11445                  struct bxe_fastpath           *fp,
11446                  struct ecore_txq_setup_params *txq_init,
11447                  uint8_t                       cos)
11448 {
11449     /*
11450      * XXX If multiple CoS is ever supported then each fastpath structure
11451      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11452      * fp->txdata[cos]->tx_dma.paddr;
11453      */
11454     txq_init->dscr_map     = fp->tx_dma.paddr;
11455     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11456     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11457     txq_init->fw_sb_id     = fp->fw_sb_id;
11458 
11459     /*
11460      * set the TSS leading client id for TX classfication to the
11461      * leading RSS client id
11462      */
11463     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11464 }
11465 
11466 /*
11467  * This function performs 2 steps in a queue state machine:
11468  *   1) RESET->INIT
11469  *   2) INIT->SETUP
11470  */
11471 static int
11472 bxe_setup_queue(struct bxe_softc    *sc,
11473                 struct bxe_fastpath *fp,
11474                 uint8_t             leading)
11475 {
11476     struct ecore_queue_state_params q_params = { NULL };
11477     struct ecore_queue_setup_params *setup_params =
11478                         &q_params.params.setup;
11479     int rc;
11480 
11481     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11482 
11483     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11484 
11485     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11486 
11487     /* we want to wait for completion in this context */
11488     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11489 
11490     /* prepare the INIT parameters */
11491     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11492 
11493     /* Set the command */
11494     q_params.cmd = ECORE_Q_CMD_INIT;
11495 
11496     /* Change the state to INIT */
11497     rc = ecore_queue_state_change(sc, &q_params);
11498     if (rc) {
11499         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11500         return (rc);
11501     }
11502 
11503     BLOGD(sc, DBG_LOAD, "init complete\n");
11504 
11505     /* now move the Queue to the SETUP state */
11506     memset(setup_params, 0, sizeof(*setup_params));
11507 
11508     /* set Queue flags */
11509     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11510 
11511     /* set general SETUP parameters */
11512     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11513                           FIRST_TX_COS_INDEX);
11514 
11515     bxe_pf_rx_q_prep(sc, fp,
11516                      &setup_params->pause_params,
11517                      &setup_params->rxq_params);
11518 
11519     bxe_pf_tx_q_prep(sc, fp,
11520                      &setup_params->txq_params,
11521                      FIRST_TX_COS_INDEX);
11522 
11523     /* Set the command */
11524     q_params.cmd = ECORE_Q_CMD_SETUP;
11525 
11526     /* change the state to SETUP */
11527     rc = ecore_queue_state_change(sc, &q_params);
11528     if (rc) {
11529         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11530         return (rc);
11531     }
11532 
11533     return (rc);
11534 }
11535 
11536 static int
11537 bxe_setup_leading(struct bxe_softc *sc)
11538 {
11539     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11540 }
11541 
11542 static int
11543 bxe_config_rss_pf(struct bxe_softc            *sc,
11544                   struct ecore_rss_config_obj *rss_obj,
11545                   uint8_t                     config_hash)
11546 {
11547     struct ecore_config_rss_params params = { NULL };
11548     int i;
11549 
11550     /*
11551      * Although RSS is meaningless when there is a single HW queue we
11552      * still need it enabled in order to have HW Rx hash generated.
11553      */
11554 
11555     params.rss_obj = rss_obj;
11556 
11557     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11558 
11559     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11560 
11561     /* RSS configuration */
11562     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11563     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11564     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11565     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11566     if (rss_obj->udp_rss_v4) {
11567         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11568     }
11569     if (rss_obj->udp_rss_v6) {
11570         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11571     }
11572 
11573     /* Hash bits */
11574     params.rss_result_mask = MULTI_MASK;
11575 
11576     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11577 
11578     if (config_hash) {
11579         /* RSS keys */
11580         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11581             params.rss_key[i] = arc4random();
11582         }
11583 
11584         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11585     }
11586 
11587     return (ecore_config_rss(sc, &params));
11588 }
11589 
11590 static int
11591 bxe_config_rss_eth(struct bxe_softc *sc,
11592                    uint8_t          config_hash)
11593 {
11594     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11595 }
11596 
11597 static int
11598 bxe_init_rss_pf(struct bxe_softc *sc)
11599 {
11600     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11601     int i;
11602 
11603     /*
11604      * Prepare the initial contents of the indirection table if
11605      * RSS is enabled
11606      */
11607     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11608         sc->rss_conf_obj.ind_table[i] =
11609             (sc->fp->cl_id + (i % num_eth_queues));
11610     }
11611 
11612     if (sc->udp_rss) {
11613         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11614     }
11615 
11616     /*
11617      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11618      * per-port, so if explicit configuration is needed, do it only
11619      * for a PMF.
11620      *
11621      * For 57712 and newer it's a per-function configuration.
11622      */
11623     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11624 }
11625 
11626 static int
11627 bxe_set_mac_one(struct bxe_softc          *sc,
11628                 uint8_t                   *mac,
11629                 struct ecore_vlan_mac_obj *obj,
11630                 uint8_t                   set,
11631                 int                       mac_type,
11632                 unsigned long             *ramrod_flags)
11633 {
11634     struct ecore_vlan_mac_ramrod_params ramrod_param;
11635     int rc;
11636 
11637     memset(&ramrod_param, 0, sizeof(ramrod_param));
11638 
11639     /* fill in general parameters */
11640     ramrod_param.vlan_mac_obj = obj;
11641     ramrod_param.ramrod_flags = *ramrod_flags;
11642 
11643     /* fill a user request section if needed */
11644     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11645         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11646 
11647         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11648 
11649         /* Set the command: ADD or DEL */
11650         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11651                                             ECORE_VLAN_MAC_DEL;
11652     }
11653 
11654     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11655 
11656     if (rc == ECORE_EXISTS) {
11657         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11658         /* do not treat adding same MAC as error */
11659         rc = 0;
11660     } else if (rc < 0) {
11661         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11662     }
11663 
11664     return (rc);
11665 }
11666 
11667 static int
11668 bxe_set_eth_mac(struct bxe_softc *sc,
11669                 uint8_t          set)
11670 {
11671     unsigned long ramrod_flags = 0;
11672 
11673     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11674 
11675     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11676 
11677     /* Eth MAC is set on RSS leading client (fp[0]) */
11678     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11679                             &sc->sp_objs->mac_obj,
11680                             set, ECORE_ETH_MAC, &ramrod_flags));
11681 }
11682 
11683 static int
11684 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11685 {
11686     uint32_t sel_phy_idx = 0;
11687 
11688     if (sc->link_params.num_phys <= 1) {
11689         return (ELINK_INT_PHY);
11690     }
11691 
11692     if (sc->link_vars.link_up) {
11693         sel_phy_idx = ELINK_EXT_PHY1;
11694         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11695         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11696             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11697              ELINK_SUPPORTED_FIBRE))
11698             sel_phy_idx = ELINK_EXT_PHY2;
11699     } else {
11700         switch (elink_phy_selection(&sc->link_params)) {
11701         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11702         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11703         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11704                sel_phy_idx = ELINK_EXT_PHY1;
11705                break;
11706         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11707         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11708                sel_phy_idx = ELINK_EXT_PHY2;
11709                break;
11710         }
11711     }
11712 
11713     return (sel_phy_idx);
11714 }
11715 
11716 static int
11717 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11718 {
11719     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11720 
11721     /*
11722      * The selected activated PHY is always after swapping (in case PHY
11723      * swapping is enabled). So when swapping is enabled, we need to reverse
11724      * the configuration
11725      */
11726 
11727     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11728         if (sel_phy_idx == ELINK_EXT_PHY1)
11729             sel_phy_idx = ELINK_EXT_PHY2;
11730         else if (sel_phy_idx == ELINK_EXT_PHY2)
11731             sel_phy_idx = ELINK_EXT_PHY1;
11732     }
11733 
11734     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11735 }
11736 
11737 static void
11738 bxe_set_requested_fc(struct bxe_softc *sc)
11739 {
11740     /*
11741      * Initialize link parameters structure variables
11742      * It is recommended to turn off RX FC for jumbo frames
11743      * for better performance
11744      */
11745     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11746         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11747     } else {
11748         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11749     }
11750 }
11751 
11752 static void
11753 bxe_calc_fc_adv(struct bxe_softc *sc)
11754 {
11755     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11756 
11757 
11758     sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11759                                            ADVERTISED_Pause);
11760 
11761     switch (sc->link_vars.ieee_fc &
11762             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11763 
11764     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11765         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11766                                           ADVERTISED_Pause);
11767         break;
11768 
11769     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11770         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11771         break;
11772 
11773     default:
11774         break;
11775 
11776     }
11777 }
11778 
11779 static uint16_t
11780 bxe_get_mf_speed(struct bxe_softc *sc)
11781 {
11782     uint16_t line_speed = sc->link_vars.line_speed;
11783     if (IS_MF(sc)) {
11784         uint16_t maxCfg =
11785             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11786 
11787         /* calculate the current MAX line speed limit for the MF devices */
11788         if (IS_MF_SI(sc)) {
11789             line_speed = (line_speed * maxCfg) / 100;
11790         } else { /* SD mode */
11791             uint16_t vn_max_rate = maxCfg * 100;
11792 
11793             if (vn_max_rate < line_speed) {
11794                 line_speed = vn_max_rate;
11795             }
11796         }
11797     }
11798 
11799     return (line_speed);
11800 }
11801 
11802 static void
11803 bxe_fill_report_data(struct bxe_softc            *sc,
11804                      struct bxe_link_report_data *data)
11805 {
11806     uint16_t line_speed = bxe_get_mf_speed(sc);
11807 
11808     memset(data, 0, sizeof(*data));
11809 
11810     /* fill the report data with the effective line speed */
11811     data->line_speed = line_speed;
11812 
11813     /* Link is down */
11814     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11815         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11816     }
11817 
11818     /* Full DUPLEX */
11819     if (sc->link_vars.duplex == DUPLEX_FULL) {
11820         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11821     }
11822 
11823     /* Rx Flow Control is ON */
11824     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11825         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11826     }
11827 
11828     /* Tx Flow Control is ON */
11829     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11830         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11831     }
11832 }
11833 
11834 /* report link status to OS, should be called under phy_lock */
11835 static void
11836 bxe_link_report_locked(struct bxe_softc *sc)
11837 {
11838     struct bxe_link_report_data cur_data;
11839 
11840     /* reread mf_cfg */
11841     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11842         bxe_read_mf_cfg(sc);
11843     }
11844 
11845     /* Read the current link report info */
11846     bxe_fill_report_data(sc, &cur_data);
11847 
11848     /* Don't report link down or exactly the same link status twice */
11849     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11850         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11851                       &sc->last_reported_link.link_report_flags) &&
11852          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11853                       &cur_data.link_report_flags))) {
11854         return;
11855     }
11856 
11857 	ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11858 					cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11859     sc->link_cnt++;
11860 
11861 	ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11862     /* report new link params and remember the state for the next time */
11863     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11864 
11865     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11866                      &cur_data.link_report_flags)) {
11867         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11868     } else {
11869         const char *duplex;
11870         const char *flow;
11871 
11872         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11873                                    &cur_data.link_report_flags)) {
11874             duplex = "full";
11875 			ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11876         } else {
11877             duplex = "half";
11878 			ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11879         }
11880 
11881         /*
11882          * Handle the FC at the end so that only these flags would be
11883          * possibly set. This way we may easily check if there is no FC
11884          * enabled.
11885          */
11886         if (cur_data.link_report_flags) {
11887             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11888                              &cur_data.link_report_flags) &&
11889                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11890                              &cur_data.link_report_flags)) {
11891                 flow = "ON - receive & transmit";
11892             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11893                                     &cur_data.link_report_flags) &&
11894                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11895                                      &cur_data.link_report_flags)) {
11896                 flow = "ON - receive";
11897             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11898                                      &cur_data.link_report_flags) &&
11899                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11900                                     &cur_data.link_report_flags)) {
11901                 flow = "ON - transmit";
11902             } else {
11903                 flow = "none"; /* possible? */
11904             }
11905         } else {
11906             flow = "none";
11907         }
11908 
11909         if_link_state_change(sc->ifp, LINK_STATE_UP);
11910         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11911               cur_data.line_speed, duplex, flow);
11912     }
11913 }
11914 
11915 static void
11916 bxe_link_report(struct bxe_softc *sc)
11917 {
11918     bxe_acquire_phy_lock(sc);
11919     bxe_link_report_locked(sc);
11920     bxe_release_phy_lock(sc);
11921 }
11922 
11923 static void
11924 bxe_link_status_update(struct bxe_softc *sc)
11925 {
11926     if (sc->state != BXE_STATE_OPEN) {
11927         return;
11928     }
11929 
11930     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11931         elink_link_status_update(&sc->link_params, &sc->link_vars);
11932     } else {
11933         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11934                                   ELINK_SUPPORTED_10baseT_Full |
11935                                   ELINK_SUPPORTED_100baseT_Half |
11936                                   ELINK_SUPPORTED_100baseT_Full |
11937                                   ELINK_SUPPORTED_1000baseT_Full |
11938                                   ELINK_SUPPORTED_2500baseX_Full |
11939                                   ELINK_SUPPORTED_10000baseT_Full |
11940                                   ELINK_SUPPORTED_TP |
11941                                   ELINK_SUPPORTED_FIBRE |
11942                                   ELINK_SUPPORTED_Autoneg |
11943                                   ELINK_SUPPORTED_Pause |
11944                                   ELINK_SUPPORTED_Asym_Pause);
11945         sc->port.advertising[0] = sc->port.supported[0];
11946 
11947         sc->link_params.sc                = sc;
11948         sc->link_params.port              = SC_PORT(sc);
11949         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11950         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11951         sc->link_params.req_line_speed[0] = SPEED_10000;
11952         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11953         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11954 
11955         if (CHIP_REV_IS_FPGA(sc)) {
11956             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11957             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11958             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11959                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11960         } else {
11961             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11962             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11963             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11964                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11965         }
11966 
11967         sc->link_vars.link_up = 1;
11968 
11969         sc->link_vars.duplex    = DUPLEX_FULL;
11970         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11971 
11972         if (IS_PF(sc)) {
11973             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11974             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11975             bxe_link_report(sc);
11976         }
11977     }
11978 
11979     if (IS_PF(sc)) {
11980         if (sc->link_vars.link_up) {
11981             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11982         } else {
11983             bxe_stats_handle(sc, STATS_EVENT_STOP);
11984         }
11985         bxe_link_report(sc);
11986     } else {
11987         bxe_link_report(sc);
11988         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11989     }
11990 }
11991 
11992 static int
11993 bxe_initial_phy_init(struct bxe_softc *sc,
11994                      int              load_mode)
11995 {
11996     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11997     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11998     struct elink_params *lp = &sc->link_params;
11999 
12000     bxe_set_requested_fc(sc);
12001 
12002     if (CHIP_REV_IS_SLOW(sc)) {
12003         uint32_t bond = CHIP_BOND_ID(sc);
12004         uint32_t feat = 0;
12005 
12006         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
12007             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12008         } else if (bond & 0x4) {
12009             if (CHIP_IS_E3(sc)) {
12010                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
12011             } else {
12012                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12013             }
12014         } else if (bond & 0x8) {
12015             if (CHIP_IS_E3(sc)) {
12016                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
12017             } else {
12018                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12019             }
12020         }
12021 
12022         /* disable EMAC for E3 and above */
12023         if (bond & 0x2) {
12024             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12025         }
12026 
12027         sc->link_params.feature_config_flags |= feat;
12028     }
12029 
12030     bxe_acquire_phy_lock(sc);
12031 
12032     if (load_mode == LOAD_DIAG) {
12033         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12034         /* Prefer doing PHY loopback at 10G speed, if possible */
12035         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12036             if (lp->speed_cap_mask[cfg_idx] &
12037                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12038                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12039             } else {
12040                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12041             }
12042         }
12043     }
12044 
12045     if (load_mode == LOAD_LOOPBACK_EXT) {
12046         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12047     }
12048 
12049     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12050 
12051     bxe_release_phy_lock(sc);
12052 
12053     bxe_calc_fc_adv(sc);
12054 
12055     if (sc->link_vars.link_up) {
12056         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12057         bxe_link_report(sc);
12058     }
12059 
12060     if (!CHIP_REV_IS_SLOW(sc)) {
12061         bxe_periodic_start(sc);
12062     }
12063 
12064     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12065     return (rc);
12066 }
12067 
12068 static u_int
12069 bxe_push_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
12070 {
12071     struct ecore_mcast_list_elem *mc_mac = arg;
12072 
12073     mc_mac += cnt;
12074     mc_mac->mac = (uint8_t *)LLADDR(sdl);
12075 
12076     return (1);
12077 }
12078 
12079 static int
12080 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12081                          struct ecore_mcast_ramrod_params *p)
12082 {
12083     if_t ifp = sc->ifp;
12084     int mc_count;
12085     struct ecore_mcast_list_elem *mc_mac;
12086 
12087     ECORE_LIST_INIT(&p->mcast_list);
12088     p->mcast_list_len = 0;
12089 
12090     /* XXXGL: multicast count may change later */
12091     mc_count = if_llmaddr_count(ifp);
12092 
12093     if (!mc_count) {
12094         return (0);
12095     }
12096 
12097     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12098                     (M_NOWAIT | M_ZERO));
12099     if (!mc_mac) {
12100         BLOGE(sc, "Failed to allocate temp mcast list\n");
12101         return (-1);
12102     }
12103     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12104     if_foreach_llmaddr(ifp, bxe_push_maddr, mc_mac);
12105 
12106     for (int i = 0; i < mc_count; i ++) {
12107         ECORE_LIST_PUSH_TAIL(&mc_mac[i].link, &p->mcast_list);
12108         BLOGD(sc, DBG_LOAD,
12109               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X and mc_count %d\n",
12110               mc_mac[i].mac[0], mc_mac[i].mac[1], mc_mac[i].mac[2],
12111               mc_mac[i].mac[3], mc_mac[i].mac[4], mc_mac[i].mac[5],
12112               mc_count);
12113     }
12114 
12115     p->mcast_list_len = mc_count;
12116 
12117     return (0);
12118 }
12119 
12120 static void
12121 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12122 {
12123     struct ecore_mcast_list_elem *mc_mac =
12124         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12125                                struct ecore_mcast_list_elem,
12126                                link);
12127 
12128     if (mc_mac) {
12129         /* only a single free as all mc_macs are in the same heap array */
12130         free(mc_mac, M_DEVBUF);
12131     }
12132 }
12133 static int
12134 bxe_set_mc_list(struct bxe_softc *sc)
12135 {
12136     struct ecore_mcast_ramrod_params rparam = { NULL };
12137     int rc = 0;
12138 
12139     rparam.mcast_obj = &sc->mcast_obj;
12140 
12141     BXE_MCAST_LOCK(sc);
12142 
12143     /* first, clear all configured multicast MACs */
12144     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12145     if (rc < 0) {
12146         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12147         /* Manual backport parts of FreeBSD upstream r284470. */
12148         BXE_MCAST_UNLOCK(sc);
12149         return (rc);
12150     }
12151 
12152     /* configure a new MACs list */
12153     rc = bxe_init_mcast_macs_list(sc, &rparam);
12154     if (rc) {
12155         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12156         BXE_MCAST_UNLOCK(sc);
12157         return (rc);
12158     }
12159 
12160     /* Now add the new MACs */
12161     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12162     if (rc < 0) {
12163         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12164     }
12165 
12166     bxe_free_mcast_macs_list(&rparam);
12167 
12168     BXE_MCAST_UNLOCK(sc);
12169 
12170     return (rc);
12171 }
12172 
12173 struct bxe_set_addr_ctx {
12174    struct bxe_softc *sc;
12175    unsigned long ramrod_flags;
12176    int rc;
12177 };
12178 
12179 static u_int
12180 bxe_set_addr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
12181 {
12182     struct bxe_set_addr_ctx *ctx = arg;
12183     struct ecore_vlan_mac_obj *mac_obj = &ctx->sc->sp_objs->mac_obj;
12184     int rc;
12185 
12186     if (ctx->rc < 0)
12187 	return (0);
12188 
12189     rc = bxe_set_mac_one(ctx->sc, (uint8_t *)LLADDR(sdl), mac_obj, TRUE,
12190                          ECORE_UC_LIST_MAC, &ctx->ramrod_flags);
12191 
12192     /* do not treat adding same MAC as an error */
12193     if (rc == -EEXIST)
12194 	BLOGD(ctx->sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12195     else if (rc < 0) {
12196             BLOGE(ctx->sc, "Failed to schedule ADD operations (%d)\n", rc);
12197             ctx->rc = rc;
12198     }
12199 
12200     return (1);
12201 }
12202 
12203 static int
12204 bxe_set_uc_list(struct bxe_softc *sc)
12205 {
12206     if_t ifp = sc->ifp;
12207     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12208     struct bxe_set_addr_ctx ctx = { sc, 0, 0 };
12209     int rc;
12210 
12211     /* first schedule a cleanup up of old configuration */
12212     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12213     if (rc < 0) {
12214         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12215         return (rc);
12216     }
12217 
12218     if_foreach_lladdr(ifp, bxe_set_addr, &ctx);
12219     if (ctx.rc < 0)
12220 	return (ctx.rc);
12221 
12222     /* Execute the pending commands */
12223     bit_set(&ctx.ramrod_flags, RAMROD_CONT);
12224     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12225                             ECORE_UC_LIST_MAC, &ctx.ramrod_flags));
12226 }
12227 
12228 static void
12229 bxe_set_rx_mode(struct bxe_softc *sc)
12230 {
12231     if_t ifp = sc->ifp;
12232     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12233 
12234     if (sc->state != BXE_STATE_OPEN) {
12235         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12236         return;
12237     }
12238 
12239     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12240 
12241     if (if_getflags(ifp) & IFF_PROMISC) {
12242         rx_mode = BXE_RX_MODE_PROMISC;
12243     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12244                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12245                 CHIP_IS_E1(sc))) {
12246         rx_mode = BXE_RX_MODE_ALLMULTI;
12247     } else {
12248         if (IS_PF(sc)) {
12249             /* some multicasts */
12250             if (bxe_set_mc_list(sc) < 0) {
12251                 rx_mode = BXE_RX_MODE_ALLMULTI;
12252             }
12253             if (bxe_set_uc_list(sc) < 0) {
12254                 rx_mode = BXE_RX_MODE_PROMISC;
12255             }
12256         }
12257     }
12258 
12259     sc->rx_mode = rx_mode;
12260 
12261     /* schedule the rx_mode command */
12262     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12263         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12264         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12265         return;
12266     }
12267 
12268     if (IS_PF(sc)) {
12269         bxe_set_storm_rx_mode(sc);
12270     }
12271 }
12272 
12273 
12274 /* update flags in shmem */
12275 static void
12276 bxe_update_drv_flags(struct bxe_softc *sc,
12277                      uint32_t         flags,
12278                      uint32_t         set)
12279 {
12280     uint32_t drv_flags;
12281 
12282     if (SHMEM2_HAS(sc, drv_flags)) {
12283         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12284         drv_flags = SHMEM2_RD(sc, drv_flags);
12285 
12286         if (set) {
12287             SET_FLAGS(drv_flags, flags);
12288         } else {
12289             RESET_FLAGS(drv_flags, flags);
12290         }
12291 
12292         SHMEM2_WR(sc, drv_flags, drv_flags);
12293         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12294 
12295         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12296     }
12297 }
12298 
12299 /* periodic timer callout routine, only runs when the interface is up */
12300 
12301 static void
12302 bxe_periodic_callout_func(void *xsc)
12303 {
12304     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12305     int i;
12306 
12307     if (!BXE_CORE_TRYLOCK(sc)) {
12308         /* just bail and try again next time */
12309 
12310         if ((sc->state == BXE_STATE_OPEN) &&
12311             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12312             /* schedule the next periodic callout */
12313             callout_reset(&sc->periodic_callout, hz,
12314                           bxe_periodic_callout_func, sc);
12315         }
12316 
12317         return;
12318     }
12319 
12320     if ((sc->state != BXE_STATE_OPEN) ||
12321         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12322         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12323         BXE_CORE_UNLOCK(sc);
12324         return;
12325         }
12326 
12327 
12328     /* Check for TX timeouts on any fastpath. */
12329     FOR_EACH_QUEUE(sc, i) {
12330         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12331             /* Ruh-Roh, chip was reset! */
12332             break;
12333         }
12334     }
12335 
12336     if (!CHIP_REV_IS_SLOW(sc)) {
12337         /*
12338          * This barrier is needed to ensure the ordering between the writing
12339          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12340          * the reading here.
12341          */
12342         mb();
12343         if (sc->port.pmf) {
12344 	    bxe_acquire_phy_lock(sc);
12345             elink_period_func(&sc->link_params, &sc->link_vars);
12346 	    bxe_release_phy_lock(sc);
12347         }
12348     }
12349 
12350     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12351         int mb_idx = SC_FW_MB_IDX(sc);
12352         uint32_t drv_pulse;
12353         uint32_t mcp_pulse;
12354 
12355         ++sc->fw_drv_pulse_wr_seq;
12356         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12357 
12358         drv_pulse = sc->fw_drv_pulse_wr_seq;
12359         bxe_drv_pulse(sc);
12360 
12361         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12362                      MCP_PULSE_SEQ_MASK);
12363 
12364         /*
12365          * The delta between driver pulse and mcp response should
12366          * be 1 (before mcp response) or 0 (after mcp response).
12367          */
12368         if ((drv_pulse != mcp_pulse) &&
12369             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12370             /* someone lost a heartbeat... */
12371             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12372                   drv_pulse, mcp_pulse);
12373         }
12374     }
12375 
12376     /* state is BXE_STATE_OPEN */
12377     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12378 
12379     BXE_CORE_UNLOCK(sc);
12380 
12381     if ((sc->state == BXE_STATE_OPEN) &&
12382         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12383         /* schedule the next periodic callout */
12384         callout_reset(&sc->periodic_callout, hz,
12385                       bxe_periodic_callout_func, sc);
12386     }
12387 }
12388 
12389 static void
12390 bxe_periodic_start(struct bxe_softc *sc)
12391 {
12392     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12393     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12394 }
12395 
12396 static void
12397 bxe_periodic_stop(struct bxe_softc *sc)
12398 {
12399     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12400     callout_drain(&sc->periodic_callout);
12401 }
12402 
12403 void
12404 bxe_parity_recover(struct bxe_softc *sc)
12405 {
12406     uint8_t global = FALSE;
12407     uint32_t error_recovered, error_unrecovered;
12408     bool is_parity;
12409 
12410 
12411     if ((sc->recovery_state == BXE_RECOVERY_FAILED) &&
12412         (sc->state == BXE_STATE_ERROR)) {
12413         BLOGE(sc, "RECOVERY failed, "
12414             "stack notified driver is NOT running! "
12415             "Please reboot/power cycle the system.\n");
12416         return;
12417     }
12418 
12419     while (1) {
12420         BLOGD(sc, DBG_SP,
12421            "%s sc=%p state=0x%x rec_state=0x%x error_status=%x\n",
12422             __func__, sc, sc->state, sc->recovery_state, sc->error_status);
12423 
12424         switch(sc->recovery_state) {
12425 
12426         case BXE_RECOVERY_INIT:
12427             is_parity = bxe_chk_parity_attn(sc, &global, FALSE);
12428 
12429             if ((CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ||
12430                 (sc->error_status & BXE_ERR_MCP_ASSERT) ||
12431                 (sc->error_status & BXE_ERR_GLOBAL)) {
12432 
12433                 BXE_CORE_LOCK(sc);
12434                 if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12435                     bxe_periodic_stop(sc);
12436                 }
12437                 bxe_nic_unload(sc, UNLOAD_RECOVERY, false);
12438                 sc->state = BXE_STATE_ERROR;
12439                 sc->recovery_state = BXE_RECOVERY_FAILED;
12440                 BLOGE(sc, " No Recovery tried for error 0x%x"
12441                     " stack notified driver is NOT running!"
12442                     " Please reboot/power cycle the system.\n",
12443                     sc->error_status);
12444                 BXE_CORE_UNLOCK(sc);
12445                 return;
12446             }
12447 
12448 
12449            /* Try to get a LEADER_LOCK HW lock */
12450             if (bxe_trylock_leader_lock(sc)) {
12451 
12452                 bxe_set_reset_in_progress(sc);
12453                 /*
12454                  * Check if there is a global attention and if
12455                  * there was a global attention, set the global
12456                  * reset bit.
12457                  */
12458                 if (global) {
12459                     bxe_set_reset_global(sc);
12460                 }
12461                 sc->is_leader = 1;
12462             }
12463 
12464             /* If interface has been removed - break */
12465 
12466             if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12467                 bxe_periodic_stop(sc);
12468             }
12469 
12470             BXE_CORE_LOCK(sc);
12471             bxe_nic_unload(sc,UNLOAD_RECOVERY, false);
12472             sc->recovery_state = BXE_RECOVERY_WAIT;
12473             BXE_CORE_UNLOCK(sc);
12474 
12475             /*
12476              * Ensure "is_leader", MCP command sequence and
12477              * "recovery_state" update values are seen on other
12478              * CPUs.
12479              */
12480             mb();
12481             break;
12482         case BXE_RECOVERY_WAIT:
12483 
12484             if (sc->is_leader) {
12485                 int other_engine = SC_PATH(sc) ? 0 : 1;
12486                 bool other_load_status =
12487                     bxe_get_load_status(sc, other_engine);
12488                 bool load_status =
12489                     bxe_get_load_status(sc, SC_PATH(sc));
12490                 global = bxe_reset_is_global(sc);
12491 
12492                 /*
12493                  * In case of a parity in a global block, let
12494                  * the first leader that performs a
12495                  * leader_reset() reset the global blocks in
12496                  * order to clear global attentions. Otherwise
12497                  * the gates will remain closed for that
12498                  * engine.
12499                  */
12500                 if (load_status ||
12501                     (global && other_load_status)) {
12502                     /*
12503                      * Wait until all other functions get
12504                      * down.
12505                      */
12506                     taskqueue_enqueue_timeout(taskqueue_thread,
12507                         &sc->sp_err_timeout_task, hz/10);
12508                     return;
12509                 } else {
12510                     /*
12511                      * If all other functions got down
12512                      * try to bring the chip back to
12513                      * normal. In any case it's an exit
12514                      * point for a leader.
12515                      */
12516                     if (bxe_leader_reset(sc)) {
12517                         BLOGE(sc, "RECOVERY failed, "
12518                             "stack notified driver is NOT running!\n");
12519                         sc->recovery_state = BXE_RECOVERY_FAILED;
12520                         sc->state = BXE_STATE_ERROR;
12521                         mb();
12522                         return;
12523                     }
12524 
12525                     /*
12526                      * If we are here, means that the
12527                      * leader has succeeded and doesn't
12528                      * want to be a leader any more. Try
12529                      * to continue as a none-leader.
12530                      */
12531                 break;
12532                 }
12533 
12534             } else { /* non-leader */
12535                 if (!bxe_reset_is_done(sc, SC_PATH(sc))) {
12536                     /*
12537                      * Try to get a LEADER_LOCK HW lock as
12538                      * long as a former leader may have
12539                      * been unloaded by the user or
12540                      * released a leadership by another
12541                      * reason.
12542                      */
12543                     if (bxe_trylock_leader_lock(sc)) {
12544                         /*
12545                          * I'm a leader now! Restart a
12546                          * switch case.
12547                          */
12548                         sc->is_leader = 1;
12549                         break;
12550                     }
12551 
12552                     taskqueue_enqueue_timeout(taskqueue_thread,
12553                         &sc->sp_err_timeout_task, hz/10);
12554                     return;
12555 
12556                 } else {
12557                     /*
12558                      * If there was a global attention, wait
12559                      * for it to be cleared.
12560                      */
12561                     if (bxe_reset_is_global(sc)) {
12562                         taskqueue_enqueue_timeout(taskqueue_thread,
12563                             &sc->sp_err_timeout_task, hz/10);
12564                         return;
12565                      }
12566 
12567                      error_recovered =
12568                          sc->eth_stats.recoverable_error;
12569                      error_unrecovered =
12570                          sc->eth_stats.unrecoverable_error;
12571                      BXE_CORE_LOCK(sc);
12572                      sc->recovery_state =
12573                          BXE_RECOVERY_NIC_LOADING;
12574                      if (bxe_nic_load(sc, LOAD_NORMAL)) {
12575                          error_unrecovered++;
12576                          sc->recovery_state = BXE_RECOVERY_FAILED;
12577                          sc->state = BXE_STATE_ERROR;
12578                          BLOGE(sc, "Recovery is NOT successfull, "
12579                             " state=0x%x recovery_state=0x%x error=%x\n",
12580                             sc->state, sc->recovery_state, sc->error_status);
12581                          sc->error_status = 0;
12582                      } else {
12583                          sc->recovery_state =
12584                              BXE_RECOVERY_DONE;
12585                          error_recovered++;
12586                          BLOGI(sc, "Recovery is successfull from errors %x,"
12587                             " state=0x%x"
12588                             " recovery_state=0x%x \n", sc->error_status,
12589                             sc->state, sc->recovery_state);
12590                          mb();
12591                      }
12592                      sc->error_status = 0;
12593                      BXE_CORE_UNLOCK(sc);
12594                      sc->eth_stats.recoverable_error =
12595                          error_recovered;
12596                      sc->eth_stats.unrecoverable_error =
12597                          error_unrecovered;
12598 
12599                      return;
12600                  }
12601              }
12602          default:
12603              return;
12604          }
12605     }
12606 }
12607 void
12608 bxe_handle_error(struct bxe_softc * sc)
12609 {
12610 
12611     if(sc->recovery_state == BXE_RECOVERY_WAIT) {
12612         return;
12613     }
12614     if(sc->error_status) {
12615         if (sc->state == BXE_STATE_OPEN)  {
12616             bxe_int_disable(sc);
12617         }
12618         if (sc->link_vars.link_up) {
12619             if_link_state_change(sc->ifp, LINK_STATE_DOWN);
12620         }
12621         sc->recovery_state = BXE_RECOVERY_INIT;
12622         BLOGI(sc, "bxe%d: Recovery started errors 0x%x recovery state 0x%x\n",
12623             sc->unit, sc->error_status, sc->recovery_state);
12624         bxe_parity_recover(sc);
12625    }
12626 }
12627 
12628 static void
12629 bxe_sp_err_timeout_task(void *arg, int pending)
12630 {
12631 
12632     struct bxe_softc *sc = (struct bxe_softc *)arg;
12633 
12634     BLOGD(sc, DBG_SP,
12635         "%s state = 0x%x rec state=0x%x error_status=%x\n",
12636         __func__, sc->state, sc->recovery_state, sc->error_status);
12637 
12638     if((sc->recovery_state == BXE_RECOVERY_FAILED) &&
12639        (sc->state == BXE_STATE_ERROR)) {
12640         return;
12641     }
12642     /* if can be taken */
12643     if ((sc->error_status) && (sc->trigger_grcdump)) {
12644         bxe_grc_dump(sc);
12645     }
12646     if (sc->recovery_state != BXE_RECOVERY_DONE) {
12647         bxe_handle_error(sc);
12648         bxe_parity_recover(sc);
12649     } else if (sc->error_status) {
12650         bxe_handle_error(sc);
12651     }
12652 
12653     return;
12654 }
12655 
12656 /* start the controller */
12657 static __noinline int
12658 bxe_nic_load(struct bxe_softc *sc,
12659              int              load_mode)
12660 {
12661     uint32_t val;
12662     int load_code = 0;
12663     int i, rc = 0;
12664 
12665     BXE_CORE_LOCK_ASSERT(sc);
12666 
12667     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12668 
12669     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12670 
12671     if (IS_PF(sc)) {
12672         /* must be called before memory allocation and HW init */
12673         bxe_ilt_set_info(sc);
12674     }
12675 
12676     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12677 
12678     bxe_set_fp_rx_buf_size(sc);
12679 
12680     if (bxe_alloc_fp_buffers(sc) != 0) {
12681         BLOGE(sc, "Failed to allocate fastpath memory\n");
12682         sc->state = BXE_STATE_CLOSED;
12683         rc = ENOMEM;
12684         goto bxe_nic_load_error0;
12685     }
12686 
12687     if (bxe_alloc_mem(sc) != 0) {
12688         sc->state = BXE_STATE_CLOSED;
12689         rc = ENOMEM;
12690         goto bxe_nic_load_error0;
12691     }
12692 
12693     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12694         sc->state = BXE_STATE_CLOSED;
12695         rc = ENOMEM;
12696         goto bxe_nic_load_error0;
12697     }
12698 
12699     if (IS_PF(sc)) {
12700         /* set pf load just before approaching the MCP */
12701         bxe_set_pf_load(sc);
12702 
12703         /* if MCP exists send load request and analyze response */
12704         if (!BXE_NOMCP(sc)) {
12705             /* attempt to load pf */
12706             if (bxe_nic_load_request(sc, &load_code) != 0) {
12707                 sc->state = BXE_STATE_CLOSED;
12708                 rc = ENXIO;
12709                 goto bxe_nic_load_error1;
12710             }
12711 
12712             /* what did the MCP say? */
12713             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12714                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12715                 sc->state = BXE_STATE_CLOSED;
12716                 rc = ENXIO;
12717                 goto bxe_nic_load_error2;
12718             }
12719         } else {
12720             BLOGI(sc, "Device has no MCP!\n");
12721             load_code = bxe_nic_load_no_mcp(sc);
12722         }
12723 
12724         /* mark PMF if applicable */
12725         bxe_nic_load_pmf(sc, load_code);
12726 
12727         /* Init Function state controlling object */
12728         bxe_init_func_obj(sc);
12729 
12730         /* Initialize HW */
12731         if (bxe_init_hw(sc, load_code) != 0) {
12732             BLOGE(sc, "HW init failed\n");
12733             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12734             sc->state = BXE_STATE_CLOSED;
12735             rc = ENXIO;
12736             goto bxe_nic_load_error2;
12737         }
12738     }
12739 
12740     /* set ALWAYS_ALIVE bit in shmem */
12741     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12742     bxe_drv_pulse(sc);
12743     sc->flags |= BXE_NO_PULSE;
12744 
12745     /* attach interrupts */
12746     if (bxe_interrupt_attach(sc) != 0) {
12747         sc->state = BXE_STATE_CLOSED;
12748         rc = ENXIO;
12749         goto bxe_nic_load_error2;
12750     }
12751 
12752     bxe_nic_init(sc, load_code);
12753 
12754     /* Init per-function objects */
12755     if (IS_PF(sc)) {
12756         bxe_init_objs(sc);
12757         // XXX bxe_iov_nic_init(sc);
12758 
12759         /* set AFEX default VLAN tag to an invalid value */
12760         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12761         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12762 
12763         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12764         rc = bxe_func_start(sc);
12765         if (rc) {
12766             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12767             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12768             sc->state = BXE_STATE_ERROR;
12769             goto bxe_nic_load_error3;
12770         }
12771 
12772         /* send LOAD_DONE command to MCP */
12773         if (!BXE_NOMCP(sc)) {
12774             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12775             if (!load_code) {
12776                 BLOGE(sc, "MCP response failure, aborting\n");
12777                 sc->state = BXE_STATE_ERROR;
12778                 rc = ENXIO;
12779                 goto bxe_nic_load_error3;
12780             }
12781         }
12782 
12783         rc = bxe_setup_leading(sc);
12784         if (rc) {
12785             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12786             sc->state = BXE_STATE_ERROR;
12787             goto bxe_nic_load_error3;
12788         }
12789 
12790         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12791             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12792             if (rc) {
12793                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12794                 sc->state = BXE_STATE_ERROR;
12795                 goto bxe_nic_load_error3;
12796             }
12797         }
12798 
12799         rc = bxe_init_rss_pf(sc);
12800         if (rc) {
12801             BLOGE(sc, "PF RSS init failed\n");
12802             sc->state = BXE_STATE_ERROR;
12803             goto bxe_nic_load_error3;
12804         }
12805     }
12806     /* XXX VF */
12807 
12808     /* now when Clients are configured we are ready to work */
12809     sc->state = BXE_STATE_OPEN;
12810 
12811     /* Configure a ucast MAC */
12812     if (IS_PF(sc)) {
12813         rc = bxe_set_eth_mac(sc, TRUE);
12814     }
12815     if (rc) {
12816         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12817         sc->state = BXE_STATE_ERROR;
12818         goto bxe_nic_load_error3;
12819     }
12820 
12821     if (sc->port.pmf) {
12822         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12823         if (rc) {
12824             sc->state = BXE_STATE_ERROR;
12825             goto bxe_nic_load_error3;
12826         }
12827     }
12828 
12829     sc->link_params.feature_config_flags &=
12830         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12831 
12832     /* start fast path */
12833 
12834     /* Initialize Rx filter */
12835     bxe_set_rx_mode(sc);
12836 
12837     /* start the Tx */
12838     switch (/* XXX load_mode */LOAD_OPEN) {
12839     case LOAD_NORMAL:
12840     case LOAD_OPEN:
12841         break;
12842 
12843     case LOAD_DIAG:
12844     case LOAD_LOOPBACK_EXT:
12845         sc->state = BXE_STATE_DIAG;
12846         break;
12847 
12848     default:
12849         break;
12850     }
12851 
12852     if (sc->port.pmf) {
12853         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12854     } else {
12855         bxe_link_status_update(sc);
12856     }
12857 
12858     /* start the periodic timer callout */
12859     bxe_periodic_start(sc);
12860 
12861     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12862         /* mark driver is loaded in shmem2 */
12863         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12864         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12865                   (val |
12866                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12867                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12868     }
12869 
12870     /* wait for all pending SP commands to complete */
12871     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12872         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12873         bxe_periodic_stop(sc);
12874         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12875         return (ENXIO);
12876     }
12877 
12878     /* Tell the stack the driver is running! */
12879     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12880 
12881     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12882 
12883     return (0);
12884 
12885 bxe_nic_load_error3:
12886 
12887     if (IS_PF(sc)) {
12888         bxe_int_disable_sync(sc, 1);
12889 
12890         /* clean out queued objects */
12891         bxe_squeeze_objects(sc);
12892     }
12893 
12894     bxe_interrupt_detach(sc);
12895 
12896 bxe_nic_load_error2:
12897 
12898     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12899         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12900         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12901     }
12902 
12903     sc->port.pmf = 0;
12904 
12905 bxe_nic_load_error1:
12906 
12907     /* clear pf_load status, as it was already set */
12908     if (IS_PF(sc)) {
12909         bxe_clear_pf_load(sc);
12910     }
12911 
12912 bxe_nic_load_error0:
12913 
12914     bxe_free_fw_stats_mem(sc);
12915     bxe_free_fp_buffers(sc);
12916     bxe_free_mem(sc);
12917 
12918     return (rc);
12919 }
12920 
12921 static int
12922 bxe_init_locked(struct bxe_softc *sc)
12923 {
12924     int other_engine = SC_PATH(sc) ? 0 : 1;
12925     uint8_t other_load_status, load_status;
12926     uint8_t global = FALSE;
12927     int rc;
12928 
12929     BXE_CORE_LOCK_ASSERT(sc);
12930 
12931     /* check if the driver is already running */
12932     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12933         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12934         return (0);
12935     }
12936 
12937     if((sc->state == BXE_STATE_ERROR) &&
12938         (sc->recovery_state == BXE_RECOVERY_FAILED)) {
12939         BLOGE(sc, "Initialization not done, "
12940                   "as previous recovery failed."
12941                   "Reboot/Power-cycle the system\n" );
12942         return (ENXIO);
12943     }
12944 
12945 
12946     bxe_set_power_state(sc, PCI_PM_D0);
12947 
12948     /*
12949      * If parity occurred during the unload, then attentions and/or
12950      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12951      * loaded on the current engine to complete the recovery. Parity recovery
12952      * is only relevant for PF driver.
12953      */
12954     if (IS_PF(sc)) {
12955         other_load_status = bxe_get_load_status(sc, other_engine);
12956         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12957 
12958         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12959             bxe_chk_parity_attn(sc, &global, TRUE)) {
12960             do {
12961                 /*
12962                  * If there are attentions and they are in global blocks, set
12963                  * the GLOBAL_RESET bit regardless whether it will be this
12964                  * function that will complete the recovery or not.
12965                  */
12966                 if (global) {
12967                     bxe_set_reset_global(sc);
12968                 }
12969 
12970                 /*
12971                  * Only the first function on the current engine should try
12972                  * to recover in open. In case of attentions in global blocks
12973                  * only the first in the chip should try to recover.
12974                  */
12975                 if ((!load_status && (!global || !other_load_status)) &&
12976                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12977                     BLOGI(sc, "Recovered during init\n");
12978                     break;
12979                 }
12980 
12981                 /* recovery has failed... */
12982                 bxe_set_power_state(sc, PCI_PM_D3hot);
12983                 sc->recovery_state = BXE_RECOVERY_FAILED;
12984 
12985                 BLOGE(sc, "Recovery flow hasn't properly "
12986                           "completed yet, try again later. "
12987                           "If you still see this message after a "
12988                           "few retries then power cycle is required.\n");
12989 
12990                 rc = ENXIO;
12991                 goto bxe_init_locked_done;
12992             } while (0);
12993         }
12994     }
12995 
12996     sc->recovery_state = BXE_RECOVERY_DONE;
12997 
12998     rc = bxe_nic_load(sc, LOAD_OPEN);
12999 
13000 bxe_init_locked_done:
13001 
13002     if (rc) {
13003         /* Tell the stack the driver is NOT running! */
13004         BLOGE(sc, "Initialization failed, "
13005                   "stack notified driver is NOT running!\n");
13006 	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
13007     }
13008 
13009     return (rc);
13010 }
13011 
13012 static int
13013 bxe_stop_locked(struct bxe_softc *sc)
13014 {
13015     BXE_CORE_LOCK_ASSERT(sc);
13016     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
13017 }
13018 
13019 /*
13020  * Handles controller initialization when called from an unlocked routine.
13021  * ifconfig calls this function.
13022  *
13023  * Returns:
13024  *   void
13025  */
13026 static void
13027 bxe_init(void *xsc)
13028 {
13029     struct bxe_softc *sc = (struct bxe_softc *)xsc;
13030 
13031     BXE_CORE_LOCK(sc);
13032     bxe_init_locked(sc);
13033     BXE_CORE_UNLOCK(sc);
13034 }
13035 
13036 static int
13037 bxe_init_ifnet(struct bxe_softc *sc)
13038 {
13039     if_t ifp;
13040     int capabilities;
13041 
13042     /* ifconfig entrypoint for media type/status reporting */
13043     ifmedia_init(&sc->ifmedia, IFM_IMASK,
13044                  bxe_ifmedia_update,
13045                  bxe_ifmedia_status);
13046 
13047     /* set the default interface values */
13048     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
13049     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
13050     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
13051 
13052     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
13053 	BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
13054 
13055     /* allocate the ifnet structure */
13056     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
13057         BLOGE(sc, "Interface allocation failed!\n");
13058         return (ENXIO);
13059     }
13060 
13061     if_setsoftc(ifp, sc);
13062     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
13063     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
13064     if_setioctlfn(ifp, bxe_ioctl);
13065     if_setstartfn(ifp, bxe_tx_start);
13066     if_setgetcounterfn(ifp, bxe_get_counter);
13067 #if __FreeBSD_version >= 901504
13068     if_settransmitfn(ifp, bxe_tx_mq_start);
13069     if_setqflushfn(ifp, bxe_mq_flush);
13070 #endif
13071 #ifdef FreeBSD8_0
13072     if_settimer(ifp, 0);
13073 #endif
13074     if_setinitfn(ifp, bxe_init);
13075     if_setmtu(ifp, sc->mtu);
13076     if_sethwassist(ifp, (CSUM_IP      |
13077                         CSUM_TCP      |
13078                         CSUM_UDP      |
13079                         CSUM_TSO      |
13080                         CSUM_TCP_IPV6 |
13081                         CSUM_UDP_IPV6));
13082 
13083     capabilities =
13084 #if __FreeBSD_version < 700000
13085         (IFCAP_VLAN_MTU       |
13086          IFCAP_VLAN_HWTAGGING |
13087          IFCAP_HWCSUM         |
13088          IFCAP_JUMBO_MTU      |
13089          IFCAP_LRO);
13090 #else
13091         (IFCAP_VLAN_MTU       |
13092          IFCAP_VLAN_HWTAGGING |
13093          IFCAP_VLAN_HWTSO     |
13094          IFCAP_VLAN_HWFILTER  |
13095          IFCAP_VLAN_HWCSUM    |
13096          IFCAP_HWCSUM         |
13097          IFCAP_JUMBO_MTU      |
13098          IFCAP_LRO            |
13099          IFCAP_TSO4           |
13100          IFCAP_TSO6           |
13101          IFCAP_WOL_MAGIC);
13102 #endif
13103     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
13104     if_setcapenable(ifp, if_getcapabilities(ifp));
13105     if_setbaudrate(ifp, IF_Gbps(10));
13106 /* XXX */
13107     if_setsendqlen(ifp, sc->tx_ring_size);
13108     if_setsendqready(ifp);
13109 /* XXX */
13110 
13111     sc->ifp = ifp;
13112 
13113     /* attach to the Ethernet interface list */
13114     ether_ifattach(ifp, sc->link_params.mac_addr);
13115 
13116     /* Attach driver debugnet methods. */
13117     DEBUGNET_SET(ifp, bxe);
13118 
13119     return (0);
13120 }
13121 
13122 static void
13123 bxe_deallocate_bars(struct bxe_softc *sc)
13124 {
13125     int i;
13126 
13127     for (i = 0; i < MAX_BARS; i++) {
13128         if (sc->bar[i].resource != NULL) {
13129             bus_release_resource(sc->dev,
13130                                  SYS_RES_MEMORY,
13131                                  sc->bar[i].rid,
13132                                  sc->bar[i].resource);
13133             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
13134                   i, PCIR_BAR(i));
13135         }
13136     }
13137 }
13138 
13139 static int
13140 bxe_allocate_bars(struct bxe_softc *sc)
13141 {
13142     u_int flags;
13143     int i;
13144 
13145     memset(sc->bar, 0, sizeof(sc->bar));
13146 
13147     for (i = 0; i < MAX_BARS; i++) {
13148 
13149         /* memory resources reside at BARs 0, 2, 4 */
13150         /* Run `pciconf -lb` to see mappings */
13151         if ((i != 0) && (i != 2) && (i != 4)) {
13152             continue;
13153         }
13154 
13155         sc->bar[i].rid = PCIR_BAR(i);
13156 
13157         flags = RF_ACTIVE;
13158         if (i == 0) {
13159             flags |= RF_SHAREABLE;
13160         }
13161 
13162         if ((sc->bar[i].resource =
13163              bus_alloc_resource_any(sc->dev,
13164                                     SYS_RES_MEMORY,
13165                                     &sc->bar[i].rid,
13166                                     flags)) == NULL) {
13167             return (0);
13168         }
13169 
13170         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
13171         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
13172         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
13173 
13174         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %#jx-%#jx (%jd) -> %#jx\n",
13175               i, PCIR_BAR(i),
13176               rman_get_start(sc->bar[i].resource),
13177               rman_get_end(sc->bar[i].resource),
13178               rman_get_size(sc->bar[i].resource),
13179               (uintmax_t)sc->bar[i].kva);
13180     }
13181 
13182     return (0);
13183 }
13184 
13185 static void
13186 bxe_get_function_num(struct bxe_softc *sc)
13187 {
13188     uint32_t val = 0;
13189 
13190     /*
13191      * Read the ME register to get the function number. The ME register
13192      * holds the relative-function number and absolute-function number. The
13193      * absolute-function number appears only in E2 and above. Before that
13194      * these bits always contained zero, therefore we cannot blindly use them.
13195      */
13196 
13197     val = REG_RD(sc, BAR_ME_REGISTER);
13198 
13199     sc->pfunc_rel =
13200         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
13201     sc->path_id =
13202         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
13203 
13204     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13205         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
13206     } else {
13207         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
13208     }
13209 
13210     BLOGD(sc, DBG_LOAD,
13211           "Relative function %d, Absolute function %d, Path %d\n",
13212           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
13213 }
13214 
13215 static uint32_t
13216 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
13217 {
13218     uint32_t shmem2_size;
13219     uint32_t offset;
13220     uint32_t mf_cfg_offset_value;
13221 
13222     /* Non 57712 */
13223     offset = (SHMEM_RD(sc, func_mb) +
13224               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
13225 
13226     /* 57712 plus */
13227     if (sc->devinfo.shmem2_base != 0) {
13228         shmem2_size = SHMEM2_RD(sc, size);
13229         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
13230             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
13231             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
13232                 offset = mf_cfg_offset_value;
13233             }
13234         }
13235     }
13236 
13237     return (offset);
13238 }
13239 
13240 static uint32_t
13241 bxe_pcie_capability_read(struct bxe_softc *sc,
13242                          int    reg,
13243                          int    width)
13244 {
13245     int pcie_reg;
13246 
13247     /* ensure PCIe capability is enabled */
13248     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
13249         if (pcie_reg != 0) {
13250             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
13251             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
13252         }
13253     }
13254 
13255     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
13256 
13257     return (0);
13258 }
13259 
13260 static uint8_t
13261 bxe_is_pcie_pending(struct bxe_softc *sc)
13262 {
13263     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
13264             PCIM_EXP_STA_TRANSACTION_PND);
13265 }
13266 
13267 /*
13268  * Walk the PCI capabiites list for the device to find what features are
13269  * supported. These capabilites may be enabled/disabled by firmware so it's
13270  * best to walk the list rather than make assumptions.
13271  */
13272 static void
13273 bxe_probe_pci_caps(struct bxe_softc *sc)
13274 {
13275     uint16_t link_status;
13276     int reg;
13277 
13278     /* check if PCI Power Management is enabled */
13279     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13280         if (reg != 0) {
13281             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13282 
13283             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13284             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13285         }
13286     }
13287 
13288     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13289 
13290     /* handle PCIe 2.0 workarounds for 57710 */
13291     if (CHIP_IS_E1(sc)) {
13292         /* workaround for 57710 errata E4_57710_27462 */
13293         sc->devinfo.pcie_link_speed =
13294             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13295 
13296         /* workaround for 57710 errata E4_57710_27488 */
13297         sc->devinfo.pcie_link_width =
13298             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13299         if (sc->devinfo.pcie_link_speed > 1) {
13300             sc->devinfo.pcie_link_width =
13301                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13302         }
13303     } else {
13304         sc->devinfo.pcie_link_speed =
13305             (link_status & PCIM_LINK_STA_SPEED);
13306         sc->devinfo.pcie_link_width =
13307             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13308     }
13309 
13310     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13311           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13312 
13313     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13314     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13315 
13316     /* check if MSI capability is enabled */
13317     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13318         if (reg != 0) {
13319             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13320 
13321             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13322             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13323         }
13324     }
13325 
13326     /* check if MSI-X capability is enabled */
13327     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13328         if (reg != 0) {
13329             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13330 
13331             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13332             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13333         }
13334     }
13335 }
13336 
13337 static int
13338 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13339 {
13340     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13341     uint32_t val;
13342 
13343     /* get the outer vlan if we're in switch-dependent mode */
13344 
13345     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13346     mf_info->ext_id = (uint16_t)val;
13347 
13348     mf_info->multi_vnics_mode = 1;
13349 
13350     if (!VALID_OVLAN(mf_info->ext_id)) {
13351         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13352         return (1);
13353     }
13354 
13355     /* get the capabilities */
13356     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13357         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13358         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13359     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13360                FUNC_MF_CFG_PROTOCOL_FCOE) {
13361         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13362     } else {
13363         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13364     }
13365 
13366     mf_info->vnics_per_port =
13367         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13368 
13369     return (0);
13370 }
13371 
13372 static uint32_t
13373 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13374 {
13375     uint32_t retval = 0;
13376     uint32_t val;
13377 
13378     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13379 
13380     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13381         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13382             retval |= MF_PROTO_SUPPORT_ETHERNET;
13383         }
13384         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13385             retval |= MF_PROTO_SUPPORT_ISCSI;
13386         }
13387         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13388             retval |= MF_PROTO_SUPPORT_FCOE;
13389         }
13390     }
13391 
13392     return (retval);
13393 }
13394 
13395 static int
13396 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13397 {
13398     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13399     uint32_t val;
13400 
13401     /*
13402      * There is no outer vlan if we're in switch-independent mode.
13403      * If the mac is valid then assume multi-function.
13404      */
13405 
13406     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13407 
13408     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13409 
13410     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13411 
13412     mf_info->vnics_per_port =
13413         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13414 
13415     return (0);
13416 }
13417 
13418 static int
13419 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13420 {
13421     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13422     uint32_t e1hov_tag;
13423     uint32_t func_config;
13424     uint32_t niv_config;
13425 
13426     mf_info->multi_vnics_mode = 1;
13427 
13428     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13429     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13430     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13431 
13432     mf_info->ext_id =
13433         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13434                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13435 
13436     mf_info->default_vlan =
13437         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13438                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13439 
13440     mf_info->niv_allowed_priorities =
13441         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13442                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13443 
13444     mf_info->niv_default_cos =
13445         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13446                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13447 
13448     mf_info->afex_vlan_mode =
13449         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13450          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13451 
13452     mf_info->niv_mba_enabled =
13453         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13454          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13455 
13456     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13457 
13458     mf_info->vnics_per_port =
13459         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13460 
13461     return (0);
13462 }
13463 
13464 static int
13465 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13466 {
13467     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13468     uint32_t mf_cfg1;
13469     uint32_t mf_cfg2;
13470     uint32_t ovlan1;
13471     uint32_t ovlan2;
13472     uint8_t i, j;
13473 
13474     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13475           SC_PORT(sc));
13476     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13477           mf_info->mf_config[SC_VN(sc)]);
13478     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13479           mf_info->multi_vnics_mode);
13480     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13481           mf_info->vnics_per_port);
13482     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13483           mf_info->ext_id);
13484     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13485           mf_info->min_bw[0], mf_info->min_bw[1],
13486           mf_info->min_bw[2], mf_info->min_bw[3]);
13487     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13488           mf_info->max_bw[0], mf_info->max_bw[1],
13489           mf_info->max_bw[2], mf_info->max_bw[3]);
13490     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13491           sc->mac_addr_str);
13492 
13493     /* various MF mode sanity checks... */
13494 
13495     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13496         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13497               SC_PORT(sc));
13498         return (1);
13499     }
13500 
13501     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13502         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13503               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13504         return (1);
13505     }
13506 
13507     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13508         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13509         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13510             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13511                   SC_VN(sc), OVLAN(sc));
13512             return (1);
13513         }
13514 
13515         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13516             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13517                   mf_info->multi_vnics_mode, OVLAN(sc));
13518             return (1);
13519         }
13520 
13521         /*
13522          * Verify all functions are either MF or SF mode. If MF, make sure
13523          * sure that all non-hidden functions have a valid ovlan. If SF,
13524          * make sure that all non-hidden functions have an invalid ovlan.
13525          */
13526         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13527             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13528             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13529             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13530                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13531                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13532                 BLOGE(sc, "mf_mode=SD function %d MF config "
13533                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13534                       i, mf_info->multi_vnics_mode, ovlan1);
13535                 return (1);
13536             }
13537         }
13538 
13539         /* Verify all funcs on the same port each have a different ovlan. */
13540         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13541             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13542             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13543             /* iterate from the next function on the port to the max func */
13544             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13545                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13546                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13547                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13548                     VALID_OVLAN(ovlan1) &&
13549                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13550                     VALID_OVLAN(ovlan2) &&
13551                     (ovlan1 == ovlan2)) {
13552                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13553                               "have the same ovlan (%d)\n",
13554                           i, j, ovlan1);
13555                     return (1);
13556                 }
13557             }
13558         }
13559     } /* MULTI_FUNCTION_SD */
13560 
13561     return (0);
13562 }
13563 
13564 static int
13565 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13566 {
13567     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13568     uint32_t val, mac_upper;
13569     uint8_t i, vnic;
13570 
13571     /* initialize mf_info defaults */
13572     mf_info->vnics_per_port   = 1;
13573     mf_info->multi_vnics_mode = FALSE;
13574     mf_info->path_has_ovlan   = FALSE;
13575     mf_info->mf_mode          = SINGLE_FUNCTION;
13576 
13577     if (!CHIP_IS_MF_CAP(sc)) {
13578         return (0);
13579     }
13580 
13581     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13582         BLOGE(sc, "Invalid mf_cfg_base!\n");
13583         return (1);
13584     }
13585 
13586     /* get the MF mode (switch dependent / independent / single-function) */
13587 
13588     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13589 
13590     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13591     {
13592     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13593 
13594         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13595 
13596         /* check for legal upper mac bytes */
13597         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13598             mf_info->mf_mode = MULTI_FUNCTION_SI;
13599         } else {
13600             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13601         }
13602 
13603         break;
13604 
13605     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13606     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13607 
13608         /* get outer vlan configuration */
13609         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13610 
13611         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13612             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13613             mf_info->mf_mode = MULTI_FUNCTION_SD;
13614         } else {
13615             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13616         }
13617 
13618         break;
13619 
13620     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13621 
13622         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13623         return (0);
13624 
13625     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13626 
13627         /*
13628          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13629          * and the MAC address is valid.
13630          */
13631         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13632 
13633         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13634             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13635             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13636         } else {
13637             BLOGE(sc, "Invalid config for AFEX mode\n");
13638         }
13639 
13640         break;
13641 
13642     default:
13643 
13644         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13645               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13646 
13647         return (1);
13648     }
13649 
13650     /* set path mf_mode (which could be different than function mf_mode) */
13651     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13652         mf_info->path_has_ovlan = TRUE;
13653     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13654         /*
13655          * Decide on path multi vnics mode. If we're not in MF mode and in
13656          * 4-port mode, this is good enough to check vnic-0 of the other port
13657          * on the same path
13658          */
13659         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13660             uint8_t other_port = !(PORT_ID(sc) & 1);
13661             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13662 
13663             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13664 
13665             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13666         }
13667     }
13668 
13669     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13670         /* invalid MF config */
13671         if (SC_VN(sc) >= 1) {
13672             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13673             return (1);
13674         }
13675 
13676         return (0);
13677     }
13678 
13679     /* get the MF configuration */
13680     mf_info->mf_config[SC_VN(sc)] =
13681         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13682 
13683     switch(mf_info->mf_mode)
13684     {
13685     case MULTI_FUNCTION_SD:
13686 
13687         bxe_get_shmem_mf_cfg_info_sd(sc);
13688         break;
13689 
13690     case MULTI_FUNCTION_SI:
13691 
13692         bxe_get_shmem_mf_cfg_info_si(sc);
13693         break;
13694 
13695     case MULTI_FUNCTION_AFEX:
13696 
13697         bxe_get_shmem_mf_cfg_info_niv(sc);
13698         break;
13699 
13700     default:
13701 
13702         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13703               mf_info->mf_mode);
13704         return (1);
13705     }
13706 
13707     /* get the congestion management parameters */
13708 
13709     vnic = 0;
13710     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13711         /* get min/max bw */
13712         val = MFCFG_RD(sc, func_mf_config[i].config);
13713         mf_info->min_bw[vnic] =
13714             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13715         mf_info->max_bw[vnic] =
13716             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13717         vnic++;
13718     }
13719 
13720     return (bxe_check_valid_mf_cfg(sc));
13721 }
13722 
13723 static int
13724 bxe_get_shmem_info(struct bxe_softc *sc)
13725 {
13726     int port;
13727     uint32_t mac_hi, mac_lo, val;
13728 
13729     port = SC_PORT(sc);
13730     mac_hi = mac_lo = 0;
13731 
13732     sc->link_params.sc   = sc;
13733     sc->link_params.port = port;
13734 
13735     /* get the hardware config info */
13736     sc->devinfo.hw_config =
13737         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13738     sc->devinfo.hw_config2 =
13739         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13740 
13741     sc->link_params.hw_led_mode =
13742         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13743          SHARED_HW_CFG_LED_MODE_SHIFT);
13744 
13745     /* get the port feature config */
13746     sc->port.config =
13747         SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13748 
13749     /* get the link params */
13750     sc->link_params.speed_cap_mask[0] =
13751         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13752     sc->link_params.speed_cap_mask[1] =
13753         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13754 
13755     /* get the lane config */
13756     sc->link_params.lane_config =
13757         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13758 
13759     /* get the link config */
13760     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13761     sc->port.link_config[ELINK_INT_PHY] = val;
13762     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13763     sc->port.link_config[ELINK_EXT_PHY1] =
13764         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13765 
13766     /* get the override preemphasis flag and enable it or turn it off */
13767     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13768     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13769         sc->link_params.feature_config_flags |=
13770             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13771     } else {
13772         sc->link_params.feature_config_flags &=
13773             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13774     }
13775 
13776     /* get the initial value of the link params */
13777     sc->link_params.multi_phy_config =
13778         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13779 
13780     /* get external phy info */
13781     sc->port.ext_phy_config =
13782         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13783 
13784     /* get the multifunction configuration */
13785     bxe_get_mf_cfg_info(sc);
13786 
13787     /* get the mac address */
13788     if (IS_MF(sc)) {
13789         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13790         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13791     } else {
13792         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13793         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13794     }
13795 
13796     if ((mac_lo == 0) && (mac_hi == 0)) {
13797         *sc->mac_addr_str = 0;
13798         BLOGE(sc, "No Ethernet address programmed!\n");
13799     } else {
13800         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13801         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13802         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13803         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13804         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13805         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13806         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13807                  "%02x:%02x:%02x:%02x:%02x:%02x",
13808                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13809                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13810                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13811         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13812     }
13813 
13814     return (0);
13815 }
13816 
13817 static void
13818 bxe_get_tunable_params(struct bxe_softc *sc)
13819 {
13820     /* sanity checks */
13821 
13822     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13823         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13824         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13825         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13826         bxe_interrupt_mode = INTR_MODE_MSIX;
13827     }
13828 
13829     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13830         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13831         bxe_queue_count = 0;
13832     }
13833 
13834     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13835         if (bxe_max_rx_bufs == 0) {
13836             bxe_max_rx_bufs = RX_BD_USABLE;
13837         } else {
13838             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13839             bxe_max_rx_bufs = 2048;
13840         }
13841     }
13842 
13843     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13844         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13845         bxe_hc_rx_ticks = 25;
13846     }
13847 
13848     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13849         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13850         bxe_hc_tx_ticks = 50;
13851     }
13852 
13853     if (bxe_max_aggregation_size == 0) {
13854         bxe_max_aggregation_size = TPA_AGG_SIZE;
13855     }
13856 
13857     if (bxe_max_aggregation_size > 0xffff) {
13858         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13859               bxe_max_aggregation_size);
13860         bxe_max_aggregation_size = TPA_AGG_SIZE;
13861     }
13862 
13863     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13864         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13865         bxe_mrrs = -1;
13866     }
13867 
13868     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13869         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13870         bxe_autogreeen = 0;
13871     }
13872 
13873     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13874         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13875         bxe_udp_rss = 0;
13876     }
13877 
13878     /* pull in user settings */
13879 
13880     sc->interrupt_mode       = bxe_interrupt_mode;
13881     sc->max_rx_bufs          = bxe_max_rx_bufs;
13882     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13883     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13884     sc->max_aggregation_size = bxe_max_aggregation_size;
13885     sc->mrrs                 = bxe_mrrs;
13886     sc->autogreeen           = bxe_autogreeen;
13887     sc->udp_rss              = bxe_udp_rss;
13888 
13889     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13890         sc->num_queues = 1;
13891     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13892         sc->num_queues =
13893             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13894                 MAX_RSS_CHAINS);
13895         if (sc->num_queues > mp_ncpus) {
13896             sc->num_queues = mp_ncpus;
13897         }
13898     }
13899 
13900     BLOGD(sc, DBG_LOAD,
13901           "User Config: "
13902           "debug=0x%lx "
13903           "interrupt_mode=%d "
13904           "queue_count=%d "
13905           "hc_rx_ticks=%d "
13906           "hc_tx_ticks=%d "
13907           "rx_budget=%d "
13908           "max_aggregation_size=%d "
13909           "mrrs=%d "
13910           "autogreeen=%d "
13911           "udp_rss=%d\n",
13912           bxe_debug,
13913           sc->interrupt_mode,
13914           sc->num_queues,
13915           sc->hc_rx_ticks,
13916           sc->hc_tx_ticks,
13917           bxe_rx_budget,
13918           sc->max_aggregation_size,
13919           sc->mrrs,
13920           sc->autogreeen,
13921           sc->udp_rss);
13922 }
13923 
13924 static int
13925 bxe_media_detect(struct bxe_softc *sc)
13926 {
13927     int port_type;
13928     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13929 
13930     switch (sc->link_params.phy[phy_idx].media_type) {
13931     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13932     case ELINK_ETH_PHY_XFP_FIBER:
13933         BLOGI(sc, "Found 10Gb Fiber media.\n");
13934         sc->media = IFM_10G_SR;
13935         port_type = PORT_FIBRE;
13936         break;
13937     case ELINK_ETH_PHY_SFP_1G_FIBER:
13938         BLOGI(sc, "Found 1Gb Fiber media.\n");
13939         sc->media = IFM_1000_SX;
13940         port_type = PORT_FIBRE;
13941         break;
13942     case ELINK_ETH_PHY_KR:
13943     case ELINK_ETH_PHY_CX4:
13944         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13945         sc->media = IFM_10G_CX4;
13946         port_type = PORT_FIBRE;
13947         break;
13948     case ELINK_ETH_PHY_DA_TWINAX:
13949         BLOGI(sc, "Found 10Gb Twinax media.\n");
13950         sc->media = IFM_10G_TWINAX;
13951         port_type = PORT_DA;
13952         break;
13953     case ELINK_ETH_PHY_BASE_T:
13954         if (sc->link_params.speed_cap_mask[0] &
13955             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13956             BLOGI(sc, "Found 10GBase-T media.\n");
13957             sc->media = IFM_10G_T;
13958             port_type = PORT_TP;
13959         } else {
13960             BLOGI(sc, "Found 1000Base-T media.\n");
13961             sc->media = IFM_1000_T;
13962             port_type = PORT_TP;
13963         }
13964         break;
13965     case ELINK_ETH_PHY_NOT_PRESENT:
13966         BLOGI(sc, "Media not present.\n");
13967         sc->media = 0;
13968         port_type = PORT_OTHER;
13969         break;
13970     case ELINK_ETH_PHY_UNSPECIFIED:
13971     default:
13972         BLOGI(sc, "Unknown media!\n");
13973         sc->media = 0;
13974         port_type = PORT_OTHER;
13975         break;
13976     }
13977     return port_type;
13978 }
13979 
13980 #define GET_FIELD(value, fname)                     \
13981     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13982 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13983 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13984 
13985 static int
13986 bxe_get_igu_cam_info(struct bxe_softc *sc)
13987 {
13988     int pfid = SC_FUNC(sc);
13989     int igu_sb_id;
13990     uint32_t val;
13991     uint8_t fid, igu_sb_cnt = 0;
13992 
13993     sc->igu_base_sb = 0xff;
13994 
13995     if (CHIP_INT_MODE_IS_BC(sc)) {
13996         int vn = SC_VN(sc);
13997         igu_sb_cnt = sc->igu_sb_cnt;
13998         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13999                            FP_SB_MAX_E1x);
14000         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
14001                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
14002         return (0);
14003     }
14004 
14005     /* IGU in normal mode - read CAM */
14006     for (igu_sb_id = 0;
14007          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
14008          igu_sb_id++) {
14009         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
14010         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
14011             continue;
14012         }
14013         fid = IGU_FID(val);
14014         if ((fid & IGU_FID_ENCODE_IS_PF)) {
14015             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
14016                 continue;
14017             }
14018             if (IGU_VEC(val) == 0) {
14019                 /* default status block */
14020                 sc->igu_dsb_id = igu_sb_id;
14021             } else {
14022                 if (sc->igu_base_sb == 0xff) {
14023                     sc->igu_base_sb = igu_sb_id;
14024                 }
14025                 igu_sb_cnt++;
14026             }
14027         }
14028     }
14029 
14030     /*
14031      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
14032      * that number of CAM entries will not be equal to the value advertised in
14033      * PCI. Driver should use the minimal value of both as the actual status
14034      * block count
14035      */
14036     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
14037 
14038     if (igu_sb_cnt == 0) {
14039         BLOGE(sc, "CAM configuration error\n");
14040         return (-1);
14041     }
14042 
14043     return (0);
14044 }
14045 
14046 /*
14047  * Gather various information from the device config space, the device itself,
14048  * shmem, and the user input.
14049  */
14050 static int
14051 bxe_get_device_info(struct bxe_softc *sc)
14052 {
14053     uint32_t val;
14054     int rc;
14055 
14056     /* Get the data for the device */
14057     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
14058     sc->devinfo.device_id    = pci_get_device(sc->dev);
14059     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
14060     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
14061 
14062     /* get the chip revision (chip metal comes from pci config space) */
14063     sc->devinfo.chip_id     =
14064     sc->link_params.chip_id =
14065         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
14066          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
14067          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
14068          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
14069 
14070     /* force 57811 according to MISC register */
14071     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
14072         if (CHIP_IS_57810(sc)) {
14073             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
14074                                    (sc->devinfo.chip_id & 0x0000ffff));
14075         } else if (CHIP_IS_57810_MF(sc)) {
14076             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
14077                                    (sc->devinfo.chip_id & 0x0000ffff));
14078         }
14079         sc->devinfo.chip_id |= 0x1;
14080     }
14081 
14082     BLOGD(sc, DBG_LOAD,
14083           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
14084           sc->devinfo.chip_id,
14085           ((sc->devinfo.chip_id >> 16) & 0xffff),
14086           ((sc->devinfo.chip_id >> 12) & 0xf),
14087           ((sc->devinfo.chip_id >>  4) & 0xff),
14088           ((sc->devinfo.chip_id >>  0) & 0xf));
14089 
14090     val = (REG_RD(sc, 0x2874) & 0x55);
14091     if ((sc->devinfo.chip_id & 0x1) ||
14092         (CHIP_IS_E1(sc) && val) ||
14093         (CHIP_IS_E1H(sc) && (val == 0x55))) {
14094         sc->flags |= BXE_ONE_PORT_FLAG;
14095         BLOGD(sc, DBG_LOAD, "single port device\n");
14096     }
14097 
14098     /* set the doorbell size */
14099     sc->doorbell_size = (1 << BXE_DB_SHIFT);
14100 
14101     /* determine whether the device is in 2 port or 4 port mode */
14102     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
14103     if (CHIP_IS_E2E3(sc)) {
14104         /*
14105          * Read port4mode_en_ovwr[0]:
14106          *   If 1, four port mode is in port4mode_en_ovwr[1].
14107          *   If 0, four port mode is in port4mode_en[0].
14108          */
14109         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
14110         if (val & 1) {
14111             val = ((val >> 1) & 1);
14112         } else {
14113             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
14114         }
14115 
14116         sc->devinfo.chip_port_mode =
14117             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
14118 
14119         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
14120     }
14121 
14122     /* get the function and path info for the device */
14123     bxe_get_function_num(sc);
14124 
14125     /* get the shared memory base address */
14126     sc->devinfo.shmem_base     =
14127     sc->link_params.shmem_base =
14128         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
14129     sc->devinfo.shmem2_base =
14130         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
14131                                   MISC_REG_GENERIC_CR_0));
14132 
14133     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
14134           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
14135 
14136     if (!sc->devinfo.shmem_base) {
14137         /* this should ONLY prevent upcoming shmem reads */
14138         BLOGI(sc, "MCP not active\n");
14139         sc->flags |= BXE_NO_MCP_FLAG;
14140         return (0);
14141     }
14142 
14143     /* make sure the shared memory contents are valid */
14144     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
14145     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
14146         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
14147         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
14148         return (0);
14149     }
14150     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
14151 
14152     /* get the bootcode version */
14153     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
14154     snprintf(sc->devinfo.bc_ver_str,
14155              sizeof(sc->devinfo.bc_ver_str),
14156              "%d.%d.%d",
14157              ((sc->devinfo.bc_ver >> 24) & 0xff),
14158              ((sc->devinfo.bc_ver >> 16) & 0xff),
14159              ((sc->devinfo.bc_ver >>  8) & 0xff));
14160     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
14161 
14162     /* get the bootcode shmem address */
14163     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
14164     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
14165 
14166     /* clean indirect addresses as they're not used */
14167     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
14168     if (IS_PF(sc)) {
14169         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
14170         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
14171         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
14172         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
14173         if (CHIP_IS_E1x(sc)) {
14174             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
14175             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
14176             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
14177             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
14178         }
14179 
14180         /*
14181          * Enable internal target-read (in case we are probed after PF
14182          * FLR). Must be done prior to any BAR read access. Only for
14183          * 57712 and up
14184          */
14185         if (!CHIP_IS_E1x(sc)) {
14186             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
14187         }
14188     }
14189 
14190     /* get the nvram size */
14191     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
14192     sc->devinfo.flash_size =
14193         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
14194     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
14195 
14196     /* get PCI capabilites */
14197     bxe_probe_pci_caps(sc);
14198 
14199     bxe_set_power_state(sc, PCI_PM_D0);
14200 
14201     /* get various configuration parameters from shmem */
14202     bxe_get_shmem_info(sc);
14203 
14204     if (sc->devinfo.pcie_msix_cap_reg != 0) {
14205         val = pci_read_config(sc->dev,
14206                               (sc->devinfo.pcie_msix_cap_reg +
14207                                PCIR_MSIX_CTRL),
14208                               2);
14209         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
14210     } else {
14211         sc->igu_sb_cnt = 1;
14212     }
14213 
14214     sc->igu_base_addr = BAR_IGU_INTMEM;
14215 
14216     /* initialize IGU parameters */
14217     if (CHIP_IS_E1x(sc)) {
14218         sc->devinfo.int_block = INT_BLOCK_HC;
14219         sc->igu_dsb_id = DEF_SB_IGU_ID;
14220         sc->igu_base_sb = 0;
14221     } else {
14222         sc->devinfo.int_block = INT_BLOCK_IGU;
14223 
14224         /* do not allow device reset during IGU info preocessing */
14225         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14226 
14227         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
14228 
14229         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14230             int tout = 5000;
14231 
14232             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
14233 
14234             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
14235             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
14236             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
14237 
14238             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14239                 tout--;
14240                 DELAY(1000);
14241             }
14242 
14243             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14244                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
14245                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14246                 return (-1);
14247             }
14248         }
14249 
14250         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14251             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
14252             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
14253         } else {
14254             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
14255         }
14256 
14257         rc = bxe_get_igu_cam_info(sc);
14258 
14259         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14260 
14261         if (rc) {
14262             return (rc);
14263         }
14264     }
14265 
14266     /*
14267      * Get base FW non-default (fast path) status block ID. This value is
14268      * used to initialize the fw_sb_id saved on the fp/queue structure to
14269      * determine the id used by the FW.
14270      */
14271     if (CHIP_IS_E1x(sc)) {
14272         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14273     } else {
14274         /*
14275          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14276          * the same queue are indicated on the same IGU SB). So we prefer
14277          * FW and IGU SBs to be the same value.
14278          */
14279         sc->base_fw_ndsb = sc->igu_base_sb;
14280     }
14281 
14282     BLOGD(sc, DBG_LOAD,
14283           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14284           sc->igu_dsb_id, sc->igu_base_sb,
14285           sc->igu_sb_cnt, sc->base_fw_ndsb);
14286 
14287     elink_phy_probe(&sc->link_params);
14288 
14289     return (0);
14290 }
14291 
14292 static void
14293 bxe_link_settings_supported(struct bxe_softc *sc,
14294                             uint32_t         switch_cfg)
14295 {
14296     uint32_t cfg_size = 0;
14297     uint32_t idx;
14298     uint8_t port = SC_PORT(sc);
14299 
14300     /* aggregation of supported attributes of all external phys */
14301     sc->port.supported[0] = 0;
14302     sc->port.supported[1] = 0;
14303 
14304     switch (sc->link_params.num_phys) {
14305     case 1:
14306         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14307         cfg_size = 1;
14308         break;
14309     case 2:
14310         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14311         cfg_size = 1;
14312         break;
14313     case 3:
14314         if (sc->link_params.multi_phy_config &
14315             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14316             sc->port.supported[1] =
14317                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14318             sc->port.supported[0] =
14319                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14320         } else {
14321             sc->port.supported[0] =
14322                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14323             sc->port.supported[1] =
14324                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14325         }
14326         cfg_size = 2;
14327         break;
14328     }
14329 
14330     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14331         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14332               SHMEM_RD(sc,
14333                        dev_info.port_hw_config[port].external_phy_config),
14334               SHMEM_RD(sc,
14335                        dev_info.port_hw_config[port].external_phy_config2));
14336         return;
14337     }
14338 
14339     if (CHIP_IS_E3(sc))
14340         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14341     else {
14342         switch (switch_cfg) {
14343         case ELINK_SWITCH_CFG_1G:
14344             sc->port.phy_addr =
14345                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14346             break;
14347         case ELINK_SWITCH_CFG_10G:
14348             sc->port.phy_addr =
14349                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14350             break;
14351         default:
14352             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14353                   sc->port.link_config[0]);
14354             return;
14355         }
14356     }
14357 
14358     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14359 
14360     /* mask what we support according to speed_cap_mask per configuration */
14361     for (idx = 0; idx < cfg_size; idx++) {
14362         if (!(sc->link_params.speed_cap_mask[idx] &
14363               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14364             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14365         }
14366 
14367         if (!(sc->link_params.speed_cap_mask[idx] &
14368               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14369             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14370         }
14371 
14372         if (!(sc->link_params.speed_cap_mask[idx] &
14373               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14374             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14375         }
14376 
14377         if (!(sc->link_params.speed_cap_mask[idx] &
14378               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14379             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14380         }
14381 
14382         if (!(sc->link_params.speed_cap_mask[idx] &
14383               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14384             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14385         }
14386 
14387         if (!(sc->link_params.speed_cap_mask[idx] &
14388               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14389             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14390         }
14391 
14392         if (!(sc->link_params.speed_cap_mask[idx] &
14393               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14394             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14395         }
14396 
14397         if (!(sc->link_params.speed_cap_mask[idx] &
14398               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14399             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14400         }
14401     }
14402 
14403     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14404           sc->port.supported[0], sc->port.supported[1]);
14405 	ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14406 					sc->port.supported[0], sc->port.supported[1]);
14407 }
14408 
14409 static void
14410 bxe_link_settings_requested(struct bxe_softc *sc)
14411 {
14412     uint32_t link_config;
14413     uint32_t idx;
14414     uint32_t cfg_size = 0;
14415 
14416     sc->port.advertising[0] = 0;
14417     sc->port.advertising[1] = 0;
14418 
14419     switch (sc->link_params.num_phys) {
14420     case 1:
14421     case 2:
14422         cfg_size = 1;
14423         break;
14424     case 3:
14425         cfg_size = 2;
14426         break;
14427     }
14428 
14429     for (idx = 0; idx < cfg_size; idx++) {
14430         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14431         link_config = sc->port.link_config[idx];
14432 
14433         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14434         case PORT_FEATURE_LINK_SPEED_AUTO:
14435             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14436                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14437                 sc->port.advertising[idx] |= sc->port.supported[idx];
14438                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14439                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14440                     sc->port.advertising[idx] |=
14441                         (ELINK_SUPPORTED_100baseT_Half |
14442                          ELINK_SUPPORTED_100baseT_Full);
14443             } else {
14444                 /* force 10G, no AN */
14445                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14446                 sc->port.advertising[idx] |=
14447                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14448                 continue;
14449             }
14450             break;
14451 
14452         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14453             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14454                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14455                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14456                                               ADVERTISED_TP);
14457             } else {
14458                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14459                           "speed_cap_mask=0x%08x\n",
14460                       link_config, sc->link_params.speed_cap_mask[idx]);
14461                 return;
14462             }
14463             break;
14464 
14465         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14466             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14467                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14468                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14469                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14470                                               ADVERTISED_TP);
14471 				ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14472 								sc->link_params.req_duplex[idx]);
14473             } else {
14474                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14475                           "speed_cap_mask=0x%08x\n",
14476                       link_config, sc->link_params.speed_cap_mask[idx]);
14477                 return;
14478             }
14479             break;
14480 
14481         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14482             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14483                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14484                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14485                                               ADVERTISED_TP);
14486             } else {
14487                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14488                           "speed_cap_mask=0x%08x\n",
14489                       link_config, sc->link_params.speed_cap_mask[idx]);
14490                 return;
14491             }
14492             break;
14493 
14494         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14495             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14496                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14497                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14498                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14499                                               ADVERTISED_TP);
14500             } else {
14501                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14502                           "speed_cap_mask=0x%08x\n",
14503                       link_config, sc->link_params.speed_cap_mask[idx]);
14504                 return;
14505             }
14506             break;
14507 
14508         case PORT_FEATURE_LINK_SPEED_1G:
14509             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14510                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14511                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14512                                               ADVERTISED_TP);
14513             } else {
14514                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14515                           "speed_cap_mask=0x%08x\n",
14516                       link_config, sc->link_params.speed_cap_mask[idx]);
14517                 return;
14518             }
14519             break;
14520 
14521         case PORT_FEATURE_LINK_SPEED_2_5G:
14522             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14523                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14524                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14525                                               ADVERTISED_TP);
14526             } else {
14527                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14528                           "speed_cap_mask=0x%08x\n",
14529                       link_config, sc->link_params.speed_cap_mask[idx]);
14530                 return;
14531             }
14532             break;
14533 
14534         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14535             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14536                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14537                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14538                                               ADVERTISED_FIBRE);
14539             } else {
14540                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14541                           "speed_cap_mask=0x%08x\n",
14542                       link_config, sc->link_params.speed_cap_mask[idx]);
14543                 return;
14544             }
14545             break;
14546 
14547         case PORT_FEATURE_LINK_SPEED_20G:
14548             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14549             break;
14550 
14551         default:
14552             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14553                       "speed_cap_mask=0x%08x\n",
14554                   link_config, sc->link_params.speed_cap_mask[idx]);
14555             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14556             sc->port.advertising[idx] = sc->port.supported[idx];
14557             break;
14558         }
14559 
14560         sc->link_params.req_flow_ctrl[idx] =
14561             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14562 
14563         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14564             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14565                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14566             } else {
14567                 bxe_set_requested_fc(sc);
14568             }
14569         }
14570 
14571         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14572                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14573               sc->link_params.req_line_speed[idx],
14574               sc->link_params.req_duplex[idx],
14575               sc->link_params.req_flow_ctrl[idx],
14576               sc->port.advertising[idx]);
14577 		ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14578 						"advertising=0x%x\n",
14579 						sc->link_params.req_line_speed[idx],
14580 						sc->link_params.req_duplex[idx],
14581 						sc->port.advertising[idx]);
14582     }
14583 }
14584 
14585 static void
14586 bxe_get_phy_info(struct bxe_softc *sc)
14587 {
14588     uint8_t port = SC_PORT(sc);
14589     uint32_t config = sc->port.config;
14590     uint32_t eee_mode;
14591 
14592     /* shmem data already read in bxe_get_shmem_info() */
14593 
14594     ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14595                         "link_config0=0x%08x\n",
14596                sc->link_params.lane_config,
14597                sc->link_params.speed_cap_mask[0],
14598                sc->port.link_config[0]);
14599 
14600 
14601     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14602     bxe_link_settings_requested(sc);
14603 
14604     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14605         sc->link_params.feature_config_flags |=
14606             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14607     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14608         sc->link_params.feature_config_flags &=
14609             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14610     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14611         sc->link_params.feature_config_flags |=
14612             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14613     }
14614 
14615     /* configure link feature according to nvram value */
14616     eee_mode =
14617         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14618           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14619          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14620     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14621         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14622                                     ELINK_EEE_MODE_ENABLE_LPI |
14623                                     ELINK_EEE_MODE_OUTPUT_TIME);
14624     } else {
14625         sc->link_params.eee_mode = 0;
14626     }
14627 
14628     /* get the media type */
14629     bxe_media_detect(sc);
14630 	ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14631 }
14632 
14633 static void
14634 bxe_get_params(struct bxe_softc *sc)
14635 {
14636     /* get user tunable params */
14637     bxe_get_tunable_params(sc);
14638 
14639     /* select the RX and TX ring sizes */
14640     sc->tx_ring_size = TX_BD_USABLE;
14641     sc->rx_ring_size = RX_BD_USABLE;
14642 
14643     /* XXX disable WoL */
14644     sc->wol = 0;
14645 }
14646 
14647 static void
14648 bxe_set_modes_bitmap(struct bxe_softc *sc)
14649 {
14650     uint32_t flags = 0;
14651 
14652     if (CHIP_REV_IS_FPGA(sc)) {
14653         SET_FLAGS(flags, MODE_FPGA);
14654     } else if (CHIP_REV_IS_EMUL(sc)) {
14655         SET_FLAGS(flags, MODE_EMUL);
14656     } else {
14657         SET_FLAGS(flags, MODE_ASIC);
14658     }
14659 
14660     if (CHIP_IS_MODE_4_PORT(sc)) {
14661         SET_FLAGS(flags, MODE_PORT4);
14662     } else {
14663         SET_FLAGS(flags, MODE_PORT2);
14664     }
14665 
14666     if (CHIP_IS_E2(sc)) {
14667         SET_FLAGS(flags, MODE_E2);
14668     } else if (CHIP_IS_E3(sc)) {
14669         SET_FLAGS(flags, MODE_E3);
14670         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14671             SET_FLAGS(flags, MODE_E3_A0);
14672         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14673             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14674         }
14675     }
14676 
14677     if (IS_MF(sc)) {
14678         SET_FLAGS(flags, MODE_MF);
14679         switch (sc->devinfo.mf_info.mf_mode) {
14680         case MULTI_FUNCTION_SD:
14681             SET_FLAGS(flags, MODE_MF_SD);
14682             break;
14683         case MULTI_FUNCTION_SI:
14684             SET_FLAGS(flags, MODE_MF_SI);
14685             break;
14686         case MULTI_FUNCTION_AFEX:
14687             SET_FLAGS(flags, MODE_MF_AFEX);
14688             break;
14689         }
14690     } else {
14691         SET_FLAGS(flags, MODE_SF);
14692     }
14693 
14694 #if defined(__LITTLE_ENDIAN)
14695     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14696 #else /* __BIG_ENDIAN */
14697     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14698 #endif
14699 
14700     INIT_MODE_FLAGS(sc) = flags;
14701 }
14702 
14703 static int
14704 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14705 {
14706     struct bxe_fastpath *fp;
14707     bus_addr_t busaddr;
14708     int max_agg_queues;
14709     int max_segments;
14710     bus_size_t max_size;
14711     bus_size_t max_seg_size;
14712     char buf[32];
14713     int rc;
14714     int i, j;
14715 
14716     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14717 
14718     /* allocate the parent bus DMA tag */
14719     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14720                             1,                        /* alignment */
14721                             0,                        /* boundary limit */
14722                             BUS_SPACE_MAXADDR,        /* restricted low */
14723                             BUS_SPACE_MAXADDR,        /* restricted hi */
14724                             NULL,                     /* addr filter() */
14725                             NULL,                     /* addr filter() arg */
14726                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14727                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14728                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14729                             0,                        /* flags */
14730                             NULL,                     /* lock() */
14731                             NULL,                     /* lock() arg */
14732                             &sc->parent_dma_tag);     /* returned dma tag */
14733     if (rc != 0) {
14734         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14735         return (1);
14736     }
14737 
14738     /************************/
14739     /* DEFAULT STATUS BLOCK */
14740     /************************/
14741 
14742     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14743                       &sc->def_sb_dma, "default status block") != 0) {
14744         /* XXX */
14745         bus_dma_tag_destroy(sc->parent_dma_tag);
14746         return (1);
14747     }
14748 
14749     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14750 
14751     /***************/
14752     /* EVENT QUEUE */
14753     /***************/
14754 
14755     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14756                       &sc->eq_dma, "event queue") != 0) {
14757         /* XXX */
14758         bxe_dma_free(sc, &sc->def_sb_dma);
14759         sc->def_sb = NULL;
14760         bus_dma_tag_destroy(sc->parent_dma_tag);
14761         return (1);
14762     }
14763 
14764     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14765 
14766     /*************/
14767     /* SLOW PATH */
14768     /*************/
14769 
14770     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14771                       &sc->sp_dma, "slow path") != 0) {
14772         /* XXX */
14773         bxe_dma_free(sc, &sc->eq_dma);
14774         sc->eq = NULL;
14775         bxe_dma_free(sc, &sc->def_sb_dma);
14776         sc->def_sb = NULL;
14777         bus_dma_tag_destroy(sc->parent_dma_tag);
14778         return (1);
14779     }
14780 
14781     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14782 
14783     /*******************/
14784     /* SLOW PATH QUEUE */
14785     /*******************/
14786 
14787     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14788                       &sc->spq_dma, "slow path queue") != 0) {
14789         /* XXX */
14790         bxe_dma_free(sc, &sc->sp_dma);
14791         sc->sp = NULL;
14792         bxe_dma_free(sc, &sc->eq_dma);
14793         sc->eq = NULL;
14794         bxe_dma_free(sc, &sc->def_sb_dma);
14795         sc->def_sb = NULL;
14796         bus_dma_tag_destroy(sc->parent_dma_tag);
14797         return (1);
14798     }
14799 
14800     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14801 
14802     /***************************/
14803     /* FW DECOMPRESSION BUFFER */
14804     /***************************/
14805 
14806     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14807                       "fw decompression buffer") != 0) {
14808         /* XXX */
14809         bxe_dma_free(sc, &sc->spq_dma);
14810         sc->spq = NULL;
14811         bxe_dma_free(sc, &sc->sp_dma);
14812         sc->sp = NULL;
14813         bxe_dma_free(sc, &sc->eq_dma);
14814         sc->eq = NULL;
14815         bxe_dma_free(sc, &sc->def_sb_dma);
14816         sc->def_sb = NULL;
14817         bus_dma_tag_destroy(sc->parent_dma_tag);
14818         return (1);
14819     }
14820 
14821     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14822 
14823     if ((sc->gz_strm =
14824          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14825         /* XXX */
14826         bxe_dma_free(sc, &sc->gz_buf_dma);
14827         sc->gz_buf = NULL;
14828         bxe_dma_free(sc, &sc->spq_dma);
14829         sc->spq = NULL;
14830         bxe_dma_free(sc, &sc->sp_dma);
14831         sc->sp = NULL;
14832         bxe_dma_free(sc, &sc->eq_dma);
14833         sc->eq = NULL;
14834         bxe_dma_free(sc, &sc->def_sb_dma);
14835         sc->def_sb = NULL;
14836         bus_dma_tag_destroy(sc->parent_dma_tag);
14837         return (1);
14838     }
14839 
14840     /*************/
14841     /* FASTPATHS */
14842     /*************/
14843 
14844     /* allocate DMA memory for each fastpath structure */
14845     for (i = 0; i < sc->num_queues; i++) {
14846         fp = &sc->fp[i];
14847         fp->sc    = sc;
14848         fp->index = i;
14849 
14850         /*******************/
14851         /* FP STATUS BLOCK */
14852         /*******************/
14853 
14854         snprintf(buf, sizeof(buf), "fp %d status block", i);
14855         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14856                           &fp->sb_dma, buf) != 0) {
14857             /* XXX unwind and free previous fastpath allocations */
14858             BLOGE(sc, "Failed to alloc %s\n", buf);
14859             return (1);
14860         } else {
14861             if (CHIP_IS_E2E3(sc)) {
14862                 fp->status_block.e2_sb =
14863                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14864             } else {
14865                 fp->status_block.e1x_sb =
14866                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14867             }
14868         }
14869 
14870         /******************/
14871         /* FP TX BD CHAIN */
14872         /******************/
14873 
14874         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14875         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14876                           &fp->tx_dma, buf) != 0) {
14877             /* XXX unwind and free previous fastpath allocations */
14878             BLOGE(sc, "Failed to alloc %s\n", buf);
14879             return (1);
14880         } else {
14881             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14882         }
14883 
14884         /* link together the tx bd chain pages */
14885         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14886             /* index into the tx bd chain array to last entry per page */
14887             struct eth_tx_next_bd *tx_next_bd =
14888                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14889             /* point to the next page and wrap from last page */
14890             busaddr = (fp->tx_dma.paddr +
14891                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14892             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14893             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14894         }
14895 
14896         /******************/
14897         /* FP RX BD CHAIN */
14898         /******************/
14899 
14900         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14901         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14902                           &fp->rx_dma, buf) != 0) {
14903             /* XXX unwind and free previous fastpath allocations */
14904             BLOGE(sc, "Failed to alloc %s\n", buf);
14905             return (1);
14906         } else {
14907             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14908         }
14909 
14910         /* link together the rx bd chain pages */
14911         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14912             /* index into the rx bd chain array to last entry per page */
14913             struct eth_rx_bd *rx_bd =
14914                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14915             /* point to the next page and wrap from last page */
14916             busaddr = (fp->rx_dma.paddr +
14917                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14918             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14919             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14920         }
14921 
14922         /*******************/
14923         /* FP RX RCQ CHAIN */
14924         /*******************/
14925 
14926         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14927         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14928                           &fp->rcq_dma, buf) != 0) {
14929             /* XXX unwind and free previous fastpath allocations */
14930             BLOGE(sc, "Failed to alloc %s\n", buf);
14931             return (1);
14932         } else {
14933             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14934         }
14935 
14936         /* link together the rcq chain pages */
14937         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14938             /* index into the rcq chain array to last entry per page */
14939             struct eth_rx_cqe_next_page *rx_cqe_next =
14940                 (struct eth_rx_cqe_next_page *)
14941                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14942             /* point to the next page and wrap from last page */
14943             busaddr = (fp->rcq_dma.paddr +
14944                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14945             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14946             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14947         }
14948 
14949         /*******************/
14950         /* FP RX SGE CHAIN */
14951         /*******************/
14952 
14953         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14954         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14955                           &fp->rx_sge_dma, buf) != 0) {
14956             /* XXX unwind and free previous fastpath allocations */
14957             BLOGE(sc, "Failed to alloc %s\n", buf);
14958             return (1);
14959         } else {
14960             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14961         }
14962 
14963         /* link together the sge chain pages */
14964         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14965             /* index into the rcq chain array to last entry per page */
14966             struct eth_rx_sge *rx_sge =
14967                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14968             /* point to the next page and wrap from last page */
14969             busaddr = (fp->rx_sge_dma.paddr +
14970                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14971             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14972             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14973         }
14974 
14975         /***********************/
14976         /* FP TX MBUF DMA MAPS */
14977         /***********************/
14978 
14979         /* set required sizes before mapping to conserve resources */
14980         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14981             max_size     = BXE_TSO_MAX_SIZE;
14982             max_segments = BXE_TSO_MAX_SEGMENTS;
14983             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14984         } else {
14985             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14986             max_segments = BXE_MAX_SEGMENTS;
14987             max_seg_size = MCLBYTES;
14988         }
14989 
14990         /* create a dma tag for the tx mbufs */
14991         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14992                                 1,                  /* alignment */
14993                                 0,                  /* boundary limit */
14994                                 BUS_SPACE_MAXADDR,  /* restricted low */
14995                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14996                                 NULL,               /* addr filter() */
14997                                 NULL,               /* addr filter() arg */
14998                                 max_size,           /* max map size */
14999                                 max_segments,       /* num discontinuous */
15000                                 max_seg_size,       /* max seg size */
15001                                 0,                  /* flags */
15002                                 NULL,               /* lock() */
15003                                 NULL,               /* lock() arg */
15004                                 &fp->tx_mbuf_tag);  /* returned dma tag */
15005         if (rc != 0) {
15006             /* XXX unwind and free previous fastpath allocations */
15007             BLOGE(sc, "Failed to create dma tag for "
15008                       "'fp %d tx mbufs' (%d)\n", i, rc);
15009             return (1);
15010         }
15011 
15012         /* create dma maps for each of the tx mbuf clusters */
15013         for (j = 0; j < TX_BD_TOTAL; j++) {
15014             if (bus_dmamap_create(fp->tx_mbuf_tag,
15015                                   BUS_DMA_NOWAIT,
15016                                   &fp->tx_mbuf_chain[j].m_map)) {
15017                 /* XXX unwind and free previous fastpath allocations */
15018                 BLOGE(sc, "Failed to create dma map for "
15019                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
15020                 return (1);
15021             }
15022         }
15023 
15024         /***********************/
15025         /* FP RX MBUF DMA MAPS */
15026         /***********************/
15027 
15028         /* create a dma tag for the rx mbufs */
15029         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15030                                 1,                  /* alignment */
15031                                 0,                  /* boundary limit */
15032                                 BUS_SPACE_MAXADDR,  /* restricted low */
15033                                 BUS_SPACE_MAXADDR,  /* restricted hi */
15034                                 NULL,               /* addr filter() */
15035                                 NULL,               /* addr filter() arg */
15036                                 MJUM9BYTES,         /* max map size */
15037                                 1,                  /* num discontinuous */
15038                                 MJUM9BYTES,         /* max seg size */
15039                                 0,                  /* flags */
15040                                 NULL,               /* lock() */
15041                                 NULL,               /* lock() arg */
15042                                 &fp->rx_mbuf_tag);  /* returned dma tag */
15043         if (rc != 0) {
15044             /* XXX unwind and free previous fastpath allocations */
15045             BLOGE(sc, "Failed to create dma tag for "
15046                       "'fp %d rx mbufs' (%d)\n", i, rc);
15047             return (1);
15048         }
15049 
15050         /* create dma maps for each of the rx mbuf clusters */
15051         for (j = 0; j < RX_BD_TOTAL; j++) {
15052             if (bus_dmamap_create(fp->rx_mbuf_tag,
15053                                   BUS_DMA_NOWAIT,
15054                                   &fp->rx_mbuf_chain[j].m_map)) {
15055                 /* XXX unwind and free previous fastpath allocations */
15056                 BLOGE(sc, "Failed to create dma map for "
15057                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
15058                 return (1);
15059             }
15060         }
15061 
15062         /* create dma map for the spare rx mbuf cluster */
15063         if (bus_dmamap_create(fp->rx_mbuf_tag,
15064                               BUS_DMA_NOWAIT,
15065                               &fp->rx_mbuf_spare_map)) {
15066             /* XXX unwind and free previous fastpath allocations */
15067             BLOGE(sc, "Failed to create dma map for "
15068                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
15069             return (1);
15070         }
15071 
15072         /***************************/
15073         /* FP RX SGE MBUF DMA MAPS */
15074         /***************************/
15075 
15076         /* create a dma tag for the rx sge mbufs */
15077         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15078                                 1,                  /* alignment */
15079                                 0,                  /* boundary limit */
15080                                 BUS_SPACE_MAXADDR,  /* restricted low */
15081                                 BUS_SPACE_MAXADDR,  /* restricted hi */
15082                                 NULL,               /* addr filter() */
15083                                 NULL,               /* addr filter() arg */
15084                                 BCM_PAGE_SIZE,      /* max map size */
15085                                 1,                  /* num discontinuous */
15086                                 BCM_PAGE_SIZE,      /* max seg size */
15087                                 0,                  /* flags */
15088                                 NULL,               /* lock() */
15089                                 NULL,               /* lock() arg */
15090                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
15091         if (rc != 0) {
15092             /* XXX unwind and free previous fastpath allocations */
15093             BLOGE(sc, "Failed to create dma tag for "
15094                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
15095             return (1);
15096         }
15097 
15098         /* create dma maps for the rx sge mbuf clusters */
15099         for (j = 0; j < RX_SGE_TOTAL; j++) {
15100             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15101                                   BUS_DMA_NOWAIT,
15102                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
15103                 /* XXX unwind and free previous fastpath allocations */
15104                 BLOGE(sc, "Failed to create dma map for "
15105                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
15106                 return (1);
15107             }
15108         }
15109 
15110         /* create dma map for the spare rx sge mbuf cluster */
15111         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15112                               BUS_DMA_NOWAIT,
15113                               &fp->rx_sge_mbuf_spare_map)) {
15114             /* XXX unwind and free previous fastpath allocations */
15115             BLOGE(sc, "Failed to create dma map for "
15116                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
15117             return (1);
15118         }
15119 
15120         /***************************/
15121         /* FP RX TPA MBUF DMA MAPS */
15122         /***************************/
15123 
15124         /* create dma maps for the rx tpa mbuf clusters */
15125         max_agg_queues = MAX_AGG_QS(sc);
15126 
15127         for (j = 0; j < max_agg_queues; j++) {
15128             if (bus_dmamap_create(fp->rx_mbuf_tag,
15129                                   BUS_DMA_NOWAIT,
15130                                   &fp->rx_tpa_info[j].bd.m_map)) {
15131                 /* XXX unwind and free previous fastpath allocations */
15132                 BLOGE(sc, "Failed to create dma map for "
15133                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
15134                 return (1);
15135             }
15136         }
15137 
15138         /* create dma map for the spare rx tpa mbuf cluster */
15139         if (bus_dmamap_create(fp->rx_mbuf_tag,
15140                               BUS_DMA_NOWAIT,
15141                               &fp->rx_tpa_info_mbuf_spare_map)) {
15142             /* XXX unwind and free previous fastpath allocations */
15143             BLOGE(sc, "Failed to create dma map for "
15144                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
15145             return (1);
15146         }
15147 
15148         bxe_init_sge_ring_bit_mask(fp);
15149     }
15150 
15151     return (0);
15152 }
15153 
15154 static void
15155 bxe_free_hsi_mem(struct bxe_softc *sc)
15156 {
15157     struct bxe_fastpath *fp;
15158     int max_agg_queues;
15159     int i, j;
15160 
15161     if (sc->parent_dma_tag == NULL) {
15162         return; /* assume nothing was allocated */
15163     }
15164 
15165     for (i = 0; i < sc->num_queues; i++) {
15166         fp = &sc->fp[i];
15167 
15168         /*******************/
15169         /* FP STATUS BLOCK */
15170         /*******************/
15171 
15172         bxe_dma_free(sc, &fp->sb_dma);
15173         memset(&fp->status_block, 0, sizeof(fp->status_block));
15174 
15175         /******************/
15176         /* FP TX BD CHAIN */
15177         /******************/
15178 
15179         bxe_dma_free(sc, &fp->tx_dma);
15180         fp->tx_chain = NULL;
15181 
15182         /******************/
15183         /* FP RX BD CHAIN */
15184         /******************/
15185 
15186         bxe_dma_free(sc, &fp->rx_dma);
15187         fp->rx_chain = NULL;
15188 
15189         /*******************/
15190         /* FP RX RCQ CHAIN */
15191         /*******************/
15192 
15193         bxe_dma_free(sc, &fp->rcq_dma);
15194         fp->rcq_chain = NULL;
15195 
15196         /*******************/
15197         /* FP RX SGE CHAIN */
15198         /*******************/
15199 
15200         bxe_dma_free(sc, &fp->rx_sge_dma);
15201         fp->rx_sge_chain = NULL;
15202 
15203         /***********************/
15204         /* FP TX MBUF DMA MAPS */
15205         /***********************/
15206 
15207         if (fp->tx_mbuf_tag != NULL) {
15208             for (j = 0; j < TX_BD_TOTAL; j++) {
15209                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
15210                     bus_dmamap_unload(fp->tx_mbuf_tag,
15211                                       fp->tx_mbuf_chain[j].m_map);
15212                     bus_dmamap_destroy(fp->tx_mbuf_tag,
15213                                        fp->tx_mbuf_chain[j].m_map);
15214                 }
15215             }
15216 
15217             bus_dma_tag_destroy(fp->tx_mbuf_tag);
15218             fp->tx_mbuf_tag = NULL;
15219         }
15220 
15221         /***********************/
15222         /* FP RX MBUF DMA MAPS */
15223         /***********************/
15224 
15225         if (fp->rx_mbuf_tag != NULL) {
15226             for (j = 0; j < RX_BD_TOTAL; j++) {
15227                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
15228                     bus_dmamap_unload(fp->rx_mbuf_tag,
15229                                       fp->rx_mbuf_chain[j].m_map);
15230                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15231                                        fp->rx_mbuf_chain[j].m_map);
15232                 }
15233             }
15234 
15235             if (fp->rx_mbuf_spare_map != NULL) {
15236                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15237                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15238             }
15239 
15240             /***************************/
15241             /* FP RX TPA MBUF DMA MAPS */
15242             /***************************/
15243 
15244             max_agg_queues = MAX_AGG_QS(sc);
15245 
15246             for (j = 0; j < max_agg_queues; j++) {
15247                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
15248                     bus_dmamap_unload(fp->rx_mbuf_tag,
15249                                       fp->rx_tpa_info[j].bd.m_map);
15250                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15251                                        fp->rx_tpa_info[j].bd.m_map);
15252                 }
15253             }
15254 
15255             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
15256                 bus_dmamap_unload(fp->rx_mbuf_tag,
15257                                   fp->rx_tpa_info_mbuf_spare_map);
15258                 bus_dmamap_destroy(fp->rx_mbuf_tag,
15259                                    fp->rx_tpa_info_mbuf_spare_map);
15260             }
15261 
15262             bus_dma_tag_destroy(fp->rx_mbuf_tag);
15263             fp->rx_mbuf_tag = NULL;
15264         }
15265 
15266         /***************************/
15267         /* FP RX SGE MBUF DMA MAPS */
15268         /***************************/
15269 
15270         if (fp->rx_sge_mbuf_tag != NULL) {
15271             for (j = 0; j < RX_SGE_TOTAL; j++) {
15272                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
15273                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15274                                       fp->rx_sge_mbuf_chain[j].m_map);
15275                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15276                                        fp->rx_sge_mbuf_chain[j].m_map);
15277                 }
15278             }
15279 
15280             if (fp->rx_sge_mbuf_spare_map != NULL) {
15281                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15282                                   fp->rx_sge_mbuf_spare_map);
15283                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15284                                    fp->rx_sge_mbuf_spare_map);
15285             }
15286 
15287             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15288             fp->rx_sge_mbuf_tag = NULL;
15289         }
15290     }
15291 
15292     /***************************/
15293     /* FW DECOMPRESSION BUFFER */
15294     /***************************/
15295 
15296     bxe_dma_free(sc, &sc->gz_buf_dma);
15297     sc->gz_buf = NULL;
15298     free(sc->gz_strm, M_DEVBUF);
15299     sc->gz_strm = NULL;
15300 
15301     /*******************/
15302     /* SLOW PATH QUEUE */
15303     /*******************/
15304 
15305     bxe_dma_free(sc, &sc->spq_dma);
15306     sc->spq = NULL;
15307 
15308     /*************/
15309     /* SLOW PATH */
15310     /*************/
15311 
15312     bxe_dma_free(sc, &sc->sp_dma);
15313     sc->sp = NULL;
15314 
15315     /***************/
15316     /* EVENT QUEUE */
15317     /***************/
15318 
15319     bxe_dma_free(sc, &sc->eq_dma);
15320     sc->eq = NULL;
15321 
15322     /************************/
15323     /* DEFAULT STATUS BLOCK */
15324     /************************/
15325 
15326     bxe_dma_free(sc, &sc->def_sb_dma);
15327     sc->def_sb = NULL;
15328 
15329     bus_dma_tag_destroy(sc->parent_dma_tag);
15330     sc->parent_dma_tag = NULL;
15331 }
15332 
15333 /*
15334  * Previous driver DMAE transaction may have occurred when pre-boot stage
15335  * ended and boot began. This would invalidate the addresses of the
15336  * transaction, resulting in was-error bit set in the PCI causing all
15337  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15338  * the interrupt which detected this from the pglueb and the was-done bit
15339  */
15340 static void
15341 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15342 {
15343     uint32_t val;
15344 
15345     if (!CHIP_IS_E1x(sc)) {
15346         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15347         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15348             BLOGD(sc, DBG_LOAD,
15349                   "Clearing 'was-error' bit that was set in pglueb");
15350             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15351         }
15352     }
15353 }
15354 
15355 static int
15356 bxe_prev_mcp_done(struct bxe_softc *sc)
15357 {
15358     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15359                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15360     if (!rc) {
15361         BLOGE(sc, "MCP response failure, aborting\n");
15362         return (-1);
15363     }
15364 
15365     return (0);
15366 }
15367 
15368 static struct bxe_prev_list_node *
15369 bxe_prev_path_get_entry(struct bxe_softc *sc)
15370 {
15371     struct bxe_prev_list_node *tmp;
15372 
15373     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15374         if ((sc->pcie_bus == tmp->bus) &&
15375             (sc->pcie_device == tmp->slot) &&
15376             (SC_PATH(sc) == tmp->path)) {
15377             return (tmp);
15378         }
15379     }
15380 
15381     return (NULL);
15382 }
15383 
15384 static uint8_t
15385 bxe_prev_is_path_marked(struct bxe_softc *sc)
15386 {
15387     struct bxe_prev_list_node *tmp;
15388     int rc = FALSE;
15389 
15390     mtx_lock(&bxe_prev_mtx);
15391 
15392     tmp = bxe_prev_path_get_entry(sc);
15393     if (tmp) {
15394         if (tmp->aer) {
15395             BLOGD(sc, DBG_LOAD,
15396                   "Path %d/%d/%d was marked by AER\n",
15397                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15398         } else {
15399             rc = TRUE;
15400             BLOGD(sc, DBG_LOAD,
15401                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15402                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15403         }
15404     }
15405 
15406     mtx_unlock(&bxe_prev_mtx);
15407 
15408     return (rc);
15409 }
15410 
15411 static int
15412 bxe_prev_mark_path(struct bxe_softc *sc,
15413                    uint8_t          after_undi)
15414 {
15415     struct bxe_prev_list_node *tmp;
15416 
15417     mtx_lock(&bxe_prev_mtx);
15418 
15419     /* Check whether the entry for this path already exists */
15420     tmp = bxe_prev_path_get_entry(sc);
15421     if (tmp) {
15422         if (!tmp->aer) {
15423             BLOGD(sc, DBG_LOAD,
15424                   "Re-marking AER in path %d/%d/%d\n",
15425                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15426         } else {
15427             BLOGD(sc, DBG_LOAD,
15428                   "Removing AER indication from path %d/%d/%d\n",
15429                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15430             tmp->aer = 0;
15431         }
15432 
15433         mtx_unlock(&bxe_prev_mtx);
15434         return (0);
15435     }
15436 
15437     mtx_unlock(&bxe_prev_mtx);
15438 
15439     /* Create an entry for this path and add it */
15440     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15441                  (M_NOWAIT | M_ZERO));
15442     if (!tmp) {
15443         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15444         return (-1);
15445     }
15446 
15447     tmp->bus  = sc->pcie_bus;
15448     tmp->slot = sc->pcie_device;
15449     tmp->path = SC_PATH(sc);
15450     tmp->aer  = 0;
15451     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15452 
15453     mtx_lock(&bxe_prev_mtx);
15454 
15455     BLOGD(sc, DBG_LOAD,
15456           "Marked path %d/%d/%d - finished previous unload\n",
15457           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15458     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15459 
15460     mtx_unlock(&bxe_prev_mtx);
15461 
15462     return (0);
15463 }
15464 
15465 static int
15466 bxe_do_flr(struct bxe_softc *sc)
15467 {
15468     int i;
15469 
15470     /* only E2 and onwards support FLR */
15471     if (CHIP_IS_E1x(sc)) {
15472         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15473         return (-1);
15474     }
15475 
15476     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15477     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15478         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15479               sc->devinfo.bc_ver);
15480         return (-1);
15481     }
15482 
15483     /* Wait for Transaction Pending bit clean */
15484     for (i = 0; i < 4; i++) {
15485         if (i) {
15486             DELAY(((1 << (i - 1)) * 100) * 1000);
15487         }
15488 
15489         if (!bxe_is_pcie_pending(sc)) {
15490             goto clear;
15491         }
15492     }
15493 
15494     BLOGE(sc, "PCIE transaction is not cleared, "
15495               "proceeding with reset anyway\n");
15496 
15497 clear:
15498 
15499     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15500     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15501 
15502     return (0);
15503 }
15504 
15505 struct bxe_mac_vals {
15506     uint32_t xmac_addr;
15507     uint32_t xmac_val;
15508     uint32_t emac_addr;
15509     uint32_t emac_val;
15510     uint32_t umac_addr;
15511     uint32_t umac_val;
15512     uint32_t bmac_addr;
15513     uint32_t bmac_val[2];
15514 };
15515 
15516 static void
15517 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15518                           struct bxe_mac_vals *vals)
15519 {
15520     uint32_t val, base_addr, offset, mask, reset_reg;
15521     uint8_t mac_stopped = FALSE;
15522     uint8_t port = SC_PORT(sc);
15523     uint32_t wb_data[2];
15524 
15525     /* reset addresses as they also mark which values were changed */
15526     vals->bmac_addr = 0;
15527     vals->umac_addr = 0;
15528     vals->xmac_addr = 0;
15529     vals->emac_addr = 0;
15530 
15531     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15532 
15533     if (!CHIP_IS_E3(sc)) {
15534         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15535         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15536         if ((mask & reset_reg) && val) {
15537             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15538             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15539                                     : NIG_REG_INGRESS_BMAC0_MEM;
15540             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15541                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15542 
15543             /*
15544              * use rd/wr since we cannot use dmae. This is safe
15545              * since MCP won't access the bus due to the request
15546              * to unload, and no function on the path can be
15547              * loaded at this time.
15548              */
15549             wb_data[0] = REG_RD(sc, base_addr + offset);
15550             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15551             vals->bmac_addr = base_addr + offset;
15552             vals->bmac_val[0] = wb_data[0];
15553             vals->bmac_val[1] = wb_data[1];
15554             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15555             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15556             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15557         }
15558 
15559         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15560         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15561         vals->emac_val = REG_RD(sc, vals->emac_addr);
15562         REG_WR(sc, vals->emac_addr, 0);
15563         mac_stopped = TRUE;
15564     } else {
15565         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15566             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15567             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15568             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15569             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15570             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15571             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15572             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15573             REG_WR(sc, vals->xmac_addr, 0);
15574             mac_stopped = TRUE;
15575         }
15576 
15577         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15578         if (mask & reset_reg) {
15579             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15580             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15581             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15582             vals->umac_val = REG_RD(sc, vals->umac_addr);
15583             REG_WR(sc, vals->umac_addr, 0);
15584             mac_stopped = TRUE;
15585         }
15586     }
15587 
15588     if (mac_stopped) {
15589         DELAY(20000);
15590     }
15591 }
15592 
15593 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15594 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15595 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15596 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15597 
15598 static void
15599 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15600                          uint8_t          port,
15601                          uint8_t          inc)
15602 {
15603     uint16_t rcq, bd;
15604     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15605 
15606     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15607     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15608 
15609     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15610     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15611 
15612     BLOGD(sc, DBG_LOAD,
15613           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15614           port, bd, rcq);
15615 }
15616 
15617 static int
15618 bxe_prev_unload_common(struct bxe_softc *sc)
15619 {
15620     uint32_t reset_reg, tmp_reg = 0, rc;
15621     uint8_t prev_undi = FALSE;
15622     struct bxe_mac_vals mac_vals;
15623     uint32_t timer_count = 1000;
15624     uint32_t prev_brb;
15625 
15626     /*
15627      * It is possible a previous function received 'common' answer,
15628      * but hasn't loaded yet, therefore creating a scenario of
15629      * multiple functions receiving 'common' on the same path.
15630      */
15631     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15632 
15633     memset(&mac_vals, 0, sizeof(mac_vals));
15634 
15635     if (bxe_prev_is_path_marked(sc)) {
15636         return (bxe_prev_mcp_done(sc));
15637     }
15638 
15639     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15640 
15641     /* Reset should be performed after BRB is emptied */
15642     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15643         /* Close the MAC Rx to prevent BRB from filling up */
15644         bxe_prev_unload_close_mac(sc, &mac_vals);
15645 
15646         /* close LLH filters towards the BRB */
15647         elink_set_rx_filter(&sc->link_params, 0);
15648 
15649         /*
15650          * Check if the UNDI driver was previously loaded.
15651          * UNDI driver initializes CID offset for normal bell to 0x7
15652          */
15653         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15654             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15655             if (tmp_reg == 0x7) {
15656                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15657                 prev_undi = TRUE;
15658                 /* clear the UNDI indication */
15659                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15660                 /* clear possible idle check errors */
15661                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15662             }
15663         }
15664 
15665         /* wait until BRB is empty */
15666         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15667         while (timer_count) {
15668             prev_brb = tmp_reg;
15669 
15670             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15671             if (!tmp_reg) {
15672                 break;
15673             }
15674 
15675             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15676 
15677             /* reset timer as long as BRB actually gets emptied */
15678             if (prev_brb > tmp_reg) {
15679                 timer_count = 1000;
15680             } else {
15681                 timer_count--;
15682             }
15683 
15684             /* If UNDI resides in memory, manually increment it */
15685             if (prev_undi) {
15686                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15687             }
15688 
15689             DELAY(10);
15690         }
15691 
15692         if (!timer_count) {
15693             BLOGE(sc, "Failed to empty BRB\n");
15694         }
15695     }
15696 
15697     /* No packets are in the pipeline, path is ready for reset */
15698     bxe_reset_common(sc);
15699 
15700     if (mac_vals.xmac_addr) {
15701         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15702     }
15703     if (mac_vals.umac_addr) {
15704         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15705     }
15706     if (mac_vals.emac_addr) {
15707         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15708     }
15709     if (mac_vals.bmac_addr) {
15710         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15711         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15712     }
15713 
15714     rc = bxe_prev_mark_path(sc, prev_undi);
15715     if (rc) {
15716         bxe_prev_mcp_done(sc);
15717         return (rc);
15718     }
15719 
15720     return (bxe_prev_mcp_done(sc));
15721 }
15722 
15723 static int
15724 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15725 {
15726     int rc;
15727 
15728     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15729 
15730     /* Test if previous unload process was already finished for this path */
15731     if (bxe_prev_is_path_marked(sc)) {
15732         return (bxe_prev_mcp_done(sc));
15733     }
15734 
15735     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15736 
15737     /*
15738      * If function has FLR capabilities, and existing FW version matches
15739      * the one required, then FLR will be sufficient to clean any residue
15740      * left by previous driver
15741      */
15742     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15743     if (!rc) {
15744         /* fw version is good */
15745         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15746         rc = bxe_do_flr(sc);
15747     }
15748 
15749     if (!rc) {
15750         /* FLR was performed */
15751         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15752         return (0);
15753     }
15754 
15755     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15756 
15757     /* Close the MCP request, return failure*/
15758     rc = bxe_prev_mcp_done(sc);
15759     if (!rc) {
15760         rc = BXE_PREV_WAIT_NEEDED;
15761     }
15762 
15763     return (rc);
15764 }
15765 
15766 static int
15767 bxe_prev_unload(struct bxe_softc *sc)
15768 {
15769     int time_counter = 10;
15770     uint32_t fw, hw_lock_reg, hw_lock_val;
15771     uint32_t rc = 0;
15772 
15773     /*
15774      * Clear HW from errors which may have resulted from an interrupted
15775      * DMAE transaction.
15776      */
15777     bxe_prev_interrupted_dmae(sc);
15778 
15779     /* Release previously held locks */
15780     hw_lock_reg =
15781         (SC_FUNC(sc) <= 5) ?
15782             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15783             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15784 
15785     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15786     if (hw_lock_val) {
15787         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15788             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15789             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15790                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15791         }
15792         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15793         REG_WR(sc, hw_lock_reg, 0xffffffff);
15794     } else {
15795         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15796     }
15797 
15798     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15799         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15800         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15801     }
15802 
15803     do {
15804         /* Lock MCP using an unload request */
15805         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15806         if (!fw) {
15807             BLOGE(sc, "MCP response failure, aborting\n");
15808             rc = -1;
15809             break;
15810         }
15811 
15812         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15813             rc = bxe_prev_unload_common(sc);
15814             break;
15815         }
15816 
15817         /* non-common reply from MCP night require looping */
15818         rc = bxe_prev_unload_uncommon(sc);
15819         if (rc != BXE_PREV_WAIT_NEEDED) {
15820             break;
15821         }
15822 
15823         DELAY(20000);
15824     } while (--time_counter);
15825 
15826     if (!time_counter || rc) {
15827         BLOGE(sc, "Failed to unload previous driver!"
15828             " time_counter %d rc %d\n", time_counter, rc);
15829         rc = -1;
15830     }
15831 
15832     return (rc);
15833 }
15834 
15835 void
15836 bxe_dcbx_set_state(struct bxe_softc *sc,
15837                    uint8_t          dcb_on,
15838                    uint32_t         dcbx_enabled)
15839 {
15840     if (!CHIP_IS_E1x(sc)) {
15841         sc->dcb_state = dcb_on;
15842         sc->dcbx_enabled = dcbx_enabled;
15843     } else {
15844         sc->dcb_state = FALSE;
15845         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15846     }
15847     BLOGD(sc, DBG_LOAD,
15848           "DCB state [%s:%s]\n",
15849           dcb_on ? "ON" : "OFF",
15850           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15851           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15852           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15853           "on-chip with negotiation" : "invalid");
15854 }
15855 
15856 /* must be called after sriov-enable */
15857 static int
15858 bxe_set_qm_cid_count(struct bxe_softc *sc)
15859 {
15860     int cid_count = BXE_L2_MAX_CID(sc);
15861 
15862     if (IS_SRIOV(sc)) {
15863         cid_count += BXE_VF_CIDS;
15864     }
15865 
15866     if (CNIC_SUPPORT(sc)) {
15867         cid_count += CNIC_CID_MAX;
15868     }
15869 
15870     return (roundup(cid_count, QM_CID_ROUND));
15871 }
15872 
15873 static void
15874 bxe_init_multi_cos(struct bxe_softc *sc)
15875 {
15876     int pri, cos;
15877 
15878     uint32_t pri_map = 0; /* XXX change to user config */
15879 
15880     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15881         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15882         if (cos < sc->max_cos) {
15883             sc->prio_to_cos[pri] = cos;
15884         } else {
15885             BLOGW(sc, "Invalid COS %d for priority %d "
15886                       "(max COS is %d), setting to 0\n",
15887                   cos, pri, (sc->max_cos - 1));
15888             sc->prio_to_cos[pri] = 0;
15889         }
15890     }
15891 }
15892 
15893 static int
15894 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15895 {
15896     struct bxe_softc *sc;
15897     int error, result;
15898 
15899     result = 0;
15900     error = sysctl_handle_int(oidp, &result, 0, req);
15901 
15902     if (error || !req->newptr) {
15903         return (error);
15904     }
15905 
15906     if (result == 1) {
15907         uint32_t  temp;
15908         sc = (struct bxe_softc *)arg1;
15909 
15910         BLOGI(sc, "... dumping driver state ...\n");
15911         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15912         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15913     }
15914 
15915     return (error);
15916 }
15917 
15918 static int
15919 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15920 {
15921     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15922     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15923     uint32_t *offset;
15924     uint64_t value = 0;
15925     int index = (int)arg2;
15926 
15927     if (index >= BXE_NUM_ETH_STATS) {
15928         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15929         return (-1);
15930     }
15931 
15932     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15933 
15934     switch (bxe_eth_stats_arr[index].size) {
15935     case 4:
15936         value = (uint64_t)*offset;
15937         break;
15938     case 8:
15939         value = HILO_U64(*offset, *(offset + 1));
15940         break;
15941     default:
15942         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15943               index, bxe_eth_stats_arr[index].size);
15944         return (-1);
15945     }
15946 
15947     return (sysctl_handle_64(oidp, &value, 0, req));
15948 }
15949 
15950 static int
15951 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15952 {
15953     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15954     uint32_t *eth_stats;
15955     uint32_t *offset;
15956     uint64_t value = 0;
15957     uint32_t q_stat = (uint32_t)arg2;
15958     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15959     uint32_t index = (q_stat & 0xffff);
15960 
15961     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15962 
15963     if (index >= BXE_NUM_ETH_Q_STATS) {
15964         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15965         return (-1);
15966     }
15967 
15968     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15969 
15970     switch (bxe_eth_q_stats_arr[index].size) {
15971     case 4:
15972         value = (uint64_t)*offset;
15973         break;
15974     case 8:
15975         value = HILO_U64(*offset, *(offset + 1));
15976         break;
15977     default:
15978         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15979               index, bxe_eth_q_stats_arr[index].size);
15980         return (-1);
15981     }
15982 
15983     return (sysctl_handle_64(oidp, &value, 0, req));
15984 }
15985 
15986 static void bxe_force_link_reset(struct bxe_softc *sc)
15987 {
15988 
15989         bxe_acquire_phy_lock(sc);
15990         elink_link_reset(&sc->link_params, &sc->link_vars, 1);
15991         bxe_release_phy_lock(sc);
15992 }
15993 
15994 static int
15995 bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
15996 {
15997         struct bxe_softc *sc = (struct bxe_softc *)arg1;;
15998         uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
15999         int rc = 0;
16000         int error;
16001         int result;
16002 
16003 
16004         error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
16005 
16006         if (error || !req->newptr) {
16007                 return (error);
16008         }
16009         if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
16010                 BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
16011                 sc->bxe_pause_param = 8;
16012         }
16013 
16014         result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
16015 
16016 
16017         if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
16018                         BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
16019                         return -EINVAL;
16020         }
16021 
16022         if(IS_MF(sc))
16023                 return 0;
16024        sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
16025         if(result & ELINK_FLOW_CTRL_RX)
16026                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
16027 
16028         if(result & ELINK_FLOW_CTRL_TX)
16029                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
16030         if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
16031                 sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
16032 
16033         if(result & 0x400) {
16034                 if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
16035                         sc->link_params.req_flow_ctrl[cfg_idx] =
16036                                 ELINK_FLOW_CTRL_AUTO;
16037                 }
16038                 sc->link_params.req_fc_auto_adv = 0;
16039                 if (result & ELINK_FLOW_CTRL_RX)
16040                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
16041 
16042                 if (result & ELINK_FLOW_CTRL_TX)
16043                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
16044                 if (!sc->link_params.req_fc_auto_adv)
16045                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
16046         }
16047          if (IS_PF(sc)) {
16048                         if (sc->link_vars.link_up) {
16049                                 bxe_stats_handle(sc, STATS_EVENT_STOP);
16050                         }
16051 			if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
16052                         bxe_force_link_reset(sc);
16053                         bxe_acquire_phy_lock(sc);
16054 
16055                         rc = elink_phy_init(&sc->link_params, &sc->link_vars);
16056 
16057                         bxe_release_phy_lock(sc);
16058 
16059                         bxe_calc_fc_adv(sc);
16060                         }
16061         }
16062         return rc;
16063 }
16064 
16065 
16066 static void
16067 bxe_add_sysctls(struct bxe_softc *sc)
16068 {
16069     struct sysctl_ctx_list *ctx;
16070     struct sysctl_oid_list *children;
16071     struct sysctl_oid *queue_top, *queue;
16072     struct sysctl_oid_list *queue_top_children, *queue_children;
16073     char queue_num_buf[32];
16074     uint32_t q_stat;
16075     int i, j;
16076 
16077     ctx = device_get_sysctl_ctx(sc->dev);
16078     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
16079 
16080     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
16081                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
16082                       "version");
16083 
16084     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
16085              BCM_5710_FW_MAJOR_VERSION,
16086              BCM_5710_FW_MINOR_VERSION,
16087              BCM_5710_FW_REVISION_VERSION,
16088              BCM_5710_FW_ENGINEERING_VERSION);
16089 
16090     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
16091         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
16092          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
16093          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
16094          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
16095                                                                 "Unknown"));
16096     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
16097                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
16098                     "multifunction vnics per port");
16099 
16100     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
16101         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
16102          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
16103          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
16104                                               "???GT/s"),
16105         sc->devinfo.pcie_link_width);
16106 
16107     sc->debug = bxe_debug;
16108 
16109 #if __FreeBSD_version >= 900000
16110     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16111                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
16112                       "bootcode version");
16113     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16114                       CTLFLAG_RD, sc->fw_ver_str, 0,
16115                       "firmware version");
16116     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16117                       CTLFLAG_RD, sc->mf_mode_str, 0,
16118                       "multifunction mode");
16119     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16120                       CTLFLAG_RD, sc->mac_addr_str, 0,
16121                       "mac address");
16122     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16123                       CTLFLAG_RD, sc->pci_link_str, 0,
16124                       "pci link status");
16125     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
16126                     CTLFLAG_RW, &sc->debug,
16127                     "debug logging mode");
16128 #else
16129     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16130                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
16131                       "bootcode version");
16132     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16133                       CTLFLAG_RD, &sc->fw_ver_str, 0,
16134                       "firmware version");
16135     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16136                       CTLFLAG_RD, &sc->mf_mode_str, 0,
16137                       "multifunction mode");
16138     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16139                       CTLFLAG_RD, &sc->mac_addr_str, 0,
16140                       "mac address");
16141     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16142                       CTLFLAG_RD, &sc->pci_link_str, 0,
16143                       "pci link status");
16144     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
16145                     CTLFLAG_RW, &sc->debug, 0,
16146                     "debug logging mode");
16147 #endif /* #if __FreeBSD_version >= 900000 */
16148 
16149     sc->trigger_grcdump = 0;
16150     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
16151                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
16152                    "trigger grcdump should be invoked"
16153                    "  before collecting grcdump");
16154 
16155     sc->grcdump_started = 0;
16156     sc->grcdump_done = 0;
16157     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
16158                    CTLFLAG_RD, &sc->grcdump_done, 0,
16159                    "set by driver when grcdump is done");
16160 
16161     sc->rx_budget = bxe_rx_budget;
16162     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
16163                     CTLFLAG_RW, &sc->rx_budget, 0,
16164                     "rx processing budget");
16165 
16166    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
16167                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
16168                     bxe_sysctl_pauseparam, "IU",
16169                     "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
16170 
16171 
16172     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
16173                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
16174                     bxe_sysctl_state, "IU", "dump driver state");
16175 
16176     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
16177         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
16178                         bxe_eth_stats_arr[i].string,
16179                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
16180                         bxe_sysctl_eth_stat, "LU",
16181                         bxe_eth_stats_arr[i].string);
16182     }
16183 
16184     /* add a new parent node for all queues "dev.bxe.#.queue" */
16185     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
16186                                 CTLFLAG_RD, NULL, "queue");
16187     queue_top_children = SYSCTL_CHILDREN(queue_top);
16188 
16189     for (i = 0; i < sc->num_queues; i++) {
16190         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
16191         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
16192         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
16193                                 queue_num_buf, CTLFLAG_RD, NULL,
16194                                 "single queue");
16195         queue_children = SYSCTL_CHILDREN(queue);
16196 
16197         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
16198             q_stat = ((i << 16) | j);
16199             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
16200                             bxe_eth_q_stats_arr[j].string,
16201                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
16202                             bxe_sysctl_eth_q_stat, "LU",
16203                             bxe_eth_q_stats_arr[j].string);
16204         }
16205     }
16206 }
16207 
16208 static int
16209 bxe_alloc_buf_rings(struct bxe_softc *sc)
16210 {
16211 #if __FreeBSD_version >= 901504
16212 
16213     int i;
16214     struct bxe_fastpath *fp;
16215 
16216     for (i = 0; i < sc->num_queues; i++) {
16217 
16218         fp = &sc->fp[i];
16219 
16220         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
16221                                    M_NOWAIT, &fp->tx_mtx);
16222         if (fp->tx_br == NULL)
16223             return (-1);
16224     }
16225 #endif
16226     return (0);
16227 }
16228 
16229 static void
16230 bxe_free_buf_rings(struct bxe_softc *sc)
16231 {
16232 #if __FreeBSD_version >= 901504
16233 
16234     int i;
16235     struct bxe_fastpath *fp;
16236 
16237     for (i = 0; i < sc->num_queues; i++) {
16238 
16239         fp = &sc->fp[i];
16240 
16241         if (fp->tx_br) {
16242             buf_ring_free(fp->tx_br, M_DEVBUF);
16243             fp->tx_br = NULL;
16244         }
16245     }
16246 
16247 #endif
16248 }
16249 
16250 static void
16251 bxe_init_fp_mutexs(struct bxe_softc *sc)
16252 {
16253     int i;
16254     struct bxe_fastpath *fp;
16255 
16256     for (i = 0; i < sc->num_queues; i++) {
16257 
16258         fp = &sc->fp[i];
16259 
16260         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
16261             "bxe%d_fp%d_tx_lock", sc->unit, i);
16262         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
16263 
16264         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
16265             "bxe%d_fp%d_rx_lock", sc->unit, i);
16266         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
16267     }
16268 }
16269 
16270 static void
16271 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
16272 {
16273     int i;
16274     struct bxe_fastpath *fp;
16275 
16276     for (i = 0; i < sc->num_queues; i++) {
16277 
16278         fp = &sc->fp[i];
16279 
16280         if (mtx_initialized(&fp->tx_mtx)) {
16281             mtx_destroy(&fp->tx_mtx);
16282         }
16283 
16284         if (mtx_initialized(&fp->rx_mtx)) {
16285             mtx_destroy(&fp->rx_mtx);
16286         }
16287     }
16288 }
16289 
16290 
16291 /*
16292  * Device attach function.
16293  *
16294  * Allocates device resources, performs secondary chip identification, and
16295  * initializes driver instance variables. This function is called from driver
16296  * load after a successful probe.
16297  *
16298  * Returns:
16299  *   0 = Success, >0 = Failure
16300  */
16301 static int
16302 bxe_attach(device_t dev)
16303 {
16304     struct bxe_softc *sc;
16305 
16306     sc = device_get_softc(dev);
16307 
16308     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
16309 
16310     sc->state = BXE_STATE_CLOSED;
16311 
16312     sc->dev  = dev;
16313     sc->unit = device_get_unit(dev);
16314 
16315     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16316 
16317     sc->pcie_bus    = pci_get_bus(dev);
16318     sc->pcie_device = pci_get_slot(dev);
16319     sc->pcie_func   = pci_get_function(dev);
16320 
16321     /* enable bus master capability */
16322     pci_enable_busmaster(dev);
16323 
16324     /* get the BARs */
16325     if (bxe_allocate_bars(sc) != 0) {
16326         return (ENXIO);
16327     }
16328 
16329     /* initialize the mutexes */
16330     bxe_init_mutexes(sc);
16331 
16332     /* prepare the periodic callout */
16333     callout_init(&sc->periodic_callout, 0);
16334 
16335     /* prepare the chip taskqueue */
16336     sc->chip_tq_flags = CHIP_TQ_NONE;
16337     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16338              "bxe%d_chip_tq", sc->unit);
16339     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16340     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16341                                    taskqueue_thread_enqueue,
16342                                    &sc->chip_tq);
16343     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16344                             "%s", sc->chip_tq_name);
16345 
16346     TIMEOUT_TASK_INIT(taskqueue_thread,
16347         &sc->sp_err_timeout_task, 0, bxe_sp_err_timeout_task,  sc);
16348 
16349 
16350     /* get device info and set params */
16351     if (bxe_get_device_info(sc) != 0) {
16352         BLOGE(sc, "getting device info\n");
16353         bxe_deallocate_bars(sc);
16354         pci_disable_busmaster(dev);
16355         return (ENXIO);
16356     }
16357 
16358     /* get final misc params */
16359     bxe_get_params(sc);
16360 
16361     /* set the default MTU (changed via ifconfig) */
16362     sc->mtu = ETHERMTU;
16363 
16364     bxe_set_modes_bitmap(sc);
16365 
16366     /* XXX
16367      * If in AFEX mode and the function is configured for FCoE
16368      * then bail... no L2 allowed.
16369      */
16370 
16371     /* get phy settings from shmem and 'and' against admin settings */
16372     bxe_get_phy_info(sc);
16373 
16374     /* initialize the FreeBSD ifnet interface */
16375     if (bxe_init_ifnet(sc) != 0) {
16376         bxe_release_mutexes(sc);
16377         bxe_deallocate_bars(sc);
16378         pci_disable_busmaster(dev);
16379         return (ENXIO);
16380     }
16381 
16382     if (bxe_add_cdev(sc) != 0) {
16383         if (sc->ifp != NULL) {
16384             ether_ifdetach(sc->ifp);
16385         }
16386         ifmedia_removeall(&sc->ifmedia);
16387         bxe_release_mutexes(sc);
16388         bxe_deallocate_bars(sc);
16389         pci_disable_busmaster(dev);
16390         return (ENXIO);
16391     }
16392 
16393     /* allocate device interrupts */
16394     if (bxe_interrupt_alloc(sc) != 0) {
16395         bxe_del_cdev(sc);
16396         if (sc->ifp != NULL) {
16397             ether_ifdetach(sc->ifp);
16398         }
16399         ifmedia_removeall(&sc->ifmedia);
16400         bxe_release_mutexes(sc);
16401         bxe_deallocate_bars(sc);
16402         pci_disable_busmaster(dev);
16403         return (ENXIO);
16404     }
16405 
16406     bxe_init_fp_mutexs(sc);
16407 
16408     if (bxe_alloc_buf_rings(sc) != 0) {
16409 	bxe_free_buf_rings(sc);
16410         bxe_interrupt_free(sc);
16411         bxe_del_cdev(sc);
16412         if (sc->ifp != NULL) {
16413             ether_ifdetach(sc->ifp);
16414         }
16415         ifmedia_removeall(&sc->ifmedia);
16416         bxe_release_mutexes(sc);
16417         bxe_deallocate_bars(sc);
16418         pci_disable_busmaster(dev);
16419         return (ENXIO);
16420     }
16421 
16422     /* allocate ilt */
16423     if (bxe_alloc_ilt_mem(sc) != 0) {
16424 	bxe_free_buf_rings(sc);
16425         bxe_interrupt_free(sc);
16426         bxe_del_cdev(sc);
16427         if (sc->ifp != NULL) {
16428             ether_ifdetach(sc->ifp);
16429         }
16430         ifmedia_removeall(&sc->ifmedia);
16431         bxe_release_mutexes(sc);
16432         bxe_deallocate_bars(sc);
16433         pci_disable_busmaster(dev);
16434         return (ENXIO);
16435     }
16436 
16437     /* allocate the host hardware/software hsi structures */
16438     if (bxe_alloc_hsi_mem(sc) != 0) {
16439         bxe_free_ilt_mem(sc);
16440 	bxe_free_buf_rings(sc);
16441         bxe_interrupt_free(sc);
16442         bxe_del_cdev(sc);
16443         if (sc->ifp != NULL) {
16444             ether_ifdetach(sc->ifp);
16445         }
16446         ifmedia_removeall(&sc->ifmedia);
16447         bxe_release_mutexes(sc);
16448         bxe_deallocate_bars(sc);
16449         pci_disable_busmaster(dev);
16450         return (ENXIO);
16451     }
16452 
16453     /* need to reset chip if UNDI was active */
16454     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16455         /* init fw_seq */
16456         sc->fw_seq =
16457             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16458              DRV_MSG_SEQ_NUMBER_MASK);
16459         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16460         bxe_prev_unload(sc);
16461     }
16462 
16463 #if 1
16464     /* XXX */
16465     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16466 #else
16467     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16468         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16469         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16470         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16471         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16472         bxe_dcbx_init_params(sc);
16473     } else {
16474         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16475     }
16476 #endif
16477 
16478     /* calculate qm_cid_count */
16479     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16480     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16481 
16482     sc->max_cos = 1;
16483     bxe_init_multi_cos(sc);
16484 
16485     bxe_add_sysctls(sc);
16486 
16487     return (0);
16488 }
16489 
16490 /*
16491  * Device detach function.
16492  *
16493  * Stops the controller, resets the controller, and releases resources.
16494  *
16495  * Returns:
16496  *   0 = Success, >0 = Failure
16497  */
16498 static int
16499 bxe_detach(device_t dev)
16500 {
16501     struct bxe_softc *sc;
16502     if_t ifp;
16503 
16504     sc = device_get_softc(dev);
16505 
16506     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16507 
16508     ifp = sc->ifp;
16509     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16510         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16511         return(EBUSY);
16512     }
16513 
16514     bxe_del_cdev(sc);
16515 
16516     /* stop the periodic callout */
16517     bxe_periodic_stop(sc);
16518 
16519     /* stop the chip taskqueue */
16520     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16521     if (sc->chip_tq) {
16522         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16523         taskqueue_free(sc->chip_tq);
16524         sc->chip_tq = NULL;
16525         taskqueue_drain_timeout(taskqueue_thread,
16526             &sc->sp_err_timeout_task);
16527     }
16528 
16529     /* stop and reset the controller if it was open */
16530     if (sc->state != BXE_STATE_CLOSED) {
16531         BXE_CORE_LOCK(sc);
16532         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16533         sc->state = BXE_STATE_DISABLED;
16534         BXE_CORE_UNLOCK(sc);
16535     }
16536 
16537     /* release the network interface */
16538     if (ifp != NULL) {
16539         ether_ifdetach(ifp);
16540     }
16541     ifmedia_removeall(&sc->ifmedia);
16542 
16543     /* XXX do the following based on driver state... */
16544 
16545     /* free the host hardware/software hsi structures */
16546     bxe_free_hsi_mem(sc);
16547 
16548     /* free ilt */
16549     bxe_free_ilt_mem(sc);
16550 
16551     bxe_free_buf_rings(sc);
16552 
16553     /* release the interrupts */
16554     bxe_interrupt_free(sc);
16555 
16556     /* Release the mutexes*/
16557     bxe_destroy_fp_mutexs(sc);
16558     bxe_release_mutexes(sc);
16559 
16560 
16561     /* Release the PCIe BAR mapped memory */
16562     bxe_deallocate_bars(sc);
16563 
16564     /* Release the FreeBSD interface. */
16565     if (sc->ifp != NULL) {
16566         if_free(sc->ifp);
16567     }
16568 
16569     pci_disable_busmaster(dev);
16570 
16571     return (0);
16572 }
16573 
16574 /*
16575  * Device shutdown function.
16576  *
16577  * Stops and resets the controller.
16578  *
16579  * Returns:
16580  *   Nothing
16581  */
16582 static int
16583 bxe_shutdown(device_t dev)
16584 {
16585     struct bxe_softc *sc;
16586 
16587     sc = device_get_softc(dev);
16588 
16589     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16590 
16591     /* stop the periodic callout */
16592     bxe_periodic_stop(sc);
16593 
16594     if (sc->state != BXE_STATE_CLOSED) {
16595     	BXE_CORE_LOCK(sc);
16596     	bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16597     	BXE_CORE_UNLOCK(sc);
16598     }
16599 
16600     return (0);
16601 }
16602 
16603 void
16604 bxe_igu_ack_sb(struct bxe_softc *sc,
16605                uint8_t          igu_sb_id,
16606                uint8_t          segment,
16607                uint16_t         index,
16608                uint8_t          op,
16609                uint8_t          update)
16610 {
16611     uint32_t igu_addr = sc->igu_base_addr;
16612     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16613     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16614 }
16615 
16616 static void
16617 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16618                      uint8_t          func,
16619                      uint8_t          idu_sb_id,
16620                      uint8_t          is_pf)
16621 {
16622     uint32_t data, ctl, cnt = 100;
16623     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16624     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16625     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16626     uint32_t sb_bit =  1 << (idu_sb_id%32);
16627     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16628     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16629 
16630     /* Not supported in BC mode */
16631     if (CHIP_INT_MODE_IS_BC(sc)) {
16632         return;
16633     }
16634 
16635     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16636              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16637             IGU_REGULAR_CLEANUP_SET |
16638             IGU_REGULAR_BCLEANUP);
16639 
16640     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16641            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16642            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16643 
16644     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16645             data, igu_addr_data);
16646     REG_WR(sc, igu_addr_data, data);
16647 
16648     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16649                       BUS_SPACE_BARRIER_WRITE);
16650     mb();
16651 
16652     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16653             ctl, igu_addr_ctl);
16654     REG_WR(sc, igu_addr_ctl, ctl);
16655 
16656     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16657                       BUS_SPACE_BARRIER_WRITE);
16658     mb();
16659 
16660     /* wait for clean up to finish */
16661     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16662         DELAY(20000);
16663     }
16664 
16665     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16666         BLOGD(sc, DBG_LOAD,
16667               "Unable to finish IGU cleanup: "
16668               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16669               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16670     }
16671 }
16672 
16673 static void
16674 bxe_igu_clear_sb(struct bxe_softc *sc,
16675                  uint8_t          idu_sb_id)
16676 {
16677     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16678 }
16679 
16680 
16681 
16682 
16683 
16684 
16685 
16686 /*******************/
16687 /* ECORE CALLBACKS */
16688 /*******************/
16689 
16690 static void
16691 bxe_reset_common(struct bxe_softc *sc)
16692 {
16693     uint32_t val = 0x1400;
16694 
16695     /* reset_common */
16696     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16697 
16698     if (CHIP_IS_E3(sc)) {
16699         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16700         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16701     }
16702 
16703     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16704 }
16705 
16706 static void
16707 bxe_common_init_phy(struct bxe_softc *sc)
16708 {
16709     uint32_t shmem_base[2];
16710     uint32_t shmem2_base[2];
16711 
16712     /* Avoid common init in case MFW supports LFA */
16713     if (SHMEM2_RD(sc, size) >
16714         (uint32_t)offsetof(struct shmem2_region,
16715                            lfa_host_addr[SC_PORT(sc)])) {
16716         return;
16717     }
16718 
16719     shmem_base[0]  = sc->devinfo.shmem_base;
16720     shmem2_base[0] = sc->devinfo.shmem2_base;
16721 
16722     if (!CHIP_IS_E1x(sc)) {
16723         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16724         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16725     }
16726 
16727     bxe_acquire_phy_lock(sc);
16728     elink_common_init_phy(sc, shmem_base, shmem2_base,
16729                           sc->devinfo.chip_id, 0);
16730     bxe_release_phy_lock(sc);
16731 }
16732 
16733 static void
16734 bxe_pf_disable(struct bxe_softc *sc)
16735 {
16736     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16737 
16738     val &= ~IGU_PF_CONF_FUNC_EN;
16739 
16740     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16741     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16742     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16743 }
16744 
16745 static void
16746 bxe_init_pxp(struct bxe_softc *sc)
16747 {
16748     uint16_t devctl;
16749     int r_order, w_order;
16750 
16751     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16752 
16753     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16754 
16755     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16756 
16757     if (sc->mrrs == -1) {
16758         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16759     } else {
16760         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16761         r_order = sc->mrrs;
16762     }
16763 
16764     ecore_init_pxp_arb(sc, r_order, w_order);
16765 }
16766 
16767 static uint32_t
16768 bxe_get_pretend_reg(struct bxe_softc *sc)
16769 {
16770     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16771     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16772     return (base + (SC_ABS_FUNC(sc)) * stride);
16773 }
16774 
16775 /*
16776  * Called only on E1H or E2.
16777  * When pretending to be PF, the pretend value is the function number 0..7.
16778  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16779  * combination.
16780  */
16781 static int
16782 bxe_pretend_func(struct bxe_softc *sc,
16783                  uint16_t         pretend_func_val)
16784 {
16785     uint32_t pretend_reg;
16786 
16787     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16788         return (-1);
16789     }
16790 
16791     /* get my own pretend register */
16792     pretend_reg = bxe_get_pretend_reg(sc);
16793     REG_WR(sc, pretend_reg, pretend_func_val);
16794     REG_RD(sc, pretend_reg);
16795     return (0);
16796 }
16797 
16798 static void
16799 bxe_iov_init_dmae(struct bxe_softc *sc)
16800 {
16801     return;
16802 }
16803 
16804 static void
16805 bxe_iov_init_dq(struct bxe_softc *sc)
16806 {
16807     return;
16808 }
16809 
16810 /* send a NIG loopback debug packet */
16811 static void
16812 bxe_lb_pckt(struct bxe_softc *sc)
16813 {
16814     uint32_t wb_write[3];
16815 
16816     /* Ethernet source and destination addresses */
16817     wb_write[0] = 0x55555555;
16818     wb_write[1] = 0x55555555;
16819     wb_write[2] = 0x20;     /* SOP */
16820     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16821 
16822     /* NON-IP protocol */
16823     wb_write[0] = 0x09000000;
16824     wb_write[1] = 0x55555555;
16825     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16826     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16827 }
16828 
16829 /*
16830  * Some of the internal memories are not directly readable from the driver.
16831  * To test them we send debug packets.
16832  */
16833 static int
16834 bxe_int_mem_test(struct bxe_softc *sc)
16835 {
16836     int factor;
16837     int count, i;
16838     uint32_t val = 0;
16839 
16840     if (CHIP_REV_IS_FPGA(sc)) {
16841         factor = 120;
16842     } else if (CHIP_REV_IS_EMUL(sc)) {
16843         factor = 200;
16844     } else {
16845         factor = 1;
16846     }
16847 
16848     /* disable inputs of parser neighbor blocks */
16849     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16850     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16851     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16852     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16853 
16854     /*  write 0 to parser credits for CFC search request */
16855     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16856 
16857     /* send Ethernet packet */
16858     bxe_lb_pckt(sc);
16859 
16860     /* TODO do i reset NIG statistic? */
16861     /* Wait until NIG register shows 1 packet of size 0x10 */
16862     count = 1000 * factor;
16863     while (count) {
16864         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16865         val = *BXE_SP(sc, wb_data[0]);
16866         if (val == 0x10) {
16867             break;
16868         }
16869 
16870         DELAY(10000);
16871         count--;
16872     }
16873 
16874     if (val != 0x10) {
16875         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16876         return (-1);
16877     }
16878 
16879     /* wait until PRS register shows 1 packet */
16880     count = (1000 * factor);
16881     while (count) {
16882         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16883         if (val == 1) {
16884             break;
16885         }
16886 
16887         DELAY(10000);
16888         count--;
16889     }
16890 
16891     if (val != 0x1) {
16892         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16893         return (-2);
16894     }
16895 
16896     /* Reset and init BRB, PRS */
16897     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16898     DELAY(50000);
16899     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16900     DELAY(50000);
16901     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16902     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16903 
16904     /* Disable inputs of parser neighbor blocks */
16905     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16906     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16907     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16908     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16909 
16910     /* Write 0 to parser credits for CFC search request */
16911     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16912 
16913     /* send 10 Ethernet packets */
16914     for (i = 0; i < 10; i++) {
16915         bxe_lb_pckt(sc);
16916     }
16917 
16918     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16919     count = (1000 * factor);
16920     while (count) {
16921         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16922         val = *BXE_SP(sc, wb_data[0]);
16923         if (val == 0xb0) {
16924             break;
16925         }
16926 
16927         DELAY(10000);
16928         count--;
16929     }
16930 
16931     if (val != 0xb0) {
16932         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16933         return (-3);
16934     }
16935 
16936     /* Wait until PRS register shows 2 packets */
16937     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16938     if (val != 2) {
16939         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16940     }
16941 
16942     /* Write 1 to parser credits for CFC search request */
16943     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16944 
16945     /* Wait until PRS register shows 3 packets */
16946     DELAY(10000 * factor);
16947 
16948     /* Wait until NIG register shows 1 packet of size 0x10 */
16949     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16950     if (val != 3) {
16951         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16952     }
16953 
16954     /* clear NIG EOP FIFO */
16955     for (i = 0; i < 11; i++) {
16956         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16957     }
16958 
16959     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16960     if (val != 1) {
16961         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16962         return (-4);
16963     }
16964 
16965     /* Reset and init BRB, PRS, NIG */
16966     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16967     DELAY(50000);
16968     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16969     DELAY(50000);
16970     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16971     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16972     if (!CNIC_SUPPORT(sc)) {
16973         /* set NIC mode */
16974         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16975     }
16976 
16977     /* Enable inputs of parser neighbor blocks */
16978     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16979     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16980     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16981     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16982 
16983     return (0);
16984 }
16985 
16986 static void
16987 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16988 {
16989     int is_required;
16990     uint32_t val;
16991     int port;
16992 
16993     is_required = 0;
16994     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16995            SHARED_HW_CFG_FAN_FAILURE_MASK);
16996 
16997     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16998         is_required = 1;
16999     }
17000     /*
17001      * The fan failure mechanism is usually related to the PHY type since
17002      * the power consumption of the board is affected by the PHY. Currently,
17003      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
17004      */
17005     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
17006         for (port = PORT_0; port < PORT_MAX; port++) {
17007             is_required |= elink_fan_failure_det_req(sc,
17008                                                      sc->devinfo.shmem_base,
17009                                                      sc->devinfo.shmem2_base,
17010                                                      port);
17011         }
17012     }
17013 
17014     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
17015 
17016     if (is_required == 0) {
17017         return;
17018     }
17019 
17020     /* Fan failure is indicated by SPIO 5 */
17021     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
17022 
17023     /* set to active low mode */
17024     val = REG_RD(sc, MISC_REG_SPIO_INT);
17025     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
17026     REG_WR(sc, MISC_REG_SPIO_INT, val);
17027 
17028     /* enable interrupt to signal the IGU */
17029     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17030     val |= MISC_SPIO_SPIO5;
17031     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
17032 }
17033 
17034 static void
17035 bxe_enable_blocks_attention(struct bxe_softc *sc)
17036 {
17037     uint32_t val;
17038 
17039     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17040     if (!CHIP_IS_E1x(sc)) {
17041         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
17042     } else {
17043         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
17044     }
17045     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17046     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17047     /*
17048      * mask read length error interrupts in brb for parser
17049      * (parsing unit and 'checksum and crc' unit)
17050      * these errors are legal (PU reads fixed length and CAC can cause
17051      * read length error on truncated packets)
17052      */
17053     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
17054     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
17055     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
17056     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
17057     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
17058     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
17059 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
17060 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
17061     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
17062     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
17063     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
17064 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
17065 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
17066     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
17067     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
17068     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
17069     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
17070 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
17071 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
17072 
17073     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
17074            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
17075            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
17076     if (!CHIP_IS_E1x(sc)) {
17077         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
17078                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
17079     }
17080     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
17081 
17082     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
17083     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
17084     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
17085 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
17086 
17087     if (!CHIP_IS_E1x(sc)) {
17088         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
17089         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
17090     }
17091 
17092     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
17093     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
17094 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
17095     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
17096 }
17097 
17098 /**
17099  * bxe_init_hw_common - initialize the HW at the COMMON phase.
17100  *
17101  * @sc:     driver handle
17102  */
17103 static int
17104 bxe_init_hw_common(struct bxe_softc *sc)
17105 {
17106     uint8_t abs_func_id;
17107     uint32_t val;
17108 
17109     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
17110           SC_ABS_FUNC(sc));
17111 
17112     /*
17113      * take the RESET lock to protect undi_unload flow from accessing
17114      * registers while we are resetting the chip
17115      */
17116     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17117 
17118     bxe_reset_common(sc);
17119 
17120     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
17121 
17122     val = 0xfffc;
17123     if (CHIP_IS_E3(sc)) {
17124         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
17125         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
17126     }
17127 
17128     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
17129 
17130     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17131 
17132     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
17133     BLOGD(sc, DBG_LOAD, "after misc block init\n");
17134 
17135     if (!CHIP_IS_E1x(sc)) {
17136         /*
17137          * 4-port mode or 2-port mode we need to turn off master-enable for
17138          * everyone. After that we turn it back on for self. So, we disregard
17139          * multi-function, and always disable all functions on the given path,
17140          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
17141          */
17142         for (abs_func_id = SC_PATH(sc);
17143              abs_func_id < (E2_FUNC_MAX * 2);
17144              abs_func_id += 2) {
17145             if (abs_func_id == SC_ABS_FUNC(sc)) {
17146                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17147                 continue;
17148             }
17149 
17150             bxe_pretend_func(sc, abs_func_id);
17151 
17152             /* clear pf enable */
17153             bxe_pf_disable(sc);
17154 
17155             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17156         }
17157     }
17158 
17159     BLOGD(sc, DBG_LOAD, "after pf disable\n");
17160 
17161     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
17162 
17163     if (CHIP_IS_E1(sc)) {
17164         /*
17165          * enable HW interrupt from PXP on USDM overflow
17166          * bit 16 on INT_MASK_0
17167          */
17168         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17169     }
17170 
17171     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
17172     bxe_init_pxp(sc);
17173 
17174 #ifdef __BIG_ENDIAN
17175     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
17176     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
17177     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
17178     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
17179     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
17180     /* make sure this value is 0 */
17181     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
17182 
17183     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
17184     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
17185     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
17186     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
17187     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
17188 #endif
17189 
17190     ecore_ilt_init_page_size(sc, INITOP_SET);
17191 
17192     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
17193         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
17194     }
17195 
17196     /* let the HW do it's magic... */
17197     DELAY(100000);
17198 
17199     /* finish PXP init */
17200     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
17201     if (val != 1) {
17202         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
17203             val);
17204         return (-1);
17205     }
17206     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
17207     if (val != 1) {
17208         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
17209         return (-1);
17210     }
17211 
17212     BLOGD(sc, DBG_LOAD, "after pxp init\n");
17213 
17214     /*
17215      * Timer bug workaround for E2 only. We need to set the entire ILT to have
17216      * entries with value "0" and valid bit on. This needs to be done by the
17217      * first PF that is loaded in a path (i.e. common phase)
17218      */
17219     if (!CHIP_IS_E1x(sc)) {
17220 /*
17221  * In E2 there is a bug in the timers block that can cause function 6 / 7
17222  * (i.e. vnic3) to start even if it is marked as "scan-off".
17223  * This occurs when a different function (func2,3) is being marked
17224  * as "scan-off". Real-life scenario for example: if a driver is being
17225  * load-unloaded while func6,7 are down. This will cause the timer to access
17226  * the ilt, translate to a logical address and send a request to read/write.
17227  * Since the ilt for the function that is down is not valid, this will cause
17228  * a translation error which is unrecoverable.
17229  * The Workaround is intended to make sure that when this happens nothing
17230  * fatal will occur. The workaround:
17231  *  1.  First PF driver which loads on a path will:
17232  *      a.  After taking the chip out of reset, by using pretend,
17233  *          it will write "0" to the following registers of
17234  *          the other vnics.
17235  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
17236  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
17237  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
17238  *          And for itself it will write '1' to
17239  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
17240  *          dmae-operations (writing to pram for example.)
17241  *          note: can be done for only function 6,7 but cleaner this
17242  *            way.
17243  *      b.  Write zero+valid to the entire ILT.
17244  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
17245  *          VNIC3 (of that port). The range allocated will be the
17246  *          entire ILT. This is needed to prevent  ILT range error.
17247  *  2.  Any PF driver load flow:
17248  *      a.  ILT update with the physical addresses of the allocated
17249  *          logical pages.
17250  *      b.  Wait 20msec. - note that this timeout is needed to make
17251  *          sure there are no requests in one of the PXP internal
17252  *          queues with "old" ILT addresses.
17253  *      c.  PF enable in the PGLC.
17254  *      d.  Clear the was_error of the PF in the PGLC. (could have
17255  *          occurred while driver was down)
17256  *      e.  PF enable in the CFC (WEAK + STRONG)
17257  *      f.  Timers scan enable
17258  *  3.  PF driver unload flow:
17259  *      a.  Clear the Timers scan_en.
17260  *      b.  Polling for scan_on=0 for that PF.
17261  *      c.  Clear the PF enable bit in the PXP.
17262  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
17263  *      e.  Write zero+valid to all ILT entries (The valid bit must
17264  *          stay set)
17265  *      f.  If this is VNIC 3 of a port then also init
17266  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
17267  *          to the last enrty in the ILT.
17268  *
17269  *      Notes:
17270  *      Currently the PF error in the PGLC is non recoverable.
17271  *      In the future the there will be a recovery routine for this error.
17272  *      Currently attention is masked.
17273  *      Having an MCP lock on the load/unload process does not guarantee that
17274  *      there is no Timer disable during Func6/7 enable. This is because the
17275  *      Timers scan is currently being cleared by the MCP on FLR.
17276  *      Step 2.d can be done only for PF6/7 and the driver can also check if
17277  *      there is error before clearing it. But the flow above is simpler and
17278  *      more general.
17279  *      All ILT entries are written by zero+valid and not just PF6/7
17280  *      ILT entries since in the future the ILT entries allocation for
17281  *      PF-s might be dynamic.
17282  */
17283         struct ilt_client_info ilt_cli;
17284         struct ecore_ilt ilt;
17285 
17286         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
17287         memset(&ilt, 0, sizeof(struct ecore_ilt));
17288 
17289         /* initialize dummy TM client */
17290         ilt_cli.start      = 0;
17291         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
17292         ilt_cli.client_num = ILT_CLIENT_TM;
17293 
17294         /*
17295          * Step 1: set zeroes to all ilt page entries with valid bit on
17296          * Step 2: set the timers first/last ilt entry to point
17297          * to the entire range to prevent ILT range error for 3rd/4th
17298          * vnic (this code assumes existence of the vnic)
17299          *
17300          * both steps performed by call to ecore_ilt_client_init_op()
17301          * with dummy TM client
17302          *
17303          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
17304          * and his brother are split registers
17305          */
17306 
17307         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
17308         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
17309         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17310 
17311         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
17312         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
17313         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
17314     }
17315 
17316     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
17317     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
17318 
17319     if (!CHIP_IS_E1x(sc)) {
17320         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
17321                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17322 
17323         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17324         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17325 
17326         /* let the HW do it's magic... */
17327         do {
17328             DELAY(200000);
17329             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17330         } while (factor-- && (val != 1));
17331 
17332         if (val != 1) {
17333             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17334             return (-1);
17335         }
17336     }
17337 
17338     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17339 
17340     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17341 
17342     bxe_iov_init_dmae(sc);
17343 
17344     /* clean the DMAE memory */
17345     sc->dmae_ready = 1;
17346     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17347 
17348     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17349 
17350     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17351 
17352     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17353 
17354     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17355 
17356     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17357     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17358     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17359     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17360 
17361     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17362 
17363     /* QM queues pointers table */
17364     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17365 
17366     /* soft reset pulse */
17367     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17368     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17369 
17370     if (CNIC_SUPPORT(sc))
17371         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17372 
17373     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17374     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17375     if (!CHIP_REV_IS_SLOW(sc)) {
17376         /* enable hw interrupt from doorbell Q */
17377         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17378     }
17379 
17380     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17381 
17382     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17383     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17384 
17385     if (!CHIP_IS_E1(sc)) {
17386         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17387     }
17388 
17389     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17390         if (IS_MF_AFEX(sc)) {
17391             /*
17392              * configure that AFEX and VLAN headers must be
17393              * received in AFEX mode
17394              */
17395             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17396             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17397             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17398             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17399             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17400         } else {
17401             /*
17402              * Bit-map indicating which L2 hdrs may appear
17403              * after the basic Ethernet header
17404              */
17405             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17406                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17407         }
17408     }
17409 
17410     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17411     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17412     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17413     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17414 
17415     if (!CHIP_IS_E1x(sc)) {
17416         /* reset VFC memories */
17417         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17418                VFC_MEMORIES_RST_REG_CAM_RST |
17419                VFC_MEMORIES_RST_REG_RAM_RST);
17420         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17421                VFC_MEMORIES_RST_REG_CAM_RST |
17422                VFC_MEMORIES_RST_REG_RAM_RST);
17423 
17424         DELAY(20000);
17425     }
17426 
17427     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17428     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17429     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17430     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17431 
17432     /* sync semi rtc */
17433     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17434            0x80000000);
17435     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17436            0x80000000);
17437 
17438     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17439     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17440     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17441 
17442     if (!CHIP_IS_E1x(sc)) {
17443         if (IS_MF_AFEX(sc)) {
17444             /*
17445              * configure that AFEX and VLAN headers must be
17446              * sent in AFEX mode
17447              */
17448             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17449             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17450             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17451             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17452             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17453         } else {
17454             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17455                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17456         }
17457     }
17458 
17459     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17460 
17461     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17462 
17463     if (CNIC_SUPPORT(sc)) {
17464         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17465         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17466         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17467         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17468         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17469         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17470         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17471         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17472         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17473         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17474     }
17475     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17476 
17477     if (sizeof(union cdu_context) != 1024) {
17478         /* we currently assume that a context is 1024 bytes */
17479         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17480               (long)sizeof(union cdu_context));
17481     }
17482 
17483     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17484     val = (4 << 24) + (0 << 12) + 1024;
17485     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17486 
17487     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17488 
17489     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17490     /* enable context validation interrupt from CFC */
17491     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17492 
17493     /* set the thresholds to prevent CFC/CDU race */
17494     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17495     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17496 
17497     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17498         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17499     }
17500 
17501     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17502     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17503 
17504     /* Reset PCIE errors for debug */
17505     REG_WR(sc, 0x2814, 0xffffffff);
17506     REG_WR(sc, 0x3820, 0xffffffff);
17507 
17508     if (!CHIP_IS_E1x(sc)) {
17509         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17510                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17511                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17512         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17513                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17514                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17515                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17516         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17517                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17518                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17519                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17520     }
17521 
17522     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17523 
17524     if (!CHIP_IS_E1(sc)) {
17525         /* in E3 this done in per-port section */
17526         if (!CHIP_IS_E3(sc))
17527             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17528     }
17529 
17530     if (CHIP_IS_E1H(sc)) {
17531         /* not applicable for E2 (and above ...) */
17532         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17533     }
17534 
17535     if (CHIP_REV_IS_SLOW(sc)) {
17536         DELAY(200000);
17537     }
17538 
17539     /* finish CFC init */
17540     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17541     if (val != 1) {
17542         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17543         return (-1);
17544     }
17545     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17546     if (val != 1) {
17547         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17548         return (-1);
17549     }
17550     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17551     if (val != 1) {
17552         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17553         return (-1);
17554     }
17555     REG_WR(sc, CFC_REG_DEBUG0, 0);
17556 
17557     if (CHIP_IS_E1(sc)) {
17558         /* read NIG statistic to see if this is our first up since powerup */
17559         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17560         val = *BXE_SP(sc, wb_data[0]);
17561 
17562         /* do internal memory self test */
17563         if ((val == 0) && bxe_int_mem_test(sc)) {
17564             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17565             return (-1);
17566         }
17567     }
17568 
17569     bxe_setup_fan_failure_detection(sc);
17570 
17571     /* clear PXP2 attentions */
17572     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17573 
17574     bxe_enable_blocks_attention(sc);
17575 
17576     if (!CHIP_REV_IS_SLOW(sc)) {
17577         ecore_enable_blocks_parity(sc);
17578     }
17579 
17580     if (!BXE_NOMCP(sc)) {
17581         if (CHIP_IS_E1x(sc)) {
17582             bxe_common_init_phy(sc);
17583         }
17584     }
17585 
17586     return (0);
17587 }
17588 
17589 /**
17590  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17591  *
17592  * @sc:     driver handle
17593  */
17594 static int
17595 bxe_init_hw_common_chip(struct bxe_softc *sc)
17596 {
17597     int rc = bxe_init_hw_common(sc);
17598 
17599     if (rc) {
17600         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17601         return (rc);
17602     }
17603 
17604     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17605     if (!BXE_NOMCP(sc)) {
17606         bxe_common_init_phy(sc);
17607     }
17608 
17609     return (0);
17610 }
17611 
17612 static int
17613 bxe_init_hw_port(struct bxe_softc *sc)
17614 {
17615     int port = SC_PORT(sc);
17616     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17617     uint32_t low, high;
17618     uint32_t val;
17619 
17620     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17621 
17622     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17623 
17624     ecore_init_block(sc, BLOCK_MISC, init_phase);
17625     ecore_init_block(sc, BLOCK_PXP, init_phase);
17626     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17627 
17628     /*
17629      * Timers bug workaround: disables the pf_master bit in pglue at
17630      * common phase, we need to enable it here before any dmae access are
17631      * attempted. Therefore we manually added the enable-master to the
17632      * port phase (it also happens in the function phase)
17633      */
17634     if (!CHIP_IS_E1x(sc)) {
17635         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17636     }
17637 
17638     ecore_init_block(sc, BLOCK_ATC, init_phase);
17639     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17640     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17641     ecore_init_block(sc, BLOCK_QM, init_phase);
17642 
17643     ecore_init_block(sc, BLOCK_TCM, init_phase);
17644     ecore_init_block(sc, BLOCK_UCM, init_phase);
17645     ecore_init_block(sc, BLOCK_CCM, init_phase);
17646     ecore_init_block(sc, BLOCK_XCM, init_phase);
17647 
17648     /* QM cid (connection) count */
17649     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17650 
17651     if (CNIC_SUPPORT(sc)) {
17652         ecore_init_block(sc, BLOCK_TM, init_phase);
17653         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17654         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17655     }
17656 
17657     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17658 
17659     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17660 
17661     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17662         if (IS_MF(sc)) {
17663             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17664         } else if (sc->mtu > 4096) {
17665             if (BXE_ONE_PORT(sc)) {
17666                 low = 160;
17667             } else {
17668                 val = sc->mtu;
17669                 /* (24*1024 + val*4)/256 */
17670                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17671             }
17672         } else {
17673             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17674         }
17675         high = (low + 56); /* 14*1024/256 */
17676         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17677         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17678     }
17679 
17680     if (CHIP_IS_MODE_4_PORT(sc)) {
17681         REG_WR(sc, SC_PORT(sc) ?
17682                BRB1_REG_MAC_GUARANTIED_1 :
17683                BRB1_REG_MAC_GUARANTIED_0, 40);
17684     }
17685 
17686     ecore_init_block(sc, BLOCK_PRS, init_phase);
17687     if (CHIP_IS_E3B0(sc)) {
17688         if (IS_MF_AFEX(sc)) {
17689             /* configure headers for AFEX mode */
17690             REG_WR(sc, SC_PORT(sc) ?
17691                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17692                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17693             REG_WR(sc, SC_PORT(sc) ?
17694                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17695                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17696             REG_WR(sc, SC_PORT(sc) ?
17697                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17698                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17699         } else {
17700             /* Ovlan exists only if we are in multi-function +
17701              * switch-dependent mode, in switch-independent there
17702              * is no ovlan headers
17703              */
17704             REG_WR(sc, SC_PORT(sc) ?
17705                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17706                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17707                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17708         }
17709     }
17710 
17711     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17712     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17713     ecore_init_block(sc, BLOCK_USDM, init_phase);
17714     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17715 
17716     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17717     ecore_init_block(sc, BLOCK_USEM, init_phase);
17718     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17719     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17720 
17721     ecore_init_block(sc, BLOCK_UPB, init_phase);
17722     ecore_init_block(sc, BLOCK_XPB, init_phase);
17723 
17724     ecore_init_block(sc, BLOCK_PBF, init_phase);
17725 
17726     if (CHIP_IS_E1x(sc)) {
17727         /* configure PBF to work without PAUSE mtu 9000 */
17728         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17729 
17730         /* update threshold */
17731         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17732         /* update init credit */
17733         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17734 
17735         /* probe changes */
17736         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17737         DELAY(50);
17738         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17739     }
17740 
17741     if (CNIC_SUPPORT(sc)) {
17742         ecore_init_block(sc, BLOCK_SRC, init_phase);
17743     }
17744 
17745     ecore_init_block(sc, BLOCK_CDU, init_phase);
17746     ecore_init_block(sc, BLOCK_CFC, init_phase);
17747 
17748     if (CHIP_IS_E1(sc)) {
17749         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17750         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17751     }
17752     ecore_init_block(sc, BLOCK_HC, init_phase);
17753 
17754     ecore_init_block(sc, BLOCK_IGU, init_phase);
17755 
17756     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17757     /* init aeu_mask_attn_func_0/1:
17758      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17759      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17760      *             bits 4-7 are used for "per vn group attention" */
17761     val = IS_MF(sc) ? 0xF7 : 0x7;
17762     /* Enable DCBX attention for all but E1 */
17763     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17764     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17765 
17766     ecore_init_block(sc, BLOCK_NIG, init_phase);
17767 
17768     if (!CHIP_IS_E1x(sc)) {
17769         /* Bit-map indicating which L2 hdrs may appear after the
17770          * basic Ethernet header
17771          */
17772         if (IS_MF_AFEX(sc)) {
17773             REG_WR(sc, SC_PORT(sc) ?
17774                    NIG_REG_P1_HDRS_AFTER_BASIC :
17775                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17776         } else {
17777             REG_WR(sc, SC_PORT(sc) ?
17778                    NIG_REG_P1_HDRS_AFTER_BASIC :
17779                    NIG_REG_P0_HDRS_AFTER_BASIC,
17780                    IS_MF_SD(sc) ? 7 : 6);
17781         }
17782 
17783         if (CHIP_IS_E3(sc)) {
17784             REG_WR(sc, SC_PORT(sc) ?
17785                    NIG_REG_LLH1_MF_MODE :
17786                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17787         }
17788     }
17789     if (!CHIP_IS_E3(sc)) {
17790         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17791     }
17792 
17793     if (!CHIP_IS_E1(sc)) {
17794         /* 0x2 disable mf_ov, 0x1 enable */
17795         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17796                (IS_MF_SD(sc) ? 0x1 : 0x2));
17797 
17798         if (!CHIP_IS_E1x(sc)) {
17799             val = 0;
17800             switch (sc->devinfo.mf_info.mf_mode) {
17801             case MULTI_FUNCTION_SD:
17802                 val = 1;
17803                 break;
17804             case MULTI_FUNCTION_SI:
17805             case MULTI_FUNCTION_AFEX:
17806                 val = 2;
17807                 break;
17808             }
17809 
17810             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17811                         NIG_REG_LLH0_CLS_TYPE), val);
17812         }
17813         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17814         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17815         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17816     }
17817 
17818     /* If SPIO5 is set to generate interrupts, enable it for this port */
17819     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17820     if (val & MISC_SPIO_SPIO5) {
17821         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17822                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17823         val = REG_RD(sc, reg_addr);
17824         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17825         REG_WR(sc, reg_addr, val);
17826     }
17827 
17828     return (0);
17829 }
17830 
17831 static uint32_t
17832 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17833                        uint32_t         reg,
17834                        uint32_t         expected,
17835                        uint32_t         poll_count)
17836 {
17837     uint32_t cur_cnt = poll_count;
17838     uint32_t val;
17839 
17840     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17841         DELAY(FLR_WAIT_INTERVAL);
17842     }
17843 
17844     return (val);
17845 }
17846 
17847 static int
17848 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17849                               uint32_t         reg,
17850                               char             *msg,
17851                               uint32_t         poll_cnt)
17852 {
17853     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17854 
17855     if (val != 0) {
17856         BLOGE(sc, "%s usage count=%d\n", msg, val);
17857         return (1);
17858     }
17859 
17860     return (0);
17861 }
17862 
17863 /* Common routines with VF FLR cleanup */
17864 static uint32_t
17865 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17866 {
17867     /* adjust polling timeout */
17868     if (CHIP_REV_IS_EMUL(sc)) {
17869         return (FLR_POLL_CNT * 2000);
17870     }
17871 
17872     if (CHIP_REV_IS_FPGA(sc)) {
17873         return (FLR_POLL_CNT * 120);
17874     }
17875 
17876     return (FLR_POLL_CNT);
17877 }
17878 
17879 static int
17880 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17881                            uint32_t         poll_cnt)
17882 {
17883     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17884     if (bxe_flr_clnup_poll_hw_counter(sc,
17885                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17886                                       "CFC PF usage counter timed out",
17887                                       poll_cnt)) {
17888         return (1);
17889     }
17890 
17891     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17892     if (bxe_flr_clnup_poll_hw_counter(sc,
17893                                       DORQ_REG_PF_USAGE_CNT,
17894                                       "DQ PF usage counter timed out",
17895                                       poll_cnt)) {
17896         return (1);
17897     }
17898 
17899     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17900     if (bxe_flr_clnup_poll_hw_counter(sc,
17901                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17902                                       "QM PF usage counter timed out",
17903                                       poll_cnt)) {
17904         return (1);
17905     }
17906 
17907     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17908     if (bxe_flr_clnup_poll_hw_counter(sc,
17909                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17910                                       "Timers VNIC usage counter timed out",
17911                                       poll_cnt)) {
17912         return (1);
17913     }
17914 
17915     if (bxe_flr_clnup_poll_hw_counter(sc,
17916                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17917                                       "Timers NUM_SCANS usage counter timed out",
17918                                       poll_cnt)) {
17919         return (1);
17920     }
17921 
17922     /* Wait DMAE PF usage counter to zero */
17923     if (bxe_flr_clnup_poll_hw_counter(sc,
17924                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17925                                       "DMAE dommand register timed out",
17926                                       poll_cnt)) {
17927         return (1);
17928     }
17929 
17930     return (0);
17931 }
17932 
17933 #define OP_GEN_PARAM(param)                                            \
17934     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17935 #define OP_GEN_TYPE(type)                                           \
17936     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17937 #define OP_GEN_AGG_VECT(index)                                             \
17938     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17939 
17940 static int
17941 bxe_send_final_clnup(struct bxe_softc *sc,
17942                      uint8_t          clnup_func,
17943                      uint32_t         poll_cnt)
17944 {
17945     uint32_t op_gen_command = 0;
17946     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17947                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17948     int ret = 0;
17949 
17950     if (REG_RD(sc, comp_addr)) {
17951         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17952         return (1);
17953     }
17954 
17955     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17956     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17957     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17958     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17959 
17960     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17961     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17962 
17963     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17964         BLOGE(sc, "FW final cleanup did not succeed\n");
17965         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17966               (REG_RD(sc, comp_addr)));
17967         bxe_panic(sc, ("FLR cleanup failed\n"));
17968         return (1);
17969     }
17970 
17971     /* Zero completion for nxt FLR */
17972     REG_WR(sc, comp_addr, 0);
17973 
17974     return (ret);
17975 }
17976 
17977 static void
17978 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17979                        struct pbf_pN_buf_regs *regs,
17980                        uint32_t               poll_count)
17981 {
17982     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17983     uint32_t cur_cnt = poll_count;
17984 
17985     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17986     crd = crd_start = REG_RD(sc, regs->crd);
17987     init_crd = REG_RD(sc, regs->init_crd);
17988 
17989     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17990     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17991     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17992 
17993     while ((crd != init_crd) &&
17994            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17995             (init_crd - crd_start))) {
17996         if (cur_cnt--) {
17997             DELAY(FLR_WAIT_INTERVAL);
17998             crd = REG_RD(sc, regs->crd);
17999             crd_freed = REG_RD(sc, regs->crd_freed);
18000         } else {
18001             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
18002             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
18003             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
18004             break;
18005         }
18006     }
18007 
18008     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
18009           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18010 }
18011 
18012 static void
18013 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
18014                        struct pbf_pN_cmd_regs *regs,
18015                        uint32_t               poll_count)
18016 {
18017     uint32_t occup, to_free, freed, freed_start;
18018     uint32_t cur_cnt = poll_count;
18019 
18020     occup = to_free = REG_RD(sc, regs->lines_occup);
18021     freed = freed_start = REG_RD(sc, regs->lines_freed);
18022 
18023     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18024     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18025 
18026     while (occup &&
18027            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
18028         if (cur_cnt--) {
18029             DELAY(FLR_WAIT_INTERVAL);
18030             occup = REG_RD(sc, regs->lines_occup);
18031             freed = REG_RD(sc, regs->lines_freed);
18032         } else {
18033             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
18034             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18035             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18036             break;
18037         }
18038     }
18039 
18040     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
18041           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18042 }
18043 
18044 static void
18045 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
18046 {
18047     struct pbf_pN_cmd_regs cmd_regs[] = {
18048         {0, (CHIP_IS_E3B0(sc)) ?
18049             PBF_REG_TQ_OCCUPANCY_Q0 :
18050             PBF_REG_P0_TQ_OCCUPANCY,
18051             (CHIP_IS_E3B0(sc)) ?
18052             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
18053             PBF_REG_P0_TQ_LINES_FREED_CNT},
18054         {1, (CHIP_IS_E3B0(sc)) ?
18055             PBF_REG_TQ_OCCUPANCY_Q1 :
18056             PBF_REG_P1_TQ_OCCUPANCY,
18057             (CHIP_IS_E3B0(sc)) ?
18058             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
18059             PBF_REG_P1_TQ_LINES_FREED_CNT},
18060         {4, (CHIP_IS_E3B0(sc)) ?
18061             PBF_REG_TQ_OCCUPANCY_LB_Q :
18062             PBF_REG_P4_TQ_OCCUPANCY,
18063             (CHIP_IS_E3B0(sc)) ?
18064             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
18065             PBF_REG_P4_TQ_LINES_FREED_CNT}
18066     };
18067 
18068     struct pbf_pN_buf_regs buf_regs[] = {
18069         {0, (CHIP_IS_E3B0(sc)) ?
18070             PBF_REG_INIT_CRD_Q0 :
18071             PBF_REG_P0_INIT_CRD ,
18072             (CHIP_IS_E3B0(sc)) ?
18073             PBF_REG_CREDIT_Q0 :
18074             PBF_REG_P0_CREDIT,
18075             (CHIP_IS_E3B0(sc)) ?
18076             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
18077             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
18078         {1, (CHIP_IS_E3B0(sc)) ?
18079             PBF_REG_INIT_CRD_Q1 :
18080             PBF_REG_P1_INIT_CRD,
18081             (CHIP_IS_E3B0(sc)) ?
18082             PBF_REG_CREDIT_Q1 :
18083             PBF_REG_P1_CREDIT,
18084             (CHIP_IS_E3B0(sc)) ?
18085             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
18086             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
18087         {4, (CHIP_IS_E3B0(sc)) ?
18088             PBF_REG_INIT_CRD_LB_Q :
18089             PBF_REG_P4_INIT_CRD,
18090             (CHIP_IS_E3B0(sc)) ?
18091             PBF_REG_CREDIT_LB_Q :
18092             PBF_REG_P4_CREDIT,
18093             (CHIP_IS_E3B0(sc)) ?
18094             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
18095             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
18096     };
18097 
18098     int i;
18099 
18100     /* Verify the command queues are flushed P0, P1, P4 */
18101     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
18102         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
18103     }
18104 
18105     /* Verify the transmission buffers are flushed P0, P1, P4 */
18106     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
18107         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
18108     }
18109 }
18110 
18111 static void
18112 bxe_hw_enable_status(struct bxe_softc *sc)
18113 {
18114     uint32_t val;
18115 
18116     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
18117     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
18118 
18119     val = REG_RD(sc, PBF_REG_DISABLE_PF);
18120     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
18121 
18122     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
18123     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
18124 
18125     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
18126     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
18127 
18128     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
18129     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
18130 
18131     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
18132     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
18133 
18134     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
18135     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
18136 
18137     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
18138     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
18139 }
18140 
18141 static int
18142 bxe_pf_flr_clnup(struct bxe_softc *sc)
18143 {
18144     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
18145 
18146     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
18147 
18148     /* Re-enable PF target read access */
18149     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
18150 
18151     /* Poll HW usage counters */
18152     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
18153     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
18154         return (-1);
18155     }
18156 
18157     /* Zero the igu 'trailing edge' and 'leading edge' */
18158 
18159     /* Send the FW cleanup command */
18160     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
18161         return (-1);
18162     }
18163 
18164     /* ATC cleanup */
18165 
18166     /* Verify TX hw is flushed */
18167     bxe_tx_hw_flushed(sc, poll_cnt);
18168 
18169     /* Wait 100ms (not adjusted according to platform) */
18170     DELAY(100000);
18171 
18172     /* Verify no pending pci transactions */
18173     if (bxe_is_pcie_pending(sc)) {
18174         BLOGE(sc, "PCIE Transactions still pending\n");
18175     }
18176 
18177     /* Debug */
18178     bxe_hw_enable_status(sc);
18179 
18180     /*
18181      * Master enable - Due to WB DMAE writes performed before this
18182      * register is re-initialized as part of the regular function init
18183      */
18184     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18185 
18186     return (0);
18187 }
18188 
18189 static int
18190 bxe_init_hw_func(struct bxe_softc *sc)
18191 {
18192     int port = SC_PORT(sc);
18193     int func = SC_FUNC(sc);
18194     int init_phase = PHASE_PF0 + func;
18195     struct ecore_ilt *ilt = sc->ilt;
18196     uint16_t cdu_ilt_start;
18197     uint32_t addr, val;
18198     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
18199     int i, main_mem_width, rc;
18200 
18201     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
18202 
18203     /* FLR cleanup */
18204     if (!CHIP_IS_E1x(sc)) {
18205         rc = bxe_pf_flr_clnup(sc);
18206         if (rc) {
18207             BLOGE(sc, "FLR cleanup failed!\n");
18208             // XXX bxe_fw_dump(sc);
18209             // XXX bxe_idle_chk(sc);
18210             return (rc);
18211         }
18212     }
18213 
18214     /* set MSI reconfigure capability */
18215     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18216         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
18217         val = REG_RD(sc, addr);
18218         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
18219         REG_WR(sc, addr, val);
18220     }
18221 
18222     ecore_init_block(sc, BLOCK_PXP, init_phase);
18223     ecore_init_block(sc, BLOCK_PXP2, init_phase);
18224 
18225     ilt = sc->ilt;
18226     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
18227 
18228     for (i = 0; i < L2_ILT_LINES(sc); i++) {
18229         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
18230         ilt->lines[cdu_ilt_start + i].page_mapping =
18231             sc->context[i].vcxt_dma.paddr;
18232         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
18233     }
18234     ecore_ilt_init_op(sc, INITOP_SET);
18235 
18236     /* Set NIC mode */
18237     REG_WR(sc, PRS_REG_NIC_MODE, 1);
18238     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
18239 
18240     if (!CHIP_IS_E1x(sc)) {
18241         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
18242 
18243         /* Turn on a single ISR mode in IGU if driver is going to use
18244          * INT#x or MSI
18245          */
18246         if (sc->interrupt_mode != INTR_MODE_MSIX) {
18247             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
18248         }
18249 
18250         /*
18251          * Timers workaround bug: function init part.
18252          * Need to wait 20msec after initializing ILT,
18253          * needed to make sure there are no requests in
18254          * one of the PXP internal queues with "old" ILT addresses
18255          */
18256         DELAY(20000);
18257 
18258         /*
18259          * Master enable - Due to WB DMAE writes performed before this
18260          * register is re-initialized as part of the regular function
18261          * init
18262          */
18263         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18264         /* Enable the function in IGU */
18265         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
18266     }
18267 
18268     sc->dmae_ready = 1;
18269 
18270     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
18271 
18272     if (!CHIP_IS_E1x(sc))
18273         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
18274 
18275     ecore_init_block(sc, BLOCK_ATC, init_phase);
18276     ecore_init_block(sc, BLOCK_DMAE, init_phase);
18277     ecore_init_block(sc, BLOCK_NIG, init_phase);
18278     ecore_init_block(sc, BLOCK_SRC, init_phase);
18279     ecore_init_block(sc, BLOCK_MISC, init_phase);
18280     ecore_init_block(sc, BLOCK_TCM, init_phase);
18281     ecore_init_block(sc, BLOCK_UCM, init_phase);
18282     ecore_init_block(sc, BLOCK_CCM, init_phase);
18283     ecore_init_block(sc, BLOCK_XCM, init_phase);
18284     ecore_init_block(sc, BLOCK_TSEM, init_phase);
18285     ecore_init_block(sc, BLOCK_USEM, init_phase);
18286     ecore_init_block(sc, BLOCK_CSEM, init_phase);
18287     ecore_init_block(sc, BLOCK_XSEM, init_phase);
18288 
18289     if (!CHIP_IS_E1x(sc))
18290         REG_WR(sc, QM_REG_PF_EN, 1);
18291 
18292     if (!CHIP_IS_E1x(sc)) {
18293         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18294         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18295         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18296         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18297     }
18298     ecore_init_block(sc, BLOCK_QM, init_phase);
18299 
18300     ecore_init_block(sc, BLOCK_TM, init_phase);
18301     ecore_init_block(sc, BLOCK_DORQ, init_phase);
18302 
18303     bxe_iov_init_dq(sc);
18304 
18305     ecore_init_block(sc, BLOCK_BRB1, init_phase);
18306     ecore_init_block(sc, BLOCK_PRS, init_phase);
18307     ecore_init_block(sc, BLOCK_TSDM, init_phase);
18308     ecore_init_block(sc, BLOCK_CSDM, init_phase);
18309     ecore_init_block(sc, BLOCK_USDM, init_phase);
18310     ecore_init_block(sc, BLOCK_XSDM, init_phase);
18311     ecore_init_block(sc, BLOCK_UPB, init_phase);
18312     ecore_init_block(sc, BLOCK_XPB, init_phase);
18313     ecore_init_block(sc, BLOCK_PBF, init_phase);
18314     if (!CHIP_IS_E1x(sc))
18315         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
18316 
18317     ecore_init_block(sc, BLOCK_CDU, init_phase);
18318 
18319     ecore_init_block(sc, BLOCK_CFC, init_phase);
18320 
18321     if (!CHIP_IS_E1x(sc))
18322         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18323 
18324     if (IS_MF(sc)) {
18325         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18326         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18327     }
18328 
18329     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18330 
18331     /* HC init per function */
18332     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18333         if (CHIP_IS_E1H(sc)) {
18334             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18335 
18336             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18337             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18338         }
18339         ecore_init_block(sc, BLOCK_HC, init_phase);
18340 
18341     } else {
18342         int num_segs, sb_idx, prod_offset;
18343 
18344         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18345 
18346         if (!CHIP_IS_E1x(sc)) {
18347             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18348             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18349         }
18350 
18351         ecore_init_block(sc, BLOCK_IGU, init_phase);
18352 
18353         if (!CHIP_IS_E1x(sc)) {
18354             int dsb_idx = 0;
18355             /**
18356              * Producer memory:
18357              * E2 mode: address 0-135 match to the mapping memory;
18358              * 136 - PF0 default prod; 137 - PF1 default prod;
18359              * 138 - PF2 default prod; 139 - PF3 default prod;
18360              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18361              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18362              * 144-147 reserved.
18363              *
18364              * E1.5 mode - In backward compatible mode;
18365              * for non default SB; each even line in the memory
18366              * holds the U producer and each odd line hold
18367              * the C producer. The first 128 producers are for
18368              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18369              * producers are for the DSB for each PF.
18370              * Each PF has five segments: (the order inside each
18371              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18372              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18373              * 144-147 attn prods;
18374              */
18375             /* non-default-status-blocks */
18376             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18377                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18378             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18379                 prod_offset = (sc->igu_base_sb + sb_idx) *
18380                     num_segs;
18381 
18382                 for (i = 0; i < num_segs; i++) {
18383                     addr = IGU_REG_PROD_CONS_MEMORY +
18384                             (prod_offset + i) * 4;
18385                     REG_WR(sc, addr, 0);
18386                 }
18387                 /* send consumer update with value 0 */
18388                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18389                            USTORM_ID, 0, IGU_INT_NOP, 1);
18390                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18391             }
18392 
18393             /* default-status-blocks */
18394             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18395                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18396 
18397             if (CHIP_IS_MODE_4_PORT(sc))
18398                 dsb_idx = SC_FUNC(sc);
18399             else
18400                 dsb_idx = SC_VN(sc);
18401 
18402             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18403                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18404                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18405 
18406             /*
18407              * igu prods come in chunks of E1HVN_MAX (4) -
18408              * does not matters what is the current chip mode
18409              */
18410             for (i = 0; i < (num_segs * E1HVN_MAX);
18411                  i += E1HVN_MAX) {
18412                 addr = IGU_REG_PROD_CONS_MEMORY +
18413                             (prod_offset + i)*4;
18414                 REG_WR(sc, addr, 0);
18415             }
18416             /* send consumer update with 0 */
18417             if (CHIP_INT_MODE_IS_BC(sc)) {
18418                 bxe_ack_sb(sc, sc->igu_dsb_id,
18419                            USTORM_ID, 0, IGU_INT_NOP, 1);
18420                 bxe_ack_sb(sc, sc->igu_dsb_id,
18421                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18422                 bxe_ack_sb(sc, sc->igu_dsb_id,
18423                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18424                 bxe_ack_sb(sc, sc->igu_dsb_id,
18425                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18426                 bxe_ack_sb(sc, sc->igu_dsb_id,
18427                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18428             } else {
18429                 bxe_ack_sb(sc, sc->igu_dsb_id,
18430                            USTORM_ID, 0, IGU_INT_NOP, 1);
18431                 bxe_ack_sb(sc, sc->igu_dsb_id,
18432                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18433             }
18434             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18435 
18436             /* !!! these should become driver const once
18437                rf-tool supports split-68 const */
18438             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18439             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18440             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18441             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18442             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18443             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18444         }
18445     }
18446 
18447     /* Reset PCIE errors for debug */
18448     REG_WR(sc, 0x2114, 0xffffffff);
18449     REG_WR(sc, 0x2120, 0xffffffff);
18450 
18451     if (CHIP_IS_E1x(sc)) {
18452         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18453         main_mem_base = HC_REG_MAIN_MEMORY +
18454                 SC_PORT(sc) * (main_mem_size * 4);
18455         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18456         main_mem_width = 8;
18457 
18458         val = REG_RD(sc, main_mem_prty_clr);
18459         if (val) {
18460             BLOGD(sc, DBG_LOAD,
18461                   "Parity errors in HC block during function init (0x%x)!\n",
18462                   val);
18463         }
18464 
18465         /* Clear "false" parity errors in MSI-X table */
18466         for (i = main_mem_base;
18467              i < main_mem_base + main_mem_size * 4;
18468              i += main_mem_width) {
18469             bxe_read_dmae(sc, i, main_mem_width / 4);
18470             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18471                            i, main_mem_width / 4);
18472         }
18473         /* Clear HC parity attention */
18474         REG_RD(sc, main_mem_prty_clr);
18475     }
18476 
18477 #if 1
18478     /* Enable STORMs SP logging */
18479     REG_WR8(sc, BAR_USTRORM_INTMEM +
18480            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18481     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18482            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18483     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18484            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18485     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18486            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18487 #endif
18488 
18489     elink_phy_probe(&sc->link_params);
18490 
18491     return (0);
18492 }
18493 
18494 static void
18495 bxe_link_reset(struct bxe_softc *sc)
18496 {
18497     if (!BXE_NOMCP(sc)) {
18498 	bxe_acquire_phy_lock(sc);
18499         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18500 	bxe_release_phy_lock(sc);
18501     } else {
18502         if (!CHIP_REV_IS_SLOW(sc)) {
18503             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18504         }
18505     }
18506 }
18507 
18508 static void
18509 bxe_reset_port(struct bxe_softc *sc)
18510 {
18511     int port = SC_PORT(sc);
18512     uint32_t val;
18513 
18514 	ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18515     /* reset physical Link */
18516     bxe_link_reset(sc);
18517 
18518     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18519 
18520     /* Do not rcv packets to BRB */
18521     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18522     /* Do not direct rcv packets that are not for MCP to the BRB */
18523     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18524                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18525 
18526     /* Configure AEU */
18527     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18528 
18529     DELAY(100000);
18530 
18531     /* Check for BRB port occupancy */
18532     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18533     if (val) {
18534         BLOGD(sc, DBG_LOAD,
18535               "BRB1 is not empty, %d blocks are occupied\n", val);
18536     }
18537 
18538     /* TODO: Close Doorbell port? */
18539 }
18540 
18541 static void
18542 bxe_ilt_wr(struct bxe_softc *sc,
18543            uint32_t         index,
18544            bus_addr_t       addr)
18545 {
18546     int reg;
18547     uint32_t wb_write[2];
18548 
18549     if (CHIP_IS_E1(sc)) {
18550         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18551     } else {
18552         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18553     }
18554 
18555     wb_write[0] = ONCHIP_ADDR1(addr);
18556     wb_write[1] = ONCHIP_ADDR2(addr);
18557     REG_WR_DMAE(sc, reg, wb_write, 2);
18558 }
18559 
18560 static void
18561 bxe_clear_func_ilt(struct bxe_softc *sc,
18562                    uint32_t         func)
18563 {
18564     uint32_t i, base = FUNC_ILT_BASE(func);
18565     for (i = base; i < base + ILT_PER_FUNC; i++) {
18566         bxe_ilt_wr(sc, i, 0);
18567     }
18568 }
18569 
18570 static void
18571 bxe_reset_func(struct bxe_softc *sc)
18572 {
18573     struct bxe_fastpath *fp;
18574     int port = SC_PORT(sc);
18575     int func = SC_FUNC(sc);
18576     int i;
18577 
18578     /* Disable the function in the FW */
18579     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18580     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18581     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18582     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18583 
18584     /* FP SBs */
18585     FOR_EACH_ETH_QUEUE(sc, i) {
18586         fp = &sc->fp[i];
18587         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18588                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18589                 SB_DISABLED);
18590     }
18591 
18592     /* SP SB */
18593     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18594             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18595             SB_DISABLED);
18596 
18597     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18598         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18599     }
18600 
18601     /* Configure IGU */
18602     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18603         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18604         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18605     } else {
18606         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18607         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18608     }
18609 
18610     if (CNIC_LOADED(sc)) {
18611         /* Disable Timer scan */
18612         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18613         /*
18614          * Wait for at least 10ms and up to 2 second for the timers
18615          * scan to complete
18616          */
18617         for (i = 0; i < 200; i++) {
18618             DELAY(10000);
18619             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18620                 break;
18621         }
18622     }
18623 
18624     /* Clear ILT */
18625     bxe_clear_func_ilt(sc, func);
18626 
18627     /*
18628      * Timers workaround bug for E2: if this is vnic-3,
18629      * we need to set the entire ilt range for this timers.
18630      */
18631     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18632         struct ilt_client_info ilt_cli;
18633         /* use dummy TM client */
18634         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18635         ilt_cli.start = 0;
18636         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18637         ilt_cli.client_num = ILT_CLIENT_TM;
18638 
18639         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18640     }
18641 
18642     /* this assumes that reset_port() called before reset_func()*/
18643     if (!CHIP_IS_E1x(sc)) {
18644         bxe_pf_disable(sc);
18645     }
18646 
18647     sc->dmae_ready = 0;
18648 }
18649 
18650 static int
18651 bxe_gunzip_init(struct bxe_softc *sc)
18652 {
18653     return (0);
18654 }
18655 
18656 static void
18657 bxe_gunzip_end(struct bxe_softc *sc)
18658 {
18659     return;
18660 }
18661 
18662 static int
18663 bxe_init_firmware(struct bxe_softc *sc)
18664 {
18665     if (CHIP_IS_E1(sc)) {
18666         ecore_init_e1_firmware(sc);
18667         sc->iro_array = e1_iro_arr;
18668     } else if (CHIP_IS_E1H(sc)) {
18669         ecore_init_e1h_firmware(sc);
18670         sc->iro_array = e1h_iro_arr;
18671     } else if (!CHIP_IS_E1x(sc)) {
18672         ecore_init_e2_firmware(sc);
18673         sc->iro_array = e2_iro_arr;
18674     } else {
18675         BLOGE(sc, "Unsupported chip revision\n");
18676         return (-1);
18677     }
18678 
18679     return (0);
18680 }
18681 
18682 static void
18683 bxe_release_firmware(struct bxe_softc *sc)
18684 {
18685     /* Do nothing */
18686     return;
18687 }
18688 
18689 static int
18690 ecore_gunzip(struct bxe_softc *sc,
18691              const uint8_t    *zbuf,
18692              int              len)
18693 {
18694     /* XXX : Implement... */
18695     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18696     return (FALSE);
18697 }
18698 
18699 static void
18700 ecore_reg_wr_ind(struct bxe_softc *sc,
18701                  uint32_t         addr,
18702                  uint32_t         val)
18703 {
18704     bxe_reg_wr_ind(sc, addr, val);
18705 }
18706 
18707 static void
18708 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18709                           bus_addr_t       phys_addr,
18710                           uint32_t         addr,
18711                           uint32_t         len)
18712 {
18713     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18714 }
18715 
18716 void
18717 ecore_storm_memset_struct(struct bxe_softc *sc,
18718                           uint32_t         addr,
18719                           size_t           size,
18720                           uint32_t         *data)
18721 {
18722     uint8_t i;
18723     for (i = 0; i < size/4; i++) {
18724         REG_WR(sc, addr + (i * 4), data[i]);
18725     }
18726 }
18727 
18728 
18729 /*
18730  * character device - ioctl interface definitions
18731  */
18732 
18733 
18734 #include "bxe_dump.h"
18735 #include "bxe_ioctl.h"
18736 #include <sys/conf.h>
18737 
18738 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18739                 struct thread *td);
18740 
18741 static struct cdevsw bxe_cdevsw = {
18742     .d_version = D_VERSION,
18743     .d_ioctl = bxe_eioctl,
18744     .d_name = "bxecnic",
18745 };
18746 
18747 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18748 
18749 
18750 #define DUMP_ALL_PRESETS        0x1FFF
18751 #define DUMP_MAX_PRESETS        13
18752 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18753 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18754 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18755 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18756 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18757 
18758 #define IS_REG_IN_PRESET(presets, idx)  \
18759                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18760 
18761 
18762 static int
18763 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18764 {
18765     if (CHIP_IS_E1(sc))
18766         return dump_num_registers[0][preset-1];
18767     else if (CHIP_IS_E1H(sc))
18768         return dump_num_registers[1][preset-1];
18769     else if (CHIP_IS_E2(sc))
18770         return dump_num_registers[2][preset-1];
18771     else if (CHIP_IS_E3A0(sc))
18772         return dump_num_registers[3][preset-1];
18773     else if (CHIP_IS_E3B0(sc))
18774         return dump_num_registers[4][preset-1];
18775     else
18776         return 0;
18777 }
18778 
18779 static int
18780 bxe_get_total_regs_len32(struct bxe_softc *sc)
18781 {
18782     uint32_t preset_idx;
18783     int regdump_len32 = 0;
18784 
18785 
18786     /* Calculate the total preset regs length */
18787     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18788         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18789     }
18790 
18791     return regdump_len32;
18792 }
18793 
18794 static const uint32_t *
18795 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18796 {
18797     if (CHIP_IS_E2(sc))
18798         return page_vals_e2;
18799     else if (CHIP_IS_E3(sc))
18800         return page_vals_e3;
18801     else
18802         return NULL;
18803 }
18804 
18805 static uint32_t
18806 __bxe_get_page_reg_num(struct bxe_softc *sc)
18807 {
18808     if (CHIP_IS_E2(sc))
18809         return PAGE_MODE_VALUES_E2;
18810     else if (CHIP_IS_E3(sc))
18811         return PAGE_MODE_VALUES_E3;
18812     else
18813         return 0;
18814 }
18815 
18816 static const uint32_t *
18817 __bxe_get_page_write_ar(struct bxe_softc *sc)
18818 {
18819     if (CHIP_IS_E2(sc))
18820         return page_write_regs_e2;
18821     else if (CHIP_IS_E3(sc))
18822         return page_write_regs_e3;
18823     else
18824         return NULL;
18825 }
18826 
18827 static uint32_t
18828 __bxe_get_page_write_num(struct bxe_softc *sc)
18829 {
18830     if (CHIP_IS_E2(sc))
18831         return PAGE_WRITE_REGS_E2;
18832     else if (CHIP_IS_E3(sc))
18833         return PAGE_WRITE_REGS_E3;
18834     else
18835         return 0;
18836 }
18837 
18838 static const struct reg_addr *
18839 __bxe_get_page_read_ar(struct bxe_softc *sc)
18840 {
18841     if (CHIP_IS_E2(sc))
18842         return page_read_regs_e2;
18843     else if (CHIP_IS_E3(sc))
18844         return page_read_regs_e3;
18845     else
18846         return NULL;
18847 }
18848 
18849 static uint32_t
18850 __bxe_get_page_read_num(struct bxe_softc *sc)
18851 {
18852     if (CHIP_IS_E2(sc))
18853         return PAGE_READ_REGS_E2;
18854     else if (CHIP_IS_E3(sc))
18855         return PAGE_READ_REGS_E3;
18856     else
18857         return 0;
18858 }
18859 
18860 static bool
18861 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18862 {
18863     if (CHIP_IS_E1(sc))
18864         return IS_E1_REG(reg_info->chips);
18865     else if (CHIP_IS_E1H(sc))
18866         return IS_E1H_REG(reg_info->chips);
18867     else if (CHIP_IS_E2(sc))
18868         return IS_E2_REG(reg_info->chips);
18869     else if (CHIP_IS_E3A0(sc))
18870         return IS_E3A0_REG(reg_info->chips);
18871     else if (CHIP_IS_E3B0(sc))
18872         return IS_E3B0_REG(reg_info->chips);
18873     else
18874         return 0;
18875 }
18876 
18877 static bool
18878 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18879 {
18880     if (CHIP_IS_E1(sc))
18881         return IS_E1_REG(wreg_info->chips);
18882     else if (CHIP_IS_E1H(sc))
18883         return IS_E1H_REG(wreg_info->chips);
18884     else if (CHIP_IS_E2(sc))
18885         return IS_E2_REG(wreg_info->chips);
18886     else if (CHIP_IS_E3A0(sc))
18887         return IS_E3A0_REG(wreg_info->chips);
18888     else if (CHIP_IS_E3B0(sc))
18889         return IS_E3B0_REG(wreg_info->chips);
18890     else
18891         return 0;
18892 }
18893 
18894 /**
18895  * bxe_read_pages_regs - read "paged" registers
18896  *
18897  * @bp          device handle
18898  * @p           output buffer
18899  *
18900  * Reads "paged" memories: memories that may only be read by first writing to a
18901  * specific address ("write address") and then reading from a specific address
18902  * ("read address"). There may be more than one write address per "page" and
18903  * more than one read address per write address.
18904  */
18905 static void
18906 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18907 {
18908     uint32_t i, j, k, n;
18909 
18910     /* addresses of the paged registers */
18911     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18912     /* number of paged registers */
18913     int num_pages = __bxe_get_page_reg_num(sc);
18914     /* write addresses */
18915     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18916     /* number of write addresses */
18917     int write_num = __bxe_get_page_write_num(sc);
18918     /* read addresses info */
18919     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18920     /* number of read addresses */
18921     int read_num = __bxe_get_page_read_num(sc);
18922     uint32_t addr, size;
18923 
18924     for (i = 0; i < num_pages; i++) {
18925         for (j = 0; j < write_num; j++) {
18926             REG_WR(sc, write_addr[j], page_addr[i]);
18927 
18928             for (k = 0; k < read_num; k++) {
18929                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18930                     size = read_addr[k].size;
18931                     for (n = 0; n < size; n++) {
18932                         addr = read_addr[k].addr + n*4;
18933                         *p++ = REG_RD(sc, addr);
18934                     }
18935                 }
18936             }
18937         }
18938     }
18939     return;
18940 }
18941 
18942 
18943 static int
18944 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18945 {
18946     uint32_t i, j, addr;
18947     const struct wreg_addr *wreg_addr_p = NULL;
18948 
18949     if (CHIP_IS_E1(sc))
18950         wreg_addr_p = &wreg_addr_e1;
18951     else if (CHIP_IS_E1H(sc))
18952         wreg_addr_p = &wreg_addr_e1h;
18953     else if (CHIP_IS_E2(sc))
18954         wreg_addr_p = &wreg_addr_e2;
18955     else if (CHIP_IS_E3A0(sc))
18956         wreg_addr_p = &wreg_addr_e3;
18957     else if (CHIP_IS_E3B0(sc))
18958         wreg_addr_p = &wreg_addr_e3b0;
18959     else
18960         return (-1);
18961 
18962     /* Read the idle_chk registers */
18963     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18964         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18965             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18966             for (j = 0; j < idle_reg_addrs[i].size; j++)
18967                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18968         }
18969     }
18970 
18971     /* Read the regular registers */
18972     for (i = 0; i < REGS_COUNT; i++) {
18973         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18974             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18975             for (j = 0; j < reg_addrs[i].size; j++)
18976                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18977         }
18978     }
18979 
18980     /* Read the CAM registers */
18981     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18982         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18983         for (i = 0; i < wreg_addr_p->size; i++) {
18984             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18985 
18986             /* In case of wreg_addr register, read additional
18987                registers from read_regs array
18988              */
18989             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18990                 addr = *(wreg_addr_p->read_regs);
18991                 *p++ = REG_RD(sc, addr + j*4);
18992             }
18993         }
18994     }
18995 
18996     /* Paged registers are supported in E2 & E3 only */
18997     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18998         /* Read "paged" registers */
18999         bxe_read_pages_regs(sc, p, preset);
19000     }
19001 
19002     return 0;
19003 }
19004 
19005 int
19006 bxe_grc_dump(struct bxe_softc *sc)
19007 {
19008     int rval = 0;
19009     uint32_t preset_idx;
19010     uint8_t *buf;
19011     uint32_t size;
19012     struct  dump_header *d_hdr;
19013     uint32_t i;
19014     uint32_t reg_val;
19015     uint32_t reg_addr;
19016     uint32_t cmd_offset;
19017     struct ecore_ilt *ilt = SC_ILT(sc);
19018     struct bxe_fastpath *fp;
19019     struct ilt_client_info *ilt_cli;
19020     int grc_dump_size;
19021 
19022 
19023     if (sc->grcdump_done || sc->grcdump_started)
19024 	return (rval);
19025 
19026     sc->grcdump_started = 1;
19027     BLOGI(sc, "Started collecting grcdump\n");
19028 
19029     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19030                 sizeof(struct  dump_header);
19031 
19032     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
19033 
19034     if (sc->grc_dump == NULL) {
19035         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
19036         return(ENOMEM);
19037     }
19038 
19039 
19040 
19041     /* Disable parity attentions as long as following dump may
19042      * cause false alarms by reading never written registers. We
19043      * will re-enable parity attentions right after the dump.
19044      */
19045 
19046     /* Disable parity on path 0 */
19047     bxe_pretend_func(sc, 0);
19048 
19049     ecore_disable_blocks_parity(sc);
19050 
19051     /* Disable parity on path 1 */
19052     bxe_pretend_func(sc, 1);
19053     ecore_disable_blocks_parity(sc);
19054 
19055     /* Return to current function */
19056     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
19057 
19058     buf = sc->grc_dump;
19059     d_hdr = sc->grc_dump;
19060 
19061     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
19062     d_hdr->version = BNX2X_DUMP_VERSION;
19063     d_hdr->preset = DUMP_ALL_PRESETS;
19064 
19065     if (CHIP_IS_E1(sc)) {
19066         d_hdr->dump_meta_data = DUMP_CHIP_E1;
19067     } else if (CHIP_IS_E1H(sc)) {
19068         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
19069     } else if (CHIP_IS_E2(sc)) {
19070         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
19071                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19072     } else if (CHIP_IS_E3A0(sc)) {
19073         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
19074                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19075     } else if (CHIP_IS_E3B0(sc)) {
19076         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
19077                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19078     }
19079 
19080     buf += sizeof(struct  dump_header);
19081 
19082     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
19083 
19084         /* Skip presets with IOR */
19085         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
19086             (preset_idx == 11))
19087             continue;
19088 
19089         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
19090 
19091 	if (rval)
19092             break;
19093 
19094         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
19095 
19096         buf += size;
19097     }
19098 
19099     bxe_pretend_func(sc, 0);
19100     ecore_clear_blocks_parity(sc);
19101     ecore_enable_blocks_parity(sc);
19102 
19103     bxe_pretend_func(sc, 1);
19104     ecore_clear_blocks_parity(sc);
19105     ecore_enable_blocks_parity(sc);
19106 
19107     /* Return to current function */
19108     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
19109 
19110 
19111 
19112     if(sc->state == BXE_STATE_OPEN) {
19113         if(sc->fw_stats_req  != NULL) {
19114     		BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
19115         			(uintmax_t)sc->fw_stats_req_mapping,
19116         			(uintmax_t)sc->fw_stats_data_mapping,
19117         			sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
19118 		}
19119 		if(sc->def_sb != NULL) {
19120 			BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
19121         			(void *)sc->def_sb_dma.paddr, sc->def_sb,
19122         			sizeof(struct host_sp_status_block));
19123 		}
19124 		if(sc->eq_dma.vaddr != NULL) {
19125     		BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
19126         			(uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
19127 		}
19128 		if(sc->sp_dma.vaddr != NULL) {
19129     		BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
19130         			(uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
19131         			sizeof(struct bxe_slowpath));
19132 		}
19133 		if(sc->spq_dma.vaddr != NULL) {
19134     		BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
19135         			(uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
19136 		}
19137 		if(sc->gz_buf_dma.vaddr != NULL) {
19138     		BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
19139         			(uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
19140         			FW_BUF_SIZE);
19141 		}
19142     	for (i = 0; i < sc->num_queues; i++) {
19143         	fp = &sc->fp[i];
19144 			if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
19145                         fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
19146                         fp->rx_sge_dma.vaddr != NULL) {
19147 
19148 				BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
19149             			(uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
19150             			sizeof(union bxe_host_hc_status_block));
19151 				BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19152             			(uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
19153             			(BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
19154         		BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19155             			(uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
19156             			(BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
19157         		BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
19158             			(uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
19159             			(BCM_PAGE_SIZE * RCQ_NUM_PAGES));
19160         		BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19161             			(uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
19162             			(BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
19163     		}
19164 		}
19165 		if(ilt != NULL ) {
19166     		ilt_cli = &ilt->clients[1];
19167 			if(ilt->lines != NULL) {
19168     		for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
19169         		BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
19170             			(uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
19171             			((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
19172     		}
19173 			}
19174 		}
19175 
19176 
19177     	cmd_offset = DMAE_REG_CMD_MEM;
19178     	for (i = 0; i < 224; i++) {
19179         	reg_addr = (cmd_offset +(i * 4));
19180         	reg_val = REG_RD(sc, reg_addr);
19181         	BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
19182             			reg_addr, reg_val);
19183     	}
19184 	}
19185 
19186     BLOGI(sc, "Collection of grcdump done\n");
19187     sc->grcdump_done = 1;
19188     return(rval);
19189 }
19190 
19191 static int
19192 bxe_add_cdev(struct bxe_softc *sc)
19193 {
19194     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
19195 
19196     if (sc->eeprom == NULL) {
19197         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
19198         return (-1);
19199     }
19200 
19201     sc->ioctl_dev = make_dev(&bxe_cdevsw,
19202                             sc->ifp->if_dunit,
19203                             UID_ROOT,
19204                             GID_WHEEL,
19205                             0600,
19206                             "%s",
19207                             if_name(sc->ifp));
19208 
19209     if (sc->ioctl_dev == NULL) {
19210         free(sc->eeprom, M_DEVBUF);
19211         sc->eeprom = NULL;
19212         return (-1);
19213     }
19214 
19215     sc->ioctl_dev->si_drv1 = sc;
19216 
19217     return (0);
19218 }
19219 
19220 static void
19221 bxe_del_cdev(struct bxe_softc *sc)
19222 {
19223     if (sc->ioctl_dev != NULL)
19224         destroy_dev(sc->ioctl_dev);
19225 
19226     if (sc->eeprom != NULL) {
19227         free(sc->eeprom, M_DEVBUF);
19228         sc->eeprom = NULL;
19229     }
19230     sc->ioctl_dev = NULL;
19231 
19232     return;
19233 }
19234 
19235 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
19236 {
19237 
19238     if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
19239         return FALSE;
19240 
19241     return TRUE;
19242 }
19243 
19244 
19245 static int
19246 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
19247 {
19248     int rval = 0;
19249 
19250     if(!bxe_is_nvram_accessible(sc)) {
19251         BLOGW(sc, "Cannot access eeprom when interface is down\n");
19252         return (-EAGAIN);
19253     }
19254     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
19255 
19256 
19257    return (rval);
19258 }
19259 
19260 static int
19261 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
19262 {
19263     int rval = 0;
19264 
19265     if(!bxe_is_nvram_accessible(sc)) {
19266         BLOGW(sc, "Cannot access eeprom when interface is down\n");
19267         return (-EAGAIN);
19268     }
19269     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
19270 
19271    return (rval);
19272 }
19273 
19274 static int
19275 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
19276 {
19277     int rval = 0;
19278 
19279     switch (eeprom->eeprom_cmd) {
19280 
19281     case BXE_EEPROM_CMD_SET_EEPROM:
19282 
19283         rval = copyin(eeprom->eeprom_data, sc->eeprom,
19284                        eeprom->eeprom_data_len);
19285 
19286         if (rval)
19287             break;
19288 
19289         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
19290                        eeprom->eeprom_data_len);
19291         break;
19292 
19293     case BXE_EEPROM_CMD_GET_EEPROM:
19294 
19295         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
19296                        eeprom->eeprom_data_len);
19297 
19298         if (rval) {
19299             break;
19300         }
19301 
19302         rval = copyout(sc->eeprom, eeprom->eeprom_data,
19303                        eeprom->eeprom_data_len);
19304         break;
19305 
19306     default:
19307             rval = EINVAL;
19308             break;
19309     }
19310 
19311     if (rval) {
19312         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
19313     }
19314 
19315     return (rval);
19316 }
19317 
19318 static int
19319 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
19320 {
19321     uint32_t ext_phy_config;
19322     int port = SC_PORT(sc);
19323     int cfg_idx = bxe_get_link_cfg_idx(sc);
19324 
19325     dev_p->supported = sc->port.supported[cfg_idx] |
19326             (sc->port.supported[cfg_idx ^ 1] &
19327             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
19328     dev_p->advertising = sc->port.advertising[cfg_idx];
19329     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
19330         ELINK_ETH_PHY_SFP_1G_FIBER) {
19331         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
19332         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
19333     }
19334     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
19335         !(sc->flags & BXE_MF_FUNC_DIS)) {
19336         dev_p->duplex = sc->link_vars.duplex;
19337         if (IS_MF(sc) && !BXE_NOMCP(sc))
19338             dev_p->speed = bxe_get_mf_speed(sc);
19339         else
19340             dev_p->speed = sc->link_vars.line_speed;
19341     } else {
19342         dev_p->duplex = DUPLEX_UNKNOWN;
19343         dev_p->speed = SPEED_UNKNOWN;
19344     }
19345 
19346     dev_p->port = bxe_media_detect(sc);
19347 
19348     ext_phy_config = SHMEM_RD(sc,
19349                          dev_info.port_hw_config[port].external_phy_config);
19350     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19351         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19352         dev_p->phy_address =  sc->port.phy_addr;
19353     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19354             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19355         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19356             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19357         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19358     else
19359         dev_p->phy_address = 0;
19360 
19361     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19362         dev_p->autoneg = AUTONEG_ENABLE;
19363     else
19364        dev_p->autoneg = AUTONEG_DISABLE;
19365 
19366 
19367     return 0;
19368 }
19369 
19370 static int
19371 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19372         struct thread *td)
19373 {
19374     struct bxe_softc    *sc;
19375     int                 rval = 0;
19376     device_t            pci_dev;
19377     bxe_grcdump_t       *dump = NULL;
19378     int grc_dump_size;
19379     bxe_drvinfo_t   *drv_infop = NULL;
19380     bxe_dev_setting_t  *dev_p;
19381     bxe_dev_setting_t  dev_set;
19382     bxe_get_regs_t  *reg_p;
19383     bxe_reg_rdw_t *reg_rdw_p;
19384     bxe_pcicfg_rdw_t *cfg_rdw_p;
19385     bxe_perm_mac_addr_t *mac_addr_p;
19386 
19387 
19388     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19389         return ENXIO;
19390 
19391     pci_dev= sc->dev;
19392 
19393     dump = (bxe_grcdump_t *)data;
19394 
19395     switch(cmd) {
19396 
19397         case BXE_GRC_DUMP_SIZE:
19398             dump->pci_func = sc->pcie_func;
19399             dump->grcdump_size =
19400                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19401                      sizeof(struct  dump_header);
19402             break;
19403 
19404         case BXE_GRC_DUMP:
19405 
19406             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19407                                 sizeof(struct  dump_header);
19408             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19409                 (dump->grcdump_size < grc_dump_size)) {
19410                 rval = EINVAL;
19411                 break;
19412             }
19413 
19414             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19415                 (!sc->grcdump_started)) {
19416                 rval =  bxe_grc_dump(sc);
19417             }
19418 
19419             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19420                 (sc->grc_dump != NULL))  {
19421                 dump->grcdump_dwords = grc_dump_size >> 2;
19422                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19423                 free(sc->grc_dump, M_DEVBUF);
19424                 sc->grc_dump = NULL;
19425                 sc->grcdump_started = 0;
19426                 sc->grcdump_done = 0;
19427             }
19428 
19429             break;
19430 
19431         case BXE_DRV_INFO:
19432             drv_infop = (bxe_drvinfo_t *)data;
19433             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19434             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19435                 BXE_DRIVER_VERSION);
19436             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19437                 sc->devinfo.bc_ver_str);
19438             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19439                 "%s", sc->fw_ver_str);
19440             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19441             drv_infop->reg_dump_len =
19442                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19443                     + sizeof(struct  dump_header);
19444             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19445                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19446             break;
19447 
19448         case BXE_DEV_SETTING:
19449             dev_p = (bxe_dev_setting_t *)data;
19450             bxe_get_settings(sc, &dev_set);
19451             dev_p->supported = dev_set.supported;
19452             dev_p->advertising = dev_set.advertising;
19453             dev_p->speed = dev_set.speed;
19454             dev_p->duplex = dev_set.duplex;
19455             dev_p->port = dev_set.port;
19456             dev_p->phy_address = dev_set.phy_address;
19457             dev_p->autoneg = dev_set.autoneg;
19458 
19459             break;
19460 
19461         case BXE_GET_REGS:
19462 
19463             reg_p = (bxe_get_regs_t *)data;
19464             grc_dump_size = reg_p->reg_buf_len;
19465 
19466             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19467                 bxe_grc_dump(sc);
19468             }
19469             if((sc->grcdump_done) && (sc->grcdump_started) &&
19470                 (sc->grc_dump != NULL))  {
19471                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19472                 free(sc->grc_dump, M_DEVBUF);
19473                 sc->grc_dump = NULL;
19474                 sc->grcdump_started = 0;
19475                 sc->grcdump_done = 0;
19476             }
19477 
19478             break;
19479 
19480         case BXE_RDW_REG:
19481             reg_rdw_p = (bxe_reg_rdw_t *)data;
19482             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19483                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19484                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19485 
19486             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19487                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19488                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19489 
19490             break;
19491 
19492         case BXE_RDW_PCICFG:
19493             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19494             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19495 
19496                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19497                                          cfg_rdw_p->cfg_width);
19498 
19499             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19500                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19501                             cfg_rdw_p->cfg_width);
19502             } else {
19503                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19504             }
19505             break;
19506 
19507         case BXE_MAC_ADDR:
19508             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19509             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19510                 sc->mac_addr_str);
19511             break;
19512 
19513         case BXE_EEPROM:
19514             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19515             break;
19516 
19517 
19518         default:
19519             break;
19520     }
19521 
19522     return (rval);
19523 }
19524 
19525 #ifdef DEBUGNET
19526 static void
19527 bxe_debugnet_init(struct ifnet *ifp, int *nrxr, int *ncl, int *clsize)
19528 {
19529 	struct bxe_softc *sc;
19530 
19531 	sc = if_getsoftc(ifp);
19532 	BXE_CORE_LOCK(sc);
19533 	*nrxr = sc->num_queues;
19534 	*ncl = DEBUGNET_MAX_IN_FLIGHT;
19535 	*clsize = sc->fp[0].mbuf_alloc_size;
19536 	BXE_CORE_UNLOCK(sc);
19537 }
19538 
19539 static void
19540 bxe_debugnet_event(struct ifnet *ifp __unused, enum debugnet_ev event __unused)
19541 {
19542 }
19543 
19544 static int
19545 bxe_debugnet_transmit(struct ifnet *ifp, struct mbuf *m)
19546 {
19547 	struct bxe_softc *sc;
19548 	int error;
19549 
19550 	sc = if_getsoftc(ifp);
19551 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
19552 	    IFF_DRV_RUNNING || !sc->link_vars.link_up)
19553 		return (ENOENT);
19554 
19555 	error = bxe_tx_encap(&sc->fp[0], &m);
19556 	if (error != 0 && m != NULL)
19557 		m_freem(m);
19558 	return (error);
19559 }
19560 
19561 static int
19562 bxe_debugnet_poll(struct ifnet *ifp, int count)
19563 {
19564 	struct bxe_softc *sc;
19565 	int i;
19566 
19567 	sc = if_getsoftc(ifp);
19568 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 ||
19569 	    !sc->link_vars.link_up)
19570 		return (ENOENT);
19571 
19572 	for (i = 0; i < sc->num_queues; i++)
19573 		(void)bxe_rxeof(sc, &sc->fp[i]);
19574 	(void)bxe_txeof(sc, &sc->fp[0]);
19575 	return (0);
19576 }
19577 #endif /* DEBUGNET */
19578