xref: /freebsd/sys/dev/bxe/bxe.c (revision d9f0ce31900a48d1a2bfc1c8c86f79d1e831451a)
1 /*-
2  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #define BXE_DRIVER_VERSION "1.78.81"
31 
32 #include "bxe.h"
33 #include "ecore_sp.h"
34 #include "ecore_init.h"
35 #include "ecore_init_ops.h"
36 
37 #include "57710_int_offsets.h"
38 #include "57711_int_offsets.h"
39 #include "57712_int_offsets.h"
40 
41 /*
42  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
43  * explicitly here for older kernels that don't include this changeset.
44  */
45 #ifndef CTLTYPE_U64
46 #define CTLTYPE_U64      CTLTYPE_QUAD
47 #define sysctl_handle_64 sysctl_handle_quad
48 #endif
49 
50 /*
51  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
52  * here as zero(0) for older kernels that don't include this changeset
53  * thereby masking the functionality.
54  */
55 #ifndef CSUM_TCP_IPV6
56 #define CSUM_TCP_IPV6 0
57 #define CSUM_UDP_IPV6 0
58 #endif
59 
60 /*
61  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
62  * for older kernels that don't include this changeset.
63  */
64 #if __FreeBSD_version < 900035
65 #define pci_find_cap pci_find_extcap
66 #endif
67 
68 #define BXE_DEF_SB_ATT_IDX 0x0001
69 #define BXE_DEF_SB_IDX     0x0002
70 
71 /*
72  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
73  * function HW initialization.
74  */
75 #define FLR_WAIT_USEC     10000 /* 10 msecs */
76 #define FLR_WAIT_INTERVAL 50    /* usecs */
77 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
78 
79 struct pbf_pN_buf_regs {
80     int pN;
81     uint32_t init_crd;
82     uint32_t crd;
83     uint32_t crd_freed;
84 };
85 
86 struct pbf_pN_cmd_regs {
87     int pN;
88     uint32_t lines_occup;
89     uint32_t lines_freed;
90 };
91 
92 /*
93  * PCI Device ID Table used by bxe_probe().
94  */
95 #define BXE_DEVDESC_MAX 64
96 static struct bxe_device_type bxe_devs[] = {
97     {
98         BRCM_VENDORID,
99         CHIP_NUM_57710,
100         PCI_ANY_ID, PCI_ANY_ID,
101         "QLogic NetXtreme II BCM57710 10GbE"
102     },
103     {
104         BRCM_VENDORID,
105         CHIP_NUM_57711,
106         PCI_ANY_ID, PCI_ANY_ID,
107         "QLogic NetXtreme II BCM57711 10GbE"
108     },
109     {
110         BRCM_VENDORID,
111         CHIP_NUM_57711E,
112         PCI_ANY_ID, PCI_ANY_ID,
113         "QLogic NetXtreme II BCM57711E 10GbE"
114     },
115     {
116         BRCM_VENDORID,
117         CHIP_NUM_57712,
118         PCI_ANY_ID, PCI_ANY_ID,
119         "QLogic NetXtreme II BCM57712 10GbE"
120     },
121     {
122         BRCM_VENDORID,
123         CHIP_NUM_57712_MF,
124         PCI_ANY_ID, PCI_ANY_ID,
125         "QLogic NetXtreme II BCM57712 MF 10GbE"
126     },
127     {
128         BRCM_VENDORID,
129         CHIP_NUM_57800,
130         PCI_ANY_ID, PCI_ANY_ID,
131         "QLogic NetXtreme II BCM57800 10GbE"
132     },
133     {
134         BRCM_VENDORID,
135         CHIP_NUM_57800_MF,
136         PCI_ANY_ID, PCI_ANY_ID,
137         "QLogic NetXtreme II BCM57800 MF 10GbE"
138     },
139     {
140         BRCM_VENDORID,
141         CHIP_NUM_57810,
142         PCI_ANY_ID, PCI_ANY_ID,
143         "QLogic NetXtreme II BCM57810 10GbE"
144     },
145     {
146         BRCM_VENDORID,
147         CHIP_NUM_57810_MF,
148         PCI_ANY_ID, PCI_ANY_ID,
149         "QLogic NetXtreme II BCM57810 MF 10GbE"
150     },
151     {
152         BRCM_VENDORID,
153         CHIP_NUM_57811,
154         PCI_ANY_ID, PCI_ANY_ID,
155         "QLogic NetXtreme II BCM57811 10GbE"
156     },
157     {
158         BRCM_VENDORID,
159         CHIP_NUM_57811_MF,
160         PCI_ANY_ID, PCI_ANY_ID,
161         "QLogic NetXtreme II BCM57811 MF 10GbE"
162     },
163     {
164         BRCM_VENDORID,
165         CHIP_NUM_57840_4_10,
166         PCI_ANY_ID, PCI_ANY_ID,
167         "QLogic NetXtreme II BCM57840 4x10GbE"
168     },
169     {
170         BRCM_VENDORID,
171         CHIP_NUM_57840_MF,
172         PCI_ANY_ID, PCI_ANY_ID,
173         "QLogic NetXtreme II BCM57840 MF 10GbE"
174     },
175     {
176         0, 0, 0, 0, NULL
177     }
178 };
179 
180 MALLOC_DECLARE(M_BXE_ILT);
181 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
182 
183 /*
184  * FreeBSD device entry points.
185  */
186 static int bxe_probe(device_t);
187 static int bxe_attach(device_t);
188 static int bxe_detach(device_t);
189 static int bxe_shutdown(device_t);
190 
191 /*
192  * FreeBSD KLD module/device interface event handler method.
193  */
194 static device_method_t bxe_methods[] = {
195     /* Device interface (device_if.h) */
196     DEVMETHOD(device_probe,     bxe_probe),
197     DEVMETHOD(device_attach,    bxe_attach),
198     DEVMETHOD(device_detach,    bxe_detach),
199     DEVMETHOD(device_shutdown,  bxe_shutdown),
200     /* Bus interface (bus_if.h) */
201     DEVMETHOD(bus_print_child,  bus_generic_print_child),
202     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
203     KOBJMETHOD_END
204 };
205 
206 /*
207  * FreeBSD KLD Module data declaration
208  */
209 static driver_t bxe_driver = {
210     "bxe",                   /* module name */
211     bxe_methods,             /* event handler */
212     sizeof(struct bxe_softc) /* extra data */
213 };
214 
215 /*
216  * FreeBSD dev class is needed to manage dev instances and
217  * to associate with a bus type
218  */
219 static devclass_t bxe_devclass;
220 
221 MODULE_DEPEND(bxe, pci, 1, 1, 1);
222 MODULE_DEPEND(bxe, ether, 1, 1, 1);
223 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
224 
225 /* resources needed for unloading a previously loaded device */
226 
227 #define BXE_PREV_WAIT_NEEDED 1
228 struct mtx bxe_prev_mtx;
229 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
230 struct bxe_prev_list_node {
231     LIST_ENTRY(bxe_prev_list_node) node;
232     uint8_t bus;
233     uint8_t slot;
234     uint8_t path;
235     uint8_t aer; /* XXX automatic error recovery */
236     uint8_t undi;
237 };
238 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
239 
240 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
241 
242 /* Tunable device values... */
243 
244 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
245 
246 /* Debug */
247 unsigned long bxe_debug = 0;
248 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
249              &bxe_debug, 0, "Debug logging mode");
250 
251 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
252 static int bxe_interrupt_mode = INTR_MODE_MSIX;
253 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
254            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
255 
256 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
257 static int bxe_queue_count = 4;
258 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
259            &bxe_queue_count, 0, "Multi-Queue queue count");
260 
261 /* max number of buffers per queue (default RX_BD_USABLE) */
262 static int bxe_max_rx_bufs = 0;
263 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
264            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
265 
266 /* Host interrupt coalescing RX tick timer (usecs) */
267 static int bxe_hc_rx_ticks = 25;
268 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
269            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
270 
271 /* Host interrupt coalescing TX tick timer (usecs) */
272 static int bxe_hc_tx_ticks = 50;
273 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
274            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
275 
276 /* Maximum number of Rx packets to process at a time */
277 static int bxe_rx_budget = 0xffffffff;
278 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
279            &bxe_rx_budget, 0, "Rx processing budget");
280 
281 /* Maximum LRO aggregation size */
282 static int bxe_max_aggregation_size = 0;
283 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
284            &bxe_max_aggregation_size, 0, "max aggregation size");
285 
286 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
287 static int bxe_mrrs = -1;
288 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
289            &bxe_mrrs, 0, "PCIe maximum read request size");
290 
291 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
292 static int bxe_autogreeen = 0;
293 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
294            &bxe_autogreeen, 0, "AutoGrEEEn support");
295 
296 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
297 static int bxe_udp_rss = 0;
298 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
299            &bxe_udp_rss, 0, "UDP RSS support");
300 
301 
302 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
303 
304 #define STATS_OFFSET32(stat_name)                   \
305     (offsetof(struct bxe_eth_stats, stat_name) / 4)
306 
307 #define Q_STATS_OFFSET32(stat_name)                   \
308     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
309 
310 static const struct {
311     uint32_t offset;
312     uint32_t size;
313     uint32_t flags;
314 #define STATS_FLAGS_PORT  1
315 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
316 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
317     char string[STAT_NAME_LEN];
318 } bxe_eth_stats_arr[] = {
319     { STATS_OFFSET32(total_bytes_received_hi),
320                 8, STATS_FLAGS_BOTH, "rx_bytes" },
321     { STATS_OFFSET32(error_bytes_received_hi),
322                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
323     { STATS_OFFSET32(total_unicast_packets_received_hi),
324                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
325     { STATS_OFFSET32(total_multicast_packets_received_hi),
326                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
327     { STATS_OFFSET32(total_broadcast_packets_received_hi),
328                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
329     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
330                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
331     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
332                 8, STATS_FLAGS_PORT, "rx_align_errors" },
333     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
334                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
335     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
336                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
337     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
338                 8, STATS_FLAGS_PORT, "rx_fragments" },
339     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
340                 8, STATS_FLAGS_PORT, "rx_jabbers" },
341     { STATS_OFFSET32(no_buff_discard_hi),
342                 8, STATS_FLAGS_BOTH, "rx_discards" },
343     { STATS_OFFSET32(mac_filter_discard),
344                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
345     { STATS_OFFSET32(mf_tag_discard),
346                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
347     { STATS_OFFSET32(pfc_frames_received_hi),
348                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
349     { STATS_OFFSET32(pfc_frames_sent_hi),
350                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
351     { STATS_OFFSET32(brb_drop_hi),
352                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
353     { STATS_OFFSET32(brb_truncate_hi),
354                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
355     { STATS_OFFSET32(pause_frames_received_hi),
356                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
357     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
358                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
359     { STATS_OFFSET32(nig_timer_max),
360                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
361     { STATS_OFFSET32(total_bytes_transmitted_hi),
362                 8, STATS_FLAGS_BOTH, "tx_bytes" },
363     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
364                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
365     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
366                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
367     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
368                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
369     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
370                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
371     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
372                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
373     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
374                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
375     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
376                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
377     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
378                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
379     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
380                 8, STATS_FLAGS_PORT, "tx_deferred" },
381     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
382                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
383     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
384                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
385     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
386                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
387     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
388                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
389     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
390                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
391     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
392                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
393     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
394                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
395     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
396                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
397     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
398                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
399     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
400                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
401     { STATS_OFFSET32(pause_frames_sent_hi),
402                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
403     { STATS_OFFSET32(total_tpa_aggregations_hi),
404                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
405     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
406                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
407     { STATS_OFFSET32(total_tpa_bytes_hi),
408                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
409     { STATS_OFFSET32(eee_tx_lpi),
410                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
411     { STATS_OFFSET32(rx_calls),
412                 4, STATS_FLAGS_FUNC, "rx_calls"},
413     { STATS_OFFSET32(rx_pkts),
414                 4, STATS_FLAGS_FUNC, "rx_pkts"},
415     { STATS_OFFSET32(rx_tpa_pkts),
416                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
417     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
418                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
419     { STATS_OFFSET32(rx_bxe_service_rxsgl),
420                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
421     { STATS_OFFSET32(rx_jumbo_sge_pkts),
422                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
423     { STATS_OFFSET32(rx_soft_errors),
424                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
425     { STATS_OFFSET32(rx_hw_csum_errors),
426                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
427     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
428                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
429     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
430                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
431     { STATS_OFFSET32(rx_budget_reached),
432                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
433     { STATS_OFFSET32(tx_pkts),
434                 4, STATS_FLAGS_FUNC, "tx_pkts"},
435     { STATS_OFFSET32(tx_soft_errors),
436                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
437     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
438                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
439     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
440                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
441     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
442                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
443     { STATS_OFFSET32(tx_ofld_frames_lso),
444                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
445     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
446                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
447     { STATS_OFFSET32(tx_encap_failures),
448                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
449     { STATS_OFFSET32(tx_hw_queue_full),
450                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
451     { STATS_OFFSET32(tx_hw_max_queue_depth),
452                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
453     { STATS_OFFSET32(tx_dma_mapping_failure),
454                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
455     { STATS_OFFSET32(tx_max_drbr_queue_depth),
456                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
457     { STATS_OFFSET32(tx_window_violation_std),
458                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
459     { STATS_OFFSET32(tx_window_violation_tso),
460                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
461     { STATS_OFFSET32(tx_chain_lost_mbuf),
462                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
463     { STATS_OFFSET32(tx_frames_deferred),
464                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
465     { STATS_OFFSET32(tx_queue_xoff),
466                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
467     { STATS_OFFSET32(mbuf_defrag_attempts),
468                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
469     { STATS_OFFSET32(mbuf_defrag_failures),
470                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
471     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
472                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
473     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
474                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
475     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
476                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
477     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
478                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
479     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
480                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
481     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
482                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
483     { STATS_OFFSET32(mbuf_alloc_tx),
484                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
485     { STATS_OFFSET32(mbuf_alloc_rx),
486                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
487     { STATS_OFFSET32(mbuf_alloc_sge),
488                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
489     { STATS_OFFSET32(mbuf_alloc_tpa),
490                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
491     { STATS_OFFSET32(tx_queue_full_return),
492                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"}
493 };
494 
495 static const struct {
496     uint32_t offset;
497     uint32_t size;
498     char string[STAT_NAME_LEN];
499 } bxe_eth_q_stats_arr[] = {
500     { Q_STATS_OFFSET32(total_bytes_received_hi),
501                 8, "rx_bytes" },
502     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
503                 8, "rx_ucast_packets" },
504     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
505                 8, "rx_mcast_packets" },
506     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
507                 8, "rx_bcast_packets" },
508     { Q_STATS_OFFSET32(no_buff_discard_hi),
509                 8, "rx_discards" },
510     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
511                 8, "tx_bytes" },
512     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
513                 8, "tx_ucast_packets" },
514     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
515                 8, "tx_mcast_packets" },
516     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
517                 8, "tx_bcast_packets" },
518     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
519                 8, "tpa_aggregations" },
520     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
521                 8, "tpa_aggregated_frames"},
522     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
523                 8, "tpa_bytes"},
524     { Q_STATS_OFFSET32(rx_calls),
525                 4, "rx_calls"},
526     { Q_STATS_OFFSET32(rx_pkts),
527                 4, "rx_pkts"},
528     { Q_STATS_OFFSET32(rx_tpa_pkts),
529                 4, "rx_tpa_pkts"},
530     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
531                 4, "rx_erroneous_jumbo_sge_pkts"},
532     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
533                 4, "rx_bxe_service_rxsgl"},
534     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
535                 4, "rx_jumbo_sge_pkts"},
536     { Q_STATS_OFFSET32(rx_soft_errors),
537                 4, "rx_soft_errors"},
538     { Q_STATS_OFFSET32(rx_hw_csum_errors),
539                 4, "rx_hw_csum_errors"},
540     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
541                 4, "rx_ofld_frames_csum_ip"},
542     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
543                 4, "rx_ofld_frames_csum_tcp_udp"},
544     { Q_STATS_OFFSET32(rx_budget_reached),
545                 4, "rx_budget_reached"},
546     { Q_STATS_OFFSET32(tx_pkts),
547                 4, "tx_pkts"},
548     { Q_STATS_OFFSET32(tx_soft_errors),
549                 4, "tx_soft_errors"},
550     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
551                 4, "tx_ofld_frames_csum_ip"},
552     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
553                 4, "tx_ofld_frames_csum_tcp"},
554     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
555                 4, "tx_ofld_frames_csum_udp"},
556     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
557                 4, "tx_ofld_frames_lso"},
558     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
559                 4, "tx_ofld_frames_lso_hdr_splits"},
560     { Q_STATS_OFFSET32(tx_encap_failures),
561                 4, "tx_encap_failures"},
562     { Q_STATS_OFFSET32(tx_hw_queue_full),
563                 4, "tx_hw_queue_full"},
564     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
565                 4, "tx_hw_max_queue_depth"},
566     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
567                 4, "tx_dma_mapping_failure"},
568     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
569                 4, "tx_max_drbr_queue_depth"},
570     { Q_STATS_OFFSET32(tx_window_violation_std),
571                 4, "tx_window_violation_std"},
572     { Q_STATS_OFFSET32(tx_window_violation_tso),
573                 4, "tx_window_violation_tso"},
574     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
575                 4, "tx_chain_lost_mbuf"},
576     { Q_STATS_OFFSET32(tx_frames_deferred),
577                 4, "tx_frames_deferred"},
578     { Q_STATS_OFFSET32(tx_queue_xoff),
579                 4, "tx_queue_xoff"},
580     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
581                 4, "mbuf_defrag_attempts"},
582     { Q_STATS_OFFSET32(mbuf_defrag_failures),
583                 4, "mbuf_defrag_failures"},
584     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
585                 4, "mbuf_rx_bd_alloc_failed"},
586     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
587                 4, "mbuf_rx_bd_mapping_failed"},
588     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
589                 4, "mbuf_rx_tpa_alloc_failed"},
590     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
591                 4, "mbuf_rx_tpa_mapping_failed"},
592     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
593                 4, "mbuf_rx_sge_alloc_failed"},
594     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
595                 4, "mbuf_rx_sge_mapping_failed"},
596     { Q_STATS_OFFSET32(mbuf_alloc_tx),
597                 4, "mbuf_alloc_tx"},
598     { Q_STATS_OFFSET32(mbuf_alloc_rx),
599                 4, "mbuf_alloc_rx"},
600     { Q_STATS_OFFSET32(mbuf_alloc_sge),
601                 4, "mbuf_alloc_sge"},
602     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
603                 4, "mbuf_alloc_tpa"},
604     { Q_STATS_OFFSET32(tx_queue_full_return),
605                 4, "tx_queue_full_return"}
606 };
607 
608 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
609 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
610 
611 
612 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
613                                  uint8_t          read_cfg,
614                                  uint8_t          cmng_type);
615 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
616 static void    storm_memset_cmng(struct bxe_softc *sc,
617                                  struct cmng_init *cmng,
618                                  uint8_t          port);
619 static void    bxe_set_reset_global(struct bxe_softc *sc);
620 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
621 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
622                                  int              engine);
623 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
624 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
625                                    uint8_t          *global,
626                                    uint8_t          print);
627 static void    bxe_int_disable(struct bxe_softc *sc);
628 static int     bxe_release_leader_lock(struct bxe_softc *sc);
629 static void    bxe_pf_disable(struct bxe_softc *sc);
630 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
631 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
632                                       struct bxe_fastpath *fp,
633                                       uint16_t            rx_bd_prod,
634                                       uint16_t            rx_cq_prod,
635                                       uint16_t            rx_sge_prod);
636 static void    bxe_link_report_locked(struct bxe_softc *sc);
637 static void    bxe_link_report(struct bxe_softc *sc);
638 static void    bxe_link_status_update(struct bxe_softc *sc);
639 static void    bxe_periodic_callout_func(void *xsc);
640 static void    bxe_periodic_start(struct bxe_softc *sc);
641 static void    bxe_periodic_stop(struct bxe_softc *sc);
642 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
643                                     uint16_t prev_index,
644                                     uint16_t index);
645 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
646                                      int                 queue);
647 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
648                                      uint16_t            index);
649 static uint8_t bxe_txeof(struct bxe_softc *sc,
650                          struct bxe_fastpath *fp);
651 static void    bxe_task_fp(struct bxe_fastpath *fp);
652 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
653                                      struct mbuf      *m,
654                                      uint8_t          contents);
655 static int     bxe_alloc_mem(struct bxe_softc *sc);
656 static void    bxe_free_mem(struct bxe_softc *sc);
657 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
658 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
659 static int     bxe_interrupt_attach(struct bxe_softc *sc);
660 static void    bxe_interrupt_detach(struct bxe_softc *sc);
661 static void    bxe_set_rx_mode(struct bxe_softc *sc);
662 static int     bxe_init_locked(struct bxe_softc *sc);
663 static int     bxe_stop_locked(struct bxe_softc *sc);
664 static __noinline int bxe_nic_load(struct bxe_softc *sc,
665                                    int              load_mode);
666 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
667                                      uint32_t         unload_mode,
668                                      uint8_t          keep_link);
669 
670 static void bxe_handle_sp_tq(void *context, int pending);
671 static void bxe_handle_fp_tq(void *context, int pending);
672 
673 static int bxe_add_cdev(struct bxe_softc *sc);
674 static void bxe_del_cdev(struct bxe_softc *sc);
675 static int bxe_grc_dump(struct bxe_softc *sc);
676 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
677 static void bxe_free_buf_rings(struct bxe_softc *sc);
678 
679 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
680 uint32_t
681 calc_crc32(uint8_t  *crc32_packet,
682            uint32_t crc32_length,
683            uint32_t crc32_seed,
684            uint8_t  complement)
685 {
686    uint32_t byte         = 0;
687    uint32_t bit          = 0;
688    uint8_t  msb          = 0;
689    uint32_t temp         = 0;
690    uint32_t shft         = 0;
691    uint8_t  current_byte = 0;
692    uint32_t crc32_result = crc32_seed;
693    const uint32_t CRC32_POLY = 0x1edc6f41;
694 
695    if ((crc32_packet == NULL) ||
696        (crc32_length == 0) ||
697        ((crc32_length % 8) != 0))
698     {
699         return (crc32_result);
700     }
701 
702     for (byte = 0; byte < crc32_length; byte = byte + 1)
703     {
704         current_byte = crc32_packet[byte];
705         for (bit = 0; bit < 8; bit = bit + 1)
706         {
707             /* msb = crc32_result[31]; */
708             msb = (uint8_t)(crc32_result >> 31);
709 
710             crc32_result = crc32_result << 1;
711 
712             /* it (msb != current_byte[bit]) */
713             if (msb != (0x1 & (current_byte >> bit)))
714             {
715                 crc32_result = crc32_result ^ CRC32_POLY;
716                 /* crc32_result[0] = 1 */
717                 crc32_result |= 1;
718             }
719         }
720     }
721 
722     /* Last step is to:
723      * 1. "mirror" every bit
724      * 2. swap the 4 bytes
725      * 3. complement each bit
726      */
727 
728     /* Mirror */
729     temp = crc32_result;
730     shft = sizeof(crc32_result) * 8 - 1;
731 
732     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
733     {
734         temp <<= 1;
735         temp |= crc32_result & 1;
736         shft-- ;
737     }
738 
739     /* temp[31-bit] = crc32_result[bit] */
740     temp <<= shft;
741 
742     /* Swap */
743     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
744     {
745         uint32_t t0, t1, t2, t3;
746         t0 = (0x000000ff & (temp >> 24));
747         t1 = (0x0000ff00 & (temp >> 8));
748         t2 = (0x00ff0000 & (temp << 8));
749         t3 = (0xff000000 & (temp << 24));
750         crc32_result = t0 | t1 | t2 | t3;
751     }
752 
753     /* Complement */
754     if (complement)
755     {
756         crc32_result = ~crc32_result;
757     }
758 
759     return (crc32_result);
760 }
761 
762 int
763 bxe_test_bit(int                    nr,
764              volatile unsigned long *addr)
765 {
766     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
767 }
768 
769 void
770 bxe_set_bit(unsigned int           nr,
771             volatile unsigned long *addr)
772 {
773     atomic_set_acq_long(addr, (1 << nr));
774 }
775 
776 void
777 bxe_clear_bit(int                    nr,
778               volatile unsigned long *addr)
779 {
780     atomic_clear_acq_long(addr, (1 << nr));
781 }
782 
783 int
784 bxe_test_and_set_bit(int                    nr,
785                        volatile unsigned long *addr)
786 {
787     unsigned long x;
788     nr = (1 << nr);
789     do {
790         x = *addr;
791     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
792     // if (x & nr) bit_was_set; else bit_was_not_set;
793     return (x & nr);
794 }
795 
796 int
797 bxe_test_and_clear_bit(int                    nr,
798                        volatile unsigned long *addr)
799 {
800     unsigned long x;
801     nr = (1 << nr);
802     do {
803         x = *addr;
804     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
805     // if (x & nr) bit_was_set; else bit_was_not_set;
806     return (x & nr);
807 }
808 
809 int
810 bxe_cmpxchg(volatile int *addr,
811             int          old,
812             int          new)
813 {
814     int x;
815     do {
816         x = *addr;
817     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
818     return (x);
819 }
820 
821 /*
822  * Get DMA memory from the OS.
823  *
824  * Validates that the OS has provided DMA buffers in response to a
825  * bus_dmamap_load call and saves the physical address of those buffers.
826  * When the callback is used the OS will return 0 for the mapping function
827  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
828  * failures back to the caller.
829  *
830  * Returns:
831  *   Nothing.
832  */
833 static void
834 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
835 {
836     struct bxe_dma *dma = arg;
837 
838     if (error) {
839         dma->paddr = 0;
840         dma->nseg  = 0;
841         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
842     } else {
843         dma->paddr = segs->ds_addr;
844         dma->nseg  = nseg;
845     }
846 }
847 
848 /*
849  * Allocate a block of memory and map it for DMA. No partial completions
850  * allowed and release any resources acquired if we can't acquire all
851  * resources.
852  *
853  * Returns:
854  *   0 = Success, !0 = Failure
855  */
856 int
857 bxe_dma_alloc(struct bxe_softc *sc,
858               bus_size_t       size,
859               struct bxe_dma   *dma,
860               const char       *msg)
861 {
862     int rc;
863 
864     if (dma->size > 0) {
865         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
866               (unsigned long)dma->size);
867         return (1);
868     }
869 
870     memset(dma, 0, sizeof(*dma)); /* sanity */
871     dma->sc   = sc;
872     dma->size = size;
873     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
874 
875     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
876                             BCM_PAGE_SIZE,      /* alignment */
877                             0,                  /* boundary limit */
878                             BUS_SPACE_MAXADDR,  /* restricted low */
879                             BUS_SPACE_MAXADDR,  /* restricted hi */
880                             NULL,               /* addr filter() */
881                             NULL,               /* addr filter() arg */
882                             size,               /* max map size */
883                             1,                  /* num discontinuous */
884                             size,               /* max seg size */
885                             BUS_DMA_ALLOCNOW,   /* flags */
886                             NULL,               /* lock() */
887                             NULL,               /* lock() arg */
888                             &dma->tag);         /* returned dma tag */
889     if (rc != 0) {
890         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
891         memset(dma, 0, sizeof(*dma));
892         return (1);
893     }
894 
895     rc = bus_dmamem_alloc(dma->tag,
896                           (void **)&dma->vaddr,
897                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
898                           &dma->map);
899     if (rc != 0) {
900         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
901         bus_dma_tag_destroy(dma->tag);
902         memset(dma, 0, sizeof(*dma));
903         return (1);
904     }
905 
906     rc = bus_dmamap_load(dma->tag,
907                          dma->map,
908                          dma->vaddr,
909                          size,
910                          bxe_dma_map_addr, /* BLOGD in here */
911                          dma,
912                          BUS_DMA_NOWAIT);
913     if (rc != 0) {
914         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
915         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
916         bus_dma_tag_destroy(dma->tag);
917         memset(dma, 0, sizeof(*dma));
918         return (1);
919     }
920 
921     return (0);
922 }
923 
924 void
925 bxe_dma_free(struct bxe_softc *sc,
926              struct bxe_dma   *dma)
927 {
928     if (dma->size > 0) {
929         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
930 
931         bus_dmamap_sync(dma->tag, dma->map,
932                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
933         bus_dmamap_unload(dma->tag, dma->map);
934         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
935         bus_dma_tag_destroy(dma->tag);
936     }
937 
938     memset(dma, 0, sizeof(*dma));
939 }
940 
941 /*
942  * These indirect read and write routines are only during init.
943  * The locking is handled by the MCP.
944  */
945 
946 void
947 bxe_reg_wr_ind(struct bxe_softc *sc,
948                uint32_t         addr,
949                uint32_t         val)
950 {
951     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
952     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
953     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
954 }
955 
956 uint32_t
957 bxe_reg_rd_ind(struct bxe_softc *sc,
958                uint32_t         addr)
959 {
960     uint32_t val;
961 
962     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
963     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
964     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
965 
966     return (val);
967 }
968 
969 static int
970 bxe_acquire_hw_lock(struct bxe_softc *sc,
971                     uint32_t         resource)
972 {
973     uint32_t lock_status;
974     uint32_t resource_bit = (1 << resource);
975     int func = SC_FUNC(sc);
976     uint32_t hw_lock_control_reg;
977     int cnt;
978 
979     /* validate the resource is within range */
980     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
981         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
982             " resource_bit 0x%x\n", resource, resource_bit);
983         return (-1);
984     }
985 
986     if (func <= 5) {
987         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
988     } else {
989         hw_lock_control_reg =
990                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
991     }
992 
993     /* validate the resource is not already taken */
994     lock_status = REG_RD(sc, hw_lock_control_reg);
995     if (lock_status & resource_bit) {
996         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
997               resource, lock_status, resource_bit);
998         return (-1);
999     }
1000 
1001     /* try every 5ms for 5 seconds */
1002     for (cnt = 0; cnt < 1000; cnt++) {
1003         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1004         lock_status = REG_RD(sc, hw_lock_control_reg);
1005         if (lock_status & resource_bit) {
1006             return (0);
1007         }
1008         DELAY(5000);
1009     }
1010 
1011     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1012         resource, resource_bit);
1013     return (-1);
1014 }
1015 
1016 static int
1017 bxe_release_hw_lock(struct bxe_softc *sc,
1018                     uint32_t         resource)
1019 {
1020     uint32_t lock_status;
1021     uint32_t resource_bit = (1 << resource);
1022     int func = SC_FUNC(sc);
1023     uint32_t hw_lock_control_reg;
1024 
1025     /* validate the resource is within range */
1026     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1027         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1028             " resource_bit 0x%x\n", resource, resource_bit);
1029         return (-1);
1030     }
1031 
1032     if (func <= 5) {
1033         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1034     } else {
1035         hw_lock_control_reg =
1036                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1037     }
1038 
1039     /* validate the resource is currently taken */
1040     lock_status = REG_RD(sc, hw_lock_control_reg);
1041     if (!(lock_status & resource_bit)) {
1042         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1043               resource, lock_status, resource_bit);
1044         return (-1);
1045     }
1046 
1047     REG_WR(sc, hw_lock_control_reg, resource_bit);
1048     return (0);
1049 }
1050 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1051 {
1052 	BXE_PHY_LOCK(sc);
1053 	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1054 }
1055 
1056 static void bxe_release_phy_lock(struct bxe_softc *sc)
1057 {
1058 	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1059 	BXE_PHY_UNLOCK(sc);
1060 }
1061 /*
1062  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1063  * had we done things the other way around, if two pfs from the same port
1064  * would attempt to access nvram at the same time, we could run into a
1065  * scenario such as:
1066  * pf A takes the port lock.
1067  * pf B succeeds in taking the same lock since they are from the same port.
1068  * pf A takes the per pf misc lock. Performs eeprom access.
1069  * pf A finishes. Unlocks the per pf misc lock.
1070  * Pf B takes the lock and proceeds to perform it's own access.
1071  * pf A unlocks the per port lock, while pf B is still working (!).
1072  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1073  * access corrupted by pf B).*
1074  */
1075 static int
1076 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1077 {
1078     int port = SC_PORT(sc);
1079     int count, i;
1080     uint32_t val = 0;
1081 
1082     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1083     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1084 
1085     /* adjust timeout for emulation/FPGA */
1086     count = NVRAM_TIMEOUT_COUNT;
1087     if (CHIP_REV_IS_SLOW(sc)) {
1088         count *= 100;
1089     }
1090 
1091     /* request access to nvram interface */
1092     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1093            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1094 
1095     for (i = 0; i < count*10; i++) {
1096         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1097         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1098             break;
1099         }
1100 
1101         DELAY(5);
1102     }
1103 
1104     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1105         BLOGE(sc, "Cannot get access to nvram interface "
1106             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1107             port, val);
1108         return (-1);
1109     }
1110 
1111     return (0);
1112 }
1113 
1114 static int
1115 bxe_release_nvram_lock(struct bxe_softc *sc)
1116 {
1117     int port = SC_PORT(sc);
1118     int count, i;
1119     uint32_t val = 0;
1120 
1121     /* adjust timeout for emulation/FPGA */
1122     count = NVRAM_TIMEOUT_COUNT;
1123     if (CHIP_REV_IS_SLOW(sc)) {
1124         count *= 100;
1125     }
1126 
1127     /* relinquish nvram interface */
1128     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1129            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1130 
1131     for (i = 0; i < count*10; i++) {
1132         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1133         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1134             break;
1135         }
1136 
1137         DELAY(5);
1138     }
1139 
1140     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1141         BLOGE(sc, "Cannot free access to nvram interface "
1142             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1143             port, val);
1144         return (-1);
1145     }
1146 
1147     /* release HW lock: protect against other PFs in PF Direct Assignment */
1148     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1149 
1150     return (0);
1151 }
1152 
1153 static void
1154 bxe_enable_nvram_access(struct bxe_softc *sc)
1155 {
1156     uint32_t val;
1157 
1158     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1159 
1160     /* enable both bits, even on read */
1161     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1162            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1163 }
1164 
1165 static void
1166 bxe_disable_nvram_access(struct bxe_softc *sc)
1167 {
1168     uint32_t val;
1169 
1170     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1171 
1172     /* disable both bits, even after read */
1173     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1174            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1175                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1176 }
1177 
1178 static int
1179 bxe_nvram_read_dword(struct bxe_softc *sc,
1180                      uint32_t         offset,
1181                      uint32_t         *ret_val,
1182                      uint32_t         cmd_flags)
1183 {
1184     int count, i, rc;
1185     uint32_t val;
1186 
1187     /* build the command word */
1188     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1189 
1190     /* need to clear DONE bit separately */
1191     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1192 
1193     /* address of the NVRAM to read from */
1194     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1195            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1196 
1197     /* issue a read command */
1198     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1199 
1200     /* adjust timeout for emulation/FPGA */
1201     count = NVRAM_TIMEOUT_COUNT;
1202     if (CHIP_REV_IS_SLOW(sc)) {
1203         count *= 100;
1204     }
1205 
1206     /* wait for completion */
1207     *ret_val = 0;
1208     rc = -1;
1209     for (i = 0; i < count; i++) {
1210         DELAY(5);
1211         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1212 
1213         if (val & MCPR_NVM_COMMAND_DONE) {
1214             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1215             /* we read nvram data in cpu order
1216              * but ethtool sees it as an array of bytes
1217              * converting to big-endian will do the work
1218              */
1219             *ret_val = htobe32(val);
1220             rc = 0;
1221             break;
1222         }
1223     }
1224 
1225     if (rc == -1) {
1226         BLOGE(sc, "nvram read timeout expired "
1227             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1228             offset, cmd_flags, val);
1229     }
1230 
1231     return (rc);
1232 }
1233 
1234 static int
1235 bxe_nvram_read(struct bxe_softc *sc,
1236                uint32_t         offset,
1237                uint8_t          *ret_buf,
1238                int              buf_size)
1239 {
1240     uint32_t cmd_flags;
1241     uint32_t val;
1242     int rc;
1243 
1244     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1245         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1246               offset, buf_size);
1247         return (-1);
1248     }
1249 
1250     if ((offset + buf_size) > sc->devinfo.flash_size) {
1251         BLOGE(sc, "Invalid parameter, "
1252                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1253               offset, buf_size, sc->devinfo.flash_size);
1254         return (-1);
1255     }
1256 
1257     /* request access to nvram interface */
1258     rc = bxe_acquire_nvram_lock(sc);
1259     if (rc) {
1260         return (rc);
1261     }
1262 
1263     /* enable access to nvram interface */
1264     bxe_enable_nvram_access(sc);
1265 
1266     /* read the first word(s) */
1267     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1268     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1269         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1270         memcpy(ret_buf, &val, 4);
1271 
1272         /* advance to the next dword */
1273         offset += sizeof(uint32_t);
1274         ret_buf += sizeof(uint32_t);
1275         buf_size -= sizeof(uint32_t);
1276         cmd_flags = 0;
1277     }
1278 
1279     if (rc == 0) {
1280         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1281         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1282         memcpy(ret_buf, &val, 4);
1283     }
1284 
1285     /* disable access to nvram interface */
1286     bxe_disable_nvram_access(sc);
1287     bxe_release_nvram_lock(sc);
1288 
1289     return (rc);
1290 }
1291 
1292 static int
1293 bxe_nvram_write_dword(struct bxe_softc *sc,
1294                       uint32_t         offset,
1295                       uint32_t         val,
1296                       uint32_t         cmd_flags)
1297 {
1298     int count, i, rc;
1299 
1300     /* build the command word */
1301     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1302 
1303     /* need to clear DONE bit separately */
1304     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1305 
1306     /* write the data */
1307     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1308 
1309     /* address of the NVRAM to write to */
1310     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1311            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1312 
1313     /* issue the write command */
1314     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1315 
1316     /* adjust timeout for emulation/FPGA */
1317     count = NVRAM_TIMEOUT_COUNT;
1318     if (CHIP_REV_IS_SLOW(sc)) {
1319         count *= 100;
1320     }
1321 
1322     /* wait for completion */
1323     rc = -1;
1324     for (i = 0; i < count; i++) {
1325         DELAY(5);
1326         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1327         if (val & MCPR_NVM_COMMAND_DONE) {
1328             rc = 0;
1329             break;
1330         }
1331     }
1332 
1333     if (rc == -1) {
1334         BLOGE(sc, "nvram write timeout expired "
1335             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1336             offset, cmd_flags, val);
1337     }
1338 
1339     return (rc);
1340 }
1341 
1342 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1343 
1344 static int
1345 bxe_nvram_write1(struct bxe_softc *sc,
1346                  uint32_t         offset,
1347                  uint8_t          *data_buf,
1348                  int              buf_size)
1349 {
1350     uint32_t cmd_flags;
1351     uint32_t align_offset;
1352     uint32_t val;
1353     int rc;
1354 
1355     if ((offset + buf_size) > sc->devinfo.flash_size) {
1356         BLOGE(sc, "Invalid parameter, "
1357                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1358               offset, buf_size, sc->devinfo.flash_size);
1359         return (-1);
1360     }
1361 
1362     /* request access to nvram interface */
1363     rc = bxe_acquire_nvram_lock(sc);
1364     if (rc) {
1365         return (rc);
1366     }
1367 
1368     /* enable access to nvram interface */
1369     bxe_enable_nvram_access(sc);
1370 
1371     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1372     align_offset = (offset & ~0x03);
1373     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1374 
1375     if (rc == 0) {
1376         val &= ~(0xff << BYTE_OFFSET(offset));
1377         val |= (*data_buf << BYTE_OFFSET(offset));
1378 
1379         /* nvram data is returned as an array of bytes
1380          * convert it back to cpu order
1381          */
1382         val = be32toh(val);
1383 
1384         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1385     }
1386 
1387     /* disable access to nvram interface */
1388     bxe_disable_nvram_access(sc);
1389     bxe_release_nvram_lock(sc);
1390 
1391     return (rc);
1392 }
1393 
1394 static int
1395 bxe_nvram_write(struct bxe_softc *sc,
1396                 uint32_t         offset,
1397                 uint8_t          *data_buf,
1398                 int              buf_size)
1399 {
1400     uint32_t cmd_flags;
1401     uint32_t val;
1402     uint32_t written_so_far;
1403     int rc;
1404 
1405     if (buf_size == 1) {
1406         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1407     }
1408 
1409     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1410         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1411               offset, buf_size);
1412         return (-1);
1413     }
1414 
1415     if (buf_size == 0) {
1416         return (0); /* nothing to do */
1417     }
1418 
1419     if ((offset + buf_size) > sc->devinfo.flash_size) {
1420         BLOGE(sc, "Invalid parameter, "
1421                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1422               offset, buf_size, sc->devinfo.flash_size);
1423         return (-1);
1424     }
1425 
1426     /* request access to nvram interface */
1427     rc = bxe_acquire_nvram_lock(sc);
1428     if (rc) {
1429         return (rc);
1430     }
1431 
1432     /* enable access to nvram interface */
1433     bxe_enable_nvram_access(sc);
1434 
1435     written_so_far = 0;
1436     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1437     while ((written_so_far < buf_size) && (rc == 0)) {
1438         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1439             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1440         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1441             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1442         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1443             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1444         }
1445 
1446         memcpy(&val, data_buf, 4);
1447 
1448         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1449 
1450         /* advance to the next dword */
1451         offset += sizeof(uint32_t);
1452         data_buf += sizeof(uint32_t);
1453         written_so_far += sizeof(uint32_t);
1454         cmd_flags = 0;
1455     }
1456 
1457     /* disable access to nvram interface */
1458     bxe_disable_nvram_access(sc);
1459     bxe_release_nvram_lock(sc);
1460 
1461     return (rc);
1462 }
1463 
1464 /* copy command into DMAE command memory and set DMAE command Go */
1465 void
1466 bxe_post_dmae(struct bxe_softc    *sc,
1467               struct dmae_cmd *dmae,
1468               int                 idx)
1469 {
1470     uint32_t cmd_offset;
1471     int i;
1472 
1473     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1474     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1475         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1476     }
1477 
1478     REG_WR(sc, dmae_reg_go_c[idx], 1);
1479 }
1480 
1481 uint32_t
1482 bxe_dmae_opcode_add_comp(uint32_t opcode,
1483                          uint8_t  comp_type)
1484 {
1485     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1486                       DMAE_CMD_C_TYPE_ENABLE));
1487 }
1488 
1489 uint32_t
1490 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1491 {
1492     return (opcode & ~DMAE_CMD_SRC_RESET);
1493 }
1494 
1495 uint32_t
1496 bxe_dmae_opcode(struct bxe_softc *sc,
1497                 uint8_t          src_type,
1498                 uint8_t          dst_type,
1499                 uint8_t          with_comp,
1500                 uint8_t          comp_type)
1501 {
1502     uint32_t opcode = 0;
1503 
1504     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1505                (dst_type << DMAE_CMD_DST_SHIFT));
1506 
1507     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1508 
1509     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1510 
1511     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1512                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1513 
1514     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1515 
1516 #ifdef __BIG_ENDIAN
1517     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1518 #else
1519     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1520 #endif
1521 
1522     if (with_comp) {
1523         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1524     }
1525 
1526     return (opcode);
1527 }
1528 
1529 static void
1530 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1531                         struct dmae_cmd *dmae,
1532                         uint8_t             src_type,
1533                         uint8_t             dst_type)
1534 {
1535     memset(dmae, 0, sizeof(struct dmae_cmd));
1536 
1537     /* set the opcode */
1538     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1539                                    TRUE, DMAE_COMP_PCI);
1540 
1541     /* fill in the completion parameters */
1542     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1543     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1544     dmae->comp_val     = DMAE_COMP_VAL;
1545 }
1546 
1547 /* issue a DMAE command over the init channel and wait for completion */
1548 static int
1549 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1550                          struct dmae_cmd *dmae)
1551 {
1552     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1553     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1554 
1555     BXE_DMAE_LOCK(sc);
1556 
1557     /* reset completion */
1558     *wb_comp = 0;
1559 
1560     /* post the command on the channel used for initializations */
1561     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1562 
1563     /* wait for completion */
1564     DELAY(5);
1565 
1566     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1567         if (!timeout ||
1568             (sc->recovery_state != BXE_RECOVERY_DONE &&
1569              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1570             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1571                 *wb_comp, sc->recovery_state);
1572             BXE_DMAE_UNLOCK(sc);
1573             return (DMAE_TIMEOUT);
1574         }
1575 
1576         timeout--;
1577         DELAY(50);
1578     }
1579 
1580     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1581         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1582                 *wb_comp, sc->recovery_state);
1583         BXE_DMAE_UNLOCK(sc);
1584         return (DMAE_PCI_ERROR);
1585     }
1586 
1587     BXE_DMAE_UNLOCK(sc);
1588     return (0);
1589 }
1590 
1591 void
1592 bxe_read_dmae(struct bxe_softc *sc,
1593               uint32_t         src_addr,
1594               uint32_t         len32)
1595 {
1596     struct dmae_cmd dmae;
1597     uint32_t *data;
1598     int i, rc;
1599 
1600     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1601 
1602     if (!sc->dmae_ready) {
1603         data = BXE_SP(sc, wb_data[0]);
1604 
1605         for (i = 0; i < len32; i++) {
1606             data[i] = (CHIP_IS_E1(sc)) ?
1607                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1608                           REG_RD(sc, (src_addr + (i * 4)));
1609         }
1610 
1611         return;
1612     }
1613 
1614     /* set opcode and fixed command fields */
1615     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1616 
1617     /* fill in addresses and len */
1618     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1619     dmae.src_addr_hi = 0;
1620     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1621     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1622     dmae.len         = len32;
1623 
1624     /* issue the command and wait for completion */
1625     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1626         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1627     }
1628 }
1629 
1630 void
1631 bxe_write_dmae(struct bxe_softc *sc,
1632                bus_addr_t       dma_addr,
1633                uint32_t         dst_addr,
1634                uint32_t         len32)
1635 {
1636     struct dmae_cmd dmae;
1637     int rc;
1638 
1639     if (!sc->dmae_ready) {
1640         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1641 
1642         if (CHIP_IS_E1(sc)) {
1643             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1644         } else {
1645             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1646         }
1647 
1648         return;
1649     }
1650 
1651     /* set opcode and fixed command fields */
1652     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1653 
1654     /* fill in addresses and len */
1655     dmae.src_addr_lo = U64_LO(dma_addr);
1656     dmae.src_addr_hi = U64_HI(dma_addr);
1657     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1658     dmae.dst_addr_hi = 0;
1659     dmae.len         = len32;
1660 
1661     /* issue the command and wait for completion */
1662     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1663         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1664     }
1665 }
1666 
1667 void
1668 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1669                         bus_addr_t       phys_addr,
1670                         uint32_t         addr,
1671                         uint32_t         len)
1672 {
1673     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1674     int offset = 0;
1675 
1676     while (len > dmae_wr_max) {
1677         bxe_write_dmae(sc,
1678                        (phys_addr + offset), /* src DMA address */
1679                        (addr + offset),      /* dst GRC address */
1680                        dmae_wr_max);
1681         offset += (dmae_wr_max * 4);
1682         len -= dmae_wr_max;
1683     }
1684 
1685     bxe_write_dmae(sc,
1686                    (phys_addr + offset), /* src DMA address */
1687                    (addr + offset),      /* dst GRC address */
1688                    len);
1689 }
1690 
1691 void
1692 bxe_set_ctx_validation(struct bxe_softc   *sc,
1693                        struct eth_context *cxt,
1694                        uint32_t           cid)
1695 {
1696     /* ustorm cxt validation */
1697     cxt->ustorm_ag_context.cdu_usage =
1698         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1699             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1700     /* xcontext validation */
1701     cxt->xstorm_ag_context.cdu_reserved =
1702         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1703             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1704 }
1705 
1706 static void
1707 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1708                             uint8_t          port,
1709                             uint8_t          fw_sb_id,
1710                             uint8_t          sb_index,
1711                             uint8_t          ticks)
1712 {
1713     uint32_t addr =
1714         (BAR_CSTRORM_INTMEM +
1715          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1716 
1717     REG_WR8(sc, addr, ticks);
1718 
1719     BLOGD(sc, DBG_LOAD,
1720           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1721           port, fw_sb_id, sb_index, ticks);
1722 }
1723 
1724 static void
1725 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1726                             uint8_t          port,
1727                             uint16_t         fw_sb_id,
1728                             uint8_t          sb_index,
1729                             uint8_t          disable)
1730 {
1731     uint32_t enable_flag =
1732         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1733     uint32_t addr =
1734         (BAR_CSTRORM_INTMEM +
1735          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1736     uint8_t flags;
1737 
1738     /* clear and set */
1739     flags = REG_RD8(sc, addr);
1740     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1741     flags |= enable_flag;
1742     REG_WR8(sc, addr, flags);
1743 
1744     BLOGD(sc, DBG_LOAD,
1745           "port %d fw_sb_id %d sb_index %d disable %d\n",
1746           port, fw_sb_id, sb_index, disable);
1747 }
1748 
1749 void
1750 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1751                              uint8_t          fw_sb_id,
1752                              uint8_t          sb_index,
1753                              uint8_t          disable,
1754                              uint16_t         usec)
1755 {
1756     int port = SC_PORT(sc);
1757     uint8_t ticks = (usec / 4); /* XXX ??? */
1758 
1759     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1760 
1761     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1762     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1763 }
1764 
1765 void
1766 elink_cb_udelay(struct bxe_softc *sc,
1767                 uint32_t         usecs)
1768 {
1769     DELAY(usecs);
1770 }
1771 
1772 uint32_t
1773 elink_cb_reg_read(struct bxe_softc *sc,
1774                   uint32_t         reg_addr)
1775 {
1776     return (REG_RD(sc, reg_addr));
1777 }
1778 
1779 void
1780 elink_cb_reg_write(struct bxe_softc *sc,
1781                    uint32_t         reg_addr,
1782                    uint32_t         val)
1783 {
1784     REG_WR(sc, reg_addr, val);
1785 }
1786 
1787 void
1788 elink_cb_reg_wb_write(struct bxe_softc *sc,
1789                       uint32_t         offset,
1790                       uint32_t         *wb_write,
1791                       uint16_t         len)
1792 {
1793     REG_WR_DMAE(sc, offset, wb_write, len);
1794 }
1795 
1796 void
1797 elink_cb_reg_wb_read(struct bxe_softc *sc,
1798                      uint32_t         offset,
1799                      uint32_t         *wb_write,
1800                      uint16_t         len)
1801 {
1802     REG_RD_DMAE(sc, offset, wb_write, len);
1803 }
1804 
1805 uint8_t
1806 elink_cb_path_id(struct bxe_softc *sc)
1807 {
1808     return (SC_PATH(sc));
1809 }
1810 
1811 void
1812 elink_cb_event_log(struct bxe_softc     *sc,
1813                    const elink_log_id_t elink_log_id,
1814                    ...)
1815 {
1816     /* XXX */
1817     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1818 }
1819 
1820 static int
1821 bxe_set_spio(struct bxe_softc *sc,
1822              int              spio,
1823              uint32_t         mode)
1824 {
1825     uint32_t spio_reg;
1826 
1827     /* Only 2 SPIOs are configurable */
1828     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1829         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1830         return (-1);
1831     }
1832 
1833     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1834 
1835     /* read SPIO and mask except the float bits */
1836     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1837 
1838     switch (mode) {
1839     case MISC_SPIO_OUTPUT_LOW:
1840         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1841         /* clear FLOAT and set CLR */
1842         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1843         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1844         break;
1845 
1846     case MISC_SPIO_OUTPUT_HIGH:
1847         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1848         /* clear FLOAT and set SET */
1849         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1850         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1851         break;
1852 
1853     case MISC_SPIO_INPUT_HI_Z:
1854         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1855         /* set FLOAT */
1856         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1857         break;
1858 
1859     default:
1860         break;
1861     }
1862 
1863     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1864     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1865 
1866     return (0);
1867 }
1868 
1869 static int
1870 bxe_gpio_read(struct bxe_softc *sc,
1871               int              gpio_num,
1872               uint8_t          port)
1873 {
1874     /* The GPIO should be swapped if swap register is set and active */
1875     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1876                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1877     int gpio_shift = (gpio_num +
1878                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1879     uint32_t gpio_mask = (1 << gpio_shift);
1880     uint32_t gpio_reg;
1881 
1882     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1883         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1884             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1885             gpio_mask);
1886         return (-1);
1887     }
1888 
1889     /* read GPIO value */
1890     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1891 
1892     /* get the requested pin value */
1893     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1894 }
1895 
1896 static int
1897 bxe_gpio_write(struct bxe_softc *sc,
1898                int              gpio_num,
1899                uint32_t         mode,
1900                uint8_t          port)
1901 {
1902     /* The GPIO should be swapped if swap register is set and active */
1903     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1904                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1905     int gpio_shift = (gpio_num +
1906                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1907     uint32_t gpio_mask = (1 << gpio_shift);
1908     uint32_t gpio_reg;
1909 
1910     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1911         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1912             " gpio_shift %d gpio_mask 0x%x\n",
1913             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1914         return (-1);
1915     }
1916 
1917     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1918 
1919     /* read GPIO and mask except the float bits */
1920     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1921 
1922     switch (mode) {
1923     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1924         BLOGD(sc, DBG_PHY,
1925               "Set GPIO %d (shift %d) -> output low\n",
1926               gpio_num, gpio_shift);
1927         /* clear FLOAT and set CLR */
1928         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1929         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1930         break;
1931 
1932     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1933         BLOGD(sc, DBG_PHY,
1934               "Set GPIO %d (shift %d) -> output high\n",
1935               gpio_num, gpio_shift);
1936         /* clear FLOAT and set SET */
1937         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1938         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1939         break;
1940 
1941     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1942         BLOGD(sc, DBG_PHY,
1943               "Set GPIO %d (shift %d) -> input\n",
1944               gpio_num, gpio_shift);
1945         /* set FLOAT */
1946         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1947         break;
1948 
1949     default:
1950         break;
1951     }
1952 
1953     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1954     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1955 
1956     return (0);
1957 }
1958 
1959 static int
1960 bxe_gpio_mult_write(struct bxe_softc *sc,
1961                     uint8_t          pins,
1962                     uint32_t         mode)
1963 {
1964     uint32_t gpio_reg;
1965 
1966     /* any port swapping should be handled by caller */
1967 
1968     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1969 
1970     /* read GPIO and mask except the float bits */
1971     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1972     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1973     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1974     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1975 
1976     switch (mode) {
1977     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1978         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1979         /* set CLR */
1980         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1981         break;
1982 
1983     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1984         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1985         /* set SET */
1986         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
1987         break;
1988 
1989     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1990         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
1991         /* set FLOAT */
1992         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1993         break;
1994 
1995     default:
1996         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
1997             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
1998         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1999         return (-1);
2000     }
2001 
2002     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2003     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2004 
2005     return (0);
2006 }
2007 
2008 static int
2009 bxe_gpio_int_write(struct bxe_softc *sc,
2010                    int              gpio_num,
2011                    uint32_t         mode,
2012                    uint8_t          port)
2013 {
2014     /* The GPIO should be swapped if swap register is set and active */
2015     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2016                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2017     int gpio_shift = (gpio_num +
2018                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2019     uint32_t gpio_mask = (1 << gpio_shift);
2020     uint32_t gpio_reg;
2021 
2022     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2023         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2024             " gpio_shift %d gpio_mask 0x%x\n",
2025             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2026         return (-1);
2027     }
2028 
2029     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2030 
2031     /* read GPIO int */
2032     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2033 
2034     switch (mode) {
2035     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2036         BLOGD(sc, DBG_PHY,
2037               "Clear GPIO INT %d (shift %d) -> output low\n",
2038               gpio_num, gpio_shift);
2039         /* clear SET and set CLR */
2040         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2041         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2042         break;
2043 
2044     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2045         BLOGD(sc, DBG_PHY,
2046               "Set GPIO INT %d (shift %d) -> output high\n",
2047               gpio_num, gpio_shift);
2048         /* clear CLR and set SET */
2049         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2050         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2051         break;
2052 
2053     default:
2054         break;
2055     }
2056 
2057     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2058     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2059 
2060     return (0);
2061 }
2062 
2063 uint32_t
2064 elink_cb_gpio_read(struct bxe_softc *sc,
2065                    uint16_t         gpio_num,
2066                    uint8_t          port)
2067 {
2068     return (bxe_gpio_read(sc, gpio_num, port));
2069 }
2070 
2071 uint8_t
2072 elink_cb_gpio_write(struct bxe_softc *sc,
2073                     uint16_t         gpio_num,
2074                     uint8_t          mode, /* 0=low 1=high */
2075                     uint8_t          port)
2076 {
2077     return (bxe_gpio_write(sc, gpio_num, mode, port));
2078 }
2079 
2080 uint8_t
2081 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2082                          uint8_t          pins,
2083                          uint8_t          mode) /* 0=low 1=high */
2084 {
2085     return (bxe_gpio_mult_write(sc, pins, mode));
2086 }
2087 
2088 uint8_t
2089 elink_cb_gpio_int_write(struct bxe_softc *sc,
2090                         uint16_t         gpio_num,
2091                         uint8_t          mode, /* 0=low 1=high */
2092                         uint8_t          port)
2093 {
2094     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2095 }
2096 
2097 void
2098 elink_cb_notify_link_changed(struct bxe_softc *sc)
2099 {
2100     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2101                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2102 }
2103 
2104 /* send the MCP a request, block until there is a reply */
2105 uint32_t
2106 elink_cb_fw_command(struct bxe_softc *sc,
2107                     uint32_t         command,
2108                     uint32_t         param)
2109 {
2110     int mb_idx = SC_FW_MB_IDX(sc);
2111     uint32_t seq;
2112     uint32_t rc = 0;
2113     uint32_t cnt = 1;
2114     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2115 
2116     BXE_FWMB_LOCK(sc);
2117 
2118     seq = ++sc->fw_seq;
2119     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2120     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2121 
2122     BLOGD(sc, DBG_PHY,
2123           "wrote command 0x%08x to FW MB param 0x%08x\n",
2124           (command | seq), param);
2125 
2126     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2127     do {
2128         DELAY(delay * 1000);
2129         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2130     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2131 
2132     BLOGD(sc, DBG_PHY,
2133           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2134           cnt*delay, rc, seq);
2135 
2136     /* is this a reply to our command? */
2137     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2138         rc &= FW_MSG_CODE_MASK;
2139     } else {
2140         /* Ruh-roh! */
2141         BLOGE(sc, "FW failed to respond!\n");
2142         // XXX bxe_fw_dump(sc);
2143         rc = 0;
2144     }
2145 
2146     BXE_FWMB_UNLOCK(sc);
2147     return (rc);
2148 }
2149 
2150 static uint32_t
2151 bxe_fw_command(struct bxe_softc *sc,
2152                uint32_t         command,
2153                uint32_t         param)
2154 {
2155     return (elink_cb_fw_command(sc, command, param));
2156 }
2157 
2158 static void
2159 __storm_memset_dma_mapping(struct bxe_softc *sc,
2160                            uint32_t         addr,
2161                            bus_addr_t       mapping)
2162 {
2163     REG_WR(sc, addr, U64_LO(mapping));
2164     REG_WR(sc, (addr + 4), U64_HI(mapping));
2165 }
2166 
2167 static void
2168 storm_memset_spq_addr(struct bxe_softc *sc,
2169                       bus_addr_t       mapping,
2170                       uint16_t         abs_fid)
2171 {
2172     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2173                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2174     __storm_memset_dma_mapping(sc, addr, mapping);
2175 }
2176 
2177 static void
2178 storm_memset_vf_to_pf(struct bxe_softc *sc,
2179                       uint16_t         abs_fid,
2180                       uint16_t         pf_id)
2181 {
2182     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2183     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2184     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2185     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2186 }
2187 
2188 static void
2189 storm_memset_func_en(struct bxe_softc *sc,
2190                      uint16_t         abs_fid,
2191                      uint8_t          enable)
2192 {
2193     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2194     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2195     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2196     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2197 }
2198 
2199 static void
2200 storm_memset_eq_data(struct bxe_softc       *sc,
2201                      struct event_ring_data *eq_data,
2202                      uint16_t               pfid)
2203 {
2204     uint32_t addr;
2205     size_t size;
2206 
2207     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2208     size = sizeof(struct event_ring_data);
2209     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2210 }
2211 
2212 static void
2213 storm_memset_eq_prod(struct bxe_softc *sc,
2214                      uint16_t         eq_prod,
2215                      uint16_t         pfid)
2216 {
2217     uint32_t addr = (BAR_CSTRORM_INTMEM +
2218                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2219     REG_WR16(sc, addr, eq_prod);
2220 }
2221 
2222 /*
2223  * Post a slowpath command.
2224  *
2225  * A slowpath command is used to propogate a configuration change through
2226  * the controller in a controlled manner, allowing each STORM processor and
2227  * other H/W blocks to phase in the change.  The commands sent on the
2228  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2229  * completion of the ramrod will occur in different ways.  Here's a
2230  * breakdown of ramrods and how they complete:
2231  *
2232  * RAMROD_CMD_ID_ETH_PORT_SETUP
2233  *   Used to setup the leading connection on a port.  Completes on the
2234  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2235  *
2236  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2237  *   Used to setup an additional connection on a port.  Completes on the
2238  *   RCQ of the multi-queue/RSS connection being initialized.
2239  *
2240  * RAMROD_CMD_ID_ETH_STAT_QUERY
2241  *   Used to force the storm processors to update the statistics database
2242  *   in host memory.  This ramrod is send on the leading connection CID and
2243  *   completes as an index increment of the CSTORM on the default status
2244  *   block.
2245  *
2246  * RAMROD_CMD_ID_ETH_UPDATE
2247  *   Used to update the state of the leading connection, usually to udpate
2248  *   the RSS indirection table.  Completes on the RCQ of the leading
2249  *   connection. (Not currently used under FreeBSD until OS support becomes
2250  *   available.)
2251  *
2252  * RAMROD_CMD_ID_ETH_HALT
2253  *   Used when tearing down a connection prior to driver unload.  Completes
2254  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2255  *   use this on the leading connection.
2256  *
2257  * RAMROD_CMD_ID_ETH_SET_MAC
2258  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2259  *   the RCQ of the leading connection.
2260  *
2261  * RAMROD_CMD_ID_ETH_CFC_DEL
2262  *   Used when tearing down a conneciton prior to driver unload.  Completes
2263  *   on the RCQ of the leading connection (since the current connection
2264  *   has been completely removed from controller memory).
2265  *
2266  * RAMROD_CMD_ID_ETH_PORT_DEL
2267  *   Used to tear down the leading connection prior to driver unload,
2268  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2269  *   default status block.
2270  *
2271  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2272  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2273  *   RSS connection that is being offloaded.  (Not currently used under
2274  *   FreeBSD.)
2275  *
2276  * There can only be one command pending per function.
2277  *
2278  * Returns:
2279  *   0 = Success, !0 = Failure.
2280  */
2281 
2282 /* must be called under the spq lock */
2283 static inline
2284 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2285 {
2286     struct eth_spe *next_spe = sc->spq_prod_bd;
2287 
2288     if (sc->spq_prod_bd == sc->spq_last_bd) {
2289         /* wrap back to the first eth_spq */
2290         sc->spq_prod_bd = sc->spq;
2291         sc->spq_prod_idx = 0;
2292     } else {
2293         sc->spq_prod_bd++;
2294         sc->spq_prod_idx++;
2295     }
2296 
2297     return (next_spe);
2298 }
2299 
2300 /* must be called under the spq lock */
2301 static inline
2302 void bxe_sp_prod_update(struct bxe_softc *sc)
2303 {
2304     int func = SC_FUNC(sc);
2305 
2306     /*
2307      * Make sure that BD data is updated before writing the producer.
2308      * BD data is written to the memory, the producer is read from the
2309      * memory, thus we need a full memory barrier to ensure the ordering.
2310      */
2311     mb();
2312 
2313     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2314              sc->spq_prod_idx);
2315 
2316     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2317                       BUS_SPACE_BARRIER_WRITE);
2318 }
2319 
2320 /**
2321  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2322  *
2323  * @cmd:      command to check
2324  * @cmd_type: command type
2325  */
2326 static inline
2327 int bxe_is_contextless_ramrod(int cmd,
2328                               int cmd_type)
2329 {
2330     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2331         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2332         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2333         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2334         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2335         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2336         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2337         return (TRUE);
2338     } else {
2339         return (FALSE);
2340     }
2341 }
2342 
2343 /**
2344  * bxe_sp_post - place a single command on an SP ring
2345  *
2346  * @sc:         driver handle
2347  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2348  * @cid:        SW CID the command is related to
2349  * @data_hi:    command private data address (high 32 bits)
2350  * @data_lo:    command private data address (low 32 bits)
2351  * @cmd_type:   command type (e.g. NONE, ETH)
2352  *
2353  * SP data is handled as if it's always an address pair, thus data fields are
2354  * not swapped to little endian in upper functions. Instead this function swaps
2355  * data as if it's two uint32 fields.
2356  */
2357 int
2358 bxe_sp_post(struct bxe_softc *sc,
2359             int              command,
2360             int              cid,
2361             uint32_t         data_hi,
2362             uint32_t         data_lo,
2363             int              cmd_type)
2364 {
2365     struct eth_spe *spe;
2366     uint16_t type;
2367     int common;
2368 
2369     common = bxe_is_contextless_ramrod(command, cmd_type);
2370 
2371     BXE_SP_LOCK(sc);
2372 
2373     if (common) {
2374         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2375             BLOGE(sc, "EQ ring is full!\n");
2376             BXE_SP_UNLOCK(sc);
2377             return (-1);
2378         }
2379     } else {
2380         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2381             BLOGE(sc, "SPQ ring is full!\n");
2382             BXE_SP_UNLOCK(sc);
2383             return (-1);
2384         }
2385     }
2386 
2387     spe = bxe_sp_get_next(sc);
2388 
2389     /* CID needs port number to be encoded int it */
2390     spe->hdr.conn_and_cmd_data =
2391         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2392 
2393     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2394 
2395     /* TBD: Check if it works for VFs */
2396     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2397              SPE_HDR_T_FUNCTION_ID);
2398 
2399     spe->hdr.type = htole16(type);
2400 
2401     spe->data.update_data_addr.hi = htole32(data_hi);
2402     spe->data.update_data_addr.lo = htole32(data_lo);
2403 
2404     /*
2405      * It's ok if the actual decrement is issued towards the memory
2406      * somewhere between the lock and unlock. Thus no more explict
2407      * memory barrier is needed.
2408      */
2409     if (common) {
2410         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2411     } else {
2412         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2413     }
2414 
2415     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2416     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2417           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2418     BLOGD(sc, DBG_SP,
2419           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2420           sc->spq_prod_idx,
2421           (uint32_t)U64_HI(sc->spq_dma.paddr),
2422           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2423           command,
2424           common,
2425           HW_CID(sc, cid),
2426           data_hi,
2427           data_lo,
2428           type,
2429           atomic_load_acq_long(&sc->cq_spq_left),
2430           atomic_load_acq_long(&sc->eq_spq_left));
2431 
2432     bxe_sp_prod_update(sc);
2433 
2434     BXE_SP_UNLOCK(sc);
2435     return (0);
2436 }
2437 
2438 /**
2439  * bxe_debug_print_ind_table - prints the indirection table configuration.
2440  *
2441  * @sc: driver hanlde
2442  * @p:  pointer to rss configuration
2443  */
2444 
2445 /*
2446  * FreeBSD Device probe function.
2447  *
2448  * Compares the device found to the driver's list of supported devices and
2449  * reports back to the bsd loader whether this is the right driver for the device.
2450  * This is the driver entry function called from the "kldload" command.
2451  *
2452  * Returns:
2453  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2454  */
2455 static int
2456 bxe_probe(device_t dev)
2457 {
2458     struct bxe_softc *sc;
2459     struct bxe_device_type *t;
2460     char *descbuf;
2461     uint16_t did, sdid, svid, vid;
2462 
2463     /* Find our device structure */
2464     sc = device_get_softc(dev);
2465     sc->dev = dev;
2466     t = bxe_devs;
2467 
2468     /* Get the data for the device to be probed. */
2469     vid  = pci_get_vendor(dev);
2470     did  = pci_get_device(dev);
2471     svid = pci_get_subvendor(dev);
2472     sdid = pci_get_subdevice(dev);
2473 
2474     BLOGD(sc, DBG_LOAD,
2475           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2476           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2477 
2478     /* Look through the list of known devices for a match. */
2479     while (t->bxe_name != NULL) {
2480         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2481             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2482             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2483             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2484             if (descbuf == NULL)
2485                 return (ENOMEM);
2486 
2487             /* Print out the device identity. */
2488             snprintf(descbuf, BXE_DEVDESC_MAX,
2489                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2490                      (((pci_read_config(dev, PCIR_REVID, 4) &
2491                         0xf0) >> 4) + 'A'),
2492                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2493                      BXE_DRIVER_VERSION);
2494 
2495             device_set_desc_copy(dev, descbuf);
2496             free(descbuf, M_TEMP);
2497             return (BUS_PROBE_DEFAULT);
2498         }
2499         t++;
2500     }
2501 
2502     return (ENXIO);
2503 }
2504 
2505 static void
2506 bxe_init_mutexes(struct bxe_softc *sc)
2507 {
2508 #ifdef BXE_CORE_LOCK_SX
2509     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2510              "bxe%d_core_lock", sc->unit);
2511     sx_init(&sc->core_sx, sc->core_sx_name);
2512 #else
2513     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2514              "bxe%d_core_lock", sc->unit);
2515     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2516 #endif
2517 
2518     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2519              "bxe%d_sp_lock", sc->unit);
2520     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2521 
2522     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2523              "bxe%d_dmae_lock", sc->unit);
2524     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2525 
2526     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2527              "bxe%d_phy_lock", sc->unit);
2528     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2529 
2530     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2531              "bxe%d_fwmb_lock", sc->unit);
2532     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2533 
2534     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2535              "bxe%d_print_lock", sc->unit);
2536     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2537 
2538     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2539              "bxe%d_stats_lock", sc->unit);
2540     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2541 
2542     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2543              "bxe%d_mcast_lock", sc->unit);
2544     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2545 }
2546 
2547 static void
2548 bxe_release_mutexes(struct bxe_softc *sc)
2549 {
2550 #ifdef BXE_CORE_LOCK_SX
2551     sx_destroy(&sc->core_sx);
2552 #else
2553     if (mtx_initialized(&sc->core_mtx)) {
2554         mtx_destroy(&sc->core_mtx);
2555     }
2556 #endif
2557 
2558     if (mtx_initialized(&sc->sp_mtx)) {
2559         mtx_destroy(&sc->sp_mtx);
2560     }
2561 
2562     if (mtx_initialized(&sc->dmae_mtx)) {
2563         mtx_destroy(&sc->dmae_mtx);
2564     }
2565 
2566     if (mtx_initialized(&sc->port.phy_mtx)) {
2567         mtx_destroy(&sc->port.phy_mtx);
2568     }
2569 
2570     if (mtx_initialized(&sc->fwmb_mtx)) {
2571         mtx_destroy(&sc->fwmb_mtx);
2572     }
2573 
2574     if (mtx_initialized(&sc->print_mtx)) {
2575         mtx_destroy(&sc->print_mtx);
2576     }
2577 
2578     if (mtx_initialized(&sc->stats_mtx)) {
2579         mtx_destroy(&sc->stats_mtx);
2580     }
2581 
2582     if (mtx_initialized(&sc->mcast_mtx)) {
2583         mtx_destroy(&sc->mcast_mtx);
2584     }
2585 }
2586 
2587 static void
2588 bxe_tx_disable(struct bxe_softc* sc)
2589 {
2590     if_t ifp = sc->ifp;
2591 
2592     /* tell the stack the driver is stopped and TX queue is full */
2593     if (ifp !=  NULL) {
2594         if_setdrvflags(ifp, 0);
2595     }
2596 }
2597 
2598 static void
2599 bxe_drv_pulse(struct bxe_softc *sc)
2600 {
2601     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2602              sc->fw_drv_pulse_wr_seq);
2603 }
2604 
2605 static inline uint16_t
2606 bxe_tx_avail(struct bxe_softc *sc,
2607              struct bxe_fastpath *fp)
2608 {
2609     int16_t  used;
2610     uint16_t prod;
2611     uint16_t cons;
2612 
2613     prod = fp->tx_bd_prod;
2614     cons = fp->tx_bd_cons;
2615 
2616     used = SUB_S16(prod, cons);
2617 
2618     return (int16_t)(sc->tx_ring_size) - used;
2619 }
2620 
2621 static inline int
2622 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2623 {
2624     uint16_t hw_cons;
2625 
2626     mb(); /* status block fields can change */
2627     hw_cons = le16toh(*fp->tx_cons_sb);
2628     return (hw_cons != fp->tx_pkt_cons);
2629 }
2630 
2631 static inline uint8_t
2632 bxe_has_tx_work(struct bxe_fastpath *fp)
2633 {
2634     /* expand this for multi-cos if ever supported */
2635     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2636 }
2637 
2638 static inline int
2639 bxe_has_rx_work(struct bxe_fastpath *fp)
2640 {
2641     uint16_t rx_cq_cons_sb;
2642 
2643     mb(); /* status block fields can change */
2644     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2645     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2646         rx_cq_cons_sb++;
2647     return (fp->rx_cq_cons != rx_cq_cons_sb);
2648 }
2649 
2650 static void
2651 bxe_sp_event(struct bxe_softc    *sc,
2652              struct bxe_fastpath *fp,
2653              union eth_rx_cqe    *rr_cqe)
2654 {
2655     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2656     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2657     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2658     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2659 
2660     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2661           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2662 
2663     switch (command) {
2664     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2665         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2666         drv_cmd = ECORE_Q_CMD_UPDATE;
2667         break;
2668 
2669     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2670         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2671         drv_cmd = ECORE_Q_CMD_SETUP;
2672         break;
2673 
2674     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2675         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2676         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2677         break;
2678 
2679     case (RAMROD_CMD_ID_ETH_HALT):
2680         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2681         drv_cmd = ECORE_Q_CMD_HALT;
2682         break;
2683 
2684     case (RAMROD_CMD_ID_ETH_TERMINATE):
2685         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2686         drv_cmd = ECORE_Q_CMD_TERMINATE;
2687         break;
2688 
2689     case (RAMROD_CMD_ID_ETH_EMPTY):
2690         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2691         drv_cmd = ECORE_Q_CMD_EMPTY;
2692         break;
2693 
2694     default:
2695         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2696               command, fp->index);
2697         return;
2698     }
2699 
2700     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2701         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2702         /*
2703          * q_obj->complete_cmd() failure means that this was
2704          * an unexpected completion.
2705          *
2706          * In this case we don't want to increase the sc->spq_left
2707          * because apparently we haven't sent this command the first
2708          * place.
2709          */
2710         // bxe_panic(sc, ("Unexpected SP completion\n"));
2711         return;
2712     }
2713 
2714     atomic_add_acq_long(&sc->cq_spq_left, 1);
2715 
2716     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2717           atomic_load_acq_long(&sc->cq_spq_left));
2718 }
2719 
2720 /*
2721  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2722  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2723  * the current aggregation queue as in-progress.
2724  */
2725 static void
2726 bxe_tpa_start(struct bxe_softc            *sc,
2727               struct bxe_fastpath         *fp,
2728               uint16_t                    queue,
2729               uint16_t                    cons,
2730               uint16_t                    prod,
2731               struct eth_fast_path_rx_cqe *cqe)
2732 {
2733     struct bxe_sw_rx_bd tmp_bd;
2734     struct bxe_sw_rx_bd *rx_buf;
2735     struct eth_rx_bd *rx_bd;
2736     int max_agg_queues;
2737     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2738     uint16_t index;
2739 
2740     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2741                        "cons=%d prod=%d\n",
2742           fp->index, queue, cons, prod);
2743 
2744     max_agg_queues = MAX_AGG_QS(sc);
2745 
2746     KASSERT((queue < max_agg_queues),
2747             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2748              fp->index, queue, max_agg_queues));
2749 
2750     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2751             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2752              fp->index, queue));
2753 
2754     /* copy the existing mbuf and mapping from the TPA pool */
2755     tmp_bd = tpa_info->bd;
2756 
2757     if (tmp_bd.m == NULL) {
2758         uint32_t *tmp;
2759 
2760         tmp = (uint32_t *)cqe;
2761 
2762         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2763               fp->index, queue, cons, prod);
2764         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2765             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2766 
2767         /* XXX Error handling? */
2768         return;
2769     }
2770 
2771     /* change the TPA queue to the start state */
2772     tpa_info->state            = BXE_TPA_STATE_START;
2773     tpa_info->placement_offset = cqe->placement_offset;
2774     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2775     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2776     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2777 
2778     fp->rx_tpa_queue_used |= (1 << queue);
2779 
2780     /*
2781      * If all the buffer descriptors are filled with mbufs then fill in
2782      * the current consumer index with a new BD. Else if a maximum Rx
2783      * buffer limit is imposed then fill in the next producer index.
2784      */
2785     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2786                 prod : cons;
2787 
2788     /* move the received mbuf and mapping to TPA pool */
2789     tpa_info->bd = fp->rx_mbuf_chain[cons];
2790 
2791     /* release any existing RX BD mbuf mappings */
2792     if (cons != index) {
2793         rx_buf = &fp->rx_mbuf_chain[cons];
2794 
2795         if (rx_buf->m_map != NULL) {
2796             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2797                             BUS_DMASYNC_POSTREAD);
2798             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2799         }
2800 
2801         /*
2802          * We get here when the maximum number of rx buffers is less than
2803          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2804          * it out here without concern of a memory leak.
2805          */
2806         fp->rx_mbuf_chain[cons].m = NULL;
2807     }
2808 
2809     /* update the Rx SW BD with the mbuf info from the TPA pool */
2810     fp->rx_mbuf_chain[index] = tmp_bd;
2811 
2812     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2813     rx_bd = &fp->rx_chain[index];
2814     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2815     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2816 }
2817 
2818 /*
2819  * When a TPA aggregation is completed, loop through the individual mbufs
2820  * of the aggregation, combining them into a single mbuf which will be sent
2821  * up the stack. Refill all freed SGEs with mbufs as we go along.
2822  */
2823 static int
2824 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2825                    struct bxe_fastpath       *fp,
2826                    struct bxe_sw_tpa_info    *tpa_info,
2827                    uint16_t                  queue,
2828                    uint16_t                  pages,
2829                    struct mbuf               *m,
2830 			       struct eth_end_agg_rx_cqe *cqe,
2831                    uint16_t                  cqe_idx)
2832 {
2833     struct mbuf *m_frag;
2834     uint32_t frag_len, frag_size, i;
2835     uint16_t sge_idx;
2836     int rc = 0;
2837     int j;
2838 
2839     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2840 
2841     BLOGD(sc, DBG_LRO,
2842           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2843           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2844 
2845     /* make sure the aggregated frame is not too big to handle */
2846     if (pages > 8 * PAGES_PER_SGE) {
2847 
2848         uint32_t *tmp = (uint32_t *)cqe;
2849 
2850         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2851                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2852               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2853               tpa_info->len_on_bd, frag_size);
2854 
2855         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2856             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2857 
2858         bxe_panic(sc, ("sge page count error\n"));
2859         return (EINVAL);
2860     }
2861 
2862     /*
2863      * Scan through the scatter gather list pulling individual mbufs into a
2864      * single mbuf for the host stack.
2865      */
2866     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2867         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2868 
2869         /*
2870          * Firmware gives the indices of the SGE as if the ring is an array
2871          * (meaning that the "next" element will consume 2 indices).
2872          */
2873         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2874 
2875         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2876                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2877               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2878 
2879         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2880 
2881         /* allocate a new mbuf for the SGE */
2882         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2883         if (rc) {
2884             /* Leave all remaining SGEs in the ring! */
2885             return (rc);
2886         }
2887 
2888         /* update the fragment length */
2889         m_frag->m_len = frag_len;
2890 
2891         /* concatenate the fragment to the head mbuf */
2892         m_cat(m, m_frag);
2893         fp->eth_q_stats.mbuf_alloc_sge--;
2894 
2895         /* update the TPA mbuf size and remaining fragment size */
2896         m->m_pkthdr.len += frag_len;
2897         frag_size -= frag_len;
2898     }
2899 
2900     BLOGD(sc, DBG_LRO,
2901           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2902           fp->index, queue, frag_size);
2903 
2904     return (rc);
2905 }
2906 
2907 static inline void
2908 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2909 {
2910     int i, j;
2911 
2912     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2913         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2914 
2915         for (j = 0; j < 2; j++) {
2916             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2917             idx--;
2918         }
2919     }
2920 }
2921 
2922 static inline void
2923 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2924 {
2925     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2926     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2927 
2928     /*
2929      * Clear the two last indices in the page to 1. These are the indices that
2930      * correspond to the "next" element, hence will never be indicated and
2931      * should be removed from the calculations.
2932      */
2933     bxe_clear_sge_mask_next_elems(fp);
2934 }
2935 
2936 static inline void
2937 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2938                         uint16_t            idx)
2939 {
2940     uint16_t last_max = fp->last_max_sge;
2941 
2942     if (SUB_S16(idx, last_max) > 0) {
2943         fp->last_max_sge = idx;
2944     }
2945 }
2946 
2947 static inline void
2948 bxe_update_sge_prod(struct bxe_softc          *sc,
2949                     struct bxe_fastpath       *fp,
2950                     uint16_t                  sge_len,
2951                     union eth_sgl_or_raw_data *cqe)
2952 {
2953     uint16_t last_max, last_elem, first_elem;
2954     uint16_t delta = 0;
2955     uint16_t i;
2956 
2957     if (!sge_len) {
2958         return;
2959     }
2960 
2961     /* first mark all used pages */
2962     for (i = 0; i < sge_len; i++) {
2963         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2964                             RX_SGE(le16toh(cqe->sgl[i])));
2965     }
2966 
2967     BLOGD(sc, DBG_LRO,
2968           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2969           fp->index, sge_len - 1,
2970           le16toh(cqe->sgl[sge_len - 1]));
2971 
2972     /* assume that the last SGE index is the biggest */
2973     bxe_update_last_max_sge(fp,
2974                             le16toh(cqe->sgl[sge_len - 1]));
2975 
2976     last_max = RX_SGE(fp->last_max_sge);
2977     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2978     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2979 
2980     /* if ring is not full */
2981     if (last_elem + 1 != first_elem) {
2982         last_elem++;
2983     }
2984 
2985     /* now update the prod */
2986     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2987         if (__predict_true(fp->sge_mask[i])) {
2988             break;
2989         }
2990 
2991         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
2992         delta += BIT_VEC64_ELEM_SZ;
2993     }
2994 
2995     if (delta > 0) {
2996         fp->rx_sge_prod += delta;
2997         /* clear page-end entries */
2998         bxe_clear_sge_mask_next_elems(fp);
2999     }
3000 
3001     BLOGD(sc, DBG_LRO,
3002           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3003           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3004 }
3005 
3006 /*
3007  * The aggregation on the current TPA queue has completed. Pull the individual
3008  * mbuf fragments together into a single mbuf, perform all necessary checksum
3009  * calculations, and send the resuting mbuf to the stack.
3010  */
3011 static void
3012 bxe_tpa_stop(struct bxe_softc          *sc,
3013              struct bxe_fastpath       *fp,
3014              struct bxe_sw_tpa_info    *tpa_info,
3015              uint16_t                  queue,
3016              uint16_t                  pages,
3017 			 struct eth_end_agg_rx_cqe *cqe,
3018              uint16_t                  cqe_idx)
3019 {
3020     if_t ifp = sc->ifp;
3021     struct mbuf *m;
3022     int rc = 0;
3023 
3024     BLOGD(sc, DBG_LRO,
3025           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3026           fp->index, queue, tpa_info->placement_offset,
3027           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3028 
3029     m = tpa_info->bd.m;
3030 
3031     /* allocate a replacement before modifying existing mbuf */
3032     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3033     if (rc) {
3034         /* drop the frame and log an error */
3035         fp->eth_q_stats.rx_soft_errors++;
3036         goto bxe_tpa_stop_exit;
3037     }
3038 
3039     /* we have a replacement, fixup the current mbuf */
3040     m_adj(m, tpa_info->placement_offset);
3041     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3042 
3043     /* mark the checksums valid (taken care of by the firmware) */
3044     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3045     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3046     m->m_pkthdr.csum_data = 0xffff;
3047     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3048                                CSUM_IP_VALID   |
3049                                CSUM_DATA_VALID |
3050                                CSUM_PSEUDO_HDR);
3051 
3052     /* aggregate all of the SGEs into a single mbuf */
3053     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3054     if (rc) {
3055         /* drop the packet and log an error */
3056         fp->eth_q_stats.rx_soft_errors++;
3057         m_freem(m);
3058     } else {
3059         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3060             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3061             m->m_flags |= M_VLANTAG;
3062         }
3063 
3064         /* assign packet to this interface interface */
3065         if_setrcvif(m, ifp);
3066 
3067 #if __FreeBSD_version >= 800000
3068         /* specify what RSS queue was used for this flow */
3069         m->m_pkthdr.flowid = fp->index;
3070         BXE_SET_FLOWID(m);
3071 #endif
3072 
3073         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3074         fp->eth_q_stats.rx_tpa_pkts++;
3075 
3076         /* pass the frame to the stack */
3077         if_input(ifp, m);
3078     }
3079 
3080     /* we passed an mbuf up the stack or dropped the frame */
3081     fp->eth_q_stats.mbuf_alloc_tpa--;
3082 
3083 bxe_tpa_stop_exit:
3084 
3085     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3086     fp->rx_tpa_queue_used &= ~(1 << queue);
3087 }
3088 
3089 static uint8_t
3090 bxe_service_rxsgl(
3091                  struct bxe_fastpath *fp,
3092                  uint16_t len,
3093                  uint16_t lenonbd,
3094                  struct mbuf *m,
3095                  struct eth_fast_path_rx_cqe *cqe_fp)
3096 {
3097     struct mbuf *m_frag;
3098     uint16_t frags, frag_len;
3099     uint16_t sge_idx = 0;
3100     uint16_t j;
3101     uint8_t i, rc = 0;
3102     uint32_t frag_size;
3103 
3104     /* adjust the mbuf */
3105     m->m_len = lenonbd;
3106 
3107     frag_size =  len - lenonbd;
3108     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3109 
3110     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3111         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3112 
3113         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3114         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3115         m_frag->m_len = frag_len;
3116 
3117        /* allocate a new mbuf for the SGE */
3118         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3119         if (rc) {
3120             /* Leave all remaining SGEs in the ring! */
3121             return (rc);
3122         }
3123         fp->eth_q_stats.mbuf_alloc_sge--;
3124 
3125         /* concatenate the fragment to the head mbuf */
3126         m_cat(m, m_frag);
3127 
3128         frag_size -= frag_len;
3129     }
3130 
3131     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3132 
3133     return rc;
3134 }
3135 
3136 static uint8_t
3137 bxe_rxeof(struct bxe_softc    *sc,
3138           struct bxe_fastpath *fp)
3139 {
3140     if_t ifp = sc->ifp;
3141     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3142     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3143     int rx_pkts = 0;
3144     int rc = 0;
3145 
3146     BXE_FP_RX_LOCK(fp);
3147 
3148     /* CQ "next element" is of the size of the regular element */
3149     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3150     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3151         hw_cq_cons++;
3152     }
3153 
3154     bd_cons = fp->rx_bd_cons;
3155     bd_prod = fp->rx_bd_prod;
3156     bd_prod_fw = bd_prod;
3157     sw_cq_cons = fp->rx_cq_cons;
3158     sw_cq_prod = fp->rx_cq_prod;
3159 
3160     /*
3161      * Memory barrier necessary as speculative reads of the rx
3162      * buffer can be ahead of the index in the status block
3163      */
3164     rmb();
3165 
3166     BLOGD(sc, DBG_RX,
3167           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3168           fp->index, hw_cq_cons, sw_cq_cons);
3169 
3170     while (sw_cq_cons != hw_cq_cons) {
3171         struct bxe_sw_rx_bd *rx_buf = NULL;
3172         union eth_rx_cqe *cqe;
3173         struct eth_fast_path_rx_cqe *cqe_fp;
3174         uint8_t cqe_fp_flags;
3175         enum eth_rx_cqe_type cqe_fp_type;
3176         uint16_t len, lenonbd,  pad;
3177         struct mbuf *m = NULL;
3178 
3179         comp_ring_cons = RCQ(sw_cq_cons);
3180         bd_prod = RX_BD(bd_prod);
3181         bd_cons = RX_BD(bd_cons);
3182 
3183         cqe          = &fp->rcq_chain[comp_ring_cons];
3184         cqe_fp       = &cqe->fast_path_cqe;
3185         cqe_fp_flags = cqe_fp->type_error_flags;
3186         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3187 
3188         BLOGD(sc, DBG_RX,
3189               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3190               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3191               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3192               fp->index,
3193               hw_cq_cons,
3194               sw_cq_cons,
3195               bd_prod,
3196               bd_cons,
3197               CQE_TYPE(cqe_fp_flags),
3198               cqe_fp_flags,
3199               cqe_fp->status_flags,
3200               le32toh(cqe_fp->rss_hash_result),
3201               le16toh(cqe_fp->vlan_tag),
3202               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3203               le16toh(cqe_fp->len_on_bd));
3204 
3205         /* is this a slowpath msg? */
3206         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3207             bxe_sp_event(sc, fp, cqe);
3208             goto next_cqe;
3209         }
3210 
3211         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3212 
3213         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3214             struct bxe_sw_tpa_info *tpa_info;
3215             uint16_t frag_size, pages;
3216             uint8_t queue;
3217 
3218             if (CQE_TYPE_START(cqe_fp_type)) {
3219                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3220                               bd_cons, bd_prod, cqe_fp);
3221                 m = NULL; /* packet not ready yet */
3222                 goto next_rx;
3223             }
3224 
3225             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3226                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3227 
3228             queue = cqe->end_agg_cqe.queue_index;
3229             tpa_info = &fp->rx_tpa_info[queue];
3230 
3231             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3232                   fp->index, queue);
3233 
3234             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3235                          tpa_info->len_on_bd);
3236             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3237 
3238             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3239                          &cqe->end_agg_cqe, comp_ring_cons);
3240 
3241             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3242 
3243             goto next_cqe;
3244         }
3245 
3246         /* non TPA */
3247 
3248         /* is this an error packet? */
3249         if (__predict_false(cqe_fp_flags &
3250                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3251             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3252             fp->eth_q_stats.rx_soft_errors++;
3253             goto next_rx;
3254         }
3255 
3256         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3257         lenonbd = le16toh(cqe_fp->len_on_bd);
3258         pad = cqe_fp->placement_offset;
3259 
3260         m = rx_buf->m;
3261 
3262         if (__predict_false(m == NULL)) {
3263             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3264                   bd_cons, fp->index);
3265             goto next_rx;
3266         }
3267 
3268         /* XXX double copy if packet length under a threshold */
3269 
3270         /*
3271          * If all the buffer descriptors are filled with mbufs then fill in
3272          * the current consumer index with a new BD. Else if a maximum Rx
3273          * buffer limit is imposed then fill in the next producer index.
3274          */
3275         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3276                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3277                                       bd_prod : bd_cons);
3278         if (rc != 0) {
3279 
3280             /* we simply reuse the received mbuf and don't post it to the stack */
3281             m = NULL;
3282 
3283             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3284                   fp->index, rc);
3285             fp->eth_q_stats.rx_soft_errors++;
3286 
3287             if (sc->max_rx_bufs != RX_BD_USABLE) {
3288                 /* copy this consumer index to the producer index */
3289                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3290                        sizeof(struct bxe_sw_rx_bd));
3291                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3292             }
3293 
3294             goto next_rx;
3295         }
3296 
3297         /* current mbuf was detached from the bd */
3298         fp->eth_q_stats.mbuf_alloc_rx--;
3299 
3300         /* we allocated a replacement mbuf, fixup the current one */
3301         m_adj(m, pad);
3302         m->m_pkthdr.len = m->m_len = len;
3303 
3304         if ((len > 60) && (len > lenonbd)) {
3305             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3306             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3307             if (rc)
3308                 break;
3309             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3310         } else if (lenonbd < len) {
3311             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3312         }
3313 
3314         /* assign packet to this interface interface */
3315 	if_setrcvif(m, ifp);
3316 
3317         /* assume no hardware checksum has complated */
3318         m->m_pkthdr.csum_flags = 0;
3319 
3320         /* validate checksum if offload enabled */
3321         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3322             /* check for a valid IP frame */
3323             if (!(cqe->fast_path_cqe.status_flags &
3324                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3325                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3326                 if (__predict_false(cqe_fp_flags &
3327                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3328                     fp->eth_q_stats.rx_hw_csum_errors++;
3329                 } else {
3330                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3331                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3332                 }
3333             }
3334 
3335             /* check for a valid TCP/UDP frame */
3336             if (!(cqe->fast_path_cqe.status_flags &
3337                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3338                 if (__predict_false(cqe_fp_flags &
3339                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3340                     fp->eth_q_stats.rx_hw_csum_errors++;
3341                 } else {
3342                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3343                     m->m_pkthdr.csum_data = 0xFFFF;
3344                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3345                                                CSUM_PSEUDO_HDR);
3346                 }
3347             }
3348         }
3349 
3350         /* if there is a VLAN tag then flag that info */
3351         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3352             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3353             m->m_flags |= M_VLANTAG;
3354         }
3355 
3356 #if __FreeBSD_version >= 800000
3357         /* specify what RSS queue was used for this flow */
3358         m->m_pkthdr.flowid = fp->index;
3359         BXE_SET_FLOWID(m);
3360 #endif
3361 
3362 next_rx:
3363 
3364         bd_cons    = RX_BD_NEXT(bd_cons);
3365         bd_prod    = RX_BD_NEXT(bd_prod);
3366         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3367 
3368         /* pass the frame to the stack */
3369         if (__predict_true(m != NULL)) {
3370             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3371             rx_pkts++;
3372             if_input(ifp, m);
3373         }
3374 
3375 next_cqe:
3376 
3377         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3378         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3379 
3380         /* limit spinning on the queue */
3381         if (rc != 0)
3382             break;
3383 
3384         if (rx_pkts == sc->rx_budget) {
3385             fp->eth_q_stats.rx_budget_reached++;
3386             break;
3387         }
3388     } /* while work to do */
3389 
3390     fp->rx_bd_cons = bd_cons;
3391     fp->rx_bd_prod = bd_prod_fw;
3392     fp->rx_cq_cons = sw_cq_cons;
3393     fp->rx_cq_prod = sw_cq_prod;
3394 
3395     /* Update producers */
3396     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3397 
3398     fp->eth_q_stats.rx_pkts += rx_pkts;
3399     fp->eth_q_stats.rx_calls++;
3400 
3401     BXE_FP_RX_UNLOCK(fp);
3402 
3403     return (sw_cq_cons != hw_cq_cons);
3404 }
3405 
3406 static uint16_t
3407 bxe_free_tx_pkt(struct bxe_softc    *sc,
3408                 struct bxe_fastpath *fp,
3409                 uint16_t            idx)
3410 {
3411     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3412     struct eth_tx_start_bd *tx_start_bd;
3413     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3414     uint16_t new_cons;
3415     int nbd;
3416 
3417     /* unmap the mbuf from non-paged memory */
3418     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3419 
3420     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3421     nbd = le16toh(tx_start_bd->nbd) - 1;
3422 
3423     new_cons = (tx_buf->first_bd + nbd);
3424 
3425     /* free the mbuf */
3426     if (__predict_true(tx_buf->m != NULL)) {
3427         m_freem(tx_buf->m);
3428         fp->eth_q_stats.mbuf_alloc_tx--;
3429     } else {
3430         fp->eth_q_stats.tx_chain_lost_mbuf++;
3431     }
3432 
3433     tx_buf->m = NULL;
3434     tx_buf->first_bd = 0;
3435 
3436     return (new_cons);
3437 }
3438 
3439 /* transmit timeout watchdog */
3440 static int
3441 bxe_watchdog(struct bxe_softc    *sc,
3442              struct bxe_fastpath *fp)
3443 {
3444     BXE_FP_TX_LOCK(fp);
3445 
3446     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3447         BXE_FP_TX_UNLOCK(fp);
3448         return (0);
3449     }
3450 
3451     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3452 
3453     BXE_FP_TX_UNLOCK(fp);
3454 
3455     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3456     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3457 
3458     return (-1);
3459 }
3460 
3461 /* processes transmit completions */
3462 static uint8_t
3463 bxe_txeof(struct bxe_softc    *sc,
3464           struct bxe_fastpath *fp)
3465 {
3466     if_t ifp = sc->ifp;
3467     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3468     uint16_t tx_bd_avail;
3469 
3470     BXE_FP_TX_LOCK_ASSERT(fp);
3471 
3472     bd_cons = fp->tx_bd_cons;
3473     hw_cons = le16toh(*fp->tx_cons_sb);
3474     sw_cons = fp->tx_pkt_cons;
3475 
3476     while (sw_cons != hw_cons) {
3477         pkt_cons = TX_BD(sw_cons);
3478 
3479         BLOGD(sc, DBG_TX,
3480               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3481               fp->index, hw_cons, sw_cons, pkt_cons);
3482 
3483         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3484 
3485         sw_cons++;
3486     }
3487 
3488     fp->tx_pkt_cons = sw_cons;
3489     fp->tx_bd_cons  = bd_cons;
3490 
3491     BLOGD(sc, DBG_TX,
3492           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3493           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3494 
3495     mb();
3496 
3497     tx_bd_avail = bxe_tx_avail(sc, fp);
3498 
3499     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3500         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3501     } else {
3502         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3503     }
3504 
3505     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3506         /* reset the watchdog timer if there are pending transmits */
3507         fp->watchdog_timer = BXE_TX_TIMEOUT;
3508         return (TRUE);
3509     } else {
3510         /* clear watchdog when there are no pending transmits */
3511         fp->watchdog_timer = 0;
3512         return (FALSE);
3513     }
3514 }
3515 
3516 static void
3517 bxe_drain_tx_queues(struct bxe_softc *sc)
3518 {
3519     struct bxe_fastpath *fp;
3520     int i, count;
3521 
3522     /* wait until all TX fastpath tasks have completed */
3523     for (i = 0; i < sc->num_queues; i++) {
3524         fp = &sc->fp[i];
3525 
3526         count = 1000;
3527 
3528         while (bxe_has_tx_work(fp)) {
3529 
3530             BXE_FP_TX_LOCK(fp);
3531             bxe_txeof(sc, fp);
3532             BXE_FP_TX_UNLOCK(fp);
3533 
3534             if (count == 0) {
3535                 BLOGE(sc, "Timeout waiting for fp[%d] "
3536                           "transmits to complete!\n", i);
3537                 bxe_panic(sc, ("tx drain failure\n"));
3538                 return;
3539             }
3540 
3541             count--;
3542             DELAY(1000);
3543             rmb();
3544         }
3545     }
3546 
3547     return;
3548 }
3549 
3550 static int
3551 bxe_del_all_macs(struct bxe_softc          *sc,
3552                  struct ecore_vlan_mac_obj *mac_obj,
3553                  int                       mac_type,
3554                  uint8_t                   wait_for_comp)
3555 {
3556     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3557     int rc;
3558 
3559     /* wait for completion of requested */
3560     if (wait_for_comp) {
3561         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3562     }
3563 
3564     /* Set the mac type of addresses we want to clear */
3565     bxe_set_bit(mac_type, &vlan_mac_flags);
3566 
3567     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3568     if (rc < 0) {
3569         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3570             rc, mac_type, wait_for_comp);
3571     }
3572 
3573     return (rc);
3574 }
3575 
3576 static int
3577 bxe_fill_accept_flags(struct bxe_softc *sc,
3578                       uint32_t         rx_mode,
3579                       unsigned long    *rx_accept_flags,
3580                       unsigned long    *tx_accept_flags)
3581 {
3582     /* Clear the flags first */
3583     *rx_accept_flags = 0;
3584     *tx_accept_flags = 0;
3585 
3586     switch (rx_mode) {
3587     case BXE_RX_MODE_NONE:
3588         /*
3589          * 'drop all' supersedes any accept flags that may have been
3590          * passed to the function.
3591          */
3592         break;
3593 
3594     case BXE_RX_MODE_NORMAL:
3595         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3596         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3597         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3598 
3599         /* internal switching mode */
3600         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3601         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3602         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3603 
3604         break;
3605 
3606     case BXE_RX_MODE_ALLMULTI:
3607         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3608         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3609         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3610 
3611         /* internal switching mode */
3612         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3613         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3614         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3615 
3616         break;
3617 
3618     case BXE_RX_MODE_PROMISC:
3619         /*
3620          * According to deffinition of SI mode, iface in promisc mode
3621          * should receive matched and unmatched (in resolution of port)
3622          * unicast packets.
3623          */
3624         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3625         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3626         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3627         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3628 
3629         /* internal switching mode */
3630         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3631         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3632 
3633         if (IS_MF_SI(sc)) {
3634             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3635         } else {
3636             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3637         }
3638 
3639         break;
3640 
3641     default:
3642         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3643         return (-1);
3644     }
3645 
3646     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3647     if (rx_mode != BXE_RX_MODE_NONE) {
3648         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3649         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3650     }
3651 
3652     return (0);
3653 }
3654 
3655 static int
3656 bxe_set_q_rx_mode(struct bxe_softc *sc,
3657                   uint8_t          cl_id,
3658                   unsigned long    rx_mode_flags,
3659                   unsigned long    rx_accept_flags,
3660                   unsigned long    tx_accept_flags,
3661                   unsigned long    ramrod_flags)
3662 {
3663     struct ecore_rx_mode_ramrod_params ramrod_param;
3664     int rc;
3665 
3666     memset(&ramrod_param, 0, sizeof(ramrod_param));
3667 
3668     /* Prepare ramrod parameters */
3669     ramrod_param.cid = 0;
3670     ramrod_param.cl_id = cl_id;
3671     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3672     ramrod_param.func_id = SC_FUNC(sc);
3673 
3674     ramrod_param.pstate = &sc->sp_state;
3675     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3676 
3677     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3678     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3679 
3680     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3681 
3682     ramrod_param.ramrod_flags = ramrod_flags;
3683     ramrod_param.rx_mode_flags = rx_mode_flags;
3684 
3685     ramrod_param.rx_accept_flags = rx_accept_flags;
3686     ramrod_param.tx_accept_flags = tx_accept_flags;
3687 
3688     rc = ecore_config_rx_mode(sc, &ramrod_param);
3689     if (rc < 0) {
3690         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3691             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3692             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3693             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3694             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3695         return (rc);
3696     }
3697 
3698     return (0);
3699 }
3700 
3701 static int
3702 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3703 {
3704     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3705     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3706     int rc;
3707 
3708     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3709                                &tx_accept_flags);
3710     if (rc) {
3711         return (rc);
3712     }
3713 
3714     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3715     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3716 
3717     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3718     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3719                               rx_accept_flags, tx_accept_flags,
3720                               ramrod_flags));
3721 }
3722 
3723 /* returns the "mcp load_code" according to global load_count array */
3724 static int
3725 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3726 {
3727     int path = SC_PATH(sc);
3728     int port = SC_PORT(sc);
3729 
3730     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3731           path, load_count[path][0], load_count[path][1],
3732           load_count[path][2]);
3733     load_count[path][0]++;
3734     load_count[path][1 + port]++;
3735     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3736           path, load_count[path][0], load_count[path][1],
3737           load_count[path][2]);
3738     if (load_count[path][0] == 1) {
3739         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3740     } else if (load_count[path][1 + port] == 1) {
3741         return (FW_MSG_CODE_DRV_LOAD_PORT);
3742     } else {
3743         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3744     }
3745 }
3746 
3747 /* returns the "mcp load_code" according to global load_count array */
3748 static int
3749 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3750 {
3751     int port = SC_PORT(sc);
3752     int path = SC_PATH(sc);
3753 
3754     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3755           path, load_count[path][0], load_count[path][1],
3756           load_count[path][2]);
3757     load_count[path][0]--;
3758     load_count[path][1 + port]--;
3759     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3760           path, load_count[path][0], load_count[path][1],
3761           load_count[path][2]);
3762     if (load_count[path][0] == 0) {
3763         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3764     } else if (load_count[path][1 + port] == 0) {
3765         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3766     } else {
3767         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3768     }
3769 }
3770 
3771 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3772 static uint32_t
3773 bxe_send_unload_req(struct bxe_softc *sc,
3774                     int              unload_mode)
3775 {
3776     uint32_t reset_code = 0;
3777 
3778     /* Select the UNLOAD request mode */
3779     if (unload_mode == UNLOAD_NORMAL) {
3780         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3781     } else {
3782         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3783     }
3784 
3785     /* Send the request to the MCP */
3786     if (!BXE_NOMCP(sc)) {
3787         reset_code = bxe_fw_command(sc, reset_code, 0);
3788     } else {
3789         reset_code = bxe_nic_unload_no_mcp(sc);
3790     }
3791 
3792     return (reset_code);
3793 }
3794 
3795 /* send UNLOAD_DONE command to the MCP */
3796 static void
3797 bxe_send_unload_done(struct bxe_softc *sc,
3798                      uint8_t          keep_link)
3799 {
3800     uint32_t reset_param =
3801         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3802 
3803     /* Report UNLOAD_DONE to MCP */
3804     if (!BXE_NOMCP(sc)) {
3805         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3806     }
3807 }
3808 
3809 static int
3810 bxe_func_wait_started(struct bxe_softc *sc)
3811 {
3812     int tout = 50;
3813 
3814     if (!sc->port.pmf) {
3815         return (0);
3816     }
3817 
3818     /*
3819      * (assumption: No Attention from MCP at this stage)
3820      * PMF probably in the middle of TX disable/enable transaction
3821      * 1. Sync IRS for default SB
3822      * 2. Sync SP queue - this guarantees us that attention handling started
3823      * 3. Wait, that TX disable/enable transaction completes
3824      *
3825      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3826      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3827      * received completion for the transaction the state is TX_STOPPED.
3828      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3829      * transaction.
3830      */
3831 
3832     /* XXX make sure default SB ISR is done */
3833     /* need a way to synchronize an irq (intr_mtx?) */
3834 
3835     /* XXX flush any work queues */
3836 
3837     while (ecore_func_get_state(sc, &sc->func_obj) !=
3838            ECORE_F_STATE_STARTED && tout--) {
3839         DELAY(20000);
3840     }
3841 
3842     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3843         /*
3844          * Failed to complete the transaction in a "good way"
3845          * Force both transactions with CLR bit.
3846          */
3847         struct ecore_func_state_params func_params = { NULL };
3848 
3849         BLOGE(sc, "Unexpected function state! "
3850                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3851 
3852         func_params.f_obj = &sc->func_obj;
3853         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3854 
3855         /* STARTED-->TX_STOPPED */
3856         func_params.cmd = ECORE_F_CMD_TX_STOP;
3857         ecore_func_state_change(sc, &func_params);
3858 
3859         /* TX_STOPPED-->STARTED */
3860         func_params.cmd = ECORE_F_CMD_TX_START;
3861         return (ecore_func_state_change(sc, &func_params));
3862     }
3863 
3864     return (0);
3865 }
3866 
3867 static int
3868 bxe_stop_queue(struct bxe_softc *sc,
3869                int              index)
3870 {
3871     struct bxe_fastpath *fp = &sc->fp[index];
3872     struct ecore_queue_state_params q_params = { NULL };
3873     int rc;
3874 
3875     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3876 
3877     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3878     /* We want to wait for completion in this context */
3879     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3880 
3881     /* Stop the primary connection: */
3882 
3883     /* ...halt the connection */
3884     q_params.cmd = ECORE_Q_CMD_HALT;
3885     rc = ecore_queue_state_change(sc, &q_params);
3886     if (rc) {
3887         return (rc);
3888     }
3889 
3890     /* ...terminate the connection */
3891     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3892     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3893     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3894     rc = ecore_queue_state_change(sc, &q_params);
3895     if (rc) {
3896         return (rc);
3897     }
3898 
3899     /* ...delete cfc entry */
3900     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3901     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3902     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3903     return (ecore_queue_state_change(sc, &q_params));
3904 }
3905 
3906 /* wait for the outstanding SP commands */
3907 static inline uint8_t
3908 bxe_wait_sp_comp(struct bxe_softc *sc,
3909                  unsigned long    mask)
3910 {
3911     unsigned long tmp;
3912     int tout = 5000; /* wait for 5 secs tops */
3913 
3914     while (tout--) {
3915         mb();
3916         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3917             return (TRUE);
3918         }
3919 
3920         DELAY(1000);
3921     }
3922 
3923     mb();
3924 
3925     tmp = atomic_load_acq_long(&sc->sp_state);
3926     if (tmp & mask) {
3927         BLOGE(sc, "Filtering completion timed out: "
3928                   "sp_state 0x%lx, mask 0x%lx\n",
3929               tmp, mask);
3930         return (FALSE);
3931     }
3932 
3933     return (FALSE);
3934 }
3935 
3936 static int
3937 bxe_func_stop(struct bxe_softc *sc)
3938 {
3939     struct ecore_func_state_params func_params = { NULL };
3940     int rc;
3941 
3942     /* prepare parameters for function state transitions */
3943     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3944     func_params.f_obj = &sc->func_obj;
3945     func_params.cmd = ECORE_F_CMD_STOP;
3946 
3947     /*
3948      * Try to stop the function the 'good way'. If it fails (in case
3949      * of a parity error during bxe_chip_cleanup()) and we are
3950      * not in a debug mode, perform a state transaction in order to
3951      * enable further HW_RESET transaction.
3952      */
3953     rc = ecore_func_state_change(sc, &func_params);
3954     if (rc) {
3955         BLOGE(sc, "FUNC_STOP ramrod failed. "
3956                   "Running a dry transaction (%d)\n", rc);
3957         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3958         return (ecore_func_state_change(sc, &func_params));
3959     }
3960 
3961     return (0);
3962 }
3963 
3964 static int
3965 bxe_reset_hw(struct bxe_softc *sc,
3966              uint32_t         load_code)
3967 {
3968     struct ecore_func_state_params func_params = { NULL };
3969 
3970     /* Prepare parameters for function state transitions */
3971     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3972 
3973     func_params.f_obj = &sc->func_obj;
3974     func_params.cmd = ECORE_F_CMD_HW_RESET;
3975 
3976     func_params.params.hw_init.load_phase = load_code;
3977 
3978     return (ecore_func_state_change(sc, &func_params));
3979 }
3980 
3981 static void
3982 bxe_int_disable_sync(struct bxe_softc *sc,
3983                      int              disable_hw)
3984 {
3985     if (disable_hw) {
3986         /* prevent the HW from sending interrupts */
3987         bxe_int_disable(sc);
3988     }
3989 
3990     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
3991     /* make sure all ISRs are done */
3992 
3993     /* XXX make sure sp_task is not running */
3994     /* cancel and flush work queues */
3995 }
3996 
3997 static void
3998 bxe_chip_cleanup(struct bxe_softc *sc,
3999                  uint32_t         unload_mode,
4000                  uint8_t          keep_link)
4001 {
4002     int port = SC_PORT(sc);
4003     struct ecore_mcast_ramrod_params rparam = { NULL };
4004     uint32_t reset_code;
4005     int i, rc = 0;
4006 
4007     bxe_drain_tx_queues(sc);
4008 
4009     /* give HW time to discard old tx messages */
4010     DELAY(1000);
4011 
4012     /* Clean all ETH MACs */
4013     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4014     if (rc < 0) {
4015         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4016     }
4017 
4018     /* Clean up UC list  */
4019     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4020     if (rc < 0) {
4021         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4022     }
4023 
4024     /* Disable LLH */
4025     if (!CHIP_IS_E1(sc)) {
4026         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4027     }
4028 
4029     /* Set "drop all" to stop Rx */
4030 
4031     /*
4032      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4033      * a race between the completion code and this code.
4034      */
4035     BXE_MCAST_LOCK(sc);
4036 
4037     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4038         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4039     } else {
4040         bxe_set_storm_rx_mode(sc);
4041     }
4042 
4043     /* Clean up multicast configuration */
4044     rparam.mcast_obj = &sc->mcast_obj;
4045     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4046     if (rc < 0) {
4047         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4048     }
4049 
4050     BXE_MCAST_UNLOCK(sc);
4051 
4052     // XXX bxe_iov_chip_cleanup(sc);
4053 
4054     /*
4055      * Send the UNLOAD_REQUEST to the MCP. This will return if
4056      * this function should perform FUNCTION, PORT, or COMMON HW
4057      * reset.
4058      */
4059     reset_code = bxe_send_unload_req(sc, unload_mode);
4060 
4061     /*
4062      * (assumption: No Attention from MCP at this stage)
4063      * PMF probably in the middle of TX disable/enable transaction
4064      */
4065     rc = bxe_func_wait_started(sc);
4066     if (rc) {
4067         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4068     }
4069 
4070     /*
4071      * Close multi and leading connections
4072      * Completions for ramrods are collected in a synchronous way
4073      */
4074     for (i = 0; i < sc->num_queues; i++) {
4075         if (bxe_stop_queue(sc, i)) {
4076             goto unload_error;
4077         }
4078     }
4079 
4080     /*
4081      * If SP settings didn't get completed so far - something
4082      * very wrong has happen.
4083      */
4084     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4085         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4086     }
4087 
4088 unload_error:
4089 
4090     rc = bxe_func_stop(sc);
4091     if (rc) {
4092         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4093     }
4094 
4095     /* disable HW interrupts */
4096     bxe_int_disable_sync(sc, TRUE);
4097 
4098     /* detach interrupts */
4099     bxe_interrupt_detach(sc);
4100 
4101     /* Reset the chip */
4102     rc = bxe_reset_hw(sc, reset_code);
4103     if (rc) {
4104         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4105     }
4106 
4107     /* Report UNLOAD_DONE to MCP */
4108     bxe_send_unload_done(sc, keep_link);
4109 }
4110 
4111 static void
4112 bxe_disable_close_the_gate(struct bxe_softc *sc)
4113 {
4114     uint32_t val;
4115     int port = SC_PORT(sc);
4116 
4117     BLOGD(sc, DBG_LOAD,
4118           "Disabling 'close the gates'\n");
4119 
4120     if (CHIP_IS_E1(sc)) {
4121         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4122                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4123         val = REG_RD(sc, addr);
4124         val &= ~(0x300);
4125         REG_WR(sc, addr, val);
4126     } else {
4127         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4128         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4129                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4130         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4131     }
4132 }
4133 
4134 /*
4135  * Cleans the object that have internal lists without sending
4136  * ramrods. Should be run when interrutps are disabled.
4137  */
4138 static void
4139 bxe_squeeze_objects(struct bxe_softc *sc)
4140 {
4141     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4142     struct ecore_mcast_ramrod_params rparam = { NULL };
4143     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4144     int rc;
4145 
4146     /* Cleanup MACs' object first... */
4147 
4148     /* Wait for completion of requested */
4149     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4150     /* Perform a dry cleanup */
4151     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4152 
4153     /* Clean ETH primary MAC */
4154     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4155     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4156                              &ramrod_flags);
4157     if (rc != 0) {
4158         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4159     }
4160 
4161     /* Cleanup UC list */
4162     vlan_mac_flags = 0;
4163     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4164     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4165                              &ramrod_flags);
4166     if (rc != 0) {
4167         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4168     }
4169 
4170     /* Now clean mcast object... */
4171 
4172     rparam.mcast_obj = &sc->mcast_obj;
4173     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4174 
4175     /* Add a DEL command... */
4176     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4177     if (rc < 0) {
4178         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4179     }
4180 
4181     /* now wait until all pending commands are cleared */
4182 
4183     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4184     while (rc != 0) {
4185         if (rc < 0) {
4186             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4187             return;
4188         }
4189 
4190         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4191     }
4192 }
4193 
4194 /* stop the controller */
4195 static __noinline int
4196 bxe_nic_unload(struct bxe_softc *sc,
4197                uint32_t         unload_mode,
4198                uint8_t          keep_link)
4199 {
4200     uint8_t global = FALSE;
4201     uint32_t val;
4202     int i;
4203 
4204     BXE_CORE_LOCK_ASSERT(sc);
4205 
4206     if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4207 
4208     for (i = 0; i < sc->num_queues; i++) {
4209         struct bxe_fastpath *fp;
4210 
4211         fp = &sc->fp[i];
4212         BXE_FP_TX_LOCK(fp);
4213         BXE_FP_TX_UNLOCK(fp);
4214     }
4215 
4216     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4217 
4218     /* mark driver as unloaded in shmem2 */
4219     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4220         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4221         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4222                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4223     }
4224 
4225     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4226         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4227         /*
4228          * We can get here if the driver has been unloaded
4229          * during parity error recovery and is either waiting for a
4230          * leader to complete or for other functions to unload and
4231          * then ifconfig down has been issued. In this case we want to
4232          * unload and let other functions to complete a recovery
4233          * process.
4234          */
4235         sc->recovery_state = BXE_RECOVERY_DONE;
4236         sc->is_leader = 0;
4237         bxe_release_leader_lock(sc);
4238         mb();
4239 
4240         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4241         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4242             " state = 0x%x\n", sc->recovery_state, sc->state);
4243         return (-1);
4244     }
4245 
4246     /*
4247      * Nothing to do during unload if previous bxe_nic_load()
4248      * did not completed succesfully - all resourses are released.
4249      */
4250     if ((sc->state == BXE_STATE_CLOSED) ||
4251         (sc->state == BXE_STATE_ERROR)) {
4252         return (0);
4253     }
4254 
4255     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4256     mb();
4257 
4258     /* stop tx */
4259     bxe_tx_disable(sc);
4260 
4261     sc->rx_mode = BXE_RX_MODE_NONE;
4262     /* XXX set rx mode ??? */
4263 
4264     if (IS_PF(sc) && !sc->grcdump_done) {
4265         /* set ALWAYS_ALIVE bit in shmem */
4266         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4267 
4268         bxe_drv_pulse(sc);
4269 
4270         bxe_stats_handle(sc, STATS_EVENT_STOP);
4271         bxe_save_statistics(sc);
4272     }
4273 
4274     /* wait till consumers catch up with producers in all queues */
4275     bxe_drain_tx_queues(sc);
4276 
4277     /* if VF indicate to PF this function is going down (PF will delete sp
4278      * elements and clear initializations
4279      */
4280     if (IS_VF(sc)) {
4281         ; /* bxe_vfpf_close_vf(sc); */
4282     } else if (unload_mode != UNLOAD_RECOVERY) {
4283         /* if this is a normal/close unload need to clean up chip */
4284         if (!sc->grcdump_done)
4285             bxe_chip_cleanup(sc, unload_mode, keep_link);
4286     } else {
4287         /* Send the UNLOAD_REQUEST to the MCP */
4288         bxe_send_unload_req(sc, unload_mode);
4289 
4290         /*
4291          * Prevent transactions to host from the functions on the
4292          * engine that doesn't reset global blocks in case of global
4293          * attention once gloabl blocks are reset and gates are opened
4294          * (the engine which leader will perform the recovery
4295          * last).
4296          */
4297         if (!CHIP_IS_E1x(sc)) {
4298             bxe_pf_disable(sc);
4299         }
4300 
4301         /* disable HW interrupts */
4302         bxe_int_disable_sync(sc, TRUE);
4303 
4304         /* detach interrupts */
4305         bxe_interrupt_detach(sc);
4306 
4307         /* Report UNLOAD_DONE to MCP */
4308         bxe_send_unload_done(sc, FALSE);
4309     }
4310 
4311     /*
4312      * At this stage no more interrupts will arrive so we may safely clean
4313      * the queue'able objects here in case they failed to get cleaned so far.
4314      */
4315     if (IS_PF(sc)) {
4316         bxe_squeeze_objects(sc);
4317     }
4318 
4319     /* There should be no more pending SP commands at this stage */
4320     sc->sp_state = 0;
4321 
4322     sc->port.pmf = 0;
4323 
4324     bxe_free_fp_buffers(sc);
4325 
4326     if (IS_PF(sc)) {
4327         bxe_free_mem(sc);
4328     }
4329 
4330     bxe_free_fw_stats_mem(sc);
4331 
4332     sc->state = BXE_STATE_CLOSED;
4333 
4334     /*
4335      * Check if there are pending parity attentions. If there are - set
4336      * RECOVERY_IN_PROGRESS.
4337      */
4338     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4339         bxe_set_reset_in_progress(sc);
4340 
4341         /* Set RESET_IS_GLOBAL if needed */
4342         if (global) {
4343             bxe_set_reset_global(sc);
4344         }
4345     }
4346 
4347     /*
4348      * The last driver must disable a "close the gate" if there is no
4349      * parity attention or "process kill" pending.
4350      */
4351     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4352         bxe_reset_is_done(sc, SC_PATH(sc))) {
4353         bxe_disable_close_the_gate(sc);
4354     }
4355 
4356     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4357 
4358     return (0);
4359 }
4360 
4361 /*
4362  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4363  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4364  */
4365 static int
4366 bxe_ifmedia_update(struct ifnet  *ifp)
4367 {
4368     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4369     struct ifmedia *ifm;
4370 
4371     ifm = &sc->ifmedia;
4372 
4373     /* We only support Ethernet media type. */
4374     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4375         return (EINVAL);
4376     }
4377 
4378     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4379     case IFM_AUTO:
4380          break;
4381     case IFM_10G_CX4:
4382     case IFM_10G_SR:
4383     case IFM_10G_T:
4384     case IFM_10G_TWINAX:
4385     default:
4386         /* We don't support changing the media type. */
4387         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4388               IFM_SUBTYPE(ifm->ifm_media));
4389         return (EINVAL);
4390     }
4391 
4392     return (0);
4393 }
4394 
4395 /*
4396  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4397  */
4398 static void
4399 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4400 {
4401     struct bxe_softc *sc = if_getsoftc(ifp);
4402 
4403     /* Report link down if the driver isn't running. */
4404     if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4405         ifmr->ifm_active |= IFM_NONE;
4406         return;
4407     }
4408 
4409     /* Setup the default interface info. */
4410     ifmr->ifm_status = IFM_AVALID;
4411     ifmr->ifm_active = IFM_ETHER;
4412 
4413     if (sc->link_vars.link_up) {
4414         ifmr->ifm_status |= IFM_ACTIVE;
4415     } else {
4416         ifmr->ifm_active |= IFM_NONE;
4417         return;
4418     }
4419 
4420     ifmr->ifm_active |= sc->media;
4421 
4422     if (sc->link_vars.duplex == DUPLEX_FULL) {
4423         ifmr->ifm_active |= IFM_FDX;
4424     } else {
4425         ifmr->ifm_active |= IFM_HDX;
4426     }
4427 }
4428 
4429 static int
4430 bxe_ioctl_nvram(struct bxe_softc *sc,
4431                 uint32_t         priv_op,
4432                 struct ifreq     *ifr)
4433 {
4434     struct bxe_nvram_data nvdata_base;
4435     struct bxe_nvram_data *nvdata;
4436     int len;
4437     int error = 0;
4438 
4439     copyin(ifr->ifr_data, &nvdata_base, sizeof(nvdata_base));
4440 
4441     len = (sizeof(struct bxe_nvram_data) +
4442            nvdata_base.len -
4443            sizeof(uint32_t));
4444 
4445     if (len > sizeof(struct bxe_nvram_data)) {
4446         if ((nvdata = (struct bxe_nvram_data *)
4447                  malloc(len, M_DEVBUF,
4448                         (M_NOWAIT | M_ZERO))) == NULL) {
4449             BLOGE(sc, "BXE_IOC_RD_NVRAM malloc failed priv_op 0x%x "
4450                 " len = 0x%x\n", priv_op, len);
4451             return (1);
4452         }
4453         memcpy(nvdata, &nvdata_base, sizeof(struct bxe_nvram_data));
4454     } else {
4455         nvdata = &nvdata_base;
4456     }
4457 
4458     if (priv_op == BXE_IOC_RD_NVRAM) {
4459         BLOGD(sc, DBG_IOCTL, "IOC_RD_NVRAM 0x%x %d\n",
4460               nvdata->offset, nvdata->len);
4461         error = bxe_nvram_read(sc,
4462                                nvdata->offset,
4463                                (uint8_t *)nvdata->value,
4464                                nvdata->len);
4465         copyout(nvdata, ifr->ifr_data, len);
4466     } else { /* BXE_IOC_WR_NVRAM */
4467         BLOGD(sc, DBG_IOCTL, "IOC_WR_NVRAM 0x%x %d\n",
4468               nvdata->offset, nvdata->len);
4469         copyin(ifr->ifr_data, nvdata, len);
4470         error = bxe_nvram_write(sc,
4471                                 nvdata->offset,
4472                                 (uint8_t *)nvdata->value,
4473                                 nvdata->len);
4474     }
4475 
4476     if (len > sizeof(struct bxe_nvram_data)) {
4477         free(nvdata, M_DEVBUF);
4478     }
4479 
4480     return (error);
4481 }
4482 
4483 static int
4484 bxe_ioctl_stats_show(struct bxe_softc *sc,
4485                      uint32_t         priv_op,
4486                      struct ifreq     *ifr)
4487 {
4488     const size_t str_size   = (BXE_NUM_ETH_STATS * STAT_NAME_LEN);
4489     const size_t stats_size = (BXE_NUM_ETH_STATS * sizeof(uint64_t));
4490     caddr_t p_tmp;
4491     uint32_t *offset;
4492     int i;
4493 
4494     switch (priv_op)
4495     {
4496     case BXE_IOC_STATS_SHOW_NUM:
4497         memset(ifr->ifr_data, 0, sizeof(union bxe_stats_show_data));
4498         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.num =
4499             BXE_NUM_ETH_STATS;
4500         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.len =
4501             STAT_NAME_LEN;
4502         return (0);
4503 
4504     case BXE_IOC_STATS_SHOW_STR:
4505         memset(ifr->ifr_data, 0, str_size);
4506         p_tmp = ifr->ifr_data;
4507         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4508             strcpy(p_tmp, bxe_eth_stats_arr[i].string);
4509             p_tmp += STAT_NAME_LEN;
4510         }
4511         return (0);
4512 
4513     case BXE_IOC_STATS_SHOW_CNT:
4514         memset(ifr->ifr_data, 0, stats_size);
4515         p_tmp = ifr->ifr_data;
4516         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4517             offset = ((uint32_t *)&sc->eth_stats +
4518                       bxe_eth_stats_arr[i].offset);
4519             switch (bxe_eth_stats_arr[i].size) {
4520             case 4:
4521                 *((uint64_t *)p_tmp) = (uint64_t)*offset;
4522                 break;
4523             case 8:
4524                 *((uint64_t *)p_tmp) = HILO_U64(*offset, *(offset + 1));
4525                 break;
4526             default:
4527                 *((uint64_t *)p_tmp) = 0;
4528             }
4529             p_tmp += sizeof(uint64_t);
4530         }
4531         return (0);
4532 
4533     default:
4534         return (-1);
4535     }
4536 }
4537 
4538 static void
4539 bxe_handle_chip_tq(void *context,
4540                    int  pending)
4541 {
4542     struct bxe_softc *sc = (struct bxe_softc *)context;
4543     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4544 
4545     switch (work)
4546     {
4547 
4548     case CHIP_TQ_REINIT:
4549         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4550             /* restart the interface */
4551             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4552             bxe_periodic_stop(sc);
4553             BXE_CORE_LOCK(sc);
4554             bxe_stop_locked(sc);
4555             bxe_init_locked(sc);
4556             BXE_CORE_UNLOCK(sc);
4557         }
4558         break;
4559 
4560     default:
4561         break;
4562     }
4563 }
4564 
4565 /*
4566  * Handles any IOCTL calls from the operating system.
4567  *
4568  * Returns:
4569  *   0 = Success, >0 Failure
4570  */
4571 static int
4572 bxe_ioctl(if_t ifp,
4573           u_long       command,
4574           caddr_t      data)
4575 {
4576     struct bxe_softc *sc = if_getsoftc(ifp);
4577     struct ifreq *ifr = (struct ifreq *)data;
4578     struct bxe_nvram_data *nvdata;
4579     uint32_t priv_op;
4580     int mask = 0;
4581     int reinit = 0;
4582     int error = 0;
4583 
4584     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4585     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4586 
4587     switch (command)
4588     {
4589     case SIOCSIFMTU:
4590         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4591               ifr->ifr_mtu);
4592 
4593         if (sc->mtu == ifr->ifr_mtu) {
4594             /* nothing to change */
4595             break;
4596         }
4597 
4598         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4599             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4600                   ifr->ifr_mtu, mtu_min, mtu_max);
4601             error = EINVAL;
4602             break;
4603         }
4604 
4605         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4606                              (unsigned long)ifr->ifr_mtu);
4607 	/*
4608         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4609                               (unsigned long)ifr->ifr_mtu);
4610 	XXX - Not sure why it needs to be atomic
4611 	*/
4612 	if_setmtu(ifp, ifr->ifr_mtu);
4613         reinit = 1;
4614         break;
4615 
4616     case SIOCSIFFLAGS:
4617         /* toggle the interface state up or down */
4618         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4619 
4620 	BXE_CORE_LOCK(sc);
4621         /* check if the interface is up */
4622         if (if_getflags(ifp) & IFF_UP) {
4623             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4624                 /* set the receive mode flags */
4625                 bxe_set_rx_mode(sc);
4626             } else if(sc->state != BXE_STATE_DISABLED) {
4627 		bxe_init_locked(sc);
4628             }
4629         } else {
4630             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4631 		bxe_periodic_stop(sc);
4632 		bxe_stop_locked(sc);
4633             }
4634         }
4635 	BXE_CORE_UNLOCK(sc);
4636 
4637         break;
4638 
4639     case SIOCADDMULTI:
4640     case SIOCDELMULTI:
4641         /* add/delete multicast addresses */
4642         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4643 
4644         /* check if the interface is up */
4645         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4646             /* set the receive mode flags */
4647 	    BXE_CORE_LOCK(sc);
4648             bxe_set_rx_mode(sc);
4649 	    BXE_CORE_UNLOCK(sc);
4650         }
4651 
4652         break;
4653 
4654     case SIOCSIFCAP:
4655         /* find out which capabilities have changed */
4656         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4657 
4658         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4659               mask);
4660 
4661         /* toggle the LRO capabilites enable flag */
4662         if (mask & IFCAP_LRO) {
4663 	    if_togglecapenable(ifp, IFCAP_LRO);
4664             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4665                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4666             reinit = 1;
4667         }
4668 
4669         /* toggle the TXCSUM checksum capabilites enable flag */
4670         if (mask & IFCAP_TXCSUM) {
4671 	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4672             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4673                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4674             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4675                 if_sethwassistbits(ifp, (CSUM_IP      |
4676                                     CSUM_TCP      |
4677                                     CSUM_UDP      |
4678                                     CSUM_TSO      |
4679                                     CSUM_TCP_IPV6 |
4680                                     CSUM_UDP_IPV6), 0);
4681             } else {
4682 		if_clearhwassist(ifp); /* XXX */
4683             }
4684         }
4685 
4686         /* toggle the RXCSUM checksum capabilities enable flag */
4687         if (mask & IFCAP_RXCSUM) {
4688 	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4689             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4690                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4691             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4692                 if_sethwassistbits(ifp, (CSUM_IP      |
4693                                     CSUM_TCP      |
4694                                     CSUM_UDP      |
4695                                     CSUM_TSO      |
4696                                     CSUM_TCP_IPV6 |
4697                                     CSUM_UDP_IPV6), 0);
4698             } else {
4699 		if_clearhwassist(ifp); /* XXX */
4700             }
4701         }
4702 
4703         /* toggle TSO4 capabilities enabled flag */
4704         if (mask & IFCAP_TSO4) {
4705             if_togglecapenable(ifp, IFCAP_TSO4);
4706             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4707                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4708         }
4709 
4710         /* toggle TSO6 capabilities enabled flag */
4711         if (mask & IFCAP_TSO6) {
4712 	    if_togglecapenable(ifp, IFCAP_TSO6);
4713             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4714                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4715         }
4716 
4717         /* toggle VLAN_HWTSO capabilities enabled flag */
4718         if (mask & IFCAP_VLAN_HWTSO) {
4719 
4720 	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4721             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4722                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4723         }
4724 
4725         /* toggle VLAN_HWCSUM capabilities enabled flag */
4726         if (mask & IFCAP_VLAN_HWCSUM) {
4727             /* XXX investigate this... */
4728             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4729             error = EINVAL;
4730         }
4731 
4732         /* toggle VLAN_MTU capabilities enable flag */
4733         if (mask & IFCAP_VLAN_MTU) {
4734             /* XXX investigate this... */
4735             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4736             error = EINVAL;
4737         }
4738 
4739         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4740         if (mask & IFCAP_VLAN_HWTAGGING) {
4741             /* XXX investigate this... */
4742             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4743             error = EINVAL;
4744         }
4745 
4746         /* toggle VLAN_HWFILTER capabilities enabled flag */
4747         if (mask & IFCAP_VLAN_HWFILTER) {
4748             /* XXX investigate this... */
4749             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4750             error = EINVAL;
4751         }
4752 
4753         /* XXX not yet...
4754          * IFCAP_WOL_MAGIC
4755          */
4756 
4757         break;
4758 
4759     case SIOCSIFMEDIA:
4760     case SIOCGIFMEDIA:
4761         /* set/get interface media */
4762         BLOGD(sc, DBG_IOCTL,
4763               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4764               (command & 0xff));
4765         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4766         break;
4767 
4768     case SIOCGPRIVATE_0:
4769         copyin(ifr->ifr_data, &priv_op, sizeof(priv_op));
4770 
4771         switch (priv_op)
4772         {
4773         case BXE_IOC_RD_NVRAM:
4774         case BXE_IOC_WR_NVRAM:
4775             nvdata = (struct bxe_nvram_data *)ifr->ifr_data;
4776             BLOGD(sc, DBG_IOCTL,
4777                   "Received Private NVRAM ioctl addr=0x%x size=%u\n",
4778                   nvdata->offset, nvdata->len);
4779             error = bxe_ioctl_nvram(sc, priv_op, ifr);
4780             break;
4781 
4782         case BXE_IOC_STATS_SHOW_NUM:
4783         case BXE_IOC_STATS_SHOW_STR:
4784         case BXE_IOC_STATS_SHOW_CNT:
4785             BLOGD(sc, DBG_IOCTL, "Received Private Stats ioctl (%d)\n",
4786                   priv_op);
4787             error = bxe_ioctl_stats_show(sc, priv_op, ifr);
4788             break;
4789 
4790         default:
4791             BLOGW(sc, "Received Private Unknown ioctl (%d)\n", priv_op);
4792             error = EINVAL;
4793             break;
4794         }
4795 
4796         break;
4797 
4798     default:
4799         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4800               (command & 0xff));
4801         error = ether_ioctl(ifp, command, data);
4802         break;
4803     }
4804 
4805     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4806         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4807               "Re-initializing hardware from IOCTL change\n");
4808 	bxe_periodic_stop(sc);
4809 	BXE_CORE_LOCK(sc);
4810 	bxe_stop_locked(sc);
4811 	bxe_init_locked(sc);
4812 	BXE_CORE_UNLOCK(sc);
4813     }
4814 
4815     return (error);
4816 }
4817 
4818 static __noinline void
4819 bxe_dump_mbuf(struct bxe_softc *sc,
4820               struct mbuf      *m,
4821               uint8_t          contents)
4822 {
4823     char * type;
4824     int i = 0;
4825 
4826     if (!(sc->debug & DBG_MBUF)) {
4827         return;
4828     }
4829 
4830     if (m == NULL) {
4831         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4832         return;
4833     }
4834 
4835     while (m) {
4836 
4837 #if __FreeBSD_version >= 1000000
4838         BLOGD(sc, DBG_MBUF,
4839               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4840               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4841 
4842         if (m->m_flags & M_PKTHDR) {
4843              BLOGD(sc, DBG_MBUF,
4844                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4845                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4846                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4847         }
4848 #else
4849         BLOGD(sc, DBG_MBUF,
4850               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4851               i, m, m->m_len, m->m_flags,
4852               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4853 
4854         if (m->m_flags & M_PKTHDR) {
4855              BLOGD(sc, DBG_MBUF,
4856                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4857                    i, m->m_pkthdr.len, m->m_flags,
4858                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4859                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4860                    "\22M_PROMISC\23M_NOFREE",
4861                    (int)m->m_pkthdr.csum_flags,
4862                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4863                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4864                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4865                    "\14CSUM_PSEUDO_HDR");
4866         }
4867 #endif /* #if __FreeBSD_version >= 1000000 */
4868 
4869         if (m->m_flags & M_EXT) {
4870             switch (m->m_ext.ext_type) {
4871             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4872             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4873             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4874             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4875             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4876             case EXT_PACKET:     type = "EXT_PACKET";     break;
4877             case EXT_MBUF:       type = "EXT_MBUF";       break;
4878             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4879             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4880             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4881             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4882             default:             type = "UNKNOWN";        break;
4883             }
4884 
4885             BLOGD(sc, DBG_MBUF,
4886                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4887                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4888         }
4889 
4890         if (contents) {
4891             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4892         }
4893 
4894         m = m->m_next;
4895         i++;
4896     }
4897 }
4898 
4899 /*
4900  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4901  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4902  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4903  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4904  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4905  */
4906 static int
4907 bxe_chktso_window(struct bxe_softc  *sc,
4908                   int               nsegs,
4909                   bus_dma_segment_t *segs,
4910                   struct mbuf       *m)
4911 {
4912     uint32_t num_wnds, wnd_size, wnd_sum;
4913     int32_t frag_idx, wnd_idx;
4914     unsigned short lso_mss;
4915     int defrag;
4916 
4917     defrag = 0;
4918     wnd_sum = 0;
4919     wnd_size = 10;
4920     num_wnds = nsegs - wnd_size;
4921     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4922 
4923     /*
4924      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4925      * first window sum of data while skipping the first assuming it is the
4926      * header in FreeBSD.
4927      */
4928     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4929         wnd_sum += htole16(segs[frag_idx].ds_len);
4930     }
4931 
4932     /* check the first 10 bd window size */
4933     if (wnd_sum < lso_mss) {
4934         return (1);
4935     }
4936 
4937     /* run through the windows */
4938     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4939         /* subtract the first mbuf->m_len of the last wndw(-header) */
4940         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4941         /* add the next mbuf len to the len of our new window */
4942         wnd_sum += htole16(segs[frag_idx].ds_len);
4943         if (wnd_sum < lso_mss) {
4944             return (1);
4945         }
4946     }
4947 
4948     return (0);
4949 }
4950 
4951 static uint8_t
4952 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4953                     struct mbuf         *m,
4954                     uint32_t            *parsing_data)
4955 {
4956     struct ether_vlan_header *eh = NULL;
4957     struct ip *ip4 = NULL;
4958     struct ip6_hdr *ip6 = NULL;
4959     caddr_t ip = NULL;
4960     struct tcphdr *th = NULL;
4961     int e_hlen, ip_hlen, l4_off;
4962     uint16_t proto;
4963 
4964     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4965         /* no L4 checksum offload needed */
4966         return (0);
4967     }
4968 
4969     /* get the Ethernet header */
4970     eh = mtod(m, struct ether_vlan_header *);
4971 
4972     /* handle VLAN encapsulation if present */
4973     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4974         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4975         proto  = ntohs(eh->evl_proto);
4976     } else {
4977         e_hlen = ETHER_HDR_LEN;
4978         proto  = ntohs(eh->evl_encap_proto);
4979     }
4980 
4981     switch (proto) {
4982     case ETHERTYPE_IP:
4983         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4984         ip4 = (m->m_len < sizeof(struct ip)) ?
4985                   (struct ip *)m->m_next->m_data :
4986                   (struct ip *)(m->m_data + e_hlen);
4987         /* ip_hl is number of 32-bit words */
4988         ip_hlen = (ip4->ip_hl << 2);
4989         ip = (caddr_t)ip4;
4990         break;
4991     case ETHERTYPE_IPV6:
4992         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4993         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4994                   (struct ip6_hdr *)m->m_next->m_data :
4995                   (struct ip6_hdr *)(m->m_data + e_hlen);
4996         /* XXX cannot support offload with IPv6 extensions */
4997         ip_hlen = sizeof(struct ip6_hdr);
4998         ip = (caddr_t)ip6;
4999         break;
5000     default:
5001         /* We can't offload in this case... */
5002         /* XXX error stat ??? */
5003         return (0);
5004     }
5005 
5006     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5007     l4_off = (e_hlen + ip_hlen);
5008 
5009     *parsing_data |=
5010         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
5011          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
5012 
5013     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5014                                   CSUM_TSO |
5015                                   CSUM_TCP_IPV6)) {
5016         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5017         th = (struct tcphdr *)(ip + ip_hlen);
5018         /* th_off is number of 32-bit words */
5019         *parsing_data |= ((th->th_off <<
5020                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
5021                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
5022         return (l4_off + (th->th_off << 2)); /* entire header length */
5023     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5024                                          CSUM_UDP_IPV6)) {
5025         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5026         return (l4_off + sizeof(struct udphdr)); /* entire header length */
5027     } else {
5028         /* XXX error stat ??? */
5029         return (0);
5030     }
5031 }
5032 
5033 static uint8_t
5034 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
5035                  struct mbuf                *m,
5036                  struct eth_tx_parse_bd_e1x *pbd)
5037 {
5038     struct ether_vlan_header *eh = NULL;
5039     struct ip *ip4 = NULL;
5040     struct ip6_hdr *ip6 = NULL;
5041     caddr_t ip = NULL;
5042     struct tcphdr *th = NULL;
5043     struct udphdr *uh = NULL;
5044     int e_hlen, ip_hlen;
5045     uint16_t proto;
5046     uint8_t hlen;
5047     uint16_t tmp_csum;
5048     uint32_t *tmp_uh;
5049 
5050     /* get the Ethernet header */
5051     eh = mtod(m, struct ether_vlan_header *);
5052 
5053     /* handle VLAN encapsulation if present */
5054     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5055         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5056         proto  = ntohs(eh->evl_proto);
5057     } else {
5058         e_hlen = ETHER_HDR_LEN;
5059         proto  = ntohs(eh->evl_encap_proto);
5060     }
5061 
5062     switch (proto) {
5063     case ETHERTYPE_IP:
5064         /* get the IP header, if mbuf len < 20 then header in next mbuf */
5065         ip4 = (m->m_len < sizeof(struct ip)) ?
5066                   (struct ip *)m->m_next->m_data :
5067                   (struct ip *)(m->m_data + e_hlen);
5068         /* ip_hl is number of 32-bit words */
5069         ip_hlen = (ip4->ip_hl << 1);
5070         ip = (caddr_t)ip4;
5071         break;
5072     case ETHERTYPE_IPV6:
5073         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5074         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5075                   (struct ip6_hdr *)m->m_next->m_data :
5076                   (struct ip6_hdr *)(m->m_data + e_hlen);
5077         /* XXX cannot support offload with IPv6 extensions */
5078         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
5079         ip = (caddr_t)ip6;
5080         break;
5081     default:
5082         /* We can't offload in this case... */
5083         /* XXX error stat ??? */
5084         return (0);
5085     }
5086 
5087     hlen = (e_hlen >> 1);
5088 
5089     /* note that rest of global_data is indirectly zeroed here */
5090     if (m->m_flags & M_VLANTAG) {
5091         pbd->global_data =
5092             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5093     } else {
5094         pbd->global_data = htole16(hlen);
5095     }
5096 
5097     pbd->ip_hlen_w = ip_hlen;
5098 
5099     hlen += pbd->ip_hlen_w;
5100 
5101     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5102 
5103     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5104                                   CSUM_TSO |
5105                                   CSUM_TCP_IPV6)) {
5106         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5107         /* th_off is number of 32-bit words */
5108         hlen += (uint16_t)(th->th_off << 1);
5109     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5110                                          CSUM_UDP_IPV6)) {
5111         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5112         hlen += (sizeof(struct udphdr) / 2);
5113     } else {
5114         /* valid case as only CSUM_IP was set */
5115         return (0);
5116     }
5117 
5118     pbd->total_hlen_w = htole16(hlen);
5119 
5120     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5121                                   CSUM_TSO |
5122                                   CSUM_TCP_IPV6)) {
5123         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5124         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5125     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5126                                          CSUM_UDP_IPV6)) {
5127         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5128 
5129         /*
5130          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5131          * checksums and does not know anything about the UDP header and where
5132          * the checksum field is located. It only knows about TCP. Therefore
5133          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5134          * offload. Since the checksum field offset for TCP is 16 bytes and
5135          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5136          * bytes less than the start of the UDP header. This allows the
5137          * hardware to write the checksum in the correct spot. But the
5138          * hardware will compute a checksum which includes the last 10 bytes
5139          * of the IP header. To correct this we tweak the stack computed
5140          * pseudo checksum by folding in the calculation of the inverse
5141          * checksum for those final 10 bytes of the IP header. This allows
5142          * the correct checksum to be computed by the hardware.
5143          */
5144 
5145         /* set pointer 10 bytes before UDP header */
5146         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5147 
5148         /* calculate a pseudo header checksum over the first 10 bytes */
5149         tmp_csum = in_pseudo(*tmp_uh,
5150                              *(tmp_uh + 1),
5151                              *(uint16_t *)(tmp_uh + 2));
5152 
5153         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5154     }
5155 
5156     return (hlen * 2); /* entire header length, number of bytes */
5157 }
5158 
5159 static void
5160 bxe_set_pbd_lso_e2(struct mbuf *m,
5161                    uint32_t    *parsing_data)
5162 {
5163     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5164                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5165                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5166 
5167     /* XXX test for IPv6 with extension header... */
5168 }
5169 
5170 static void
5171 bxe_set_pbd_lso(struct mbuf                *m,
5172                 struct eth_tx_parse_bd_e1x *pbd)
5173 {
5174     struct ether_vlan_header *eh = NULL;
5175     struct ip *ip = NULL;
5176     struct tcphdr *th = NULL;
5177     int e_hlen;
5178 
5179     /* get the Ethernet header */
5180     eh = mtod(m, struct ether_vlan_header *);
5181 
5182     /* handle VLAN encapsulation if present */
5183     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5184                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5185 
5186     /* get the IP and TCP header, with LSO entire header in first mbuf */
5187     /* XXX assuming IPv4 */
5188     ip = (struct ip *)(m->m_data + e_hlen);
5189     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5190 
5191     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5192     pbd->tcp_send_seq = ntohl(th->th_seq);
5193     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5194 
5195 #if 1
5196         /* XXX IPv4 */
5197         pbd->ip_id = ntohs(ip->ip_id);
5198         pbd->tcp_pseudo_csum =
5199             ntohs(in_pseudo(ip->ip_src.s_addr,
5200                             ip->ip_dst.s_addr,
5201                             htons(IPPROTO_TCP)));
5202 #else
5203         /* XXX IPv6 */
5204         pbd->tcp_pseudo_csum =
5205             ntohs(in_pseudo(&ip6->ip6_src,
5206                             &ip6->ip6_dst,
5207                             htons(IPPROTO_TCP)));
5208 #endif
5209 
5210     pbd->global_data |=
5211         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5212 }
5213 
5214 /*
5215  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5216  * visible to the controller.
5217  *
5218  * If an mbuf is submitted to this routine and cannot be given to the
5219  * controller (e.g. it has too many fragments) then the function may free
5220  * the mbuf and return to the caller.
5221  *
5222  * Returns:
5223  *   0 = Success, !0 = Failure
5224  *   Note the side effect that an mbuf may be freed if it causes a problem.
5225  */
5226 static int
5227 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5228 {
5229     bus_dma_segment_t segs[32];
5230     struct mbuf *m0;
5231     struct bxe_sw_tx_bd *tx_buf;
5232     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5233     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5234     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5235     struct eth_tx_bd *tx_data_bd;
5236     struct eth_tx_bd *tx_total_pkt_size_bd;
5237     struct eth_tx_start_bd *tx_start_bd;
5238     uint16_t bd_prod, pkt_prod, total_pkt_size;
5239     uint8_t mac_type;
5240     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5241     struct bxe_softc *sc;
5242     uint16_t tx_bd_avail;
5243     struct ether_vlan_header *eh;
5244     uint32_t pbd_e2_parsing_data = 0;
5245     uint8_t hlen = 0;
5246     int tmp_bd;
5247     int i;
5248 
5249     sc = fp->sc;
5250 
5251 #if __FreeBSD_version >= 800000
5252     M_ASSERTPKTHDR(*m_head);
5253 #endif /* #if __FreeBSD_version >= 800000 */
5254 
5255     m0 = *m_head;
5256     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5257     tx_start_bd = NULL;
5258     tx_data_bd = NULL;
5259     tx_total_pkt_size_bd = NULL;
5260 
5261     /* get the H/W pointer for packets and BDs */
5262     pkt_prod = fp->tx_pkt_prod;
5263     bd_prod = fp->tx_bd_prod;
5264 
5265     mac_type = UNICAST_ADDRESS;
5266 
5267     /* map the mbuf into the next open DMAable memory */
5268     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5269     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5270                                     tx_buf->m_map, m0,
5271                                     segs, &nsegs, BUS_DMA_NOWAIT);
5272 
5273     /* mapping errors */
5274     if(__predict_false(error != 0)) {
5275         fp->eth_q_stats.tx_dma_mapping_failure++;
5276         if (error == ENOMEM) {
5277             /* resource issue, try again later */
5278             rc = ENOMEM;
5279         } else if (error == EFBIG) {
5280             /* possibly recoverable with defragmentation */
5281             fp->eth_q_stats.mbuf_defrag_attempts++;
5282             m0 = m_defrag(*m_head, M_NOWAIT);
5283             if (m0 == NULL) {
5284                 fp->eth_q_stats.mbuf_defrag_failures++;
5285                 rc = ENOBUFS;
5286             } else {
5287                 /* defrag successful, try mapping again */
5288                 *m_head = m0;
5289                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5290                                                 tx_buf->m_map, m0,
5291                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5292                 if (error) {
5293                     fp->eth_q_stats.tx_dma_mapping_failure++;
5294                     rc = error;
5295                 }
5296             }
5297         } else {
5298             /* unknown, unrecoverable mapping error */
5299             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5300             bxe_dump_mbuf(sc, m0, FALSE);
5301             rc = error;
5302         }
5303 
5304         goto bxe_tx_encap_continue;
5305     }
5306 
5307     tx_bd_avail = bxe_tx_avail(sc, fp);
5308 
5309     /* make sure there is enough room in the send queue */
5310     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5311         /* Recoverable, try again later. */
5312         fp->eth_q_stats.tx_hw_queue_full++;
5313         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5314         rc = ENOMEM;
5315         goto bxe_tx_encap_continue;
5316     }
5317 
5318     /* capture the current H/W TX chain high watermark */
5319     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5320                         (TX_BD_USABLE - tx_bd_avail))) {
5321         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5322     }
5323 
5324     /* make sure it fits in the packet window */
5325     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5326         /*
5327          * The mbuf may be to big for the controller to handle. If the frame
5328          * is a TSO frame we'll need to do an additional check.
5329          */
5330         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5331             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5332                 goto bxe_tx_encap_continue; /* OK to send */
5333             } else {
5334                 fp->eth_q_stats.tx_window_violation_tso++;
5335             }
5336         } else {
5337             fp->eth_q_stats.tx_window_violation_std++;
5338         }
5339 
5340         /* lets try to defragment this mbuf and remap it */
5341         fp->eth_q_stats.mbuf_defrag_attempts++;
5342         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5343 
5344         m0 = m_defrag(*m_head, M_NOWAIT);
5345         if (m0 == NULL) {
5346             fp->eth_q_stats.mbuf_defrag_failures++;
5347             /* Ugh, just drop the frame... :( */
5348             rc = ENOBUFS;
5349         } else {
5350             /* defrag successful, try mapping again */
5351             *m_head = m0;
5352             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5353                                             tx_buf->m_map, m0,
5354                                             segs, &nsegs, BUS_DMA_NOWAIT);
5355             if (error) {
5356                 fp->eth_q_stats.tx_dma_mapping_failure++;
5357                 /* No sense in trying to defrag/copy chain, drop it. :( */
5358                 rc = error;
5359             }
5360             else {
5361                 /* if the chain is still too long then drop it */
5362                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5363                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5364                     rc = ENODEV;
5365                 }
5366             }
5367         }
5368     }
5369 
5370 bxe_tx_encap_continue:
5371 
5372     /* Check for errors */
5373     if (rc) {
5374         if (rc == ENOMEM) {
5375             /* recoverable try again later  */
5376         } else {
5377             fp->eth_q_stats.tx_soft_errors++;
5378             fp->eth_q_stats.mbuf_alloc_tx--;
5379             m_freem(*m_head);
5380             *m_head = NULL;
5381         }
5382 
5383         return (rc);
5384     }
5385 
5386     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5387     if (m0->m_flags & M_BCAST) {
5388         mac_type = BROADCAST_ADDRESS;
5389     } else if (m0->m_flags & M_MCAST) {
5390         mac_type = MULTICAST_ADDRESS;
5391     }
5392 
5393     /* store the mbuf into the mbuf ring */
5394     tx_buf->m        = m0;
5395     tx_buf->first_bd = fp->tx_bd_prod;
5396     tx_buf->flags    = 0;
5397 
5398     /* prepare the first transmit (start) BD for the mbuf */
5399     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5400 
5401     BLOGD(sc, DBG_TX,
5402           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5403           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5404 
5405     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5406     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5407     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5408     total_pkt_size += tx_start_bd->nbytes;
5409     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5410 
5411     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5412 
5413     /* all frames have at least Start BD + Parsing BD */
5414     nbds = nsegs + 1;
5415     tx_start_bd->nbd = htole16(nbds);
5416 
5417     if (m0->m_flags & M_VLANTAG) {
5418         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5419         tx_start_bd->bd_flags.as_bitfield |=
5420             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5421     } else {
5422         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5423         if (IS_VF(sc)) {
5424             /* map ethernet header to find type and header length */
5425             eh = mtod(m0, struct ether_vlan_header *);
5426             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5427         } else {
5428             /* used by FW for packet accounting */
5429             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5430         }
5431     }
5432 
5433     /*
5434      * add a parsing BD from the chain. The parsing BD is always added
5435      * though it is only used for TSO and chksum
5436      */
5437     bd_prod = TX_BD_NEXT(bd_prod);
5438 
5439     if (m0->m_pkthdr.csum_flags) {
5440         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5441             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5442             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5443         }
5444 
5445         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5446             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5447                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5448         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5449             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5450                                                   ETH_TX_BD_FLAGS_IS_UDP |
5451                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5452         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5453                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5454             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5455         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5456             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5457                                                   ETH_TX_BD_FLAGS_IS_UDP);
5458         }
5459     }
5460 
5461     if (!CHIP_IS_E1x(sc)) {
5462         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5463         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5464 
5465         if (m0->m_pkthdr.csum_flags) {
5466             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5467         }
5468 
5469         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5470                  mac_type);
5471     } else {
5472         uint16_t global_data = 0;
5473 
5474         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5475         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5476 
5477         if (m0->m_pkthdr.csum_flags) {
5478             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5479         }
5480 
5481         SET_FLAG(global_data,
5482                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5483         pbd_e1x->global_data |= htole16(global_data);
5484     }
5485 
5486     /* setup the parsing BD with TSO specific info */
5487     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5488         fp->eth_q_stats.tx_ofld_frames_lso++;
5489         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5490 
5491         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5492             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5493 
5494             /* split the first BD into header/data making the fw job easy */
5495             nbds++;
5496             tx_start_bd->nbd = htole16(nbds);
5497             tx_start_bd->nbytes = htole16(hlen);
5498 
5499             bd_prod = TX_BD_NEXT(bd_prod);
5500 
5501             /* new transmit BD after the tx_parse_bd */
5502             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5503             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5504             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5505             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5506             if (tx_total_pkt_size_bd == NULL) {
5507                 tx_total_pkt_size_bd = tx_data_bd;
5508             }
5509 
5510             BLOGD(sc, DBG_TX,
5511                   "TSO split header size is %d (%x:%x) nbds %d\n",
5512                   le16toh(tx_start_bd->nbytes),
5513                   le32toh(tx_start_bd->addr_hi),
5514                   le32toh(tx_start_bd->addr_lo),
5515                   nbds);
5516         }
5517 
5518         if (!CHIP_IS_E1x(sc)) {
5519             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5520         } else {
5521             bxe_set_pbd_lso(m0, pbd_e1x);
5522         }
5523     }
5524 
5525     if (pbd_e2_parsing_data) {
5526         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5527     }
5528 
5529     /* prepare remaining BDs, start tx bd contains first seg/frag */
5530     for (i = 1; i < nsegs ; i++) {
5531         bd_prod = TX_BD_NEXT(bd_prod);
5532         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5533         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5534         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5535         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5536         if (tx_total_pkt_size_bd == NULL) {
5537             tx_total_pkt_size_bd = tx_data_bd;
5538         }
5539         total_pkt_size += tx_data_bd->nbytes;
5540     }
5541 
5542     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5543 
5544     if (tx_total_pkt_size_bd != NULL) {
5545         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5546     }
5547 
5548     if (__predict_false(sc->debug & DBG_TX)) {
5549         tmp_bd = tx_buf->first_bd;
5550         for (i = 0; i < nbds; i++)
5551         {
5552             if (i == 0) {
5553                 BLOGD(sc, DBG_TX,
5554                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5555                       "bd_flags=0x%x hdr_nbds=%d\n",
5556                       tx_start_bd,
5557                       tmp_bd,
5558                       le16toh(tx_start_bd->nbd),
5559                       le16toh(tx_start_bd->vlan_or_ethertype),
5560                       tx_start_bd->bd_flags.as_bitfield,
5561                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5562             } else if (i == 1) {
5563                 if (pbd_e1x) {
5564                     BLOGD(sc, DBG_TX,
5565                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5566                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5567                           "tcp_seq=%u total_hlen_w=%u\n",
5568                           pbd_e1x,
5569                           tmp_bd,
5570                           pbd_e1x->global_data,
5571                           pbd_e1x->ip_hlen_w,
5572                           pbd_e1x->ip_id,
5573                           pbd_e1x->lso_mss,
5574                           pbd_e1x->tcp_flags,
5575                           pbd_e1x->tcp_pseudo_csum,
5576                           pbd_e1x->tcp_send_seq,
5577                           le16toh(pbd_e1x->total_hlen_w));
5578                 } else { /* if (pbd_e2) */
5579                     BLOGD(sc, DBG_TX,
5580                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5581                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5582                           pbd_e2,
5583                           tmp_bd,
5584                           pbd_e2->data.mac_addr.dst_hi,
5585                           pbd_e2->data.mac_addr.dst_mid,
5586                           pbd_e2->data.mac_addr.dst_lo,
5587                           pbd_e2->data.mac_addr.src_hi,
5588                           pbd_e2->data.mac_addr.src_mid,
5589                           pbd_e2->data.mac_addr.src_lo,
5590                           pbd_e2->parsing_data);
5591                 }
5592             }
5593 
5594             if (i != 1) { /* skip parse db as it doesn't hold data */
5595                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5596                 BLOGD(sc, DBG_TX,
5597                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5598                       tx_data_bd,
5599                       tmp_bd,
5600                       le16toh(tx_data_bd->nbytes),
5601                       le32toh(tx_data_bd->addr_hi),
5602                       le32toh(tx_data_bd->addr_lo));
5603             }
5604 
5605             tmp_bd = TX_BD_NEXT(tmp_bd);
5606         }
5607     }
5608 
5609     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5610 
5611     /* update TX BD producer index value for next TX */
5612     bd_prod = TX_BD_NEXT(bd_prod);
5613 
5614     /*
5615      * If the chain of tx_bd's describing this frame is adjacent to or spans
5616      * an eth_tx_next_bd element then we need to increment the nbds value.
5617      */
5618     if (TX_BD_IDX(bd_prod) < nbds) {
5619         nbds++;
5620     }
5621 
5622     /* don't allow reordering of writes for nbd and packets */
5623     mb();
5624 
5625     fp->tx_db.data.prod += nbds;
5626 
5627     /* producer points to the next free tx_bd at this point */
5628     fp->tx_pkt_prod++;
5629     fp->tx_bd_prod = bd_prod;
5630 
5631     DOORBELL(sc, fp->index, fp->tx_db.raw);
5632 
5633     fp->eth_q_stats.tx_pkts++;
5634 
5635     /* Prevent speculative reads from getting ahead of the status block. */
5636     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5637                       0, 0, BUS_SPACE_BARRIER_READ);
5638 
5639     /* Prevent speculative reads from getting ahead of the doorbell. */
5640     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5641                       0, 0, BUS_SPACE_BARRIER_READ);
5642 
5643     return (0);
5644 }
5645 
5646 static void
5647 bxe_tx_start_locked(struct bxe_softc *sc,
5648                     if_t ifp,
5649                     struct bxe_fastpath *fp)
5650 {
5651     struct mbuf *m = NULL;
5652     int tx_count = 0;
5653     uint16_t tx_bd_avail;
5654 
5655     BXE_FP_TX_LOCK_ASSERT(fp);
5656 
5657     /* keep adding entries while there are frames to send */
5658     while (!if_sendq_empty(ifp)) {
5659 
5660         /*
5661          * check for any frames to send
5662          * dequeue can still be NULL even if queue is not empty
5663          */
5664         m = if_dequeue(ifp);
5665         if (__predict_false(m == NULL)) {
5666             break;
5667         }
5668 
5669         /* the mbuf now belongs to us */
5670         fp->eth_q_stats.mbuf_alloc_tx++;
5671 
5672         /*
5673          * Put the frame into the transmit ring. If we don't have room,
5674          * place the mbuf back at the head of the TX queue, set the
5675          * OACTIVE flag, and wait for the NIC to drain the chain.
5676          */
5677         if (__predict_false(bxe_tx_encap(fp, &m))) {
5678             fp->eth_q_stats.tx_encap_failures++;
5679             if (m != NULL) {
5680                 /* mark the TX queue as full and return the frame */
5681                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5682 		if_sendq_prepend(ifp, m);
5683                 fp->eth_q_stats.mbuf_alloc_tx--;
5684                 fp->eth_q_stats.tx_queue_xoff++;
5685             }
5686 
5687             /* stop looking for more work */
5688             break;
5689         }
5690 
5691         /* the frame was enqueued successfully */
5692         tx_count++;
5693 
5694         /* send a copy of the frame to any BPF listeners. */
5695         if_etherbpfmtap(ifp, m);
5696 
5697         tx_bd_avail = bxe_tx_avail(sc, fp);
5698 
5699         /* handle any completions if we're running low */
5700         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5701             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5702             bxe_txeof(sc, fp);
5703             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5704                 break;
5705             }
5706         }
5707     }
5708 
5709     /* all TX packets were dequeued and/or the tx ring is full */
5710     if (tx_count > 0) {
5711         /* reset the TX watchdog timeout timer */
5712         fp->watchdog_timer = BXE_TX_TIMEOUT;
5713     }
5714 }
5715 
5716 /* Legacy (non-RSS) dispatch routine */
5717 static void
5718 bxe_tx_start(if_t ifp)
5719 {
5720     struct bxe_softc *sc;
5721     struct bxe_fastpath *fp;
5722 
5723     sc = if_getsoftc(ifp);
5724 
5725     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5726         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5727         return;
5728     }
5729 
5730     if (!sc->link_vars.link_up) {
5731         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5732         return;
5733     }
5734 
5735     fp = &sc->fp[0];
5736 
5737     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5738         fp->eth_q_stats.tx_queue_full_return++;
5739         return;
5740     }
5741 
5742     BXE_FP_TX_LOCK(fp);
5743     bxe_tx_start_locked(sc, ifp, fp);
5744     BXE_FP_TX_UNLOCK(fp);
5745 }
5746 
5747 #if __FreeBSD_version >= 800000
5748 
5749 static int
5750 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5751                        if_t                ifp,
5752                        struct bxe_fastpath *fp,
5753                        struct mbuf         *m)
5754 {
5755     struct buf_ring *tx_br = fp->tx_br;
5756     struct mbuf *next;
5757     int depth, rc, tx_count;
5758     uint16_t tx_bd_avail;
5759 
5760     rc = tx_count = 0;
5761 
5762     BXE_FP_TX_LOCK_ASSERT(fp);
5763 
5764     if (!tx_br) {
5765         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5766         return (EINVAL);
5767     }
5768 
5769     if (!sc->link_vars.link_up ||
5770         (if_getdrvflags(ifp) &
5771         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5772         rc = drbr_enqueue(ifp, tx_br, m);
5773         goto bxe_tx_mq_start_locked_exit;
5774     }
5775 
5776     /* fetch the depth of the driver queue */
5777     depth = drbr_inuse_drv(ifp, tx_br);
5778     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5779         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5780     }
5781 
5782     if (m == NULL) {
5783         /* no new work, check for pending frames */
5784         next = drbr_dequeue_drv(ifp, tx_br);
5785     } else if (drbr_needs_enqueue_drv(ifp, tx_br)) {
5786         /* have both new and pending work, maintain packet order */
5787         rc = drbr_enqueue(ifp, tx_br, m);
5788         if (rc != 0) {
5789             fp->eth_q_stats.tx_soft_errors++;
5790             goto bxe_tx_mq_start_locked_exit;
5791         }
5792         next = drbr_dequeue_drv(ifp, tx_br);
5793     } else {
5794         /* new work only and nothing pending */
5795         next = m;
5796     }
5797 
5798     /* keep adding entries while there are frames to send */
5799     while (next != NULL) {
5800 
5801         /* the mbuf now belongs to us */
5802         fp->eth_q_stats.mbuf_alloc_tx++;
5803 
5804         /*
5805          * Put the frame into the transmit ring. If we don't have room,
5806          * place the mbuf back at the head of the TX queue, set the
5807          * OACTIVE flag, and wait for the NIC to drain the chain.
5808          */
5809         rc = bxe_tx_encap(fp, &next);
5810         if (__predict_false(rc != 0)) {
5811             fp->eth_q_stats.tx_encap_failures++;
5812             if (next != NULL) {
5813                 /* mark the TX queue as full and save the frame */
5814                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5815                 /* XXX this may reorder the frame */
5816                 rc = drbr_enqueue(ifp, tx_br, next);
5817                 fp->eth_q_stats.mbuf_alloc_tx--;
5818                 fp->eth_q_stats.tx_frames_deferred++;
5819             }
5820 
5821             /* stop looking for more work */
5822             break;
5823         }
5824 
5825         /* the transmit frame was enqueued successfully */
5826         tx_count++;
5827 
5828         /* send a copy of the frame to any BPF listeners */
5829 	if_etherbpfmtap(ifp, next);
5830 
5831         tx_bd_avail = bxe_tx_avail(sc, fp);
5832 
5833         /* handle any completions if we're running low */
5834         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5835             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5836             bxe_txeof(sc, fp);
5837             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5838                 break;
5839             }
5840         }
5841 
5842         next = drbr_dequeue_drv(ifp, tx_br);
5843     }
5844 
5845     /* all TX packets were dequeued and/or the tx ring is full */
5846     if (tx_count > 0) {
5847         /* reset the TX watchdog timeout timer */
5848         fp->watchdog_timer = BXE_TX_TIMEOUT;
5849     }
5850 
5851 bxe_tx_mq_start_locked_exit:
5852 
5853     return (rc);
5854 }
5855 
5856 /* Multiqueue (TSS) dispatch routine. */
5857 static int
5858 bxe_tx_mq_start(struct ifnet *ifp,
5859                 struct mbuf  *m)
5860 {
5861     struct bxe_softc *sc = if_getsoftc(ifp);
5862     struct bxe_fastpath *fp;
5863     int fp_index, rc;
5864 
5865     fp_index = 0; /* default is the first queue */
5866 
5867     /* check if flowid is set */
5868 
5869     if (BXE_VALID_FLOWID(m))
5870         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5871 
5872     fp = &sc->fp[fp_index];
5873 
5874     if (BXE_FP_TX_TRYLOCK(fp)) {
5875         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5876         BXE_FP_TX_UNLOCK(fp);
5877     } else
5878         rc = drbr_enqueue(ifp, fp->tx_br, m);
5879 
5880     return (rc);
5881 }
5882 
5883 static void
5884 bxe_mq_flush(struct ifnet *ifp)
5885 {
5886     struct bxe_softc *sc = if_getsoftc(ifp);
5887     struct bxe_fastpath *fp;
5888     struct mbuf *m;
5889     int i;
5890 
5891     for (i = 0; i < sc->num_queues; i++) {
5892         fp = &sc->fp[i];
5893 
5894         if (fp->state != BXE_FP_STATE_OPEN) {
5895             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5896                   fp->index, fp->state);
5897             continue;
5898         }
5899 
5900         if (fp->tx_br != NULL) {
5901             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5902             BXE_FP_TX_LOCK(fp);
5903             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5904                 m_freem(m);
5905             }
5906             BXE_FP_TX_UNLOCK(fp);
5907         }
5908     }
5909 
5910     if_qflush(ifp);
5911 }
5912 
5913 #endif /* FreeBSD_version >= 800000 */
5914 
5915 static uint16_t
5916 bxe_cid_ilt_lines(struct bxe_softc *sc)
5917 {
5918     if (IS_SRIOV(sc)) {
5919         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5920     }
5921     return (L2_ILT_LINES(sc));
5922 }
5923 
5924 static void
5925 bxe_ilt_set_info(struct bxe_softc *sc)
5926 {
5927     struct ilt_client_info *ilt_client;
5928     struct ecore_ilt *ilt = sc->ilt;
5929     uint16_t line = 0;
5930 
5931     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5932     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5933 
5934     /* CDU */
5935     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5936     ilt_client->client_num = ILT_CLIENT_CDU;
5937     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5938     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5939     ilt_client->start = line;
5940     line += bxe_cid_ilt_lines(sc);
5941 
5942     if (CNIC_SUPPORT(sc)) {
5943         line += CNIC_ILT_LINES;
5944     }
5945 
5946     ilt_client->end = (line - 1);
5947 
5948     BLOGD(sc, DBG_LOAD,
5949           "ilt client[CDU]: start %d, end %d, "
5950           "psz 0x%x, flags 0x%x, hw psz %d\n",
5951           ilt_client->start, ilt_client->end,
5952           ilt_client->page_size,
5953           ilt_client->flags,
5954           ilog2(ilt_client->page_size >> 12));
5955 
5956     /* QM */
5957     if (QM_INIT(sc->qm_cid_count)) {
5958         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5959         ilt_client->client_num = ILT_CLIENT_QM;
5960         ilt_client->page_size = QM_ILT_PAGE_SZ;
5961         ilt_client->flags = 0;
5962         ilt_client->start = line;
5963 
5964         /* 4 bytes for each cid */
5965         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5966                              QM_ILT_PAGE_SZ);
5967 
5968         ilt_client->end = (line - 1);
5969 
5970         BLOGD(sc, DBG_LOAD,
5971               "ilt client[QM]: start %d, end %d, "
5972               "psz 0x%x, flags 0x%x, hw psz %d\n",
5973               ilt_client->start, ilt_client->end,
5974               ilt_client->page_size, ilt_client->flags,
5975               ilog2(ilt_client->page_size >> 12));
5976     }
5977 
5978     if (CNIC_SUPPORT(sc)) {
5979         /* SRC */
5980         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5981         ilt_client->client_num = ILT_CLIENT_SRC;
5982         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5983         ilt_client->flags = 0;
5984         ilt_client->start = line;
5985         line += SRC_ILT_LINES;
5986         ilt_client->end = (line - 1);
5987 
5988         BLOGD(sc, DBG_LOAD,
5989               "ilt client[SRC]: start %d, end %d, "
5990               "psz 0x%x, flags 0x%x, hw psz %d\n",
5991               ilt_client->start, ilt_client->end,
5992               ilt_client->page_size, ilt_client->flags,
5993               ilog2(ilt_client->page_size >> 12));
5994 
5995         /* TM */
5996         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5997         ilt_client->client_num = ILT_CLIENT_TM;
5998         ilt_client->page_size = TM_ILT_PAGE_SZ;
5999         ilt_client->flags = 0;
6000         ilt_client->start = line;
6001         line += TM_ILT_LINES;
6002         ilt_client->end = (line - 1);
6003 
6004         BLOGD(sc, DBG_LOAD,
6005               "ilt client[TM]: start %d, end %d, "
6006               "psz 0x%x, flags 0x%x, hw psz %d\n",
6007               ilt_client->start, ilt_client->end,
6008               ilt_client->page_size, ilt_client->flags,
6009               ilog2(ilt_client->page_size >> 12));
6010     }
6011 
6012     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
6013 }
6014 
6015 static void
6016 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
6017 {
6018     int i;
6019     uint32_t rx_buf_size;
6020 
6021     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
6022 
6023     for (i = 0; i < sc->num_queues; i++) {
6024         if(rx_buf_size <= MCLBYTES){
6025             sc->fp[i].rx_buf_size = rx_buf_size;
6026             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6027         }else if (rx_buf_size <= MJUMPAGESIZE){
6028             sc->fp[i].rx_buf_size = rx_buf_size;
6029             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6030         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
6031             sc->fp[i].rx_buf_size = MCLBYTES;
6032             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6033         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
6034             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
6035             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6036         }else {
6037             sc->fp[i].rx_buf_size = MCLBYTES;
6038             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6039         }
6040     }
6041 }
6042 
6043 static int
6044 bxe_alloc_ilt_mem(struct bxe_softc *sc)
6045 {
6046     int rc = 0;
6047 
6048     if ((sc->ilt =
6049          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6050                                     M_BXE_ILT,
6051                                     (M_NOWAIT | M_ZERO))) == NULL) {
6052         rc = 1;
6053     }
6054 
6055     return (rc);
6056 }
6057 
6058 static int
6059 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6060 {
6061     int rc = 0;
6062 
6063     if ((sc->ilt->lines =
6064          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6065                                     M_BXE_ILT,
6066                                     (M_NOWAIT | M_ZERO))) == NULL) {
6067         rc = 1;
6068     }
6069 
6070     return (rc);
6071 }
6072 
6073 static void
6074 bxe_free_ilt_mem(struct bxe_softc *sc)
6075 {
6076     if (sc->ilt != NULL) {
6077         free(sc->ilt, M_BXE_ILT);
6078         sc->ilt = NULL;
6079     }
6080 }
6081 
6082 static void
6083 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6084 {
6085     if (sc->ilt->lines != NULL) {
6086         free(sc->ilt->lines, M_BXE_ILT);
6087         sc->ilt->lines = NULL;
6088     }
6089 }
6090 
6091 static void
6092 bxe_free_mem(struct bxe_softc *sc)
6093 {
6094     int i;
6095 
6096     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6097         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6098         sc->context[i].vcxt = NULL;
6099         sc->context[i].size = 0;
6100     }
6101 
6102     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6103 
6104     bxe_free_ilt_lines_mem(sc);
6105 
6106 }
6107 
6108 static int
6109 bxe_alloc_mem(struct bxe_softc *sc)
6110 {
6111     int context_size;
6112     int allocated;
6113     int i;
6114 
6115     /*
6116      * Allocate memory for CDU context:
6117      * This memory is allocated separately and not in the generic ILT
6118      * functions because CDU differs in few aspects:
6119      * 1. There can be multiple entities allocating memory for context -
6120      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6121      * its own ILT lines.
6122      * 2. Since CDU page-size is not a single 4KB page (which is the case
6123      * for the other ILT clients), to be efficient we want to support
6124      * allocation of sub-page-size in the last entry.
6125      * 3. Context pointers are used by the driver to pass to FW / update
6126      * the context (for the other ILT clients the pointers are used just to
6127      * free the memory during unload).
6128      */
6129     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6130     for (i = 0, allocated = 0; allocated < context_size; i++) {
6131         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6132                                   (context_size - allocated));
6133 
6134         if (bxe_dma_alloc(sc, sc->context[i].size,
6135                           &sc->context[i].vcxt_dma,
6136                           "cdu context") != 0) {
6137             bxe_free_mem(sc);
6138             return (-1);
6139         }
6140 
6141         sc->context[i].vcxt =
6142             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6143 
6144         allocated += sc->context[i].size;
6145     }
6146 
6147     bxe_alloc_ilt_lines_mem(sc);
6148 
6149     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6150           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6151     {
6152         for (i = 0; i < 4; i++) {
6153             BLOGD(sc, DBG_LOAD,
6154                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6155                   i,
6156                   sc->ilt->clients[i].page_size,
6157                   sc->ilt->clients[i].start,
6158                   sc->ilt->clients[i].end,
6159                   sc->ilt->clients[i].client_num,
6160                   sc->ilt->clients[i].flags);
6161         }
6162     }
6163     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6164         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6165         bxe_free_mem(sc);
6166         return (-1);
6167     }
6168 
6169     return (0);
6170 }
6171 
6172 static void
6173 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6174 {
6175     struct bxe_softc *sc;
6176     int i;
6177 
6178     sc = fp->sc;
6179 
6180     if (fp->rx_mbuf_tag == NULL) {
6181         return;
6182     }
6183 
6184     /* free all mbufs and unload all maps */
6185     for (i = 0; i < RX_BD_TOTAL; i++) {
6186         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6187             bus_dmamap_sync(fp->rx_mbuf_tag,
6188                             fp->rx_mbuf_chain[i].m_map,
6189                             BUS_DMASYNC_POSTREAD);
6190             bus_dmamap_unload(fp->rx_mbuf_tag,
6191                               fp->rx_mbuf_chain[i].m_map);
6192         }
6193 
6194         if (fp->rx_mbuf_chain[i].m != NULL) {
6195             m_freem(fp->rx_mbuf_chain[i].m);
6196             fp->rx_mbuf_chain[i].m = NULL;
6197             fp->eth_q_stats.mbuf_alloc_rx--;
6198         }
6199     }
6200 }
6201 
6202 static void
6203 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6204 {
6205     struct bxe_softc *sc;
6206     int i, max_agg_queues;
6207 
6208     sc = fp->sc;
6209 
6210     if (fp->rx_mbuf_tag == NULL) {
6211         return;
6212     }
6213 
6214     max_agg_queues = MAX_AGG_QS(sc);
6215 
6216     /* release all mbufs and unload all DMA maps in the TPA pool */
6217     for (i = 0; i < max_agg_queues; i++) {
6218         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6219             bus_dmamap_sync(fp->rx_mbuf_tag,
6220                             fp->rx_tpa_info[i].bd.m_map,
6221                             BUS_DMASYNC_POSTREAD);
6222             bus_dmamap_unload(fp->rx_mbuf_tag,
6223                               fp->rx_tpa_info[i].bd.m_map);
6224         }
6225 
6226         if (fp->rx_tpa_info[i].bd.m != NULL) {
6227             m_freem(fp->rx_tpa_info[i].bd.m);
6228             fp->rx_tpa_info[i].bd.m = NULL;
6229             fp->eth_q_stats.mbuf_alloc_tpa--;
6230         }
6231     }
6232 }
6233 
6234 static void
6235 bxe_free_sge_chain(struct bxe_fastpath *fp)
6236 {
6237     struct bxe_softc *sc;
6238     int i;
6239 
6240     sc = fp->sc;
6241 
6242     if (fp->rx_sge_mbuf_tag == NULL) {
6243         return;
6244     }
6245 
6246     /* rree all mbufs and unload all maps */
6247     for (i = 0; i < RX_SGE_TOTAL; i++) {
6248         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6249             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6250                             fp->rx_sge_mbuf_chain[i].m_map,
6251                             BUS_DMASYNC_POSTREAD);
6252             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6253                               fp->rx_sge_mbuf_chain[i].m_map);
6254         }
6255 
6256         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6257             m_freem(fp->rx_sge_mbuf_chain[i].m);
6258             fp->rx_sge_mbuf_chain[i].m = NULL;
6259             fp->eth_q_stats.mbuf_alloc_sge--;
6260         }
6261     }
6262 }
6263 
6264 static void
6265 bxe_free_fp_buffers(struct bxe_softc *sc)
6266 {
6267     struct bxe_fastpath *fp;
6268     int i;
6269 
6270     for (i = 0; i < sc->num_queues; i++) {
6271         fp = &sc->fp[i];
6272 
6273 #if __FreeBSD_version >= 800000
6274         if (fp->tx_br != NULL) {
6275             /* just in case bxe_mq_flush() wasn't called */
6276             if (mtx_initialized(&fp->tx_mtx)) {
6277                 struct mbuf *m;
6278 
6279                 BXE_FP_TX_LOCK(fp);
6280                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6281                     m_freem(m);
6282                 BXE_FP_TX_UNLOCK(fp);
6283             }
6284         }
6285 #endif
6286 
6287         /* free all RX buffers */
6288         bxe_free_rx_bd_chain(fp);
6289         bxe_free_tpa_pool(fp);
6290         bxe_free_sge_chain(fp);
6291 
6292         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6293             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6294                   fp->eth_q_stats.mbuf_alloc_rx);
6295         }
6296 
6297         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6298             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6299                   fp->eth_q_stats.mbuf_alloc_sge);
6300         }
6301 
6302         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6303             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6304                   fp->eth_q_stats.mbuf_alloc_tpa);
6305         }
6306 
6307         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6308             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6309                   fp->eth_q_stats.mbuf_alloc_tx);
6310         }
6311 
6312         /* XXX verify all mbufs were reclaimed */
6313     }
6314 }
6315 
6316 static int
6317 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6318                      uint16_t            prev_index,
6319                      uint16_t            index)
6320 {
6321     struct bxe_sw_rx_bd *rx_buf;
6322     struct eth_rx_bd *rx_bd;
6323     bus_dma_segment_t segs[1];
6324     bus_dmamap_t map;
6325     struct mbuf *m;
6326     int nsegs, rc;
6327 
6328     rc = 0;
6329 
6330     /* allocate the new RX BD mbuf */
6331     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6332     if (__predict_false(m == NULL)) {
6333         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6334         return (ENOBUFS);
6335     }
6336 
6337     fp->eth_q_stats.mbuf_alloc_rx++;
6338 
6339     /* initialize the mbuf buffer length */
6340     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6341 
6342     /* map the mbuf into non-paged pool */
6343     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6344                                  fp->rx_mbuf_spare_map,
6345                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6346     if (__predict_false(rc != 0)) {
6347         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6348         m_freem(m);
6349         fp->eth_q_stats.mbuf_alloc_rx--;
6350         return (rc);
6351     }
6352 
6353     /* all mbufs must map to a single segment */
6354     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6355 
6356     /* release any existing RX BD mbuf mappings */
6357 
6358     if (prev_index != index) {
6359         rx_buf = &fp->rx_mbuf_chain[prev_index];
6360 
6361         if (rx_buf->m_map != NULL) {
6362             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6363                             BUS_DMASYNC_POSTREAD);
6364             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6365         }
6366 
6367         /*
6368          * We only get here from bxe_rxeof() when the maximum number
6369          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6370          * holds the mbuf in the prev_index so it's OK to NULL it out
6371          * here without concern of a memory leak.
6372          */
6373         fp->rx_mbuf_chain[prev_index].m = NULL;
6374     }
6375 
6376     rx_buf = &fp->rx_mbuf_chain[index];
6377 
6378     if (rx_buf->m_map != NULL) {
6379         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6380                         BUS_DMASYNC_POSTREAD);
6381         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6382     }
6383 
6384     /* save the mbuf and mapping info for a future packet */
6385     map = (prev_index != index) ?
6386               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6387     rx_buf->m_map = fp->rx_mbuf_spare_map;
6388     fp->rx_mbuf_spare_map = map;
6389     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6390                     BUS_DMASYNC_PREREAD);
6391     rx_buf->m = m;
6392 
6393     rx_bd = &fp->rx_chain[index];
6394     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6395     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6396 
6397     return (rc);
6398 }
6399 
6400 static int
6401 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6402                       int                 queue)
6403 {
6404     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6405     bus_dma_segment_t segs[1];
6406     bus_dmamap_t map;
6407     struct mbuf *m;
6408     int nsegs;
6409     int rc = 0;
6410 
6411     /* allocate the new TPA mbuf */
6412     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6413     if (__predict_false(m == NULL)) {
6414         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6415         return (ENOBUFS);
6416     }
6417 
6418     fp->eth_q_stats.mbuf_alloc_tpa++;
6419 
6420     /* initialize the mbuf buffer length */
6421     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6422 
6423     /* map the mbuf into non-paged pool */
6424     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6425                                  fp->rx_tpa_info_mbuf_spare_map,
6426                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6427     if (__predict_false(rc != 0)) {
6428         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6429         m_free(m);
6430         fp->eth_q_stats.mbuf_alloc_tpa--;
6431         return (rc);
6432     }
6433 
6434     /* all mbufs must map to a single segment */
6435     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6436 
6437     /* release any existing TPA mbuf mapping */
6438     if (tpa_info->bd.m_map != NULL) {
6439         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6440                         BUS_DMASYNC_POSTREAD);
6441         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6442     }
6443 
6444     /* save the mbuf and mapping info for the TPA mbuf */
6445     map = tpa_info->bd.m_map;
6446     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6447     fp->rx_tpa_info_mbuf_spare_map = map;
6448     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6449                     BUS_DMASYNC_PREREAD);
6450     tpa_info->bd.m = m;
6451     tpa_info->seg = segs[0];
6452 
6453     return (rc);
6454 }
6455 
6456 /*
6457  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6458  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6459  * chain.
6460  */
6461 static int
6462 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6463                       uint16_t            index)
6464 {
6465     struct bxe_sw_rx_bd *sge_buf;
6466     struct eth_rx_sge *sge;
6467     bus_dma_segment_t segs[1];
6468     bus_dmamap_t map;
6469     struct mbuf *m;
6470     int nsegs;
6471     int rc = 0;
6472 
6473     /* allocate a new SGE mbuf */
6474     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6475     if (__predict_false(m == NULL)) {
6476         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6477         return (ENOMEM);
6478     }
6479 
6480     fp->eth_q_stats.mbuf_alloc_sge++;
6481 
6482     /* initialize the mbuf buffer length */
6483     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6484 
6485     /* map the SGE mbuf into non-paged pool */
6486     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6487                                  fp->rx_sge_mbuf_spare_map,
6488                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6489     if (__predict_false(rc != 0)) {
6490         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6491         m_freem(m);
6492         fp->eth_q_stats.mbuf_alloc_sge--;
6493         return (rc);
6494     }
6495 
6496     /* all mbufs must map to a single segment */
6497     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6498 
6499     sge_buf = &fp->rx_sge_mbuf_chain[index];
6500 
6501     /* release any existing SGE mbuf mapping */
6502     if (sge_buf->m_map != NULL) {
6503         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6504                         BUS_DMASYNC_POSTREAD);
6505         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6506     }
6507 
6508     /* save the mbuf and mapping info for a future packet */
6509     map = sge_buf->m_map;
6510     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6511     fp->rx_sge_mbuf_spare_map = map;
6512     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6513                     BUS_DMASYNC_PREREAD);
6514     sge_buf->m = m;
6515 
6516     sge = &fp->rx_sge_chain[index];
6517     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6518     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6519 
6520     return (rc);
6521 }
6522 
6523 static __noinline int
6524 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6525 {
6526     struct bxe_fastpath *fp;
6527     int i, j, rc = 0;
6528     int ring_prod, cqe_ring_prod;
6529     int max_agg_queues;
6530 
6531     for (i = 0; i < sc->num_queues; i++) {
6532         fp = &sc->fp[i];
6533 
6534         ring_prod = cqe_ring_prod = 0;
6535         fp->rx_bd_cons = 0;
6536         fp->rx_cq_cons = 0;
6537 
6538         /* allocate buffers for the RX BDs in RX BD chain */
6539         for (j = 0; j < sc->max_rx_bufs; j++) {
6540             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6541             if (rc != 0) {
6542                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6543                       i, rc);
6544                 goto bxe_alloc_fp_buffers_error;
6545             }
6546 
6547             ring_prod     = RX_BD_NEXT(ring_prod);
6548             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6549         }
6550 
6551         fp->rx_bd_prod = ring_prod;
6552         fp->rx_cq_prod = cqe_ring_prod;
6553         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6554 
6555         max_agg_queues = MAX_AGG_QS(sc);
6556 
6557         fp->tpa_enable = TRUE;
6558 
6559         /* fill the TPA pool */
6560         for (j = 0; j < max_agg_queues; j++) {
6561             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6562             if (rc != 0) {
6563                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6564                           i, j);
6565                 fp->tpa_enable = FALSE;
6566                 goto bxe_alloc_fp_buffers_error;
6567             }
6568 
6569             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6570         }
6571 
6572         if (fp->tpa_enable) {
6573             /* fill the RX SGE chain */
6574             ring_prod = 0;
6575             for (j = 0; j < RX_SGE_USABLE; j++) {
6576                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6577                 if (rc != 0) {
6578                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6579                               i, ring_prod);
6580                     fp->tpa_enable = FALSE;
6581                     ring_prod = 0;
6582                     goto bxe_alloc_fp_buffers_error;
6583                 }
6584 
6585                 ring_prod = RX_SGE_NEXT(ring_prod);
6586             }
6587 
6588             fp->rx_sge_prod = ring_prod;
6589         }
6590     }
6591 
6592     return (0);
6593 
6594 bxe_alloc_fp_buffers_error:
6595 
6596     /* unwind what was already allocated */
6597     bxe_free_rx_bd_chain(fp);
6598     bxe_free_tpa_pool(fp);
6599     bxe_free_sge_chain(fp);
6600 
6601     return (ENOBUFS);
6602 }
6603 
6604 static void
6605 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6606 {
6607     bxe_dma_free(sc, &sc->fw_stats_dma);
6608 
6609     sc->fw_stats_num = 0;
6610 
6611     sc->fw_stats_req_size = 0;
6612     sc->fw_stats_req = NULL;
6613     sc->fw_stats_req_mapping = 0;
6614 
6615     sc->fw_stats_data_size = 0;
6616     sc->fw_stats_data = NULL;
6617     sc->fw_stats_data_mapping = 0;
6618 }
6619 
6620 static int
6621 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6622 {
6623     uint8_t num_queue_stats;
6624     int num_groups;
6625 
6626     /* number of queues for statistics is number of eth queues */
6627     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6628 
6629     /*
6630      * Total number of FW statistics requests =
6631      *   1 for port stats + 1 for PF stats + num of queues
6632      */
6633     sc->fw_stats_num = (2 + num_queue_stats);
6634 
6635     /*
6636      * Request is built from stats_query_header and an array of
6637      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6638      * rules. The real number or requests is configured in the
6639      * stats_query_header.
6640      */
6641     num_groups =
6642         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6643          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6644 
6645     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6646           sc->fw_stats_num, num_groups);
6647 
6648     sc->fw_stats_req_size =
6649         (sizeof(struct stats_query_header) +
6650          (num_groups * sizeof(struct stats_query_cmd_group)));
6651 
6652     /*
6653      * Data for statistics requests + stats_counter.
6654      * stats_counter holds per-STORM counters that are incremented when
6655      * STORM has finished with the current request. Memory for FCoE
6656      * offloaded statistics are counted anyway, even if they will not be sent.
6657      * VF stats are not accounted for here as the data of VF stats is stored
6658      * in memory allocated by the VF, not here.
6659      */
6660     sc->fw_stats_data_size =
6661         (sizeof(struct stats_counter) +
6662          sizeof(struct per_port_stats) +
6663          sizeof(struct per_pf_stats) +
6664          /* sizeof(struct fcoe_statistics_params) + */
6665          (sizeof(struct per_queue_stats) * num_queue_stats));
6666 
6667     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6668                       &sc->fw_stats_dma, "fw stats") != 0) {
6669         bxe_free_fw_stats_mem(sc);
6670         return (-1);
6671     }
6672 
6673     /* set up the shortcuts */
6674 
6675     sc->fw_stats_req =
6676         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6677     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6678 
6679     sc->fw_stats_data =
6680         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6681                                      sc->fw_stats_req_size);
6682     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6683                                  sc->fw_stats_req_size);
6684 
6685     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6686           (uintmax_t)sc->fw_stats_req_mapping);
6687 
6688     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6689           (uintmax_t)sc->fw_stats_data_mapping);
6690 
6691     return (0);
6692 }
6693 
6694 /*
6695  * Bits map:
6696  * 0-7  - Engine0 load counter.
6697  * 8-15 - Engine1 load counter.
6698  * 16   - Engine0 RESET_IN_PROGRESS bit.
6699  * 17   - Engine1 RESET_IN_PROGRESS bit.
6700  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6701  *        function on the engine
6702  * 19   - Engine1 ONE_IS_LOADED.
6703  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6704  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6705  *        for just the one belonging to its engine).
6706  */
6707 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6708 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6709 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6710 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6711 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6712 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6713 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6714 #define BXE_GLOBAL_RESET_BIT      0x00040000
6715 
6716 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6717 static void
6718 bxe_set_reset_global(struct bxe_softc *sc)
6719 {
6720     uint32_t val;
6721     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6722     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6723     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6724     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6725 }
6726 
6727 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6728 static void
6729 bxe_clear_reset_global(struct bxe_softc *sc)
6730 {
6731     uint32_t val;
6732     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6733     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6734     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6735     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6736 }
6737 
6738 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6739 static uint8_t
6740 bxe_reset_is_global(struct bxe_softc *sc)
6741 {
6742     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6743     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6744     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6745 }
6746 
6747 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6748 static void
6749 bxe_set_reset_done(struct bxe_softc *sc)
6750 {
6751     uint32_t val;
6752     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6753                                  BXE_PATH0_RST_IN_PROG_BIT;
6754 
6755     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6756 
6757     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6758     /* Clear the bit */
6759     val &= ~bit;
6760     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6761 
6762     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6763 }
6764 
6765 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6766 static void
6767 bxe_set_reset_in_progress(struct bxe_softc *sc)
6768 {
6769     uint32_t val;
6770     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6771                                  BXE_PATH0_RST_IN_PROG_BIT;
6772 
6773     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6774 
6775     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6776     /* Set the bit */
6777     val |= bit;
6778     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6779 
6780     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6781 }
6782 
6783 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6784 static uint8_t
6785 bxe_reset_is_done(struct bxe_softc *sc,
6786                   int              engine)
6787 {
6788     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6789     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6790                             BXE_PATH0_RST_IN_PROG_BIT;
6791 
6792     /* return false if bit is set */
6793     return (val & bit) ? FALSE : TRUE;
6794 }
6795 
6796 /* get the load status for an engine, should be run under rtnl lock */
6797 static uint8_t
6798 bxe_get_load_status(struct bxe_softc *sc,
6799                     int              engine)
6800 {
6801     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6802                              BXE_PATH0_LOAD_CNT_MASK;
6803     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6804                               BXE_PATH0_LOAD_CNT_SHIFT;
6805     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6806 
6807     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6808 
6809     val = ((val & mask) >> shift);
6810 
6811     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6812 
6813     return (val != 0);
6814 }
6815 
6816 /* set pf load mark */
6817 /* XXX needs to be under rtnl lock */
6818 static void
6819 bxe_set_pf_load(struct bxe_softc *sc)
6820 {
6821     uint32_t val;
6822     uint32_t val1;
6823     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6824                                   BXE_PATH0_LOAD_CNT_MASK;
6825     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6826                                    BXE_PATH0_LOAD_CNT_SHIFT;
6827 
6828     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6829 
6830     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6831     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6832 
6833     /* get the current counter value */
6834     val1 = ((val & mask) >> shift);
6835 
6836     /* set bit of this PF */
6837     val1 |= (1 << SC_ABS_FUNC(sc));
6838 
6839     /* clear the old value */
6840     val &= ~mask;
6841 
6842     /* set the new one */
6843     val |= ((val1 << shift) & mask);
6844 
6845     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6846 
6847     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6848 }
6849 
6850 /* clear pf load mark */
6851 /* XXX needs to be under rtnl lock */
6852 static uint8_t
6853 bxe_clear_pf_load(struct bxe_softc *sc)
6854 {
6855     uint32_t val1, val;
6856     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6857                                   BXE_PATH0_LOAD_CNT_MASK;
6858     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6859                                    BXE_PATH0_LOAD_CNT_SHIFT;
6860 
6861     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6862     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6863     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6864 
6865     /* get the current counter value */
6866     val1 = (val & mask) >> shift;
6867 
6868     /* clear bit of that PF */
6869     val1 &= ~(1 << SC_ABS_FUNC(sc));
6870 
6871     /* clear the old value */
6872     val &= ~mask;
6873 
6874     /* set the new one */
6875     val |= ((val1 << shift) & mask);
6876 
6877     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6878     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6879     return (val1 != 0);
6880 }
6881 
6882 /* send load requrest to mcp and analyze response */
6883 static int
6884 bxe_nic_load_request(struct bxe_softc *sc,
6885                      uint32_t         *load_code)
6886 {
6887     /* init fw_seq */
6888     sc->fw_seq =
6889         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6890          DRV_MSG_SEQ_NUMBER_MASK);
6891 
6892     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6893 
6894     /* get the current FW pulse sequence */
6895     sc->fw_drv_pulse_wr_seq =
6896         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6897          DRV_PULSE_SEQ_MASK);
6898 
6899     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6900           sc->fw_drv_pulse_wr_seq);
6901 
6902     /* load request */
6903     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6904                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6905 
6906     /* if the MCP fails to respond we must abort */
6907     if (!(*load_code)) {
6908         BLOGE(sc, "MCP response failure!\n");
6909         return (-1);
6910     }
6911 
6912     /* if MCP refused then must abort */
6913     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6914         BLOGE(sc, "MCP refused load request\n");
6915         return (-1);
6916     }
6917 
6918     return (0);
6919 }
6920 
6921 /*
6922  * Check whether another PF has already loaded FW to chip. In virtualized
6923  * environments a pf from anoth VM may have already initialized the device
6924  * including loading FW.
6925  */
6926 static int
6927 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6928                          uint32_t         load_code)
6929 {
6930     uint32_t my_fw, loaded_fw;
6931 
6932     /* is another pf loaded on this engine? */
6933     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6934         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6935         /* build my FW version dword */
6936         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6937                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6938                  (BCM_5710_FW_REVISION_VERSION << 16) +
6939                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6940 
6941         /* read loaded FW from chip */
6942         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6943         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6944               loaded_fw, my_fw);
6945 
6946         /* abort nic load if version mismatch */
6947         if (my_fw != loaded_fw) {
6948             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6949                   loaded_fw, my_fw);
6950             return (-1);
6951         }
6952     }
6953 
6954     return (0);
6955 }
6956 
6957 /* mark PMF if applicable */
6958 static void
6959 bxe_nic_load_pmf(struct bxe_softc *sc,
6960                  uint32_t         load_code)
6961 {
6962     uint32_t ncsi_oem_data_addr;
6963 
6964     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6965         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6966         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6967         /*
6968          * Barrier here for ordering between the writing to sc->port.pmf here
6969          * and reading it from the periodic task.
6970          */
6971         sc->port.pmf = 1;
6972         mb();
6973     } else {
6974         sc->port.pmf = 0;
6975     }
6976 
6977     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6978 
6979     /* XXX needed? */
6980     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6981         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6982             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6983             if (ncsi_oem_data_addr) {
6984                 REG_WR(sc,
6985                        (ncsi_oem_data_addr +
6986                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6987                        0);
6988             }
6989         }
6990     }
6991 }
6992 
6993 static void
6994 bxe_read_mf_cfg(struct bxe_softc *sc)
6995 {
6996     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6997     int abs_func;
6998     int vn;
6999 
7000     if (BXE_NOMCP(sc)) {
7001         return; /* what should be the default bvalue in this case */
7002     }
7003 
7004     /*
7005      * The formula for computing the absolute function number is...
7006      * For 2 port configuration (4 functions per port):
7007      *   abs_func = 2 * vn + SC_PORT + SC_PATH
7008      * For 4 port configuration (2 functions per port):
7009      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
7010      */
7011     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
7012         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
7013         if (abs_func >= E1H_FUNC_MAX) {
7014             break;
7015         }
7016         sc->devinfo.mf_info.mf_config[vn] =
7017             MFCFG_RD(sc, func_mf_config[abs_func].config);
7018     }
7019 
7020     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
7021         FUNC_MF_CFG_FUNC_DISABLED) {
7022         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
7023         sc->flags |= BXE_MF_FUNC_DIS;
7024     } else {
7025         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
7026         sc->flags &= ~BXE_MF_FUNC_DIS;
7027     }
7028 }
7029 
7030 /* acquire split MCP access lock register */
7031 static int bxe_acquire_alr(struct bxe_softc *sc)
7032 {
7033     uint32_t j, val;
7034 
7035     for (j = 0; j < 1000; j++) {
7036         val = (1UL << 31);
7037         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
7038         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
7039         if (val & (1L << 31))
7040             break;
7041 
7042         DELAY(5000);
7043     }
7044 
7045     if (!(val & (1L << 31))) {
7046         BLOGE(sc, "Cannot acquire MCP access lock register\n");
7047         return (-1);
7048     }
7049 
7050     return (0);
7051 }
7052 
7053 /* release split MCP access lock register */
7054 static void bxe_release_alr(struct bxe_softc *sc)
7055 {
7056     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7057 }
7058 
7059 static void
7060 bxe_fan_failure(struct bxe_softc *sc)
7061 {
7062     int port = SC_PORT(sc);
7063     uint32_t ext_phy_config;
7064 
7065     /* mark the failure */
7066     ext_phy_config =
7067         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7068 
7069     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7070     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7071     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7072              ext_phy_config);
7073 
7074     /* log the failure */
7075     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7076               "the card to prevent permanent damage. "
7077               "Please contact OEM Support for assistance\n");
7078 
7079     /* XXX */
7080 #if 1
7081     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7082 #else
7083     /*
7084      * Schedule device reset (unload)
7085      * This is due to some boards consuming sufficient power when driver is
7086      * up to overheat if fan fails.
7087      */
7088     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7089     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7090 #endif
7091 }
7092 
7093 /* this function is called upon a link interrupt */
7094 static void
7095 bxe_link_attn(struct bxe_softc *sc)
7096 {
7097     uint32_t pause_enabled = 0;
7098     struct host_port_stats *pstats;
7099     int cmng_fns;
7100 
7101     /* Make sure that we are synced with the current statistics */
7102     bxe_stats_handle(sc, STATS_EVENT_STOP);
7103 
7104     elink_link_update(&sc->link_params, &sc->link_vars);
7105 
7106     if (sc->link_vars.link_up) {
7107 
7108         /* dropless flow control */
7109         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7110             pause_enabled = 0;
7111 
7112             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7113                 pause_enabled = 1;
7114             }
7115 
7116             REG_WR(sc,
7117                    (BAR_USTRORM_INTMEM +
7118                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7119                    pause_enabled);
7120         }
7121 
7122         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7123             pstats = BXE_SP(sc, port_stats);
7124             /* reset old mac stats */
7125             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7126         }
7127 
7128         if (sc->state == BXE_STATE_OPEN) {
7129             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7130         }
7131     }
7132 
7133     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7134         cmng_fns = bxe_get_cmng_fns_mode(sc);
7135 
7136         if (cmng_fns != CMNG_FNS_NONE) {
7137             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7138             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7139         } else {
7140             /* rate shaping and fairness are disabled */
7141             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7142         }
7143     }
7144 
7145     bxe_link_report_locked(sc);
7146 
7147     if (IS_MF(sc)) {
7148         ; // XXX bxe_link_sync_notify(sc);
7149     }
7150 }
7151 
7152 static void
7153 bxe_attn_int_asserted(struct bxe_softc *sc,
7154                       uint32_t         asserted)
7155 {
7156     int port = SC_PORT(sc);
7157     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7158                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7159     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7160                                         NIG_REG_MASK_INTERRUPT_PORT0;
7161     uint32_t aeu_mask;
7162     uint32_t nig_mask = 0;
7163     uint32_t reg_addr;
7164     uint32_t igu_acked;
7165     uint32_t cnt;
7166 
7167     if (sc->attn_state & asserted) {
7168         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7169     }
7170 
7171     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7172 
7173     aeu_mask = REG_RD(sc, aeu_addr);
7174 
7175     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7176           aeu_mask, asserted);
7177 
7178     aeu_mask &= ~(asserted & 0x3ff);
7179 
7180     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7181 
7182     REG_WR(sc, aeu_addr, aeu_mask);
7183 
7184     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7185 
7186     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7187     sc->attn_state |= asserted;
7188     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7189 
7190     if (asserted & ATTN_HARD_WIRED_MASK) {
7191         if (asserted & ATTN_NIG_FOR_FUNC) {
7192 
7193 	    bxe_acquire_phy_lock(sc);
7194             /* save nig interrupt mask */
7195             nig_mask = REG_RD(sc, nig_int_mask_addr);
7196 
7197             /* If nig_mask is not set, no need to call the update function */
7198             if (nig_mask) {
7199                 REG_WR(sc, nig_int_mask_addr, 0);
7200 
7201                 bxe_link_attn(sc);
7202             }
7203 
7204             /* handle unicore attn? */
7205         }
7206 
7207         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7208             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7209         }
7210 
7211         if (asserted & GPIO_2_FUNC) {
7212             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7213         }
7214 
7215         if (asserted & GPIO_3_FUNC) {
7216             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7217         }
7218 
7219         if (asserted & GPIO_4_FUNC) {
7220             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7221         }
7222 
7223         if (port == 0) {
7224             if (asserted & ATTN_GENERAL_ATTN_1) {
7225                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7226                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7227             }
7228             if (asserted & ATTN_GENERAL_ATTN_2) {
7229                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7230                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7231             }
7232             if (asserted & ATTN_GENERAL_ATTN_3) {
7233                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7234                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7235             }
7236         } else {
7237             if (asserted & ATTN_GENERAL_ATTN_4) {
7238                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7239                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7240             }
7241             if (asserted & ATTN_GENERAL_ATTN_5) {
7242                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7243                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7244             }
7245             if (asserted & ATTN_GENERAL_ATTN_6) {
7246                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7247                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7248             }
7249         }
7250     } /* hardwired */
7251 
7252     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7253         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7254     } else {
7255         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7256     }
7257 
7258     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7259           asserted,
7260           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7261     REG_WR(sc, reg_addr, asserted);
7262 
7263     /* now set back the mask */
7264     if (asserted & ATTN_NIG_FOR_FUNC) {
7265         /*
7266          * Verify that IGU ack through BAR was written before restoring
7267          * NIG mask. This loop should exit after 2-3 iterations max.
7268          */
7269         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7270             cnt = 0;
7271 
7272             do {
7273                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7274             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7275                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7276 
7277             if (!igu_acked) {
7278                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7279             }
7280 
7281             mb();
7282         }
7283 
7284         REG_WR(sc, nig_int_mask_addr, nig_mask);
7285 
7286 	bxe_release_phy_lock(sc);
7287     }
7288 }
7289 
7290 static void
7291 bxe_print_next_block(struct bxe_softc *sc,
7292                      int              idx,
7293                      const char       *blk)
7294 {
7295     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7296 }
7297 
7298 static int
7299 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7300                               uint32_t         sig,
7301                               int              par_num,
7302                               uint8_t          print)
7303 {
7304     uint32_t cur_bit = 0;
7305     int i = 0;
7306 
7307     for (i = 0; sig; i++) {
7308         cur_bit = ((uint32_t)0x1 << i);
7309         if (sig & cur_bit) {
7310             switch (cur_bit) {
7311             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7312                 if (print)
7313                     bxe_print_next_block(sc, par_num++, "BRB");
7314                 break;
7315             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7316                 if (print)
7317                     bxe_print_next_block(sc, par_num++, "PARSER");
7318                 break;
7319             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7320                 if (print)
7321                     bxe_print_next_block(sc, par_num++, "TSDM");
7322                 break;
7323             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7324                 if (print)
7325                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7326                 break;
7327             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7328                 if (print)
7329                     bxe_print_next_block(sc, par_num++, "TCM");
7330                 break;
7331             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7332                 if (print)
7333                     bxe_print_next_block(sc, par_num++, "TSEMI");
7334                 break;
7335             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7336                 if (print)
7337                     bxe_print_next_block(sc, par_num++, "XPB");
7338                 break;
7339             }
7340 
7341             /* Clear the bit */
7342             sig &= ~cur_bit;
7343         }
7344     }
7345 
7346     return (par_num);
7347 }
7348 
7349 static int
7350 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7351                               uint32_t         sig,
7352                               int              par_num,
7353                               uint8_t          *global,
7354                               uint8_t          print)
7355 {
7356     int i = 0;
7357     uint32_t cur_bit = 0;
7358     for (i = 0; sig; i++) {
7359         cur_bit = ((uint32_t)0x1 << i);
7360         if (sig & cur_bit) {
7361             switch (cur_bit) {
7362             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7363                 if (print)
7364                     bxe_print_next_block(sc, par_num++, "PBF");
7365                 break;
7366             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7367                 if (print)
7368                     bxe_print_next_block(sc, par_num++, "QM");
7369                 break;
7370             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7371                 if (print)
7372                     bxe_print_next_block(sc, par_num++, "TM");
7373                 break;
7374             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7375                 if (print)
7376                     bxe_print_next_block(sc, par_num++, "XSDM");
7377                 break;
7378             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7379                 if (print)
7380                     bxe_print_next_block(sc, par_num++, "XCM");
7381                 break;
7382             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7383                 if (print)
7384                     bxe_print_next_block(sc, par_num++, "XSEMI");
7385                 break;
7386             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7387                 if (print)
7388                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7389                 break;
7390             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7391                 if (print)
7392                     bxe_print_next_block(sc, par_num++, "NIG");
7393                 break;
7394             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7395                 if (print)
7396                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7397                 *global = TRUE;
7398                 break;
7399             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7400                 if (print)
7401                     bxe_print_next_block(sc, par_num++, "DEBUG");
7402                 break;
7403             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7404                 if (print)
7405                     bxe_print_next_block(sc, par_num++, "USDM");
7406                 break;
7407             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7408                 if (print)
7409                     bxe_print_next_block(sc, par_num++, "UCM");
7410                 break;
7411             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7412                 if (print)
7413                     bxe_print_next_block(sc, par_num++, "USEMI");
7414                 break;
7415             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7416                 if (print)
7417                     bxe_print_next_block(sc, par_num++, "UPB");
7418                 break;
7419             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7420                 if (print)
7421                     bxe_print_next_block(sc, par_num++, "CSDM");
7422                 break;
7423             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7424                 if (print)
7425                     bxe_print_next_block(sc, par_num++, "CCM");
7426                 break;
7427             }
7428 
7429             /* Clear the bit */
7430             sig &= ~cur_bit;
7431         }
7432     }
7433 
7434     return (par_num);
7435 }
7436 
7437 static int
7438 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7439                               uint32_t         sig,
7440                               int              par_num,
7441                               uint8_t          print)
7442 {
7443     uint32_t cur_bit = 0;
7444     int i = 0;
7445 
7446     for (i = 0; sig; i++) {
7447         cur_bit = ((uint32_t)0x1 << i);
7448         if (sig & cur_bit) {
7449             switch (cur_bit) {
7450             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7451                 if (print)
7452                     bxe_print_next_block(sc, par_num++, "CSEMI");
7453                 break;
7454             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7455                 if (print)
7456                     bxe_print_next_block(sc, par_num++, "PXP");
7457                 break;
7458             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7459                 if (print)
7460                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7461                 break;
7462             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7463                 if (print)
7464                     bxe_print_next_block(sc, par_num++, "CFC");
7465                 break;
7466             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7467                 if (print)
7468                     bxe_print_next_block(sc, par_num++, "CDU");
7469                 break;
7470             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7471                 if (print)
7472                     bxe_print_next_block(sc, par_num++, "DMAE");
7473                 break;
7474             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7475                 if (print)
7476                     bxe_print_next_block(sc, par_num++, "IGU");
7477                 break;
7478             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7479                 if (print)
7480                     bxe_print_next_block(sc, par_num++, "MISC");
7481                 break;
7482             }
7483 
7484             /* Clear the bit */
7485             sig &= ~cur_bit;
7486         }
7487     }
7488 
7489     return (par_num);
7490 }
7491 
7492 static int
7493 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7494                               uint32_t         sig,
7495                               int              par_num,
7496                               uint8_t          *global,
7497                               uint8_t          print)
7498 {
7499     uint32_t cur_bit = 0;
7500     int i = 0;
7501 
7502     for (i = 0; sig; i++) {
7503         cur_bit = ((uint32_t)0x1 << i);
7504         if (sig & cur_bit) {
7505             switch (cur_bit) {
7506             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7507                 if (print)
7508                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7509                 *global = TRUE;
7510                 break;
7511             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7512                 if (print)
7513                     bxe_print_next_block(sc, par_num++,
7514                               "MCP UMP RX");
7515                 *global = TRUE;
7516                 break;
7517             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7518                 if (print)
7519                     bxe_print_next_block(sc, par_num++,
7520                               "MCP UMP TX");
7521                 *global = TRUE;
7522                 break;
7523             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7524                 if (print)
7525                     bxe_print_next_block(sc, par_num++,
7526                               "MCP SCPAD");
7527                 *global = TRUE;
7528                 break;
7529             }
7530 
7531             /* Clear the bit */
7532             sig &= ~cur_bit;
7533         }
7534     }
7535 
7536     return (par_num);
7537 }
7538 
7539 static int
7540 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7541                               uint32_t         sig,
7542                               int              par_num,
7543                               uint8_t          print)
7544 {
7545     uint32_t cur_bit = 0;
7546     int i = 0;
7547 
7548     for (i = 0; sig; i++) {
7549         cur_bit = ((uint32_t)0x1 << i);
7550         if (sig & cur_bit) {
7551             switch (cur_bit) {
7552             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7553                 if (print)
7554                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7555                 break;
7556             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7557                 if (print)
7558                     bxe_print_next_block(sc, par_num++, "ATC");
7559                 break;
7560             }
7561 
7562             /* Clear the bit */
7563             sig &= ~cur_bit;
7564         }
7565     }
7566 
7567     return (par_num);
7568 }
7569 
7570 static uint8_t
7571 bxe_parity_attn(struct bxe_softc *sc,
7572                 uint8_t          *global,
7573                 uint8_t          print,
7574                 uint32_t         *sig)
7575 {
7576     int par_num = 0;
7577 
7578     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7579         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7580         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7581         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7582         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7583         BLOGE(sc, "Parity error: HW block parity attention:\n"
7584                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7585               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7586               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7587               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7588               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7589               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7590 
7591         if (print)
7592             BLOGI(sc, "Parity errors detected in blocks: ");
7593 
7594         par_num =
7595             bxe_check_blocks_with_parity0(sc, sig[0] &
7596                                           HW_PRTY_ASSERT_SET_0,
7597                                           par_num, print);
7598         par_num =
7599             bxe_check_blocks_with_parity1(sc, sig[1] &
7600                                           HW_PRTY_ASSERT_SET_1,
7601                                           par_num, global, print);
7602         par_num =
7603             bxe_check_blocks_with_parity2(sc, sig[2] &
7604                                           HW_PRTY_ASSERT_SET_2,
7605                                           par_num, print);
7606         par_num =
7607             bxe_check_blocks_with_parity3(sc, sig[3] &
7608                                           HW_PRTY_ASSERT_SET_3,
7609                                           par_num, global, print);
7610         par_num =
7611             bxe_check_blocks_with_parity4(sc, sig[4] &
7612                                           HW_PRTY_ASSERT_SET_4,
7613                                           par_num, print);
7614 
7615         if (print)
7616             BLOGI(sc, "\n");
7617 
7618         return (TRUE);
7619     }
7620 
7621     return (FALSE);
7622 }
7623 
7624 static uint8_t
7625 bxe_chk_parity_attn(struct bxe_softc *sc,
7626                     uint8_t          *global,
7627                     uint8_t          print)
7628 {
7629     struct attn_route attn = { {0} };
7630     int port = SC_PORT(sc);
7631 
7632     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7633     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7634     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7635     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7636 
7637     /*
7638      * Since MCP attentions can't be disabled inside the block, we need to
7639      * read AEU registers to see whether they're currently disabled
7640      */
7641     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7642                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7643                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7644                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7645 
7646 
7647     if (!CHIP_IS_E1x(sc))
7648         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7649 
7650     return (bxe_parity_attn(sc, global, print, attn.sig));
7651 }
7652 
7653 static void
7654 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7655                          uint32_t         attn)
7656 {
7657     uint32_t val;
7658 
7659     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7660         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7661         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7662         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7663             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7664         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7665             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7666         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7667             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7668         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7669             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7670         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7671             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7672         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7673             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7674         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7675             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7676         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7677             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7678         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7679             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7680     }
7681 
7682     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7683         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7684         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7685         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7686             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7687         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7688             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7689         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7690             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7691         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7692             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7693         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7694             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7695         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7696             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7697     }
7698 
7699     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7700                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7701         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7702               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7703                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7704     }
7705 }
7706 
7707 static void
7708 bxe_e1h_disable(struct bxe_softc *sc)
7709 {
7710     int port = SC_PORT(sc);
7711 
7712     bxe_tx_disable(sc);
7713 
7714     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7715 }
7716 
7717 static void
7718 bxe_e1h_enable(struct bxe_softc *sc)
7719 {
7720     int port = SC_PORT(sc);
7721 
7722     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7723 
7724     // XXX bxe_tx_enable(sc);
7725 }
7726 
7727 /*
7728  * called due to MCP event (on pmf):
7729  *   reread new bandwidth configuration
7730  *   configure FW
7731  *   notify others function about the change
7732  */
7733 static void
7734 bxe_config_mf_bw(struct bxe_softc *sc)
7735 {
7736     if (sc->link_vars.link_up) {
7737         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7738         // XXX bxe_link_sync_notify(sc);
7739     }
7740 
7741     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7742 }
7743 
7744 static void
7745 bxe_set_mf_bw(struct bxe_softc *sc)
7746 {
7747     bxe_config_mf_bw(sc);
7748     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7749 }
7750 
7751 static void
7752 bxe_handle_eee_event(struct bxe_softc *sc)
7753 {
7754     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7755     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7756 }
7757 
7758 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7759 
7760 static void
7761 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7762 {
7763     struct eth_stats_info *ether_stat =
7764         &sc->sp->drv_info_to_mcp.ether_stat;
7765 
7766     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7767             ETH_STAT_INFO_VERSION_LEN);
7768 
7769     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7770     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7771                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7772                                           ether_stat->mac_local + MAC_PAD,
7773                                           MAC_PAD, ETH_ALEN);
7774 
7775     ether_stat->mtu_size = sc->mtu;
7776 
7777     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7778     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7779         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7780     }
7781 
7782     // XXX ether_stat->feature_flags |= ???;
7783 
7784     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7785 
7786     ether_stat->txq_size = sc->tx_ring_size;
7787     ether_stat->rxq_size = sc->rx_ring_size;
7788 }
7789 
7790 static void
7791 bxe_handle_drv_info_req(struct bxe_softc *sc)
7792 {
7793     enum drv_info_opcode op_code;
7794     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7795 
7796     /* if drv_info version supported by MFW doesn't match - send NACK */
7797     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7798         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7799         return;
7800     }
7801 
7802     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7803                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7804 
7805     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7806 
7807     switch (op_code) {
7808     case ETH_STATS_OPCODE:
7809         bxe_drv_info_ether_stat(sc);
7810         break;
7811     case FCOE_STATS_OPCODE:
7812     case ISCSI_STATS_OPCODE:
7813     default:
7814         /* if op code isn't supported - send NACK */
7815         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7816         return;
7817     }
7818 
7819     /*
7820      * If we got drv_info attn from MFW then these fields are defined in
7821      * shmem2 for sure
7822      */
7823     SHMEM2_WR(sc, drv_info_host_addr_lo,
7824               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7825     SHMEM2_WR(sc, drv_info_host_addr_hi,
7826               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7827 
7828     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7829 }
7830 
7831 static void
7832 bxe_dcc_event(struct bxe_softc *sc,
7833               uint32_t         dcc_event)
7834 {
7835     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7836 
7837     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7838         /*
7839          * This is the only place besides the function initialization
7840          * where the sc->flags can change so it is done without any
7841          * locks
7842          */
7843         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7844             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7845             sc->flags |= BXE_MF_FUNC_DIS;
7846             bxe_e1h_disable(sc);
7847         } else {
7848             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7849             sc->flags &= ~BXE_MF_FUNC_DIS;
7850             bxe_e1h_enable(sc);
7851         }
7852         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7853     }
7854 
7855     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7856         bxe_config_mf_bw(sc);
7857         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7858     }
7859 
7860     /* Report results to MCP */
7861     if (dcc_event)
7862         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7863     else
7864         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7865 }
7866 
7867 static void
7868 bxe_pmf_update(struct bxe_softc *sc)
7869 {
7870     int port = SC_PORT(sc);
7871     uint32_t val;
7872 
7873     sc->port.pmf = 1;
7874     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7875 
7876     /*
7877      * We need the mb() to ensure the ordering between the writing to
7878      * sc->port.pmf here and reading it from the bxe_periodic_task().
7879      */
7880     mb();
7881 
7882     /* queue a periodic task */
7883     // XXX schedule task...
7884 
7885     // XXX bxe_dcbx_pmf_update(sc);
7886 
7887     /* enable nig attention */
7888     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7889     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7890         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7891         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7892     } else if (!CHIP_IS_E1x(sc)) {
7893         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7894         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7895     }
7896 
7897     bxe_stats_handle(sc, STATS_EVENT_PMF);
7898 }
7899 
7900 static int
7901 bxe_mc_assert(struct bxe_softc *sc)
7902 {
7903     char last_idx;
7904     int i, rc = 0;
7905     uint32_t row0, row1, row2, row3;
7906 
7907     /* XSTORM */
7908     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7909     if (last_idx)
7910         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7911 
7912     /* print the asserts */
7913     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7914 
7915         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7916         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7917         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7918         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7919 
7920         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7921             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7922                   i, row3, row2, row1, row0);
7923             rc++;
7924         } else {
7925             break;
7926         }
7927     }
7928 
7929     /* TSTORM */
7930     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7931     if (last_idx) {
7932         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7933     }
7934 
7935     /* print the asserts */
7936     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7937 
7938         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7939         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7940         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7941         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7942 
7943         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7944             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7945                   i, row3, row2, row1, row0);
7946             rc++;
7947         } else {
7948             break;
7949         }
7950     }
7951 
7952     /* CSTORM */
7953     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7954     if (last_idx) {
7955         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7956     }
7957 
7958     /* print the asserts */
7959     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7960 
7961         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7962         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7963         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7964         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7965 
7966         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7967             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7968                   i, row3, row2, row1, row0);
7969             rc++;
7970         } else {
7971             break;
7972         }
7973     }
7974 
7975     /* USTORM */
7976     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7977     if (last_idx) {
7978         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7979     }
7980 
7981     /* print the asserts */
7982     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7983 
7984         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7985         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7986         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7987         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7988 
7989         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7990             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7991                   i, row3, row2, row1, row0);
7992             rc++;
7993         } else {
7994             break;
7995         }
7996     }
7997 
7998     return (rc);
7999 }
8000 
8001 static void
8002 bxe_attn_int_deasserted3(struct bxe_softc *sc,
8003                          uint32_t         attn)
8004 {
8005     int func = SC_FUNC(sc);
8006     uint32_t val;
8007 
8008     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
8009 
8010         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
8011 
8012             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
8013             bxe_read_mf_cfg(sc);
8014             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
8015                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
8016             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
8017 
8018             if (val & DRV_STATUS_DCC_EVENT_MASK)
8019                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
8020 
8021             if (val & DRV_STATUS_SET_MF_BW)
8022                 bxe_set_mf_bw(sc);
8023 
8024             if (val & DRV_STATUS_DRV_INFO_REQ)
8025                 bxe_handle_drv_info_req(sc);
8026 
8027             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8028                 bxe_pmf_update(sc);
8029 
8030             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8031                 bxe_handle_eee_event(sc);
8032 
8033             if (sc->link_vars.periodic_flags &
8034                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8035                 /* sync with link */
8036 		bxe_acquire_phy_lock(sc);
8037                 sc->link_vars.periodic_flags &=
8038                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8039 		bxe_release_phy_lock(sc);
8040                 if (IS_MF(sc))
8041                     ; // XXX bxe_link_sync_notify(sc);
8042                 bxe_link_report(sc);
8043             }
8044 
8045             /*
8046              * Always call it here: bxe_link_report() will
8047              * prevent the link indication duplication.
8048              */
8049             bxe_link_status_update(sc);
8050 
8051         } else if (attn & BXE_MC_ASSERT_BITS) {
8052 
8053             BLOGE(sc, "MC assert!\n");
8054             bxe_mc_assert(sc);
8055             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8056             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8057             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8058             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8059             bxe_panic(sc, ("MC assert!\n"));
8060 
8061         } else if (attn & BXE_MCP_ASSERT) {
8062 
8063             BLOGE(sc, "MCP assert!\n");
8064             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8065             // XXX bxe_fw_dump(sc);
8066 
8067         } else {
8068             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8069         }
8070     }
8071 
8072     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8073         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8074         if (attn & BXE_GRC_TIMEOUT) {
8075             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8076             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8077         }
8078         if (attn & BXE_GRC_RSV) {
8079             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8080             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8081         }
8082         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8083     }
8084 }
8085 
8086 static void
8087 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8088                          uint32_t         attn)
8089 {
8090     int port = SC_PORT(sc);
8091     int reg_offset;
8092     uint32_t val0, mask0, val1, mask1;
8093     uint32_t val;
8094 
8095     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8096         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8097         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8098         /* CFC error attention */
8099         if (val & 0x2) {
8100             BLOGE(sc, "FATAL error from CFC\n");
8101         }
8102     }
8103 
8104     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8105         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8106         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8107         /* RQ_USDMDP_FIFO_OVERFLOW */
8108         if (val & 0x18000) {
8109             BLOGE(sc, "FATAL error from PXP\n");
8110         }
8111 
8112         if (!CHIP_IS_E1x(sc)) {
8113             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8114             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8115         }
8116     }
8117 
8118 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8119 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8120 
8121     if (attn & AEU_PXP2_HW_INT_BIT) {
8122         /*  CQ47854 workaround do not panic on
8123          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8124          */
8125         if (!CHIP_IS_E1x(sc)) {
8126             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8127             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8128             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8129             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8130             /*
8131              * If the olny PXP2_EOP_ERROR_BIT is set in
8132              * STS0 and STS1 - clear it
8133              *
8134              * probably we lose additional attentions between
8135              * STS0 and STS_CLR0, in this case user will not
8136              * be notified about them
8137              */
8138             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8139                 !(val1 & mask1))
8140                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8141 
8142             /* print the register, since no one can restore it */
8143             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8144 
8145             /*
8146              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8147              * then notify
8148              */
8149             if (val0 & PXP2_EOP_ERROR_BIT) {
8150                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8151 
8152                 /*
8153                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8154                  * set then clear attention from PXP2 block without panic
8155                  */
8156                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8157                     ((val1 & mask1) == 0))
8158                     attn &= ~AEU_PXP2_HW_INT_BIT;
8159             }
8160         }
8161     }
8162 
8163     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8164         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8165                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8166 
8167         val = REG_RD(sc, reg_offset);
8168         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8169         REG_WR(sc, reg_offset, val);
8170 
8171         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8172               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8173         bxe_panic(sc, ("HW block attention set2\n"));
8174     }
8175 }
8176 
8177 static void
8178 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8179                          uint32_t         attn)
8180 {
8181     int port = SC_PORT(sc);
8182     int reg_offset;
8183     uint32_t val;
8184 
8185     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8186         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8187         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8188         /* DORQ discard attention */
8189         if (val & 0x2) {
8190             BLOGE(sc, "FATAL error from DORQ\n");
8191         }
8192     }
8193 
8194     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8195         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8196                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8197 
8198         val = REG_RD(sc, reg_offset);
8199         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8200         REG_WR(sc, reg_offset, val);
8201 
8202         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8203               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8204         bxe_panic(sc, ("HW block attention set1\n"));
8205     }
8206 }
8207 
8208 static void
8209 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8210                          uint32_t         attn)
8211 {
8212     int port = SC_PORT(sc);
8213     int reg_offset;
8214     uint32_t val;
8215 
8216     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8217                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8218 
8219     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8220         val = REG_RD(sc, reg_offset);
8221         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8222         REG_WR(sc, reg_offset, val);
8223 
8224         BLOGW(sc, "SPIO5 hw attention\n");
8225 
8226         /* Fan failure attention */
8227         elink_hw_reset_phy(&sc->link_params);
8228         bxe_fan_failure(sc);
8229     }
8230 
8231     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8232 	bxe_acquire_phy_lock(sc);
8233         elink_handle_module_detect_int(&sc->link_params);
8234 	bxe_release_phy_lock(sc);
8235     }
8236 
8237     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8238         val = REG_RD(sc, reg_offset);
8239         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8240         REG_WR(sc, reg_offset, val);
8241 
8242         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8243                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8244     }
8245 }
8246 
8247 static void
8248 bxe_attn_int_deasserted(struct bxe_softc *sc,
8249                         uint32_t         deasserted)
8250 {
8251     struct attn_route attn;
8252     struct attn_route *group_mask;
8253     int port = SC_PORT(sc);
8254     int index;
8255     uint32_t reg_addr;
8256     uint32_t val;
8257     uint32_t aeu_mask;
8258     uint8_t global = FALSE;
8259 
8260     /*
8261      * Need to take HW lock because MCP or other port might also
8262      * try to handle this event.
8263      */
8264     bxe_acquire_alr(sc);
8265 
8266     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8267         /* XXX
8268          * In case of parity errors don't handle attentions so that
8269          * other function would "see" parity errors.
8270          */
8271         sc->recovery_state = BXE_RECOVERY_INIT;
8272         // XXX schedule a recovery task...
8273         /* disable HW interrupts */
8274         bxe_int_disable(sc);
8275         bxe_release_alr(sc);
8276         return;
8277     }
8278 
8279     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8280     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8281     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8282     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8283     if (!CHIP_IS_E1x(sc)) {
8284         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8285     } else {
8286         attn.sig[4] = 0;
8287     }
8288 
8289     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8290           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8291 
8292     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8293         if (deasserted & (1 << index)) {
8294             group_mask = &sc->attn_group[index];
8295 
8296             BLOGD(sc, DBG_INTR,
8297                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8298                   group_mask->sig[0], group_mask->sig[1],
8299                   group_mask->sig[2], group_mask->sig[3],
8300                   group_mask->sig[4]);
8301 
8302             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8303             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8304             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8305             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8306             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8307         }
8308     }
8309 
8310     bxe_release_alr(sc);
8311 
8312     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8313         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8314                     COMMAND_REG_ATTN_BITS_CLR);
8315     } else {
8316         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8317     }
8318 
8319     val = ~deasserted;
8320     BLOGD(sc, DBG_INTR,
8321           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8322           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8323     REG_WR(sc, reg_addr, val);
8324 
8325     if (~sc->attn_state & deasserted) {
8326         BLOGE(sc, "IGU error\n");
8327     }
8328 
8329     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8330                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8331 
8332     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8333 
8334     aeu_mask = REG_RD(sc, reg_addr);
8335 
8336     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8337           aeu_mask, deasserted);
8338     aeu_mask |= (deasserted & 0x3ff);
8339     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8340 
8341     REG_WR(sc, reg_addr, aeu_mask);
8342     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8343 
8344     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8345     sc->attn_state &= ~deasserted;
8346     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8347 }
8348 
8349 static void
8350 bxe_attn_int(struct bxe_softc *sc)
8351 {
8352     /* read local copy of bits */
8353     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8354     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8355     uint32_t attn_state = sc->attn_state;
8356 
8357     /* look for changed bits */
8358     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8359     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8360 
8361     BLOGD(sc, DBG_INTR,
8362           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8363           attn_bits, attn_ack, asserted, deasserted);
8364 
8365     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8366         BLOGE(sc, "BAD attention state\n");
8367     }
8368 
8369     /* handle bits that were raised */
8370     if (asserted) {
8371         bxe_attn_int_asserted(sc, asserted);
8372     }
8373 
8374     if (deasserted) {
8375         bxe_attn_int_deasserted(sc, deasserted);
8376     }
8377 }
8378 
8379 static uint16_t
8380 bxe_update_dsb_idx(struct bxe_softc *sc)
8381 {
8382     struct host_sp_status_block *def_sb = sc->def_sb;
8383     uint16_t rc = 0;
8384 
8385     mb(); /* status block is written to by the chip */
8386 
8387     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8388         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8389         rc |= BXE_DEF_SB_ATT_IDX;
8390     }
8391 
8392     if (sc->def_idx != def_sb->sp_sb.running_index) {
8393         sc->def_idx = def_sb->sp_sb.running_index;
8394         rc |= BXE_DEF_SB_IDX;
8395     }
8396 
8397     mb();
8398 
8399     return (rc);
8400 }
8401 
8402 static inline struct ecore_queue_sp_obj *
8403 bxe_cid_to_q_obj(struct bxe_softc *sc,
8404                  uint32_t         cid)
8405 {
8406     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8407     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8408 }
8409 
8410 static void
8411 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8412 {
8413     struct ecore_mcast_ramrod_params rparam;
8414     int rc;
8415 
8416     memset(&rparam, 0, sizeof(rparam));
8417 
8418     rparam.mcast_obj = &sc->mcast_obj;
8419 
8420     BXE_MCAST_LOCK(sc);
8421 
8422     /* clear pending state for the last command */
8423     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8424 
8425     /* if there are pending mcast commands - send them */
8426     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8427         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8428         if (rc < 0) {
8429             BLOGD(sc, DBG_SP,
8430                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8431         }
8432     }
8433 
8434     BXE_MCAST_UNLOCK(sc);
8435 }
8436 
8437 static void
8438 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8439                               union event_ring_elem *elem)
8440 {
8441     unsigned long ramrod_flags = 0;
8442     int rc = 0;
8443     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8444     struct ecore_vlan_mac_obj *vlan_mac_obj;
8445 
8446     /* always push next commands out, don't wait here */
8447     bit_set(&ramrod_flags, RAMROD_CONT);
8448 
8449     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8450     case ECORE_FILTER_MAC_PENDING:
8451         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8452         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8453         break;
8454 
8455     case ECORE_FILTER_MCAST_PENDING:
8456         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8457         /*
8458          * This is only relevant for 57710 where multicast MACs are
8459          * configured as unicast MACs using the same ramrod.
8460          */
8461         bxe_handle_mcast_eqe(sc);
8462         return;
8463 
8464     default:
8465         BLOGE(sc, "Unsupported classification command: %d\n",
8466               elem->message.data.eth_event.echo);
8467         return;
8468     }
8469 
8470     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8471 
8472     if (rc < 0) {
8473         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8474     } else if (rc > 0) {
8475         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8476     }
8477 }
8478 
8479 static void
8480 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8481                        union event_ring_elem *elem)
8482 {
8483     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8484 
8485     /* send rx_mode command again if was requested */
8486     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8487                                &sc->sp_state)) {
8488         bxe_set_storm_rx_mode(sc);
8489     }
8490 }
8491 
8492 static void
8493 bxe_update_eq_prod(struct bxe_softc *sc,
8494                    uint16_t         prod)
8495 {
8496     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8497     wmb(); /* keep prod updates ordered */
8498 }
8499 
8500 static void
8501 bxe_eq_int(struct bxe_softc *sc)
8502 {
8503     uint16_t hw_cons, sw_cons, sw_prod;
8504     union event_ring_elem *elem;
8505     uint8_t echo;
8506     uint32_t cid;
8507     uint8_t opcode;
8508     int spqe_cnt = 0;
8509     struct ecore_queue_sp_obj *q_obj;
8510     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8511     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8512 
8513     hw_cons = le16toh(*sc->eq_cons_sb);
8514 
8515     /*
8516      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8517      * when we get to the next-page we need to adjust so the loop
8518      * condition below will be met. The next element is the size of a
8519      * regular element and hence incrementing by 1
8520      */
8521     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8522         hw_cons++;
8523     }
8524 
8525     /*
8526      * This function may never run in parallel with itself for a
8527      * specific sc and no need for a read memory barrier here.
8528      */
8529     sw_cons = sc->eq_cons;
8530     sw_prod = sc->eq_prod;
8531 
8532     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8533           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8534 
8535     for (;
8536          sw_cons != hw_cons;
8537          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8538 
8539         elem = &sc->eq[EQ_DESC(sw_cons)];
8540 
8541         /* elem CID originates from FW, actually LE */
8542         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8543         opcode = elem->message.opcode;
8544 
8545         /* handle eq element */
8546         switch (opcode) {
8547 
8548         case EVENT_RING_OPCODE_STAT_QUERY:
8549             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8550                   sc->stats_comp++);
8551             /* nothing to do with stats comp */
8552             goto next_spqe;
8553 
8554         case EVENT_RING_OPCODE_CFC_DEL:
8555             /* handle according to cid range */
8556             /* we may want to verify here that the sc state is HALTING */
8557             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8558             q_obj = bxe_cid_to_q_obj(sc, cid);
8559             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8560                 break;
8561             }
8562             goto next_spqe;
8563 
8564         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8565             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8566             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8567                 break;
8568             }
8569             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8570             goto next_spqe;
8571 
8572         case EVENT_RING_OPCODE_START_TRAFFIC:
8573             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8574             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8575                 break;
8576             }
8577             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8578             goto next_spqe;
8579 
8580         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8581             echo = elem->message.data.function_update_event.echo;
8582             if (echo == SWITCH_UPDATE) {
8583                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8584                 if (f_obj->complete_cmd(sc, f_obj,
8585                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8586                     break;
8587                 }
8588             }
8589             else {
8590                 BLOGD(sc, DBG_SP,
8591                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8592             }
8593             goto next_spqe;
8594 
8595         case EVENT_RING_OPCODE_FORWARD_SETUP:
8596             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8597             if (q_obj->complete_cmd(sc, q_obj,
8598                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8599                 break;
8600             }
8601             goto next_spqe;
8602 
8603         case EVENT_RING_OPCODE_FUNCTION_START:
8604             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8605             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8606                 break;
8607             }
8608             goto next_spqe;
8609 
8610         case EVENT_RING_OPCODE_FUNCTION_STOP:
8611             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8612             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8613                 break;
8614             }
8615             goto next_spqe;
8616         }
8617 
8618         switch (opcode | sc->state) {
8619         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8620         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8621             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8622             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8623             rss_raw->clear_pending(rss_raw);
8624             break;
8625 
8626         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8627         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8628         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8629         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8630         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8631         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8632             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8633             bxe_handle_classification_eqe(sc, elem);
8634             break;
8635 
8636         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8637         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8638         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8639             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8640             bxe_handle_mcast_eqe(sc);
8641             break;
8642 
8643         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8644         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8645         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8646             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8647             bxe_handle_rx_mode_eqe(sc, elem);
8648             break;
8649 
8650         default:
8651             /* unknown event log error and continue */
8652             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8653                   elem->message.opcode, sc->state);
8654         }
8655 
8656 next_spqe:
8657         spqe_cnt++;
8658     } /* for */
8659 
8660     mb();
8661     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8662 
8663     sc->eq_cons = sw_cons;
8664     sc->eq_prod = sw_prod;
8665 
8666     /* make sure that above mem writes were issued towards the memory */
8667     wmb();
8668 
8669     /* update producer */
8670     bxe_update_eq_prod(sc, sc->eq_prod);
8671 }
8672 
8673 static void
8674 bxe_handle_sp_tq(void *context,
8675                  int  pending)
8676 {
8677     struct bxe_softc *sc = (struct bxe_softc *)context;
8678     uint16_t status;
8679 
8680     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8681 
8682     /* what work needs to be performed? */
8683     status = bxe_update_dsb_idx(sc);
8684 
8685     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8686 
8687     /* HW attentions */
8688     if (status & BXE_DEF_SB_ATT_IDX) {
8689         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8690         bxe_attn_int(sc);
8691         status &= ~BXE_DEF_SB_ATT_IDX;
8692     }
8693 
8694     /* SP events: STAT_QUERY and others */
8695     if (status & BXE_DEF_SB_IDX) {
8696         /* handle EQ completions */
8697         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8698         bxe_eq_int(sc);
8699         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8700                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8701         status &= ~BXE_DEF_SB_IDX;
8702     }
8703 
8704     /* if status is non zero then something went wrong */
8705     if (__predict_false(status)) {
8706         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8707     }
8708 
8709     /* ack status block only if something was actually handled */
8710     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8711                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8712 
8713     /*
8714      * Must be called after the EQ processing (since eq leads to sriov
8715      * ramrod completion flows).
8716      * This flow may have been scheduled by the arrival of a ramrod
8717      * completion, or by the sriov code rescheduling itself.
8718      */
8719     // XXX bxe_iov_sp_task(sc);
8720 
8721 }
8722 
8723 static void
8724 bxe_handle_fp_tq(void *context,
8725                  int  pending)
8726 {
8727     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8728     struct bxe_softc *sc = fp->sc;
8729     uint8_t more_tx = FALSE;
8730     uint8_t more_rx = FALSE;
8731 
8732     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8733 
8734     /* XXX
8735      * IFF_DRV_RUNNING state can't be checked here since we process
8736      * slowpath events on a client queue during setup. Instead
8737      * we need to add a "process/continue" flag here that the driver
8738      * can use to tell the task here not to do anything.
8739      */
8740 #if 0
8741     if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8742         return;
8743     }
8744 #endif
8745 
8746     /* update the fastpath index */
8747     bxe_update_fp_sb_idx(fp);
8748 
8749     /* XXX add loop here if ever support multiple tx CoS */
8750     /* fp->txdata[cos] */
8751     if (bxe_has_tx_work(fp)) {
8752         BXE_FP_TX_LOCK(fp);
8753         more_tx = bxe_txeof(sc, fp);
8754         BXE_FP_TX_UNLOCK(fp);
8755     }
8756 
8757     if (bxe_has_rx_work(fp)) {
8758         more_rx = bxe_rxeof(sc, fp);
8759     }
8760 
8761     if (more_rx /*|| more_tx*/) {
8762         /* still more work to do */
8763         taskqueue_enqueue(fp->tq, &fp->tq_task);
8764         return;
8765     }
8766 
8767     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8768                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8769 }
8770 
8771 static void
8772 bxe_task_fp(struct bxe_fastpath *fp)
8773 {
8774     struct bxe_softc *sc = fp->sc;
8775     uint8_t more_tx = FALSE;
8776     uint8_t more_rx = FALSE;
8777 
8778     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8779 
8780     /* update the fastpath index */
8781     bxe_update_fp_sb_idx(fp);
8782 
8783     /* XXX add loop here if ever support multiple tx CoS */
8784     /* fp->txdata[cos] */
8785     if (bxe_has_tx_work(fp)) {
8786         BXE_FP_TX_LOCK(fp);
8787         more_tx = bxe_txeof(sc, fp);
8788         BXE_FP_TX_UNLOCK(fp);
8789     }
8790 
8791     if (bxe_has_rx_work(fp)) {
8792         more_rx = bxe_rxeof(sc, fp);
8793     }
8794 
8795     if (more_rx /*|| more_tx*/) {
8796         /* still more work to do, bail out if this ISR and process later */
8797         taskqueue_enqueue(fp->tq, &fp->tq_task);
8798         return;
8799     }
8800 
8801     /*
8802      * Here we write the fastpath index taken before doing any tx or rx work.
8803      * It is very well possible other hw events occurred up to this point and
8804      * they were actually processed accordingly above. Since we're going to
8805      * write an older fastpath index, an interrupt is coming which we might
8806      * not do any work in.
8807      */
8808     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8809                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8810 }
8811 
8812 /*
8813  * Legacy interrupt entry point.
8814  *
8815  * Verifies that the controller generated the interrupt and
8816  * then calls a separate routine to handle the various
8817  * interrupt causes: link, RX, and TX.
8818  */
8819 static void
8820 bxe_intr_legacy(void *xsc)
8821 {
8822     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8823     struct bxe_fastpath *fp;
8824     uint16_t status, mask;
8825     int i;
8826 
8827     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8828 
8829     /*
8830      * 0 for ustorm, 1 for cstorm
8831      * the bits returned from ack_int() are 0-15
8832      * bit 0 = attention status block
8833      * bit 1 = fast path status block
8834      * a mask of 0x2 or more = tx/rx event
8835      * a mask of 1 = slow path event
8836      */
8837 
8838     status = bxe_ack_int(sc);
8839 
8840     /* the interrupt is not for us */
8841     if (__predict_false(status == 0)) {
8842         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8843         return;
8844     }
8845 
8846     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8847 
8848     FOR_EACH_ETH_QUEUE(sc, i) {
8849         fp = &sc->fp[i];
8850         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8851         if (status & mask) {
8852             /* acknowledge and disable further fastpath interrupts */
8853             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8854             bxe_task_fp(fp);
8855             status &= ~mask;
8856         }
8857     }
8858 
8859     if (__predict_false(status & 0x1)) {
8860         /* acknowledge and disable further slowpath interrupts */
8861         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8862 
8863         /* schedule slowpath handler */
8864         taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8865 
8866         status &= ~0x1;
8867     }
8868 
8869     if (__predict_false(status)) {
8870         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8871     }
8872 }
8873 
8874 /* slowpath interrupt entry point */
8875 static void
8876 bxe_intr_sp(void *xsc)
8877 {
8878     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8879 
8880     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8881 
8882     /* acknowledge and disable further slowpath interrupts */
8883     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8884 
8885     /* schedule slowpath handler */
8886     taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8887 }
8888 
8889 /* fastpath interrupt entry point */
8890 static void
8891 bxe_intr_fp(void *xfp)
8892 {
8893     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8894     struct bxe_softc *sc = fp->sc;
8895 
8896     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8897 
8898     BLOGD(sc, DBG_INTR,
8899           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8900           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8901 
8902     /* acknowledge and disable further fastpath interrupts */
8903     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8904 
8905     bxe_task_fp(fp);
8906 }
8907 
8908 /* Release all interrupts allocated by the driver. */
8909 static void
8910 bxe_interrupt_free(struct bxe_softc *sc)
8911 {
8912     int i;
8913 
8914     switch (sc->interrupt_mode) {
8915     case INTR_MODE_INTX:
8916         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8917         if (sc->intr[0].resource != NULL) {
8918             bus_release_resource(sc->dev,
8919                                  SYS_RES_IRQ,
8920                                  sc->intr[0].rid,
8921                                  sc->intr[0].resource);
8922         }
8923         break;
8924     case INTR_MODE_MSI:
8925         for (i = 0; i < sc->intr_count; i++) {
8926             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8927             if (sc->intr[i].resource && sc->intr[i].rid) {
8928                 bus_release_resource(sc->dev,
8929                                      SYS_RES_IRQ,
8930                                      sc->intr[i].rid,
8931                                      sc->intr[i].resource);
8932             }
8933         }
8934         pci_release_msi(sc->dev);
8935         break;
8936     case INTR_MODE_MSIX:
8937         for (i = 0; i < sc->intr_count; i++) {
8938             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8939             if (sc->intr[i].resource && sc->intr[i].rid) {
8940                 bus_release_resource(sc->dev,
8941                                      SYS_RES_IRQ,
8942                                      sc->intr[i].rid,
8943                                      sc->intr[i].resource);
8944             }
8945         }
8946         pci_release_msi(sc->dev);
8947         break;
8948     default:
8949         /* nothing to do as initial allocation failed */
8950         break;
8951     }
8952 }
8953 
8954 /*
8955  * This function determines and allocates the appropriate
8956  * interrupt based on system capabilites and user request.
8957  *
8958  * The user may force a particular interrupt mode, specify
8959  * the number of receive queues, specify the method for
8960  * distribuitng received frames to receive queues, or use
8961  * the default settings which will automatically select the
8962  * best supported combination.  In addition, the OS may or
8963  * may not support certain combinations of these settings.
8964  * This routine attempts to reconcile the settings requested
8965  * by the user with the capabilites available from the system
8966  * to select the optimal combination of features.
8967  *
8968  * Returns:
8969  *   0 = Success, !0 = Failure.
8970  */
8971 static int
8972 bxe_interrupt_alloc(struct bxe_softc *sc)
8973 {
8974     int msix_count = 0;
8975     int msi_count = 0;
8976     int num_requested = 0;
8977     int num_allocated = 0;
8978     int rid, i, j;
8979     int rc;
8980 
8981     /* get the number of available MSI/MSI-X interrupts from the OS */
8982     if (sc->interrupt_mode > 0) {
8983         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8984             msix_count = pci_msix_count(sc->dev);
8985         }
8986 
8987         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8988             msi_count = pci_msi_count(sc->dev);
8989         }
8990 
8991         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8992               msi_count, msix_count);
8993     }
8994 
8995     do { /* try allocating MSI-X interrupt resources (at least 2) */
8996         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8997             break;
8998         }
8999 
9000         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9001             (msix_count < 2)) {
9002             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9003             break;
9004         }
9005 
9006         /* ask for the necessary number of MSI-X vectors */
9007         num_requested = min((sc->num_queues + 1), msix_count);
9008 
9009         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9010 
9011         num_allocated = num_requested;
9012         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9013             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9014             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9015             break;
9016         }
9017 
9018         if (num_allocated < 2) { /* possible? */
9019             BLOGE(sc, "MSI-X allocation less than 2!\n");
9020             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9021             pci_release_msi(sc->dev);
9022             break;
9023         }
9024 
9025         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9026               num_requested, num_allocated);
9027 
9028         /* best effort so use the number of vectors allocated to us */
9029         sc->intr_count = num_allocated;
9030         sc->num_queues = num_allocated - 1;
9031 
9032         rid = 1; /* initial resource identifier */
9033 
9034         /* allocate the MSI-X vectors */
9035         for (i = 0; i < num_allocated; i++) {
9036             sc->intr[i].rid = (rid + i);
9037 
9038             if ((sc->intr[i].resource =
9039                  bus_alloc_resource_any(sc->dev,
9040                                         SYS_RES_IRQ,
9041                                         &sc->intr[i].rid,
9042                                         RF_ACTIVE)) == NULL) {
9043                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9044                       i, (rid + i));
9045 
9046                 for (j = (i - 1); j >= 0; j--) {
9047                     bus_release_resource(sc->dev,
9048                                          SYS_RES_IRQ,
9049                                          sc->intr[j].rid,
9050                                          sc->intr[j].resource);
9051                 }
9052 
9053                 sc->intr_count = 0;
9054                 sc->num_queues = 0;
9055                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9056                 pci_release_msi(sc->dev);
9057                 break;
9058             }
9059 
9060             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9061         }
9062     } while (0);
9063 
9064     do { /* try allocating MSI vector resources (at least 2) */
9065         if (sc->interrupt_mode != INTR_MODE_MSI) {
9066             break;
9067         }
9068 
9069         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9070             (msi_count < 1)) {
9071             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9072             break;
9073         }
9074 
9075         /* ask for a single MSI vector */
9076         num_requested = 1;
9077 
9078         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9079 
9080         num_allocated = num_requested;
9081         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9082             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9083             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9084             break;
9085         }
9086 
9087         if (num_allocated != 1) { /* possible? */
9088             BLOGE(sc, "MSI allocation is not 1!\n");
9089             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9090             pci_release_msi(sc->dev);
9091             break;
9092         }
9093 
9094         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9095               num_requested, num_allocated);
9096 
9097         /* best effort so use the number of vectors allocated to us */
9098         sc->intr_count = num_allocated;
9099         sc->num_queues = num_allocated;
9100 
9101         rid = 1; /* initial resource identifier */
9102 
9103         sc->intr[0].rid = rid;
9104 
9105         if ((sc->intr[0].resource =
9106              bus_alloc_resource_any(sc->dev,
9107                                     SYS_RES_IRQ,
9108                                     &sc->intr[0].rid,
9109                                     RF_ACTIVE)) == NULL) {
9110             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9111             sc->intr_count = 0;
9112             sc->num_queues = 0;
9113             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9114             pci_release_msi(sc->dev);
9115             break;
9116         }
9117 
9118         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9119     } while (0);
9120 
9121     do { /* try allocating INTx vector resources */
9122         if (sc->interrupt_mode != INTR_MODE_INTX) {
9123             break;
9124         }
9125 
9126         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9127 
9128         /* only one vector for INTx */
9129         sc->intr_count = 1;
9130         sc->num_queues = 1;
9131 
9132         rid = 0; /* initial resource identifier */
9133 
9134         sc->intr[0].rid = rid;
9135 
9136         if ((sc->intr[0].resource =
9137              bus_alloc_resource_any(sc->dev,
9138                                     SYS_RES_IRQ,
9139                                     &sc->intr[0].rid,
9140                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9141             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9142             sc->intr_count = 0;
9143             sc->num_queues = 0;
9144             sc->interrupt_mode = -1; /* Failed! */
9145             break;
9146         }
9147 
9148         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9149     } while (0);
9150 
9151     if (sc->interrupt_mode == -1) {
9152         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9153         rc = 1;
9154     } else {
9155         BLOGD(sc, DBG_LOAD,
9156               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9157               sc->interrupt_mode, sc->num_queues);
9158         rc = 0;
9159     }
9160 
9161     return (rc);
9162 }
9163 
9164 static void
9165 bxe_interrupt_detach(struct bxe_softc *sc)
9166 {
9167     struct bxe_fastpath *fp;
9168     int i;
9169 
9170     /* release interrupt resources */
9171     for (i = 0; i < sc->intr_count; i++) {
9172         if (sc->intr[i].resource && sc->intr[i].tag) {
9173             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9174             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9175         }
9176     }
9177 
9178     for (i = 0; i < sc->num_queues; i++) {
9179         fp = &sc->fp[i];
9180         if (fp->tq) {
9181             taskqueue_drain(fp->tq, &fp->tq_task);
9182             taskqueue_free(fp->tq);
9183             fp->tq = NULL;
9184         }
9185     }
9186 
9187 
9188     if (sc->sp_tq) {
9189         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9190         taskqueue_free(sc->sp_tq);
9191         sc->sp_tq = NULL;
9192     }
9193 }
9194 
9195 /*
9196  * Enables interrupts and attach to the ISR.
9197  *
9198  * When using multiple MSI/MSI-X vectors the first vector
9199  * is used for slowpath operations while all remaining
9200  * vectors are used for fastpath operations.  If only a
9201  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9202  * ISR must look for both slowpath and fastpath completions.
9203  */
9204 static int
9205 bxe_interrupt_attach(struct bxe_softc *sc)
9206 {
9207     struct bxe_fastpath *fp;
9208     int rc = 0;
9209     int i;
9210 
9211     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9212              "bxe%d_sp_tq", sc->unit);
9213     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9214     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9215                                       taskqueue_thread_enqueue,
9216                                       &sc->sp_tq);
9217     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9218                             "%s", sc->sp_tq_name);
9219 
9220 
9221     for (i = 0; i < sc->num_queues; i++) {
9222         fp = &sc->fp[i];
9223         snprintf(fp->tq_name, sizeof(fp->tq_name),
9224                  "bxe%d_fp%d_tq", sc->unit, i);
9225         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9226         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9227                                        taskqueue_thread_enqueue,
9228                                        &fp->tq);
9229         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9230                                 "%s", fp->tq_name);
9231     }
9232 
9233     /* setup interrupt handlers */
9234     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9235         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9236 
9237         /*
9238          * Setup the interrupt handler. Note that we pass the driver instance
9239          * to the interrupt handler for the slowpath.
9240          */
9241         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9242                                  (INTR_TYPE_NET | INTR_MPSAFE),
9243                                  NULL, bxe_intr_sp, sc,
9244                                  &sc->intr[0].tag)) != 0) {
9245             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9246             goto bxe_interrupt_attach_exit;
9247         }
9248 
9249         bus_describe_intr(sc->dev, sc->intr[0].resource,
9250                           sc->intr[0].tag, "sp");
9251 
9252         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9253 
9254         /* initialize the fastpath vectors (note the first was used for sp) */
9255         for (i = 0; i < sc->num_queues; i++) {
9256             fp = &sc->fp[i];
9257             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9258 
9259             /*
9260              * Setup the interrupt handler. Note that we pass the
9261              * fastpath context to the interrupt handler in this
9262              * case.
9263              */
9264             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9265                                      (INTR_TYPE_NET | INTR_MPSAFE),
9266                                      NULL, bxe_intr_fp, fp,
9267                                      &sc->intr[i + 1].tag)) != 0) {
9268                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9269                       (i + 1), rc);
9270                 goto bxe_interrupt_attach_exit;
9271             }
9272 
9273             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9274                               sc->intr[i + 1].tag, "fp%02d", i);
9275 
9276             /* bind the fastpath instance to a cpu */
9277             if (sc->num_queues > 1) {
9278                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9279             }
9280 
9281             fp->state = BXE_FP_STATE_IRQ;
9282         }
9283     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9284         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9285 
9286         /*
9287          * Setup the interrupt handler. Note that we pass the
9288          * driver instance to the interrupt handler which
9289          * will handle both the slowpath and fastpath.
9290          */
9291         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9292                                  (INTR_TYPE_NET | INTR_MPSAFE),
9293                                  NULL, bxe_intr_legacy, sc,
9294                                  &sc->intr[0].tag)) != 0) {
9295             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9296             goto bxe_interrupt_attach_exit;
9297         }
9298 
9299     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9300         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9301 
9302         /*
9303          * Setup the interrupt handler. Note that we pass the
9304          * driver instance to the interrupt handler which
9305          * will handle both the slowpath and fastpath.
9306          */
9307         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9308                                  (INTR_TYPE_NET | INTR_MPSAFE),
9309                                  NULL, bxe_intr_legacy, sc,
9310                                  &sc->intr[0].tag)) != 0) {
9311             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9312             goto bxe_interrupt_attach_exit;
9313         }
9314     }
9315 
9316 bxe_interrupt_attach_exit:
9317 
9318     return (rc);
9319 }
9320 
9321 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9322 static int  bxe_init_hw_common(struct bxe_softc *sc);
9323 static int  bxe_init_hw_port(struct bxe_softc *sc);
9324 static int  bxe_init_hw_func(struct bxe_softc *sc);
9325 static void bxe_reset_common(struct bxe_softc *sc);
9326 static void bxe_reset_port(struct bxe_softc *sc);
9327 static void bxe_reset_func(struct bxe_softc *sc);
9328 static int  bxe_gunzip_init(struct bxe_softc *sc);
9329 static void bxe_gunzip_end(struct bxe_softc *sc);
9330 static int  bxe_init_firmware(struct bxe_softc *sc);
9331 static void bxe_release_firmware(struct bxe_softc *sc);
9332 
9333 static struct
9334 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9335     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9336     .init_hw_cmn      = bxe_init_hw_common,
9337     .init_hw_port     = bxe_init_hw_port,
9338     .init_hw_func     = bxe_init_hw_func,
9339 
9340     .reset_hw_cmn     = bxe_reset_common,
9341     .reset_hw_port    = bxe_reset_port,
9342     .reset_hw_func    = bxe_reset_func,
9343 
9344     .gunzip_init      = bxe_gunzip_init,
9345     .gunzip_end       = bxe_gunzip_end,
9346 
9347     .init_fw          = bxe_init_firmware,
9348     .release_fw       = bxe_release_firmware,
9349 };
9350 
9351 static void
9352 bxe_init_func_obj(struct bxe_softc *sc)
9353 {
9354     sc->dmae_ready = 0;
9355 
9356     ecore_init_func_obj(sc,
9357                         &sc->func_obj,
9358                         BXE_SP(sc, func_rdata),
9359                         BXE_SP_MAPPING(sc, func_rdata),
9360                         BXE_SP(sc, func_afex_rdata),
9361                         BXE_SP_MAPPING(sc, func_afex_rdata),
9362                         &bxe_func_sp_drv);
9363 }
9364 
9365 static int
9366 bxe_init_hw(struct bxe_softc *sc,
9367             uint32_t         load_code)
9368 {
9369     struct ecore_func_state_params func_params = { NULL };
9370     int rc;
9371 
9372     /* prepare the parameters for function state transitions */
9373     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9374 
9375     func_params.f_obj = &sc->func_obj;
9376     func_params.cmd = ECORE_F_CMD_HW_INIT;
9377 
9378     func_params.params.hw_init.load_phase = load_code;
9379 
9380     /*
9381      * Via a plethora of function pointers, we will eventually reach
9382      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9383      */
9384     rc = ecore_func_state_change(sc, &func_params);
9385 
9386     return (rc);
9387 }
9388 
9389 static void
9390 bxe_fill(struct bxe_softc *sc,
9391          uint32_t         addr,
9392          int              fill,
9393          uint32_t         len)
9394 {
9395     uint32_t i;
9396 
9397     if (!(len % 4) && !(addr % 4)) {
9398         for (i = 0; i < len; i += 4) {
9399             REG_WR(sc, (addr + i), fill);
9400         }
9401     } else {
9402         for (i = 0; i < len; i++) {
9403             REG_WR8(sc, (addr + i), fill);
9404         }
9405     }
9406 }
9407 
9408 /* writes FP SP data to FW - data_size in dwords */
9409 static void
9410 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9411                   int              fw_sb_id,
9412                   uint32_t         *sb_data_p,
9413                   uint32_t         data_size)
9414 {
9415     int index;
9416 
9417     for (index = 0; index < data_size; index++) {
9418         REG_WR(sc,
9419                (BAR_CSTRORM_INTMEM +
9420                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9421                 (sizeof(uint32_t) * index)),
9422                *(sb_data_p + index));
9423     }
9424 }
9425 
9426 static void
9427 bxe_zero_fp_sb(struct bxe_softc *sc,
9428                int              fw_sb_id)
9429 {
9430     struct hc_status_block_data_e2 sb_data_e2;
9431     struct hc_status_block_data_e1x sb_data_e1x;
9432     uint32_t *sb_data_p;
9433     uint32_t data_size = 0;
9434 
9435     if (!CHIP_IS_E1x(sc)) {
9436         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9437         sb_data_e2.common.state = SB_DISABLED;
9438         sb_data_e2.common.p_func.vf_valid = FALSE;
9439         sb_data_p = (uint32_t *)&sb_data_e2;
9440         data_size = (sizeof(struct hc_status_block_data_e2) /
9441                      sizeof(uint32_t));
9442     } else {
9443         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9444         sb_data_e1x.common.state = SB_DISABLED;
9445         sb_data_e1x.common.p_func.vf_valid = FALSE;
9446         sb_data_p = (uint32_t *)&sb_data_e1x;
9447         data_size = (sizeof(struct hc_status_block_data_e1x) /
9448                      sizeof(uint32_t));
9449     }
9450 
9451     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9452 
9453     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9454              0, CSTORM_STATUS_BLOCK_SIZE);
9455     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9456              0, CSTORM_SYNC_BLOCK_SIZE);
9457 }
9458 
9459 static void
9460 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9461                   struct hc_sp_status_block_data *sp_sb_data)
9462 {
9463     int i;
9464 
9465     for (i = 0;
9466          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9467          i++) {
9468         REG_WR(sc,
9469                (BAR_CSTRORM_INTMEM +
9470                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9471                 (i * sizeof(uint32_t))),
9472                *((uint32_t *)sp_sb_data + i));
9473     }
9474 }
9475 
9476 static void
9477 bxe_zero_sp_sb(struct bxe_softc *sc)
9478 {
9479     struct hc_sp_status_block_data sp_sb_data;
9480 
9481     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9482 
9483     sp_sb_data.state           = SB_DISABLED;
9484     sp_sb_data.p_func.vf_valid = FALSE;
9485 
9486     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9487 
9488     bxe_fill(sc,
9489              (BAR_CSTRORM_INTMEM +
9490               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9491               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9492     bxe_fill(sc,
9493              (BAR_CSTRORM_INTMEM +
9494               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9495               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9496 }
9497 
9498 static void
9499 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9500                              int                       igu_sb_id,
9501                              int                       igu_seg_id)
9502 {
9503     hc_sm->igu_sb_id      = igu_sb_id;
9504     hc_sm->igu_seg_id     = igu_seg_id;
9505     hc_sm->timer_value    = 0xFF;
9506     hc_sm->time_to_expire = 0xFFFFFFFF;
9507 }
9508 
9509 static void
9510 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9511 {
9512     /* zero out state machine indices */
9513 
9514     /* rx indices */
9515     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9516 
9517     /* tx indices */
9518     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9519     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9520     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9521     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9522 
9523     /* map indices */
9524 
9525     /* rx indices */
9526     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9527         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9528 
9529     /* tx indices */
9530     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9531         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9532     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9533         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9534     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9535         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9536     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9537         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9538 }
9539 
9540 static void
9541 bxe_init_sb(struct bxe_softc *sc,
9542             bus_addr_t       busaddr,
9543             int              vfid,
9544             uint8_t          vf_valid,
9545             int              fw_sb_id,
9546             int              igu_sb_id)
9547 {
9548     struct hc_status_block_data_e2  sb_data_e2;
9549     struct hc_status_block_data_e1x sb_data_e1x;
9550     struct hc_status_block_sm       *hc_sm_p;
9551     uint32_t *sb_data_p;
9552     int igu_seg_id;
9553     int data_size;
9554 
9555     if (CHIP_INT_MODE_IS_BC(sc)) {
9556         igu_seg_id = HC_SEG_ACCESS_NORM;
9557     } else {
9558         igu_seg_id = IGU_SEG_ACCESS_NORM;
9559     }
9560 
9561     bxe_zero_fp_sb(sc, fw_sb_id);
9562 
9563     if (!CHIP_IS_E1x(sc)) {
9564         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9565         sb_data_e2.common.state = SB_ENABLED;
9566         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9567         sb_data_e2.common.p_func.vf_id = vfid;
9568         sb_data_e2.common.p_func.vf_valid = vf_valid;
9569         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9570         sb_data_e2.common.same_igu_sb_1b = TRUE;
9571         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9572         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9573         hc_sm_p = sb_data_e2.common.state_machine;
9574         sb_data_p = (uint32_t *)&sb_data_e2;
9575         data_size = (sizeof(struct hc_status_block_data_e2) /
9576                      sizeof(uint32_t));
9577         bxe_map_sb_state_machines(sb_data_e2.index_data);
9578     } else {
9579         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9580         sb_data_e1x.common.state = SB_ENABLED;
9581         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9582         sb_data_e1x.common.p_func.vf_id = 0xff;
9583         sb_data_e1x.common.p_func.vf_valid = FALSE;
9584         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9585         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9586         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9587         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9588         hc_sm_p = sb_data_e1x.common.state_machine;
9589         sb_data_p = (uint32_t *)&sb_data_e1x;
9590         data_size = (sizeof(struct hc_status_block_data_e1x) /
9591                      sizeof(uint32_t));
9592         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9593     }
9594 
9595     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9596     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9597 
9598     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9599 
9600     /* write indices to HW - PCI guarantees endianity of regpairs */
9601     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9602 }
9603 
9604 static inline uint8_t
9605 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9606 {
9607     if (CHIP_IS_E1x(fp->sc)) {
9608         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9609     } else {
9610         return (fp->cl_id);
9611     }
9612 }
9613 
9614 static inline uint32_t
9615 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9616                            struct bxe_fastpath *fp)
9617 {
9618     uint32_t offset = BAR_USTRORM_INTMEM;
9619 
9620     if (!CHIP_IS_E1x(sc)) {
9621         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9622     } else {
9623         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9624     }
9625 
9626     return (offset);
9627 }
9628 
9629 static void
9630 bxe_init_eth_fp(struct bxe_softc *sc,
9631                 int              idx)
9632 {
9633     struct bxe_fastpath *fp = &sc->fp[idx];
9634     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9635     unsigned long q_type = 0;
9636     int cos;
9637 
9638     fp->sc    = sc;
9639     fp->index = idx;
9640 
9641     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9642     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9643 
9644     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9645                     (SC_L_ID(sc) + idx) :
9646                     /* want client ID same as IGU SB ID for non-E1 */
9647                     fp->igu_sb_id;
9648     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9649 
9650     /* setup sb indices */
9651     if (!CHIP_IS_E1x(sc)) {
9652         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9653         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9654     } else {
9655         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9656         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9657     }
9658 
9659     /* init shortcut */
9660     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9661 
9662     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9663 
9664     /*
9665      * XXX If multiple CoS is ever supported then each fastpath structure
9666      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9667      */
9668     for (cos = 0; cos < sc->max_cos; cos++) {
9669         cids[cos] = idx;
9670     }
9671     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9672 
9673     /* nothing more for a VF to do */
9674     if (IS_VF(sc)) {
9675         return;
9676     }
9677 
9678     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9679                 fp->fw_sb_id, fp->igu_sb_id);
9680 
9681     bxe_update_fp_sb_idx(fp);
9682 
9683     /* Configure Queue State object */
9684     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9685     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9686 
9687     ecore_init_queue_obj(sc,
9688                          &sc->sp_objs[idx].q_obj,
9689                          fp->cl_id,
9690                          cids,
9691                          sc->max_cos,
9692                          SC_FUNC(sc),
9693                          BXE_SP(sc, q_rdata),
9694                          BXE_SP_MAPPING(sc, q_rdata),
9695                          q_type);
9696 
9697     /* configure classification DBs */
9698     ecore_init_mac_obj(sc,
9699                        &sc->sp_objs[idx].mac_obj,
9700                        fp->cl_id,
9701                        idx,
9702                        SC_FUNC(sc),
9703                        BXE_SP(sc, mac_rdata),
9704                        BXE_SP_MAPPING(sc, mac_rdata),
9705                        ECORE_FILTER_MAC_PENDING,
9706                        &sc->sp_state,
9707                        ECORE_OBJ_TYPE_RX_TX,
9708                        &sc->macs_pool);
9709 
9710     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9711           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9712 }
9713 
9714 static inline void
9715 bxe_update_rx_prod(struct bxe_softc    *sc,
9716                    struct bxe_fastpath *fp,
9717                    uint16_t            rx_bd_prod,
9718                    uint16_t            rx_cq_prod,
9719                    uint16_t            rx_sge_prod)
9720 {
9721     struct ustorm_eth_rx_producers rx_prods = { 0 };
9722     uint32_t i;
9723 
9724     /* update producers */
9725     rx_prods.bd_prod  = rx_bd_prod;
9726     rx_prods.cqe_prod = rx_cq_prod;
9727     rx_prods.sge_prod = rx_sge_prod;
9728 
9729     /*
9730      * Make sure that the BD and SGE data is updated before updating the
9731      * producers since FW might read the BD/SGE right after the producer
9732      * is updated.
9733      * This is only applicable for weak-ordered memory model archs such
9734      * as IA-64. The following barrier is also mandatory since FW will
9735      * assumes BDs must have buffers.
9736      */
9737     wmb();
9738 
9739     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9740         REG_WR(sc,
9741                (fp->ustorm_rx_prods_offset + (i * 4)),
9742                ((uint32_t *)&rx_prods)[i]);
9743     }
9744 
9745     wmb(); /* keep prod updates ordered */
9746 
9747     BLOGD(sc, DBG_RX,
9748           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9749           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9750 }
9751 
9752 static void
9753 bxe_init_rx_rings(struct bxe_softc *sc)
9754 {
9755     struct bxe_fastpath *fp;
9756     int i;
9757 
9758     for (i = 0; i < sc->num_queues; i++) {
9759         fp = &sc->fp[i];
9760 
9761         fp->rx_bd_cons = 0;
9762 
9763         /*
9764          * Activate the BD ring...
9765          * Warning, this will generate an interrupt (to the TSTORM)
9766          * so this can only be done after the chip is initialized
9767          */
9768         bxe_update_rx_prod(sc, fp,
9769                            fp->rx_bd_prod,
9770                            fp->rx_cq_prod,
9771                            fp->rx_sge_prod);
9772 
9773         if (i != 0) {
9774             continue;
9775         }
9776 
9777         if (CHIP_IS_E1(sc)) {
9778             REG_WR(sc,
9779                    (BAR_USTRORM_INTMEM +
9780                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9781                    U64_LO(fp->rcq_dma.paddr));
9782             REG_WR(sc,
9783                    (BAR_USTRORM_INTMEM +
9784                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9785                    U64_HI(fp->rcq_dma.paddr));
9786         }
9787     }
9788 }
9789 
9790 static void
9791 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9792 {
9793     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9794     fp->tx_db.data.zero_fill1 = 0;
9795     fp->tx_db.data.prod = 0;
9796 
9797     fp->tx_pkt_prod = 0;
9798     fp->tx_pkt_cons = 0;
9799     fp->tx_bd_prod = 0;
9800     fp->tx_bd_cons = 0;
9801     fp->eth_q_stats.tx_pkts = 0;
9802 }
9803 
9804 static inline void
9805 bxe_init_tx_rings(struct bxe_softc *sc)
9806 {
9807     int i;
9808 
9809     for (i = 0; i < sc->num_queues; i++) {
9810         bxe_init_tx_ring_one(&sc->fp[i]);
9811     }
9812 }
9813 
9814 static void
9815 bxe_init_def_sb(struct bxe_softc *sc)
9816 {
9817     struct host_sp_status_block *def_sb = sc->def_sb;
9818     bus_addr_t mapping = sc->def_sb_dma.paddr;
9819     int igu_sp_sb_index;
9820     int igu_seg_id;
9821     int port = SC_PORT(sc);
9822     int func = SC_FUNC(sc);
9823     int reg_offset, reg_offset_en5;
9824     uint64_t section;
9825     int index, sindex;
9826     struct hc_sp_status_block_data sp_sb_data;
9827 
9828     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9829 
9830     if (CHIP_INT_MODE_IS_BC(sc)) {
9831         igu_sp_sb_index = DEF_SB_IGU_ID;
9832         igu_seg_id = HC_SEG_ACCESS_DEF;
9833     } else {
9834         igu_sp_sb_index = sc->igu_dsb_id;
9835         igu_seg_id = IGU_SEG_ACCESS_DEF;
9836     }
9837 
9838     /* attentions */
9839     section = ((uint64_t)mapping +
9840                offsetof(struct host_sp_status_block, atten_status_block));
9841     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9842     sc->attn_state = 0;
9843 
9844     reg_offset = (port) ?
9845                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9846                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9847     reg_offset_en5 = (port) ?
9848                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9849                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9850 
9851     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9852         /* take care of sig[0]..sig[4] */
9853         for (sindex = 0; sindex < 4; sindex++) {
9854             sc->attn_group[index].sig[sindex] =
9855                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9856         }
9857 
9858         if (!CHIP_IS_E1x(sc)) {
9859             /*
9860              * enable5 is separate from the rest of the registers,
9861              * and the address skip is 4 and not 16 between the
9862              * different groups
9863              */
9864             sc->attn_group[index].sig[4] =
9865                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9866         } else {
9867             sc->attn_group[index].sig[4] = 0;
9868         }
9869     }
9870 
9871     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9872         reg_offset = (port) ?
9873                          HC_REG_ATTN_MSG1_ADDR_L :
9874                          HC_REG_ATTN_MSG0_ADDR_L;
9875         REG_WR(sc, reg_offset, U64_LO(section));
9876         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9877     } else if (!CHIP_IS_E1x(sc)) {
9878         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9879         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9880     }
9881 
9882     section = ((uint64_t)mapping +
9883                offsetof(struct host_sp_status_block, sp_sb));
9884 
9885     bxe_zero_sp_sb(sc);
9886 
9887     /* PCI guarantees endianity of regpair */
9888     sp_sb_data.state           = SB_ENABLED;
9889     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9890     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9891     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9892     sp_sb_data.igu_seg_id      = igu_seg_id;
9893     sp_sb_data.p_func.pf_id    = func;
9894     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9895     sp_sb_data.p_func.vf_id    = 0xff;
9896 
9897     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9898 
9899     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9900 }
9901 
9902 static void
9903 bxe_init_sp_ring(struct bxe_softc *sc)
9904 {
9905     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9906     sc->spq_prod_idx = 0;
9907     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9908     sc->spq_prod_bd = sc->spq;
9909     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9910 }
9911 
9912 static void
9913 bxe_init_eq_ring(struct bxe_softc *sc)
9914 {
9915     union event_ring_elem *elem;
9916     int i;
9917 
9918     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9919         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9920 
9921         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9922                                                  BCM_PAGE_SIZE *
9923                                                  (i % NUM_EQ_PAGES)));
9924         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9925                                                  BCM_PAGE_SIZE *
9926                                                  (i % NUM_EQ_PAGES)));
9927     }
9928 
9929     sc->eq_cons    = 0;
9930     sc->eq_prod    = NUM_EQ_DESC;
9931     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9932 
9933     atomic_store_rel_long(&sc->eq_spq_left,
9934                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9935                                NUM_EQ_DESC) - 1));
9936 }
9937 
9938 static void
9939 bxe_init_internal_common(struct bxe_softc *sc)
9940 {
9941     int i;
9942 
9943     /*
9944      * Zero this manually as its initialization is currently missing
9945      * in the initTool.
9946      */
9947     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9948         REG_WR(sc,
9949                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9950                0);
9951     }
9952 
9953     if (!CHIP_IS_E1x(sc)) {
9954         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9955                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9956     }
9957 }
9958 
9959 static void
9960 bxe_init_internal(struct bxe_softc *sc,
9961                   uint32_t         load_code)
9962 {
9963     switch (load_code) {
9964     case FW_MSG_CODE_DRV_LOAD_COMMON:
9965     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9966         bxe_init_internal_common(sc);
9967         /* no break */
9968 
9969     case FW_MSG_CODE_DRV_LOAD_PORT:
9970         /* nothing to do */
9971         /* no break */
9972 
9973     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9974         /* internal memory per function is initialized inside bxe_pf_init */
9975         break;
9976 
9977     default:
9978         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9979         break;
9980     }
9981 }
9982 
9983 static void
9984 storm_memset_func_cfg(struct bxe_softc                         *sc,
9985                       struct tstorm_eth_function_common_config *tcfg,
9986                       uint16_t                                  abs_fid)
9987 {
9988     uint32_t addr;
9989     size_t size;
9990 
9991     addr = (BAR_TSTRORM_INTMEM +
9992             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9993     size = sizeof(struct tstorm_eth_function_common_config);
9994     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9995 }
9996 
9997 static void
9998 bxe_func_init(struct bxe_softc            *sc,
9999               struct bxe_func_init_params *p)
10000 {
10001     struct tstorm_eth_function_common_config tcfg = { 0 };
10002 
10003     if (CHIP_IS_E1x(sc)) {
10004         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10005     }
10006 
10007     /* Enable the function in the FW */
10008     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10009     storm_memset_func_en(sc, p->func_id, 1);
10010 
10011     /* spq */
10012     if (p->func_flgs & FUNC_FLG_SPQ) {
10013         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10014         REG_WR(sc,
10015                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10016                p->spq_prod);
10017     }
10018 }
10019 
10020 /*
10021  * Calculates the sum of vn_min_rates.
10022  * It's needed for further normalizing of the min_rates.
10023  * Returns:
10024  *   sum of vn_min_rates.
10025  *     or
10026  *   0 - if all the min_rates are 0.
10027  * In the later case fainess algorithm should be deactivated.
10028  * If all min rates are not zero then those that are zeroes will be set to 1.
10029  */
10030 static void
10031 bxe_calc_vn_min(struct bxe_softc       *sc,
10032                 struct cmng_init_input *input)
10033 {
10034     uint32_t vn_cfg;
10035     uint32_t vn_min_rate;
10036     int all_zero = 1;
10037     int vn;
10038 
10039     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10040         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10041         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10042                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10043 
10044         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10045             /* skip hidden VNs */
10046             vn_min_rate = 0;
10047         } else if (!vn_min_rate) {
10048             /* If min rate is zero - set it to 100 */
10049             vn_min_rate = DEF_MIN_RATE;
10050         } else {
10051             all_zero = 0;
10052         }
10053 
10054         input->vnic_min_rate[vn] = vn_min_rate;
10055     }
10056 
10057     /* if ETS or all min rates are zeros - disable fairness */
10058     if (BXE_IS_ETS_ENABLED(sc)) {
10059         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10060         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10061     } else if (all_zero) {
10062         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10063         BLOGD(sc, DBG_LOAD,
10064               "Fariness disabled (all MIN values are zeroes)\n");
10065     } else {
10066         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10067     }
10068 }
10069 
10070 static inline uint16_t
10071 bxe_extract_max_cfg(struct bxe_softc *sc,
10072                     uint32_t         mf_cfg)
10073 {
10074     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10075                         FUNC_MF_CFG_MAX_BW_SHIFT);
10076 
10077     if (!max_cfg) {
10078         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10079         max_cfg = 100;
10080     }
10081 
10082     return (max_cfg);
10083 }
10084 
10085 static void
10086 bxe_calc_vn_max(struct bxe_softc       *sc,
10087                 int                    vn,
10088                 struct cmng_init_input *input)
10089 {
10090     uint16_t vn_max_rate;
10091     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10092     uint32_t max_cfg;
10093 
10094     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10095         vn_max_rate = 0;
10096     } else {
10097         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10098 
10099         if (IS_MF_SI(sc)) {
10100             /* max_cfg in percents of linkspeed */
10101             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10102         } else { /* SD modes */
10103             /* max_cfg is absolute in 100Mb units */
10104             vn_max_rate = (max_cfg * 100);
10105         }
10106     }
10107 
10108     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10109 
10110     input->vnic_max_rate[vn] = vn_max_rate;
10111 }
10112 
10113 static void
10114 bxe_cmng_fns_init(struct bxe_softc *sc,
10115                   uint8_t          read_cfg,
10116                   uint8_t          cmng_type)
10117 {
10118     struct cmng_init_input input;
10119     int vn;
10120 
10121     memset(&input, 0, sizeof(struct cmng_init_input));
10122 
10123     input.port_rate = sc->link_vars.line_speed;
10124 
10125     if (cmng_type == CMNG_FNS_MINMAX) {
10126         /* read mf conf from shmem */
10127         if (read_cfg) {
10128             bxe_read_mf_cfg(sc);
10129         }
10130 
10131         /* get VN min rate and enable fairness if not 0 */
10132         bxe_calc_vn_min(sc, &input);
10133 
10134         /* get VN max rate */
10135         if (sc->port.pmf) {
10136             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10137                 bxe_calc_vn_max(sc, vn, &input);
10138             }
10139         }
10140 
10141         /* always enable rate shaping and fairness */
10142         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10143 
10144         ecore_init_cmng(&input, &sc->cmng);
10145         return;
10146     }
10147 
10148     /* rate shaping and fairness are disabled */
10149     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10150 }
10151 
10152 static int
10153 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10154 {
10155     if (CHIP_REV_IS_SLOW(sc)) {
10156         return (CMNG_FNS_NONE);
10157     }
10158 
10159     if (IS_MF(sc)) {
10160         return (CMNG_FNS_MINMAX);
10161     }
10162 
10163     return (CMNG_FNS_NONE);
10164 }
10165 
10166 static void
10167 storm_memset_cmng(struct bxe_softc *sc,
10168                   struct cmng_init *cmng,
10169                   uint8_t          port)
10170 {
10171     int vn;
10172     int func;
10173     uint32_t addr;
10174     size_t size;
10175 
10176     addr = (BAR_XSTRORM_INTMEM +
10177             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10178     size = sizeof(struct cmng_struct_per_port);
10179     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10180 
10181     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10182         func = func_by_vn(sc, vn);
10183 
10184         addr = (BAR_XSTRORM_INTMEM +
10185                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10186         size = sizeof(struct rate_shaping_vars_per_vn);
10187         ecore_storm_memset_struct(sc, addr, size,
10188                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10189 
10190         addr = (BAR_XSTRORM_INTMEM +
10191                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10192         size = sizeof(struct fairness_vars_per_vn);
10193         ecore_storm_memset_struct(sc, addr, size,
10194                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10195     }
10196 }
10197 
10198 static void
10199 bxe_pf_init(struct bxe_softc *sc)
10200 {
10201     struct bxe_func_init_params func_init = { 0 };
10202     struct event_ring_data eq_data = { { 0 } };
10203     uint16_t flags;
10204 
10205     if (!CHIP_IS_E1x(sc)) {
10206         /* reset IGU PF statistics: MSIX + ATTN */
10207         /* PF */
10208         REG_WR(sc,
10209                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10210                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10211                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10212                0);
10213         /* ATTN */
10214         REG_WR(sc,
10215                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10216                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10217                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10218                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10219                0);
10220     }
10221 
10222     /* function setup flags */
10223     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10224 
10225     /*
10226      * This flag is relevant for E1x only.
10227      * E2 doesn't have a TPA configuration in a function level.
10228      */
10229     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10230 
10231     func_init.func_flgs = flags;
10232     func_init.pf_id     = SC_FUNC(sc);
10233     func_init.func_id   = SC_FUNC(sc);
10234     func_init.spq_map   = sc->spq_dma.paddr;
10235     func_init.spq_prod  = sc->spq_prod_idx;
10236 
10237     bxe_func_init(sc, &func_init);
10238 
10239     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10240 
10241     /*
10242      * Congestion management values depend on the link rate.
10243      * There is no active link so initial link rate is set to 10Gbps.
10244      * When the link comes up the congestion management values are
10245      * re-calculated according to the actual link rate.
10246      */
10247     sc->link_vars.line_speed = SPEED_10000;
10248     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10249 
10250     /* Only the PMF sets the HW */
10251     if (sc->port.pmf) {
10252         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10253     }
10254 
10255     /* init Event Queue - PCI bus guarantees correct endainity */
10256     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10257     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10258     eq_data.producer     = sc->eq_prod;
10259     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10260     eq_data.sb_id        = DEF_SB_ID;
10261     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10262 }
10263 
10264 static void
10265 bxe_hc_int_enable(struct bxe_softc *sc)
10266 {
10267     int port = SC_PORT(sc);
10268     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10269     uint32_t val = REG_RD(sc, addr);
10270     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10271     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10272                            (sc->intr_count == 1)) ? TRUE : FALSE;
10273     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10274 
10275     if (msix) {
10276         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10277                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10278         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10279                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10280         if (single_msix) {
10281             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10282         }
10283     } else if (msi) {
10284         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10285         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10286                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10287                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10288     } else {
10289         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10290                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10291                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10292                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10293 
10294         if (!CHIP_IS_E1(sc)) {
10295             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10296                   val, port, addr);
10297 
10298             REG_WR(sc, addr, val);
10299 
10300             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10301         }
10302     }
10303 
10304     if (CHIP_IS_E1(sc)) {
10305         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10306     }
10307 
10308     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10309           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10310 
10311     REG_WR(sc, addr, val);
10312 
10313     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10314     mb();
10315 
10316     if (!CHIP_IS_E1(sc)) {
10317         /* init leading/trailing edge */
10318         if (IS_MF(sc)) {
10319             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10320             if (sc->port.pmf) {
10321                 /* enable nig and gpio3 attention */
10322                 val |= 0x1100;
10323             }
10324         } else {
10325             val = 0xffff;
10326         }
10327 
10328         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10329         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10330     }
10331 
10332     /* make sure that interrupts are indeed enabled from here on */
10333     mb();
10334 }
10335 
10336 static void
10337 bxe_igu_int_enable(struct bxe_softc *sc)
10338 {
10339     uint32_t val;
10340     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10341     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10342                            (sc->intr_count == 1)) ? TRUE : FALSE;
10343     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10344 
10345     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10346 
10347     if (msix) {
10348         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10349                  IGU_PF_CONF_SINGLE_ISR_EN);
10350         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10351                 IGU_PF_CONF_ATTN_BIT_EN);
10352         if (single_msix) {
10353             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10354         }
10355     } else if (msi) {
10356         val &= ~IGU_PF_CONF_INT_LINE_EN;
10357         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10358                 IGU_PF_CONF_ATTN_BIT_EN |
10359                 IGU_PF_CONF_SINGLE_ISR_EN);
10360     } else {
10361         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10362         val |= (IGU_PF_CONF_INT_LINE_EN |
10363                 IGU_PF_CONF_ATTN_BIT_EN |
10364                 IGU_PF_CONF_SINGLE_ISR_EN);
10365     }
10366 
10367     /* clean previous status - need to configure igu prior to ack*/
10368     if ((!msix) || single_msix) {
10369         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10370         bxe_ack_int(sc);
10371     }
10372 
10373     val |= IGU_PF_CONF_FUNC_EN;
10374 
10375     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10376           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10377 
10378     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10379 
10380     mb();
10381 
10382     /* init leading/trailing edge */
10383     if (IS_MF(sc)) {
10384         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10385         if (sc->port.pmf) {
10386             /* enable nig and gpio3 attention */
10387             val |= 0x1100;
10388         }
10389     } else {
10390         val = 0xffff;
10391     }
10392 
10393     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10394     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10395 
10396     /* make sure that interrupts are indeed enabled from here on */
10397     mb();
10398 }
10399 
10400 static void
10401 bxe_int_enable(struct bxe_softc *sc)
10402 {
10403     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10404         bxe_hc_int_enable(sc);
10405     } else {
10406         bxe_igu_int_enable(sc);
10407     }
10408 }
10409 
10410 static void
10411 bxe_hc_int_disable(struct bxe_softc *sc)
10412 {
10413     int port = SC_PORT(sc);
10414     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10415     uint32_t val = REG_RD(sc, addr);
10416 
10417     /*
10418      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10419      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10420      * block
10421      */
10422     if (CHIP_IS_E1(sc)) {
10423         /*
10424          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10425          * to prevent from HC sending interrupts after we exit the function
10426          */
10427         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10428 
10429         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10430                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10431                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10432     } else {
10433         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10434                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10435                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10436                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10437     }
10438 
10439     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10440 
10441     /* flush all outstanding writes */
10442     mb();
10443 
10444     REG_WR(sc, addr, val);
10445     if (REG_RD(sc, addr) != val) {
10446         BLOGE(sc, "proper val not read from HC IGU!\n");
10447     }
10448 }
10449 
10450 static void
10451 bxe_igu_int_disable(struct bxe_softc *sc)
10452 {
10453     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10454 
10455     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10456              IGU_PF_CONF_INT_LINE_EN |
10457              IGU_PF_CONF_ATTN_BIT_EN);
10458 
10459     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10460 
10461     /* flush all outstanding writes */
10462     mb();
10463 
10464     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10465     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10466         BLOGE(sc, "proper val not read from IGU!\n");
10467     }
10468 }
10469 
10470 static void
10471 bxe_int_disable(struct bxe_softc *sc)
10472 {
10473     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10474         bxe_hc_int_disable(sc);
10475     } else {
10476         bxe_igu_int_disable(sc);
10477     }
10478 }
10479 
10480 static void
10481 bxe_nic_init(struct bxe_softc *sc,
10482              int              load_code)
10483 {
10484     int i;
10485 
10486     for (i = 0; i < sc->num_queues; i++) {
10487         bxe_init_eth_fp(sc, i);
10488     }
10489 
10490     rmb(); /* ensure status block indices were read */
10491 
10492     bxe_init_rx_rings(sc);
10493     bxe_init_tx_rings(sc);
10494 
10495     if (IS_VF(sc)) {
10496         return;
10497     }
10498 
10499     /* initialize MOD_ABS interrupts */
10500     elink_init_mod_abs_int(sc, &sc->link_vars,
10501                            sc->devinfo.chip_id,
10502                            sc->devinfo.shmem_base,
10503                            sc->devinfo.shmem2_base,
10504                            SC_PORT(sc));
10505 
10506     bxe_init_def_sb(sc);
10507     bxe_update_dsb_idx(sc);
10508     bxe_init_sp_ring(sc);
10509     bxe_init_eq_ring(sc);
10510     bxe_init_internal(sc, load_code);
10511     bxe_pf_init(sc);
10512     bxe_stats_init(sc);
10513 
10514     /* flush all before enabling interrupts */
10515     mb();
10516 
10517     bxe_int_enable(sc);
10518 
10519     /* check for SPIO5 */
10520     bxe_attn_int_deasserted0(sc,
10521                              REG_RD(sc,
10522                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10523                                      SC_PORT(sc)*4)) &
10524                              AEU_INPUTS_ATTN_BITS_SPIO5);
10525 }
10526 
10527 static inline void
10528 bxe_init_objs(struct bxe_softc *sc)
10529 {
10530     /* mcast rules must be added to tx if tx switching is enabled */
10531     ecore_obj_type o_type =
10532         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10533                                          ECORE_OBJ_TYPE_RX;
10534 
10535     /* RX_MODE controlling object */
10536     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10537 
10538     /* multicast configuration controlling object */
10539     ecore_init_mcast_obj(sc,
10540                          &sc->mcast_obj,
10541                          sc->fp[0].cl_id,
10542                          sc->fp[0].index,
10543                          SC_FUNC(sc),
10544                          SC_FUNC(sc),
10545                          BXE_SP(sc, mcast_rdata),
10546                          BXE_SP_MAPPING(sc, mcast_rdata),
10547                          ECORE_FILTER_MCAST_PENDING,
10548                          &sc->sp_state,
10549                          o_type);
10550 
10551     /* Setup CAM credit pools */
10552     ecore_init_mac_credit_pool(sc,
10553                                &sc->macs_pool,
10554                                SC_FUNC(sc),
10555                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10556                                                  VNICS_PER_PATH(sc));
10557 
10558     ecore_init_vlan_credit_pool(sc,
10559                                 &sc->vlans_pool,
10560                                 SC_ABS_FUNC(sc) >> 1,
10561                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10562                                                   VNICS_PER_PATH(sc));
10563 
10564     /* RSS configuration object */
10565     ecore_init_rss_config_obj(sc,
10566                               &sc->rss_conf_obj,
10567                               sc->fp[0].cl_id,
10568                               sc->fp[0].index,
10569                               SC_FUNC(sc),
10570                               SC_FUNC(sc),
10571                               BXE_SP(sc, rss_rdata),
10572                               BXE_SP_MAPPING(sc, rss_rdata),
10573                               ECORE_FILTER_RSS_CONF_PENDING,
10574                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10575 }
10576 
10577 /*
10578  * Initialize the function. This must be called before sending CLIENT_SETUP
10579  * for the first client.
10580  */
10581 static inline int
10582 bxe_func_start(struct bxe_softc *sc)
10583 {
10584     struct ecore_func_state_params func_params = { NULL };
10585     struct ecore_func_start_params *start_params = &func_params.params.start;
10586 
10587     /* Prepare parameters for function state transitions */
10588     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10589 
10590     func_params.f_obj = &sc->func_obj;
10591     func_params.cmd = ECORE_F_CMD_START;
10592 
10593     /* Function parameters */
10594     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10595     start_params->sd_vlan_tag = OVLAN(sc);
10596 
10597     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10598         start_params->network_cos_mode = STATIC_COS;
10599     } else { /* CHIP_IS_E1X */
10600         start_params->network_cos_mode = FW_WRR;
10601     }
10602 
10603     //start_params->gre_tunnel_mode = 0;
10604     //start_params->gre_tunnel_rss  = 0;
10605 
10606     return (ecore_func_state_change(sc, &func_params));
10607 }
10608 
10609 static int
10610 bxe_set_power_state(struct bxe_softc *sc,
10611                     uint8_t          state)
10612 {
10613     uint16_t pmcsr;
10614 
10615     /* If there is no power capability, silently succeed */
10616     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10617         BLOGW(sc, "No power capability\n");
10618         return (0);
10619     }
10620 
10621     pmcsr = pci_read_config(sc->dev,
10622                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10623                             2);
10624 
10625     switch (state) {
10626     case PCI_PM_D0:
10627         pci_write_config(sc->dev,
10628                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10629                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10630 
10631         if (pmcsr & PCIM_PSTAT_DMASK) {
10632             /* delay required during transition out of D3hot */
10633             DELAY(20000);
10634         }
10635 
10636         break;
10637 
10638     case PCI_PM_D3hot:
10639         /* XXX if there are other clients above don't shut down the power */
10640 
10641         /* don't shut down the power for emulation and FPGA */
10642         if (CHIP_REV_IS_SLOW(sc)) {
10643             return (0);
10644         }
10645 
10646         pmcsr &= ~PCIM_PSTAT_DMASK;
10647         pmcsr |= PCIM_PSTAT_D3;
10648 
10649         if (sc->wol) {
10650             pmcsr |= PCIM_PSTAT_PMEENABLE;
10651         }
10652 
10653         pci_write_config(sc->dev,
10654                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10655                          pmcsr, 4);
10656 
10657         /*
10658          * No more memory access after this point until device is brought back
10659          * to D0 state.
10660          */
10661         break;
10662 
10663     default:
10664         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10665             state, pmcsr);
10666         return (-1);
10667     }
10668 
10669     return (0);
10670 }
10671 
10672 
10673 /* return true if succeeded to acquire the lock */
10674 static uint8_t
10675 bxe_trylock_hw_lock(struct bxe_softc *sc,
10676                     uint32_t         resource)
10677 {
10678     uint32_t lock_status;
10679     uint32_t resource_bit = (1 << resource);
10680     int func = SC_FUNC(sc);
10681     uint32_t hw_lock_control_reg;
10682 
10683     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10684 
10685     /* Validating that the resource is within range */
10686     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10687         BLOGD(sc, DBG_LOAD,
10688               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10689               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10690         return (FALSE);
10691     }
10692 
10693     if (func <= 5) {
10694         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10695     } else {
10696         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10697     }
10698 
10699     /* try to acquire the lock */
10700     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10701     lock_status = REG_RD(sc, hw_lock_control_reg);
10702     if (lock_status & resource_bit) {
10703         return (TRUE);
10704     }
10705 
10706     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10707         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10708         lock_status, resource_bit);
10709 
10710     return (FALSE);
10711 }
10712 
10713 /*
10714  * Get the recovery leader resource id according to the engine this function
10715  * belongs to. Currently only only 2 engines is supported.
10716  */
10717 static int
10718 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10719 {
10720     if (SC_PATH(sc)) {
10721         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10722     } else {
10723         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10724     }
10725 }
10726 
10727 /* try to acquire a leader lock for current engine */
10728 static uint8_t
10729 bxe_trylock_leader_lock(struct bxe_softc *sc)
10730 {
10731     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10732 }
10733 
10734 static int
10735 bxe_release_leader_lock(struct bxe_softc *sc)
10736 {
10737     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10738 }
10739 
10740 /* close gates #2, #3 and #4 */
10741 static void
10742 bxe_set_234_gates(struct bxe_softc *sc,
10743                   uint8_t          close)
10744 {
10745     uint32_t val;
10746 
10747     /* gates #2 and #4a are closed/opened for "not E1" only */
10748     if (!CHIP_IS_E1(sc)) {
10749         /* #4 */
10750         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10751         /* #2 */
10752         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10753     }
10754 
10755     /* #3 */
10756     if (CHIP_IS_E1x(sc)) {
10757         /* prevent interrupts from HC on both ports */
10758         val = REG_RD(sc, HC_REG_CONFIG_1);
10759         REG_WR(sc, HC_REG_CONFIG_1,
10760                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10761                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10762 
10763         val = REG_RD(sc, HC_REG_CONFIG_0);
10764         REG_WR(sc, HC_REG_CONFIG_0,
10765                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10766                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10767     } else {
10768         /* Prevent incomming interrupts in IGU */
10769         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10770 
10771         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10772                (!close) ?
10773                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10774                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10775     }
10776 
10777     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10778           close ? "closing" : "opening");
10779 
10780     wmb();
10781 }
10782 
10783 /* poll for pending writes bit, it should get cleared in no more than 1s */
10784 static int
10785 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10786 {
10787     uint32_t cnt = 1000;
10788     uint32_t pend_bits = 0;
10789 
10790     do {
10791         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10792 
10793         if (pend_bits == 0) {
10794             break;
10795         }
10796 
10797         DELAY(1000);
10798     } while (--cnt > 0);
10799 
10800     if (cnt == 0) {
10801         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10802         return (-1);
10803     }
10804 
10805     return (0);
10806 }
10807 
10808 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10809 
10810 static void
10811 bxe_clp_reset_prep(struct bxe_softc *sc,
10812                    uint32_t         *magic_val)
10813 {
10814     /* Do some magic... */
10815     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10816     *magic_val = val & SHARED_MF_CLP_MAGIC;
10817     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10818 }
10819 
10820 /* restore the value of the 'magic' bit */
10821 static void
10822 bxe_clp_reset_done(struct bxe_softc *sc,
10823                    uint32_t         magic_val)
10824 {
10825     /* Restore the 'magic' bit value... */
10826     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10827     MFCFG_WR(sc, shared_mf_config.clp_mb,
10828               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10829 }
10830 
10831 /* prepare for MCP reset, takes care of CLP configurations */
10832 static void
10833 bxe_reset_mcp_prep(struct bxe_softc *sc,
10834                    uint32_t         *magic_val)
10835 {
10836     uint32_t shmem;
10837     uint32_t validity_offset;
10838 
10839     /* set `magic' bit in order to save MF config */
10840     if (!CHIP_IS_E1(sc)) {
10841         bxe_clp_reset_prep(sc, magic_val);
10842     }
10843 
10844     /* get shmem offset */
10845     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10846     validity_offset =
10847         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10848 
10849     /* Clear validity map flags */
10850     if (shmem > 0) {
10851         REG_WR(sc, shmem + validity_offset, 0);
10852     }
10853 }
10854 
10855 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10856 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10857 
10858 static void
10859 bxe_mcp_wait_one(struct bxe_softc *sc)
10860 {
10861     /* special handling for emulation and FPGA (10 times longer) */
10862     if (CHIP_REV_IS_SLOW(sc)) {
10863         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10864     } else {
10865         DELAY((MCP_ONE_TIMEOUT) * 1000);
10866     }
10867 }
10868 
10869 /* initialize shmem_base and waits for validity signature to appear */
10870 static int
10871 bxe_init_shmem(struct bxe_softc *sc)
10872 {
10873     int cnt = 0;
10874     uint32_t val = 0;
10875 
10876     do {
10877         sc->devinfo.shmem_base     =
10878         sc->link_params.shmem_base =
10879             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10880 
10881         if (sc->devinfo.shmem_base) {
10882             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10883             if (val & SHR_MEM_VALIDITY_MB)
10884                 return (0);
10885         }
10886 
10887         bxe_mcp_wait_one(sc);
10888 
10889     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10890 
10891     BLOGE(sc, "BAD MCP validity signature\n");
10892 
10893     return (-1);
10894 }
10895 
10896 static int
10897 bxe_reset_mcp_comp(struct bxe_softc *sc,
10898                    uint32_t         magic_val)
10899 {
10900     int rc = bxe_init_shmem(sc);
10901 
10902     /* Restore the `magic' bit value */
10903     if (!CHIP_IS_E1(sc)) {
10904         bxe_clp_reset_done(sc, magic_val);
10905     }
10906 
10907     return (rc);
10908 }
10909 
10910 static void
10911 bxe_pxp_prep(struct bxe_softc *sc)
10912 {
10913     if (!CHIP_IS_E1(sc)) {
10914         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10915         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10916         wmb();
10917     }
10918 }
10919 
10920 /*
10921  * Reset the whole chip except for:
10922  *      - PCIE core
10923  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10924  *      - IGU
10925  *      - MISC (including AEU)
10926  *      - GRC
10927  *      - RBCN, RBCP
10928  */
10929 static void
10930 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10931                             uint8_t          global)
10932 {
10933     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10934     uint32_t global_bits2, stay_reset2;
10935 
10936     /*
10937      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10938      * (per chip) blocks.
10939      */
10940     global_bits2 =
10941         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10942         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10943 
10944     /*
10945      * Don't reset the following blocks.
10946      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10947      *            reset, as in 4 port device they might still be owned
10948      *            by the MCP (there is only one leader per path).
10949      */
10950     not_reset_mask1 =
10951         MISC_REGISTERS_RESET_REG_1_RST_HC |
10952         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10953         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10954 
10955     not_reset_mask2 =
10956         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10957         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10958         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10959         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10960         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10961         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10962         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10963         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10964         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10965         MISC_REGISTERS_RESET_REG_2_PGLC |
10966         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10967         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10968         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10969         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10970         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10971         MISC_REGISTERS_RESET_REG_2_UMAC1;
10972 
10973     /*
10974      * Keep the following blocks in reset:
10975      *  - all xxMACs are handled by the elink code.
10976      */
10977     stay_reset2 =
10978         MISC_REGISTERS_RESET_REG_2_XMAC |
10979         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10980 
10981     /* Full reset masks according to the chip */
10982     reset_mask1 = 0xffffffff;
10983 
10984     if (CHIP_IS_E1(sc))
10985         reset_mask2 = 0xffff;
10986     else if (CHIP_IS_E1H(sc))
10987         reset_mask2 = 0x1ffff;
10988     else if (CHIP_IS_E2(sc))
10989         reset_mask2 = 0xfffff;
10990     else /* CHIP_IS_E3 */
10991         reset_mask2 = 0x3ffffff;
10992 
10993     /* Don't reset global blocks unless we need to */
10994     if (!global)
10995         reset_mask2 &= ~global_bits2;
10996 
10997     /*
10998      * In case of attention in the QM, we need to reset PXP
10999      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11000      * because otherwise QM reset would release 'close the gates' shortly
11001      * before resetting the PXP, then the PSWRQ would send a write
11002      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11003      * read the payload data from PSWWR, but PSWWR would not
11004      * respond. The write queue in PGLUE would stuck, dmae commands
11005      * would not return. Therefore it's important to reset the second
11006      * reset register (containing the
11007      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11008      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11009      * bit).
11010      */
11011     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11012            reset_mask2 & (~not_reset_mask2));
11013 
11014     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11015            reset_mask1 & (~not_reset_mask1));
11016 
11017     mb();
11018     wmb();
11019 
11020     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11021            reset_mask2 & (~stay_reset2));
11022 
11023     mb();
11024     wmb();
11025 
11026     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11027     wmb();
11028 }
11029 
11030 static int
11031 bxe_process_kill(struct bxe_softc *sc,
11032                  uint8_t          global)
11033 {
11034     int cnt = 1000;
11035     uint32_t val = 0;
11036     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11037     uint32_t tags_63_32 = 0;
11038 
11039     /* Empty the Tetris buffer, wait for 1s */
11040     do {
11041         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11042         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11043         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11044         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11045         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11046         if (CHIP_IS_E3(sc)) {
11047             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11048         }
11049 
11050         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11051             ((port_is_idle_0 & 0x1) == 0x1) &&
11052             ((port_is_idle_1 & 0x1) == 0x1) &&
11053             (pgl_exp_rom2 == 0xffffffff) &&
11054             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11055             break;
11056         DELAY(1000);
11057     } while (cnt-- > 0);
11058 
11059     if (cnt <= 0) {
11060         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11061                   "are still outstanding read requests after 1s! "
11062                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11063                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11064               sr_cnt, blk_cnt, port_is_idle_0,
11065               port_is_idle_1, pgl_exp_rom2);
11066         return (-1);
11067     }
11068 
11069     mb();
11070 
11071     /* Close gates #2, #3 and #4 */
11072     bxe_set_234_gates(sc, TRUE);
11073 
11074     /* Poll for IGU VQs for 57712 and newer chips */
11075     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11076         return (-1);
11077     }
11078 
11079     /* XXX indicate that "process kill" is in progress to MCP */
11080 
11081     /* clear "unprepared" bit */
11082     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11083     mb();
11084 
11085     /* Make sure all is written to the chip before the reset */
11086     wmb();
11087 
11088     /*
11089      * Wait for 1ms to empty GLUE and PCI-E core queues,
11090      * PSWHST, GRC and PSWRD Tetris buffer.
11091      */
11092     DELAY(1000);
11093 
11094     /* Prepare to chip reset: */
11095     /* MCP */
11096     if (global) {
11097         bxe_reset_mcp_prep(sc, &val);
11098     }
11099 
11100     /* PXP */
11101     bxe_pxp_prep(sc);
11102     mb();
11103 
11104     /* reset the chip */
11105     bxe_process_kill_chip_reset(sc, global);
11106     mb();
11107 
11108     /* clear errors in PGB */
11109     if (!CHIP_IS_E1(sc))
11110         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11111 
11112     /* Recover after reset: */
11113     /* MCP */
11114     if (global && bxe_reset_mcp_comp(sc, val)) {
11115         return (-1);
11116     }
11117 
11118     /* XXX add resetting the NO_MCP mode DB here */
11119 
11120     /* Open the gates #2, #3 and #4 */
11121     bxe_set_234_gates(sc, FALSE);
11122 
11123     /* XXX
11124      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11125      * re-enable attentions
11126      */
11127 
11128     return (0);
11129 }
11130 
11131 static int
11132 bxe_leader_reset(struct bxe_softc *sc)
11133 {
11134     int rc = 0;
11135     uint8_t global = bxe_reset_is_global(sc);
11136     uint32_t load_code;
11137 
11138     /*
11139      * If not going to reset MCP, load "fake" driver to reset HW while
11140      * driver is owner of the HW.
11141      */
11142     if (!global && !BXE_NOMCP(sc)) {
11143         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11144                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11145         if (!load_code) {
11146             BLOGE(sc, "MCP response failure, aborting\n");
11147             rc = -1;
11148             goto exit_leader_reset;
11149         }
11150 
11151         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11152             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11153             BLOGE(sc, "MCP unexpected response, aborting\n");
11154             rc = -1;
11155             goto exit_leader_reset2;
11156         }
11157 
11158         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11159         if (!load_code) {
11160             BLOGE(sc, "MCP response failure, aborting\n");
11161             rc = -1;
11162             goto exit_leader_reset2;
11163         }
11164     }
11165 
11166     /* try to recover after the failure */
11167     if (bxe_process_kill(sc, global)) {
11168         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11169         rc = -1;
11170         goto exit_leader_reset2;
11171     }
11172 
11173     /*
11174      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11175      * state.
11176      */
11177     bxe_set_reset_done(sc);
11178     if (global) {
11179         bxe_clear_reset_global(sc);
11180     }
11181 
11182 exit_leader_reset2:
11183 
11184     /* unload "fake driver" if it was loaded */
11185     if (!global && !BXE_NOMCP(sc)) {
11186         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11187         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11188     }
11189 
11190 exit_leader_reset:
11191 
11192     sc->is_leader = 0;
11193     bxe_release_leader_lock(sc);
11194 
11195     mb();
11196     return (rc);
11197 }
11198 
11199 /*
11200  * prepare INIT transition, parameters configured:
11201  *   - HC configuration
11202  *   - Queue's CDU context
11203  */
11204 static void
11205 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11206                    struct bxe_fastpath            *fp,
11207                    struct ecore_queue_init_params *init_params)
11208 {
11209     uint8_t cos;
11210     int cxt_index, cxt_offset;
11211 
11212     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11213     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11214 
11215     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11216     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11217 
11218     /* HC rate */
11219     init_params->rx.hc_rate =
11220         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11221     init_params->tx.hc_rate =
11222         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11223 
11224     /* FW SB ID */
11225     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11226 
11227     /* CQ index among the SB indices */
11228     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11229     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11230 
11231     /* set maximum number of COSs supported by this queue */
11232     init_params->max_cos = sc->max_cos;
11233 
11234     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11235           fp->index, init_params->max_cos);
11236 
11237     /* set the context pointers queue object */
11238     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11239         /* XXX change index/cid here if ever support multiple tx CoS */
11240         /* fp->txdata[cos]->cid */
11241         cxt_index = fp->index / ILT_PAGE_CIDS;
11242         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11243         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11244     }
11245 }
11246 
11247 /* set flags that are common for the Tx-only and not normal connections */
11248 static unsigned long
11249 bxe_get_common_flags(struct bxe_softc    *sc,
11250                      struct bxe_fastpath *fp,
11251                      uint8_t             zero_stats)
11252 {
11253     unsigned long flags = 0;
11254 
11255     /* PF driver will always initialize the Queue to an ACTIVE state */
11256     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11257 
11258     /*
11259      * tx only connections collect statistics (on the same index as the
11260      * parent connection). The statistics are zeroed when the parent
11261      * connection is initialized.
11262      */
11263 
11264     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11265     if (zero_stats) {
11266         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11267     }
11268 
11269     /*
11270      * tx only connections can support tx-switching, though their
11271      * CoS-ness doesn't survive the loopback
11272      */
11273     if (sc->flags & BXE_TX_SWITCHING) {
11274         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11275     }
11276 
11277     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11278 
11279     return (flags);
11280 }
11281 
11282 static unsigned long
11283 bxe_get_q_flags(struct bxe_softc    *sc,
11284                 struct bxe_fastpath *fp,
11285                 uint8_t             leading)
11286 {
11287     unsigned long flags = 0;
11288 
11289     if (IS_MF_SD(sc)) {
11290         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11291     }
11292 
11293     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11294         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11295         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11296     }
11297 
11298     if (leading) {
11299         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11300         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11301     }
11302 
11303     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11304 
11305     /* merge with common flags */
11306     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11307 }
11308 
11309 static void
11310 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11311                       struct bxe_fastpath               *fp,
11312                       struct ecore_general_setup_params *gen_init,
11313                       uint8_t                           cos)
11314 {
11315     gen_init->stat_id = bxe_stats_id(fp);
11316     gen_init->spcl_id = fp->cl_id;
11317     gen_init->mtu = sc->mtu;
11318     gen_init->cos = cos;
11319 }
11320 
11321 static void
11322 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11323                  struct bxe_fastpath           *fp,
11324                  struct rxq_pause_params       *pause,
11325                  struct ecore_rxq_setup_params *rxq_init)
11326 {
11327     uint8_t max_sge = 0;
11328     uint16_t sge_sz = 0;
11329     uint16_t tpa_agg_size = 0;
11330 
11331     pause->sge_th_lo = SGE_TH_LO(sc);
11332     pause->sge_th_hi = SGE_TH_HI(sc);
11333 
11334     /* validate SGE ring has enough to cross high threshold */
11335     if (sc->dropless_fc &&
11336             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11337             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11338         BLOGW(sc, "sge ring threshold limit\n");
11339     }
11340 
11341     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11342     tpa_agg_size = (2 * sc->mtu);
11343     if (tpa_agg_size < sc->max_aggregation_size) {
11344         tpa_agg_size = sc->max_aggregation_size;
11345     }
11346 
11347     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11348     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11349                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11350     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11351 
11352     /* pause - not for e1 */
11353     if (!CHIP_IS_E1(sc)) {
11354         pause->bd_th_lo = BD_TH_LO(sc);
11355         pause->bd_th_hi = BD_TH_HI(sc);
11356 
11357         pause->rcq_th_lo = RCQ_TH_LO(sc);
11358         pause->rcq_th_hi = RCQ_TH_HI(sc);
11359 
11360         /* validate rings have enough entries to cross high thresholds */
11361         if (sc->dropless_fc &&
11362             pause->bd_th_hi + FW_PREFETCH_CNT >
11363             sc->rx_ring_size) {
11364             BLOGW(sc, "rx bd ring threshold limit\n");
11365         }
11366 
11367         if (sc->dropless_fc &&
11368             pause->rcq_th_hi + FW_PREFETCH_CNT >
11369             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11370             BLOGW(sc, "rcq ring threshold limit\n");
11371         }
11372 
11373         pause->pri_map = 1;
11374     }
11375 
11376     /* rxq setup */
11377     rxq_init->dscr_map   = fp->rx_dma.paddr;
11378     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11379     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11380     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11381 
11382     /*
11383      * This should be a maximum number of data bytes that may be
11384      * placed on the BD (not including paddings).
11385      */
11386     rxq_init->buf_sz = (fp->rx_buf_size -
11387                         IP_HEADER_ALIGNMENT_PADDING);
11388 
11389     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11390     rxq_init->tpa_agg_sz      = tpa_agg_size;
11391     rxq_init->sge_buf_sz      = sge_sz;
11392     rxq_init->max_sges_pkt    = max_sge;
11393     rxq_init->rss_engine_id   = SC_FUNC(sc);
11394     rxq_init->mcast_engine_id = SC_FUNC(sc);
11395 
11396     /*
11397      * Maximum number or simultaneous TPA aggregation for this Queue.
11398      * For PF Clients it should be the maximum available number.
11399      * VF driver(s) may want to define it to a smaller value.
11400      */
11401     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11402 
11403     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11404     rxq_init->fw_sb_id = fp->fw_sb_id;
11405 
11406     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11407 
11408     /*
11409      * configure silent vlan removal
11410      * if multi function mode is afex, then mask default vlan
11411      */
11412     if (IS_MF_AFEX(sc)) {
11413         rxq_init->silent_removal_value =
11414             sc->devinfo.mf_info.afex_def_vlan_tag;
11415         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11416     }
11417 }
11418 
11419 static void
11420 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11421                  struct bxe_fastpath           *fp,
11422                  struct ecore_txq_setup_params *txq_init,
11423                  uint8_t                       cos)
11424 {
11425     /*
11426      * XXX If multiple CoS is ever supported then each fastpath structure
11427      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11428      * fp->txdata[cos]->tx_dma.paddr;
11429      */
11430     txq_init->dscr_map     = fp->tx_dma.paddr;
11431     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11432     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11433     txq_init->fw_sb_id     = fp->fw_sb_id;
11434 
11435     /*
11436      * set the TSS leading client id for TX classfication to the
11437      * leading RSS client id
11438      */
11439     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11440 }
11441 
11442 /*
11443  * This function performs 2 steps in a queue state machine:
11444  *   1) RESET->INIT
11445  *   2) INIT->SETUP
11446  */
11447 static int
11448 bxe_setup_queue(struct bxe_softc    *sc,
11449                 struct bxe_fastpath *fp,
11450                 uint8_t             leading)
11451 {
11452     struct ecore_queue_state_params q_params = { NULL };
11453     struct ecore_queue_setup_params *setup_params =
11454                         &q_params.params.setup;
11455     int rc;
11456 
11457     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11458 
11459     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11460 
11461     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11462 
11463     /* we want to wait for completion in this context */
11464     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11465 
11466     /* prepare the INIT parameters */
11467     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11468 
11469     /* Set the command */
11470     q_params.cmd = ECORE_Q_CMD_INIT;
11471 
11472     /* Change the state to INIT */
11473     rc = ecore_queue_state_change(sc, &q_params);
11474     if (rc) {
11475         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11476         return (rc);
11477     }
11478 
11479     BLOGD(sc, DBG_LOAD, "init complete\n");
11480 
11481     /* now move the Queue to the SETUP state */
11482     memset(setup_params, 0, sizeof(*setup_params));
11483 
11484     /* set Queue flags */
11485     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11486 
11487     /* set general SETUP parameters */
11488     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11489                           FIRST_TX_COS_INDEX);
11490 
11491     bxe_pf_rx_q_prep(sc, fp,
11492                      &setup_params->pause_params,
11493                      &setup_params->rxq_params);
11494 
11495     bxe_pf_tx_q_prep(sc, fp,
11496                      &setup_params->txq_params,
11497                      FIRST_TX_COS_INDEX);
11498 
11499     /* Set the command */
11500     q_params.cmd = ECORE_Q_CMD_SETUP;
11501 
11502     /* change the state to SETUP */
11503     rc = ecore_queue_state_change(sc, &q_params);
11504     if (rc) {
11505         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11506         return (rc);
11507     }
11508 
11509     return (rc);
11510 }
11511 
11512 static int
11513 bxe_setup_leading(struct bxe_softc *sc)
11514 {
11515     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11516 }
11517 
11518 static int
11519 bxe_config_rss_pf(struct bxe_softc            *sc,
11520                   struct ecore_rss_config_obj *rss_obj,
11521                   uint8_t                     config_hash)
11522 {
11523     struct ecore_config_rss_params params = { NULL };
11524     int i;
11525 
11526     /*
11527      * Although RSS is meaningless when there is a single HW queue we
11528      * still need it enabled in order to have HW Rx hash generated.
11529      */
11530 
11531     params.rss_obj = rss_obj;
11532 
11533     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11534 
11535     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11536 
11537     /* RSS configuration */
11538     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11539     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11540     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11541     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11542     if (rss_obj->udp_rss_v4) {
11543         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11544     }
11545     if (rss_obj->udp_rss_v6) {
11546         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11547     }
11548 
11549     /* Hash bits */
11550     params.rss_result_mask = MULTI_MASK;
11551 
11552     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11553 
11554     if (config_hash) {
11555         /* RSS keys */
11556         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11557             params.rss_key[i] = arc4random();
11558         }
11559 
11560         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11561     }
11562 
11563     return (ecore_config_rss(sc, &params));
11564 }
11565 
11566 static int
11567 bxe_config_rss_eth(struct bxe_softc *sc,
11568                    uint8_t          config_hash)
11569 {
11570     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11571 }
11572 
11573 static int
11574 bxe_init_rss_pf(struct bxe_softc *sc)
11575 {
11576     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11577     int i;
11578 
11579     /*
11580      * Prepare the initial contents of the indirection table if
11581      * RSS is enabled
11582      */
11583     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11584         sc->rss_conf_obj.ind_table[i] =
11585             (sc->fp->cl_id + (i % num_eth_queues));
11586     }
11587 
11588     if (sc->udp_rss) {
11589         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11590     }
11591 
11592     /*
11593      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11594      * per-port, so if explicit configuration is needed, do it only
11595      * for a PMF.
11596      *
11597      * For 57712 and newer it's a per-function configuration.
11598      */
11599     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11600 }
11601 
11602 static int
11603 bxe_set_mac_one(struct bxe_softc          *sc,
11604                 uint8_t                   *mac,
11605                 struct ecore_vlan_mac_obj *obj,
11606                 uint8_t                   set,
11607                 int                       mac_type,
11608                 unsigned long             *ramrod_flags)
11609 {
11610     struct ecore_vlan_mac_ramrod_params ramrod_param;
11611     int rc;
11612 
11613     memset(&ramrod_param, 0, sizeof(ramrod_param));
11614 
11615     /* fill in general parameters */
11616     ramrod_param.vlan_mac_obj = obj;
11617     ramrod_param.ramrod_flags = *ramrod_flags;
11618 
11619     /* fill a user request section if needed */
11620     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11621         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11622 
11623         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11624 
11625         /* Set the command: ADD or DEL */
11626         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11627                                             ECORE_VLAN_MAC_DEL;
11628     }
11629 
11630     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11631 
11632     if (rc == ECORE_EXISTS) {
11633         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11634         /* do not treat adding same MAC as error */
11635         rc = 0;
11636     } else if (rc < 0) {
11637         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11638     }
11639 
11640     return (rc);
11641 }
11642 
11643 static int
11644 bxe_set_eth_mac(struct bxe_softc *sc,
11645                 uint8_t          set)
11646 {
11647     unsigned long ramrod_flags = 0;
11648 
11649     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11650 
11651     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11652 
11653     /* Eth MAC is set on RSS leading client (fp[0]) */
11654     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11655                             &sc->sp_objs->mac_obj,
11656                             set, ECORE_ETH_MAC, &ramrod_flags));
11657 }
11658 
11659 static int
11660 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11661 {
11662     uint32_t sel_phy_idx = 0;
11663 
11664     if (sc->link_params.num_phys <= 1) {
11665         return (ELINK_INT_PHY);
11666     }
11667 
11668     if (sc->link_vars.link_up) {
11669         sel_phy_idx = ELINK_EXT_PHY1;
11670         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11671         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11672             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11673              ELINK_SUPPORTED_FIBRE))
11674             sel_phy_idx = ELINK_EXT_PHY2;
11675     } else {
11676         switch (elink_phy_selection(&sc->link_params)) {
11677         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11678         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11679         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11680                sel_phy_idx = ELINK_EXT_PHY1;
11681                break;
11682         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11683         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11684                sel_phy_idx = ELINK_EXT_PHY2;
11685                break;
11686         }
11687     }
11688 
11689     return (sel_phy_idx);
11690 }
11691 
11692 static int
11693 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11694 {
11695     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11696 
11697     /*
11698      * The selected activated PHY is always after swapping (in case PHY
11699      * swapping is enabled). So when swapping is enabled, we need to reverse
11700      * the configuration
11701      */
11702 
11703     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11704         if (sel_phy_idx == ELINK_EXT_PHY1)
11705             sel_phy_idx = ELINK_EXT_PHY2;
11706         else if (sel_phy_idx == ELINK_EXT_PHY2)
11707             sel_phy_idx = ELINK_EXT_PHY1;
11708     }
11709 
11710     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11711 }
11712 
11713 static void
11714 bxe_set_requested_fc(struct bxe_softc *sc)
11715 {
11716     /*
11717      * Initialize link parameters structure variables
11718      * It is recommended to turn off RX FC for jumbo frames
11719      * for better performance
11720      */
11721     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11722         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11723     } else {
11724         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11725     }
11726 }
11727 
11728 static void
11729 bxe_calc_fc_adv(struct bxe_softc *sc)
11730 {
11731     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11732     switch (sc->link_vars.ieee_fc &
11733             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11734     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11735     default:
11736         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11737                                            ADVERTISED_Pause);
11738         break;
11739 
11740     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11741         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11742                                           ADVERTISED_Pause);
11743         break;
11744 
11745     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11746         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11747         break;
11748     }
11749 }
11750 
11751 static uint16_t
11752 bxe_get_mf_speed(struct bxe_softc *sc)
11753 {
11754     uint16_t line_speed = sc->link_vars.line_speed;
11755     if (IS_MF(sc)) {
11756         uint16_t maxCfg =
11757             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11758 
11759         /* calculate the current MAX line speed limit for the MF devices */
11760         if (IS_MF_SI(sc)) {
11761             line_speed = (line_speed * maxCfg) / 100;
11762         } else { /* SD mode */
11763             uint16_t vn_max_rate = maxCfg * 100;
11764 
11765             if (vn_max_rate < line_speed) {
11766                 line_speed = vn_max_rate;
11767             }
11768         }
11769     }
11770 
11771     return (line_speed);
11772 }
11773 
11774 static void
11775 bxe_fill_report_data(struct bxe_softc            *sc,
11776                      struct bxe_link_report_data *data)
11777 {
11778     uint16_t line_speed = bxe_get_mf_speed(sc);
11779 
11780     memset(data, 0, sizeof(*data));
11781 
11782     /* fill the report data with the effective line speed */
11783     data->line_speed = line_speed;
11784 
11785     /* Link is down */
11786     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11787         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11788     }
11789 
11790     /* Full DUPLEX */
11791     if (sc->link_vars.duplex == DUPLEX_FULL) {
11792         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11793     }
11794 
11795     /* Rx Flow Control is ON */
11796     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11797         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11798     }
11799 
11800     /* Tx Flow Control is ON */
11801     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11802         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11803     }
11804 }
11805 
11806 /* report link status to OS, should be called under phy_lock */
11807 static void
11808 bxe_link_report_locked(struct bxe_softc *sc)
11809 {
11810     struct bxe_link_report_data cur_data;
11811 
11812     /* reread mf_cfg */
11813     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11814         bxe_read_mf_cfg(sc);
11815     }
11816 
11817     /* Read the current link report info */
11818     bxe_fill_report_data(sc, &cur_data);
11819 
11820     /* Don't report link down or exactly the same link status twice */
11821     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11822         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11823                       &sc->last_reported_link.link_report_flags) &&
11824          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11825                       &cur_data.link_report_flags))) {
11826         return;
11827     }
11828 
11829     sc->link_cnt++;
11830 
11831     /* report new link params and remember the state for the next time */
11832     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11833 
11834     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11835                      &cur_data.link_report_flags)) {
11836         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11837         BLOGI(sc, "NIC Link is Down\n");
11838     } else {
11839         const char *duplex;
11840         const char *flow;
11841 
11842         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11843                                    &cur_data.link_report_flags)) {
11844             duplex = "full";
11845         } else {
11846             duplex = "half";
11847         }
11848 
11849         /*
11850          * Handle the FC at the end so that only these flags would be
11851          * possibly set. This way we may easily check if there is no FC
11852          * enabled.
11853          */
11854         if (cur_data.link_report_flags) {
11855             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11856                              &cur_data.link_report_flags) &&
11857                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11858                              &cur_data.link_report_flags)) {
11859                 flow = "ON - receive & transmit";
11860             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11861                                     &cur_data.link_report_flags) &&
11862                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11863                                      &cur_data.link_report_flags)) {
11864                 flow = "ON - receive";
11865             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11866                                      &cur_data.link_report_flags) &&
11867                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11868                                     &cur_data.link_report_flags)) {
11869                 flow = "ON - transmit";
11870             } else {
11871                 flow = "none"; /* possible? */
11872             }
11873         } else {
11874             flow = "none";
11875         }
11876 
11877         if_link_state_change(sc->ifp, LINK_STATE_UP);
11878         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11879               cur_data.line_speed, duplex, flow);
11880     }
11881 }
11882 
11883 static void
11884 bxe_link_report(struct bxe_softc *sc)
11885 {
11886     bxe_acquire_phy_lock(sc);
11887     bxe_link_report_locked(sc);
11888     bxe_release_phy_lock(sc);
11889 }
11890 
11891 static void
11892 bxe_link_status_update(struct bxe_softc *sc)
11893 {
11894     if (sc->state != BXE_STATE_OPEN) {
11895         return;
11896     }
11897 
11898     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11899         elink_link_status_update(&sc->link_params, &sc->link_vars);
11900     } else {
11901         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11902                                   ELINK_SUPPORTED_10baseT_Full |
11903                                   ELINK_SUPPORTED_100baseT_Half |
11904                                   ELINK_SUPPORTED_100baseT_Full |
11905                                   ELINK_SUPPORTED_1000baseT_Full |
11906                                   ELINK_SUPPORTED_2500baseX_Full |
11907                                   ELINK_SUPPORTED_10000baseT_Full |
11908                                   ELINK_SUPPORTED_TP |
11909                                   ELINK_SUPPORTED_FIBRE |
11910                                   ELINK_SUPPORTED_Autoneg |
11911                                   ELINK_SUPPORTED_Pause |
11912                                   ELINK_SUPPORTED_Asym_Pause);
11913         sc->port.advertising[0] = sc->port.supported[0];
11914 
11915         sc->link_params.sc                = sc;
11916         sc->link_params.port              = SC_PORT(sc);
11917         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11918         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11919         sc->link_params.req_line_speed[0] = SPEED_10000;
11920         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11921         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11922 
11923         if (CHIP_REV_IS_FPGA(sc)) {
11924             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11925             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11926             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11927                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11928         } else {
11929             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11930             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11931             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11932                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11933         }
11934 
11935         sc->link_vars.link_up = 1;
11936 
11937         sc->link_vars.duplex    = DUPLEX_FULL;
11938         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11939 
11940         if (IS_PF(sc)) {
11941             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11942             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11943             bxe_link_report(sc);
11944         }
11945     }
11946 
11947     if (IS_PF(sc)) {
11948         if (sc->link_vars.link_up) {
11949             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11950         } else {
11951             bxe_stats_handle(sc, STATS_EVENT_STOP);
11952         }
11953         bxe_link_report(sc);
11954     } else {
11955         bxe_link_report(sc);
11956         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11957     }
11958 }
11959 
11960 static int
11961 bxe_initial_phy_init(struct bxe_softc *sc,
11962                      int              load_mode)
11963 {
11964     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11965     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11966     struct elink_params *lp = &sc->link_params;
11967 
11968     bxe_set_requested_fc(sc);
11969 
11970     if (CHIP_REV_IS_SLOW(sc)) {
11971         uint32_t bond = CHIP_BOND_ID(sc);
11972         uint32_t feat = 0;
11973 
11974         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11975             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11976         } else if (bond & 0x4) {
11977             if (CHIP_IS_E3(sc)) {
11978                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11979             } else {
11980                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11981             }
11982         } else if (bond & 0x8) {
11983             if (CHIP_IS_E3(sc)) {
11984                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11985             } else {
11986                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11987             }
11988         }
11989 
11990         /* disable EMAC for E3 and above */
11991         if (bond & 0x2) {
11992             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11993         }
11994 
11995         sc->link_params.feature_config_flags |= feat;
11996     }
11997 
11998     bxe_acquire_phy_lock(sc);
11999 
12000     if (load_mode == LOAD_DIAG) {
12001         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12002         /* Prefer doing PHY loopback at 10G speed, if possible */
12003         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12004             if (lp->speed_cap_mask[cfg_idx] &
12005                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12006                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12007             } else {
12008                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12009             }
12010         }
12011     }
12012 
12013     if (load_mode == LOAD_LOOPBACK_EXT) {
12014         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12015     }
12016 
12017     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12018 
12019     bxe_release_phy_lock(sc);
12020 
12021     bxe_calc_fc_adv(sc);
12022 
12023     if (sc->link_vars.link_up) {
12024         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12025         bxe_link_report(sc);
12026     }
12027 
12028     if (!CHIP_REV_IS_SLOW(sc)) {
12029         bxe_periodic_start(sc);
12030     }
12031 
12032     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12033     return (rc);
12034 }
12035 
12036 /* must be called under IF_ADDR_LOCK */
12037 
12038 static int
12039 bxe_set_mc_list(struct bxe_softc *sc)
12040 {
12041     struct ecore_mcast_ramrod_params rparam = { NULL };
12042     int rc = 0;
12043     int mc_count = 0;
12044     int mcnt, i;
12045     struct ecore_mcast_list_elem *mc_mac, *mc_mac_start;
12046     unsigned char *mta;
12047     if_t ifp = sc->ifp;
12048 
12049     mc_count = if_multiaddr_count(ifp, -1);/* XXX they don't have a limit */
12050     if (!mc_count)
12051         return (0);
12052 
12053     mta = malloc(sizeof(unsigned char) * ETHER_ADDR_LEN *
12054             mc_count, M_DEVBUF, M_NOWAIT);
12055 
12056     if(mta == NULL) {
12057         BLOGE(sc, "Failed to allocate temp mcast list\n");
12058         return (-1);
12059     }
12060     bzero(mta, (sizeof(unsigned char) * ETHER_ADDR_LEN * mc_count));
12061 
12062     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF, (M_NOWAIT | M_ZERO));
12063     mc_mac_start = mc_mac;
12064 
12065     if (!mc_mac) {
12066         free(mta, M_DEVBUF);
12067         BLOGE(sc, "Failed to allocate temp mcast list\n");
12068         return (-1);
12069     }
12070     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12071 
12072     /* mta and mcnt not expected to be  different */
12073     if_multiaddr_array(ifp, mta, &mcnt, mc_count);
12074 
12075 
12076     rparam.mcast_obj = &sc->mcast_obj;
12077     ECORE_LIST_INIT(&rparam.mcast_list);
12078 
12079     for(i=0; i< mcnt; i++) {
12080 
12081         mc_mac->mac = (uint8_t *)(mta + (i * ETHER_ADDR_LEN));
12082         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &rparam.mcast_list);
12083 
12084         BLOGD(sc, DBG_LOAD,
12085               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12086               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12087               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12088 
12089         mc_mac++;
12090     }
12091     rparam.mcast_list_len = mc_count;
12092 
12093     BXE_MCAST_LOCK(sc);
12094 
12095     /* first, clear all configured multicast MACs */
12096     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12097     if (rc < 0) {
12098         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12099         BXE_MCAST_UNLOCK(sc);
12100     	free(mc_mac_start, M_DEVBUF);
12101         free(mta, M_DEVBUF);
12102         return (rc);
12103     }
12104 
12105     /* Now add the new MACs */
12106     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12107     if (rc < 0) {
12108         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12109     }
12110 
12111     BXE_MCAST_UNLOCK(sc);
12112 
12113     free(mc_mac_start, M_DEVBUF);
12114     free(mta, M_DEVBUF);
12115 
12116     return (rc);
12117 }
12118 
12119 static int
12120 bxe_set_uc_list(struct bxe_softc *sc)
12121 {
12122     if_t ifp = sc->ifp;
12123     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12124     struct ifaddr *ifa;
12125     unsigned long ramrod_flags = 0;
12126     int rc;
12127 
12128 #if __FreeBSD_version < 800000
12129     IF_ADDR_LOCK(ifp);
12130 #else
12131     if_addr_rlock(ifp);
12132 #endif
12133 
12134     /* first schedule a cleanup up of old configuration */
12135     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12136     if (rc < 0) {
12137         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12138 #if __FreeBSD_version < 800000
12139         IF_ADDR_UNLOCK(ifp);
12140 #else
12141         if_addr_runlock(ifp);
12142 #endif
12143         return (rc);
12144     }
12145 
12146     ifa = if_getifaddr(ifp); /* XXX Is this structure */
12147     while (ifa) {
12148         if (ifa->ifa_addr->sa_family != AF_LINK) {
12149             ifa = TAILQ_NEXT(ifa, ifa_link);
12150             continue;
12151         }
12152 
12153         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12154                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12155         if (rc == -EEXIST) {
12156             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12157             /* do not treat adding same MAC as an error */
12158             rc = 0;
12159         } else if (rc < 0) {
12160             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12161 #if __FreeBSD_version < 800000
12162             IF_ADDR_UNLOCK(ifp);
12163 #else
12164             if_addr_runlock(ifp);
12165 #endif
12166             return (rc);
12167         }
12168 
12169         ifa = TAILQ_NEXT(ifa, ifa_link);
12170     }
12171 
12172 #if __FreeBSD_version < 800000
12173     IF_ADDR_UNLOCK(ifp);
12174 #else
12175     if_addr_runlock(ifp);
12176 #endif
12177 
12178     /* Execute the pending commands */
12179     bit_set(&ramrod_flags, RAMROD_CONT);
12180     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12181                             ECORE_UC_LIST_MAC, &ramrod_flags));
12182 }
12183 
12184 static void
12185 bxe_set_rx_mode(struct bxe_softc *sc)
12186 {
12187     if_t ifp = sc->ifp;
12188     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12189 
12190     if (sc->state != BXE_STATE_OPEN) {
12191         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12192         return;
12193     }
12194 
12195     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12196 
12197     if (if_getflags(ifp) & IFF_PROMISC) {
12198         rx_mode = BXE_RX_MODE_PROMISC;
12199     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12200                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12201                 CHIP_IS_E1(sc))) {
12202         rx_mode = BXE_RX_MODE_ALLMULTI;
12203     } else {
12204         if (IS_PF(sc)) {
12205             /* some multicasts */
12206             if (bxe_set_mc_list(sc) < 0) {
12207                 rx_mode = BXE_RX_MODE_ALLMULTI;
12208             }
12209             if (bxe_set_uc_list(sc) < 0) {
12210                 rx_mode = BXE_RX_MODE_PROMISC;
12211             }
12212         }
12213     }
12214 
12215     sc->rx_mode = rx_mode;
12216 
12217     /* schedule the rx_mode command */
12218     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12219         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12220         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12221         return;
12222     }
12223 
12224     if (IS_PF(sc)) {
12225         bxe_set_storm_rx_mode(sc);
12226     }
12227 }
12228 
12229 
12230 /* update flags in shmem */
12231 static void
12232 bxe_update_drv_flags(struct bxe_softc *sc,
12233                      uint32_t         flags,
12234                      uint32_t         set)
12235 {
12236     uint32_t drv_flags;
12237 
12238     if (SHMEM2_HAS(sc, drv_flags)) {
12239         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12240         drv_flags = SHMEM2_RD(sc, drv_flags);
12241 
12242         if (set) {
12243             SET_FLAGS(drv_flags, flags);
12244         } else {
12245             RESET_FLAGS(drv_flags, flags);
12246         }
12247 
12248         SHMEM2_WR(sc, drv_flags, drv_flags);
12249         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12250 
12251         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12252     }
12253 }
12254 
12255 /* periodic timer callout routine, only runs when the interface is up */
12256 
12257 static void
12258 bxe_periodic_callout_func(void *xsc)
12259 {
12260     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12261     struct bxe_fastpath *fp;
12262     uint16_t tx_bd_avail;
12263     int i;
12264 
12265     if (!BXE_CORE_TRYLOCK(sc)) {
12266         /* just bail and try again next time */
12267 
12268         if ((sc->state == BXE_STATE_OPEN) &&
12269             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12270             /* schedule the next periodic callout */
12271             callout_reset(&sc->periodic_callout, hz,
12272                           bxe_periodic_callout_func, sc);
12273         }
12274 
12275         return;
12276     }
12277 
12278     if ((sc->state != BXE_STATE_OPEN) ||
12279         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12280         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12281         BXE_CORE_UNLOCK(sc);
12282         return;
12283     }
12284 
12285 #if __FreeBSD_version >= 800000
12286 
12287     FOR_EACH_QUEUE(sc, i) {
12288         fp = &sc->fp[i];
12289 
12290         if (BXE_FP_TX_TRYLOCK(fp)) {
12291             if_t ifp = sc->ifp;
12292             /*
12293              * If interface was stopped due to unavailable
12294              * bds, try to process some tx completions
12295              */
12296             (void) bxe_txeof(sc, fp);
12297 
12298             tx_bd_avail = bxe_tx_avail(sc, fp);
12299             if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12300                 bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
12301             }
12302             BXE_FP_TX_UNLOCK(fp);
12303         }
12304     }
12305 
12306 #else
12307 
12308     fp = &sc->fp[0];
12309     if (BXE_FP_TX_TRYLOCK(fp)) {
12310         struct ifnet *ifp = sc->ifnet;
12311         /*
12312          * If interface was stopped due to unavailable
12313          * bds, try to process some tx completions
12314          */
12315         (void) bxe_txeof(sc, fp);
12316 
12317         tx_bd_avail = bxe_tx_avail(sc, fp);
12318         if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12319             bxe_tx_start_locked(sc, ifp, fp);
12320         }
12321 
12322         BXE_FP_TX_UNLOCK(fp);
12323     }
12324 
12325 #endif /* #if __FreeBSD_version >= 800000 */
12326 
12327     /* Check for TX timeouts on any fastpath. */
12328     FOR_EACH_QUEUE(sc, i) {
12329         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12330             /* Ruh-Roh, chip was reset! */
12331             break;
12332         }
12333     }
12334 
12335     if (!CHIP_REV_IS_SLOW(sc)) {
12336         /*
12337          * This barrier is needed to ensure the ordering between the writing
12338          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12339          * the reading here.
12340          */
12341         mb();
12342         if (sc->port.pmf) {
12343 	    bxe_acquire_phy_lock(sc);
12344             elink_period_func(&sc->link_params, &sc->link_vars);
12345 	    bxe_release_phy_lock(sc);
12346         }
12347     }
12348 
12349     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12350         int mb_idx = SC_FW_MB_IDX(sc);
12351         uint32_t drv_pulse;
12352         uint32_t mcp_pulse;
12353 
12354         ++sc->fw_drv_pulse_wr_seq;
12355         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12356 
12357         drv_pulse = sc->fw_drv_pulse_wr_seq;
12358         bxe_drv_pulse(sc);
12359 
12360         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12361                      MCP_PULSE_SEQ_MASK);
12362 
12363         /*
12364          * The delta between driver pulse and mcp response should
12365          * be 1 (before mcp response) or 0 (after mcp response).
12366          */
12367         if ((drv_pulse != mcp_pulse) &&
12368             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12369             /* someone lost a heartbeat... */
12370             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12371                   drv_pulse, mcp_pulse);
12372         }
12373     }
12374 
12375     /* state is BXE_STATE_OPEN */
12376     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12377 
12378     BXE_CORE_UNLOCK(sc);
12379 
12380     if ((sc->state == BXE_STATE_OPEN) &&
12381         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12382         /* schedule the next periodic callout */
12383         callout_reset(&sc->periodic_callout, hz,
12384                       bxe_periodic_callout_func, sc);
12385     }
12386 }
12387 
12388 static void
12389 bxe_periodic_start(struct bxe_softc *sc)
12390 {
12391     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12392     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12393 }
12394 
12395 static void
12396 bxe_periodic_stop(struct bxe_softc *sc)
12397 {
12398     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12399     callout_drain(&sc->periodic_callout);
12400 }
12401 
12402 /* start the controller */
12403 static __noinline int
12404 bxe_nic_load(struct bxe_softc *sc,
12405              int              load_mode)
12406 {
12407     uint32_t val;
12408     int load_code = 0;
12409     int i, rc = 0;
12410 
12411     BXE_CORE_LOCK_ASSERT(sc);
12412 
12413     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12414 
12415     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12416 
12417     if (IS_PF(sc)) {
12418         /* must be called before memory allocation and HW init */
12419         bxe_ilt_set_info(sc);
12420     }
12421 
12422     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12423 
12424     bxe_set_fp_rx_buf_size(sc);
12425 
12426     if (bxe_alloc_fp_buffers(sc) != 0) {
12427         BLOGE(sc, "Failed to allocate fastpath memory\n");
12428         sc->state = BXE_STATE_CLOSED;
12429         rc = ENOMEM;
12430         goto bxe_nic_load_error0;
12431     }
12432 
12433     if (bxe_alloc_mem(sc) != 0) {
12434         sc->state = BXE_STATE_CLOSED;
12435         rc = ENOMEM;
12436         goto bxe_nic_load_error0;
12437     }
12438 
12439     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12440         sc->state = BXE_STATE_CLOSED;
12441         rc = ENOMEM;
12442         goto bxe_nic_load_error0;
12443     }
12444 
12445     if (IS_PF(sc)) {
12446         /* set pf load just before approaching the MCP */
12447         bxe_set_pf_load(sc);
12448 
12449         /* if MCP exists send load request and analyze response */
12450         if (!BXE_NOMCP(sc)) {
12451             /* attempt to load pf */
12452             if (bxe_nic_load_request(sc, &load_code) != 0) {
12453                 sc->state = BXE_STATE_CLOSED;
12454                 rc = ENXIO;
12455                 goto bxe_nic_load_error1;
12456             }
12457 
12458             /* what did the MCP say? */
12459             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12460                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12461                 sc->state = BXE_STATE_CLOSED;
12462                 rc = ENXIO;
12463                 goto bxe_nic_load_error2;
12464             }
12465         } else {
12466             BLOGI(sc, "Device has no MCP!\n");
12467             load_code = bxe_nic_load_no_mcp(sc);
12468         }
12469 
12470         /* mark PMF if applicable */
12471         bxe_nic_load_pmf(sc, load_code);
12472 
12473         /* Init Function state controlling object */
12474         bxe_init_func_obj(sc);
12475 
12476         /* Initialize HW */
12477         if (bxe_init_hw(sc, load_code) != 0) {
12478             BLOGE(sc, "HW init failed\n");
12479             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12480             sc->state = BXE_STATE_CLOSED;
12481             rc = ENXIO;
12482             goto bxe_nic_load_error2;
12483         }
12484     }
12485 
12486     /* set ALWAYS_ALIVE bit in shmem */
12487     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12488     bxe_drv_pulse(sc);
12489     sc->flags |= BXE_NO_PULSE;
12490 
12491     /* attach interrupts */
12492     if (bxe_interrupt_attach(sc) != 0) {
12493         sc->state = BXE_STATE_CLOSED;
12494         rc = ENXIO;
12495         goto bxe_nic_load_error2;
12496     }
12497 
12498     bxe_nic_init(sc, load_code);
12499 
12500     /* Init per-function objects */
12501     if (IS_PF(sc)) {
12502         bxe_init_objs(sc);
12503         // XXX bxe_iov_nic_init(sc);
12504 
12505         /* set AFEX default VLAN tag to an invalid value */
12506         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12507         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12508 
12509         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12510         rc = bxe_func_start(sc);
12511         if (rc) {
12512             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12513             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12514             sc->state = BXE_STATE_ERROR;
12515             goto bxe_nic_load_error3;
12516         }
12517 
12518         /* send LOAD_DONE command to MCP */
12519         if (!BXE_NOMCP(sc)) {
12520             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12521             if (!load_code) {
12522                 BLOGE(sc, "MCP response failure, aborting\n");
12523                 sc->state = BXE_STATE_ERROR;
12524                 rc = ENXIO;
12525                 goto bxe_nic_load_error3;
12526             }
12527         }
12528 
12529         rc = bxe_setup_leading(sc);
12530         if (rc) {
12531             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12532             sc->state = BXE_STATE_ERROR;
12533             goto bxe_nic_load_error3;
12534         }
12535 
12536         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12537             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12538             if (rc) {
12539                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12540                 sc->state = BXE_STATE_ERROR;
12541                 goto bxe_nic_load_error3;
12542             }
12543         }
12544 
12545         rc = bxe_init_rss_pf(sc);
12546         if (rc) {
12547             BLOGE(sc, "PF RSS init failed\n");
12548             sc->state = BXE_STATE_ERROR;
12549             goto bxe_nic_load_error3;
12550         }
12551     }
12552     /* XXX VF */
12553 
12554     /* now when Clients are configured we are ready to work */
12555     sc->state = BXE_STATE_OPEN;
12556 
12557     /* Configure a ucast MAC */
12558     if (IS_PF(sc)) {
12559         rc = bxe_set_eth_mac(sc, TRUE);
12560     }
12561     if (rc) {
12562         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12563         sc->state = BXE_STATE_ERROR;
12564         goto bxe_nic_load_error3;
12565     }
12566 
12567     if (sc->port.pmf) {
12568         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12569         if (rc) {
12570             sc->state = BXE_STATE_ERROR;
12571             goto bxe_nic_load_error3;
12572         }
12573     }
12574 
12575     sc->link_params.feature_config_flags &=
12576         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12577 
12578     /* start fast path */
12579 
12580     /* Initialize Rx filter */
12581     bxe_set_rx_mode(sc);
12582 
12583     /* start the Tx */
12584     switch (/* XXX load_mode */LOAD_OPEN) {
12585     case LOAD_NORMAL:
12586     case LOAD_OPEN:
12587         break;
12588 
12589     case LOAD_DIAG:
12590     case LOAD_LOOPBACK_EXT:
12591         sc->state = BXE_STATE_DIAG;
12592         break;
12593 
12594     default:
12595         break;
12596     }
12597 
12598     if (sc->port.pmf) {
12599         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12600     } else {
12601         bxe_link_status_update(sc);
12602     }
12603 
12604     /* start the periodic timer callout */
12605     bxe_periodic_start(sc);
12606 
12607     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12608         /* mark driver is loaded in shmem2 */
12609         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12610         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12611                   (val |
12612                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12613                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12614     }
12615 
12616     /* wait for all pending SP commands to complete */
12617     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12618         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12619         bxe_periodic_stop(sc);
12620         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12621         return (ENXIO);
12622     }
12623 
12624     /* Tell the stack the driver is running! */
12625     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12626 
12627     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12628 
12629     return (0);
12630 
12631 bxe_nic_load_error3:
12632 
12633     if (IS_PF(sc)) {
12634         bxe_int_disable_sync(sc, 1);
12635 
12636         /* clean out queued objects */
12637         bxe_squeeze_objects(sc);
12638     }
12639 
12640     bxe_interrupt_detach(sc);
12641 
12642 bxe_nic_load_error2:
12643 
12644     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12645         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12646         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12647     }
12648 
12649     sc->port.pmf = 0;
12650 
12651 bxe_nic_load_error1:
12652 
12653     /* clear pf_load status, as it was already set */
12654     if (IS_PF(sc)) {
12655         bxe_clear_pf_load(sc);
12656     }
12657 
12658 bxe_nic_load_error0:
12659 
12660     bxe_free_fw_stats_mem(sc);
12661     bxe_free_fp_buffers(sc);
12662     bxe_free_mem(sc);
12663 
12664     return (rc);
12665 }
12666 
12667 static int
12668 bxe_init_locked(struct bxe_softc *sc)
12669 {
12670     int other_engine = SC_PATH(sc) ? 0 : 1;
12671     uint8_t other_load_status, load_status;
12672     uint8_t global = FALSE;
12673     int rc;
12674 
12675     BXE_CORE_LOCK_ASSERT(sc);
12676 
12677     /* check if the driver is already running */
12678     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12679         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12680         return (0);
12681     }
12682 
12683     bxe_set_power_state(sc, PCI_PM_D0);
12684 
12685     /*
12686      * If parity occurred during the unload, then attentions and/or
12687      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12688      * loaded on the current engine to complete the recovery. Parity recovery
12689      * is only relevant for PF driver.
12690      */
12691     if (IS_PF(sc)) {
12692         other_load_status = bxe_get_load_status(sc, other_engine);
12693         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12694 
12695         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12696             bxe_chk_parity_attn(sc, &global, TRUE)) {
12697             do {
12698                 /*
12699                  * If there are attentions and they are in global blocks, set
12700                  * the GLOBAL_RESET bit regardless whether it will be this
12701                  * function that will complete the recovery or not.
12702                  */
12703                 if (global) {
12704                     bxe_set_reset_global(sc);
12705                 }
12706 
12707                 /*
12708                  * Only the first function on the current engine should try
12709                  * to recover in open. In case of attentions in global blocks
12710                  * only the first in the chip should try to recover.
12711                  */
12712                 if ((!load_status && (!global || !other_load_status)) &&
12713                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12714                     BLOGI(sc, "Recovered during init\n");
12715                     break;
12716                 }
12717 
12718                 /* recovery has failed... */
12719                 bxe_set_power_state(sc, PCI_PM_D3hot);
12720                 sc->recovery_state = BXE_RECOVERY_FAILED;
12721 
12722                 BLOGE(sc, "Recovery flow hasn't properly "
12723                           "completed yet, try again later. "
12724                           "If you still see this message after a "
12725                           "few retries then power cycle is required.\n");
12726 
12727                 rc = ENXIO;
12728                 goto bxe_init_locked_done;
12729             } while (0);
12730         }
12731     }
12732 
12733     sc->recovery_state = BXE_RECOVERY_DONE;
12734 
12735     rc = bxe_nic_load(sc, LOAD_OPEN);
12736 
12737 bxe_init_locked_done:
12738 
12739     if (rc) {
12740         /* Tell the stack the driver is NOT running! */
12741         BLOGE(sc, "Initialization failed, "
12742                   "stack notified driver is NOT running!\n");
12743 	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
12744     }
12745 
12746     return (rc);
12747 }
12748 
12749 static int
12750 bxe_stop_locked(struct bxe_softc *sc)
12751 {
12752     BXE_CORE_LOCK_ASSERT(sc);
12753     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12754 }
12755 
12756 /*
12757  * Handles controller initialization when called from an unlocked routine.
12758  * ifconfig calls this function.
12759  *
12760  * Returns:
12761  *   void
12762  */
12763 static void
12764 bxe_init(void *xsc)
12765 {
12766     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12767 
12768     BXE_CORE_LOCK(sc);
12769     bxe_init_locked(sc);
12770     BXE_CORE_UNLOCK(sc);
12771 }
12772 
12773 static int
12774 bxe_init_ifnet(struct bxe_softc *sc)
12775 {
12776     if_t ifp;
12777     int capabilities;
12778 
12779     /* ifconfig entrypoint for media type/status reporting */
12780     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12781                  bxe_ifmedia_update,
12782                  bxe_ifmedia_status);
12783 
12784     /* set the default interface values */
12785     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12786     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12787     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12788 
12789     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12790 
12791     /* allocate the ifnet structure */
12792     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
12793         BLOGE(sc, "Interface allocation failed!\n");
12794         return (ENXIO);
12795     }
12796 
12797     if_setsoftc(ifp, sc);
12798     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12799     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
12800     if_setioctlfn(ifp, bxe_ioctl);
12801     if_setstartfn(ifp, bxe_tx_start);
12802     if_setgetcounterfn(ifp, bxe_get_counter);
12803 #if __FreeBSD_version >= 800000
12804     if_settransmitfn(ifp, bxe_tx_mq_start);
12805     if_setqflushfn(ifp, bxe_mq_flush);
12806 #endif
12807 #ifdef FreeBSD8_0
12808     if_settimer(ifp, 0);
12809 #endif
12810     if_setinitfn(ifp, bxe_init);
12811     if_setmtu(ifp, sc->mtu);
12812     if_sethwassist(ifp, (CSUM_IP      |
12813                         CSUM_TCP      |
12814                         CSUM_UDP      |
12815                         CSUM_TSO      |
12816                         CSUM_TCP_IPV6 |
12817                         CSUM_UDP_IPV6));
12818 
12819     capabilities =
12820 #if __FreeBSD_version < 700000
12821         (IFCAP_VLAN_MTU       |
12822          IFCAP_VLAN_HWTAGGING |
12823          IFCAP_HWCSUM         |
12824          IFCAP_JUMBO_MTU      |
12825          IFCAP_LRO);
12826 #else
12827         (IFCAP_VLAN_MTU       |
12828          IFCAP_VLAN_HWTAGGING |
12829          IFCAP_VLAN_HWTSO     |
12830          IFCAP_VLAN_HWFILTER  |
12831          IFCAP_VLAN_HWCSUM    |
12832          IFCAP_HWCSUM         |
12833          IFCAP_JUMBO_MTU      |
12834          IFCAP_LRO            |
12835          IFCAP_TSO4           |
12836          IFCAP_TSO6           |
12837          IFCAP_WOL_MAGIC);
12838 #endif
12839     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
12840     if_setbaudrate(ifp, IF_Gbps(10));
12841 /* XXX */
12842     if_setsendqlen(ifp, sc->tx_ring_size);
12843     if_setsendqready(ifp);
12844 /* XXX */
12845 
12846     sc->ifp = ifp;
12847 
12848     /* attach to the Ethernet interface list */
12849     ether_ifattach(ifp, sc->link_params.mac_addr);
12850 
12851     return (0);
12852 }
12853 
12854 static void
12855 bxe_deallocate_bars(struct bxe_softc *sc)
12856 {
12857     int i;
12858 
12859     for (i = 0; i < MAX_BARS; i++) {
12860         if (sc->bar[i].resource != NULL) {
12861             bus_release_resource(sc->dev,
12862                                  SYS_RES_MEMORY,
12863                                  sc->bar[i].rid,
12864                                  sc->bar[i].resource);
12865             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12866                   i, PCIR_BAR(i));
12867         }
12868     }
12869 }
12870 
12871 static int
12872 bxe_allocate_bars(struct bxe_softc *sc)
12873 {
12874     u_int flags;
12875     int i;
12876 
12877     memset(sc->bar, 0, sizeof(sc->bar));
12878 
12879     for (i = 0; i < MAX_BARS; i++) {
12880 
12881         /* memory resources reside at BARs 0, 2, 4 */
12882         /* Run `pciconf -lb` to see mappings */
12883         if ((i != 0) && (i != 2) && (i != 4)) {
12884             continue;
12885         }
12886 
12887         sc->bar[i].rid = PCIR_BAR(i);
12888 
12889         flags = RF_ACTIVE;
12890         if (i == 0) {
12891             flags |= RF_SHAREABLE;
12892         }
12893 
12894         if ((sc->bar[i].resource =
12895              bus_alloc_resource_any(sc->dev,
12896                                     SYS_RES_MEMORY,
12897                                     &sc->bar[i].rid,
12898                                     flags)) == NULL) {
12899             return (0);
12900         }
12901 
12902         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12903         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12904         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12905 
12906         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%jd) -> %p\n",
12907               i, PCIR_BAR(i),
12908               (void *)rman_get_start(sc->bar[i].resource),
12909               (void *)rman_get_end(sc->bar[i].resource),
12910               rman_get_size(sc->bar[i].resource),
12911               (void *)sc->bar[i].kva);
12912     }
12913 
12914     return (0);
12915 }
12916 
12917 static void
12918 bxe_get_function_num(struct bxe_softc *sc)
12919 {
12920     uint32_t val = 0;
12921 
12922     /*
12923      * Read the ME register to get the function number. The ME register
12924      * holds the relative-function number and absolute-function number. The
12925      * absolute-function number appears only in E2 and above. Before that
12926      * these bits always contained zero, therefore we cannot blindly use them.
12927      */
12928 
12929     val = REG_RD(sc, BAR_ME_REGISTER);
12930 
12931     sc->pfunc_rel =
12932         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12933     sc->path_id =
12934         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12935 
12936     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12937         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12938     } else {
12939         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12940     }
12941 
12942     BLOGD(sc, DBG_LOAD,
12943           "Relative function %d, Absolute function %d, Path %d\n",
12944           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12945 }
12946 
12947 static uint32_t
12948 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12949 {
12950     uint32_t shmem2_size;
12951     uint32_t offset;
12952     uint32_t mf_cfg_offset_value;
12953 
12954     /* Non 57712 */
12955     offset = (SHMEM_RD(sc, func_mb) +
12956               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12957 
12958     /* 57712 plus */
12959     if (sc->devinfo.shmem2_base != 0) {
12960         shmem2_size = SHMEM2_RD(sc, size);
12961         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12962             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12963             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12964                 offset = mf_cfg_offset_value;
12965             }
12966         }
12967     }
12968 
12969     return (offset);
12970 }
12971 
12972 static uint32_t
12973 bxe_pcie_capability_read(struct bxe_softc *sc,
12974                          int    reg,
12975                          int    width)
12976 {
12977     int pcie_reg;
12978 
12979     /* ensure PCIe capability is enabled */
12980     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12981         if (pcie_reg != 0) {
12982             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12983             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12984         }
12985     }
12986 
12987     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12988 
12989     return (0);
12990 }
12991 
12992 static uint8_t
12993 bxe_is_pcie_pending(struct bxe_softc *sc)
12994 {
12995     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12996             PCIM_EXP_STA_TRANSACTION_PND);
12997 }
12998 
12999 /*
13000  * Walk the PCI capabiites list for the device to find what features are
13001  * supported. These capabilites may be enabled/disabled by firmware so it's
13002  * best to walk the list rather than make assumptions.
13003  */
13004 static void
13005 bxe_probe_pci_caps(struct bxe_softc *sc)
13006 {
13007     uint16_t link_status;
13008     int reg;
13009 
13010     /* check if PCI Power Management is enabled */
13011     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13012         if (reg != 0) {
13013             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13014 
13015             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13016             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13017         }
13018     }
13019 
13020     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13021 
13022     /* handle PCIe 2.0 workarounds for 57710 */
13023     if (CHIP_IS_E1(sc)) {
13024         /* workaround for 57710 errata E4_57710_27462 */
13025         sc->devinfo.pcie_link_speed =
13026             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13027 
13028         /* workaround for 57710 errata E4_57710_27488 */
13029         sc->devinfo.pcie_link_width =
13030             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13031         if (sc->devinfo.pcie_link_speed > 1) {
13032             sc->devinfo.pcie_link_width =
13033                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13034         }
13035     } else {
13036         sc->devinfo.pcie_link_speed =
13037             (link_status & PCIM_LINK_STA_SPEED);
13038         sc->devinfo.pcie_link_width =
13039             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13040     }
13041 
13042     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13043           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13044 
13045     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13046     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13047 
13048     /* check if MSI capability is enabled */
13049     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13050         if (reg != 0) {
13051             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13052 
13053             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13054             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13055         }
13056     }
13057 
13058     /* check if MSI-X capability is enabled */
13059     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13060         if (reg != 0) {
13061             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13062 
13063             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13064             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13065         }
13066     }
13067 }
13068 
13069 static int
13070 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13071 {
13072     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13073     uint32_t val;
13074 
13075     /* get the outer vlan if we're in switch-dependent mode */
13076 
13077     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13078     mf_info->ext_id = (uint16_t)val;
13079 
13080     mf_info->multi_vnics_mode = 1;
13081 
13082     if (!VALID_OVLAN(mf_info->ext_id)) {
13083         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13084         return (1);
13085     }
13086 
13087     /* get the capabilities */
13088     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13089         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13090         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13091     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13092                FUNC_MF_CFG_PROTOCOL_FCOE) {
13093         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13094     } else {
13095         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13096     }
13097 
13098     mf_info->vnics_per_port =
13099         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13100 
13101     return (0);
13102 }
13103 
13104 static uint32_t
13105 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13106 {
13107     uint32_t retval = 0;
13108     uint32_t val;
13109 
13110     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13111 
13112     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13113         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13114             retval |= MF_PROTO_SUPPORT_ETHERNET;
13115         }
13116         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13117             retval |= MF_PROTO_SUPPORT_ISCSI;
13118         }
13119         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13120             retval |= MF_PROTO_SUPPORT_FCOE;
13121         }
13122     }
13123 
13124     return (retval);
13125 }
13126 
13127 static int
13128 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13129 {
13130     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13131     uint32_t val;
13132 
13133     /*
13134      * There is no outer vlan if we're in switch-independent mode.
13135      * If the mac is valid then assume multi-function.
13136      */
13137 
13138     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13139 
13140     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13141 
13142     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13143 
13144     mf_info->vnics_per_port =
13145         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13146 
13147     return (0);
13148 }
13149 
13150 static int
13151 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13152 {
13153     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13154     uint32_t e1hov_tag;
13155     uint32_t func_config;
13156     uint32_t niv_config;
13157 
13158     mf_info->multi_vnics_mode = 1;
13159 
13160     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13161     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13162     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13163 
13164     mf_info->ext_id =
13165         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13166                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13167 
13168     mf_info->default_vlan =
13169         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13170                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13171 
13172     mf_info->niv_allowed_priorities =
13173         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13174                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13175 
13176     mf_info->niv_default_cos =
13177         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13178                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13179 
13180     mf_info->afex_vlan_mode =
13181         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13182          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13183 
13184     mf_info->niv_mba_enabled =
13185         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13186          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13187 
13188     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13189 
13190     mf_info->vnics_per_port =
13191         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13192 
13193     return (0);
13194 }
13195 
13196 static int
13197 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13198 {
13199     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13200     uint32_t mf_cfg1;
13201     uint32_t mf_cfg2;
13202     uint32_t ovlan1;
13203     uint32_t ovlan2;
13204     uint8_t i, j;
13205 
13206     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13207           SC_PORT(sc));
13208     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13209           mf_info->mf_config[SC_VN(sc)]);
13210     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13211           mf_info->multi_vnics_mode);
13212     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13213           mf_info->vnics_per_port);
13214     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13215           mf_info->ext_id);
13216     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13217           mf_info->min_bw[0], mf_info->min_bw[1],
13218           mf_info->min_bw[2], mf_info->min_bw[3]);
13219     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13220           mf_info->max_bw[0], mf_info->max_bw[1],
13221           mf_info->max_bw[2], mf_info->max_bw[3]);
13222     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13223           sc->mac_addr_str);
13224 
13225     /* various MF mode sanity checks... */
13226 
13227     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13228         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13229               SC_PORT(sc));
13230         return (1);
13231     }
13232 
13233     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13234         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13235               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13236         return (1);
13237     }
13238 
13239     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13240         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13241         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13242             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13243                   SC_VN(sc), OVLAN(sc));
13244             return (1);
13245         }
13246 
13247         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13248             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13249                   mf_info->multi_vnics_mode, OVLAN(sc));
13250             return (1);
13251         }
13252 
13253         /*
13254          * Verify all functions are either MF or SF mode. If MF, make sure
13255          * sure that all non-hidden functions have a valid ovlan. If SF,
13256          * make sure that all non-hidden functions have an invalid ovlan.
13257          */
13258         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13259             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13260             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13261             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13262                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13263                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13264                 BLOGE(sc, "mf_mode=SD function %d MF config "
13265                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13266                       i, mf_info->multi_vnics_mode, ovlan1);
13267                 return (1);
13268             }
13269         }
13270 
13271         /* Verify all funcs on the same port each have a different ovlan. */
13272         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13273             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13274             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13275             /* iterate from the next function on the port to the max func */
13276             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13277                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13278                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13279                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13280                     VALID_OVLAN(ovlan1) &&
13281                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13282                     VALID_OVLAN(ovlan2) &&
13283                     (ovlan1 == ovlan2)) {
13284                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13285                               "have the same ovlan (%d)\n",
13286                           i, j, ovlan1);
13287                     return (1);
13288                 }
13289             }
13290         }
13291     } /* MULTI_FUNCTION_SD */
13292 
13293     return (0);
13294 }
13295 
13296 static int
13297 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13298 {
13299     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13300     uint32_t val, mac_upper;
13301     uint8_t i, vnic;
13302 
13303     /* initialize mf_info defaults */
13304     mf_info->vnics_per_port   = 1;
13305     mf_info->multi_vnics_mode = FALSE;
13306     mf_info->path_has_ovlan   = FALSE;
13307     mf_info->mf_mode          = SINGLE_FUNCTION;
13308 
13309     if (!CHIP_IS_MF_CAP(sc)) {
13310         return (0);
13311     }
13312 
13313     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13314         BLOGE(sc, "Invalid mf_cfg_base!\n");
13315         return (1);
13316     }
13317 
13318     /* get the MF mode (switch dependent / independent / single-function) */
13319 
13320     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13321 
13322     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13323     {
13324     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13325 
13326         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13327 
13328         /* check for legal upper mac bytes */
13329         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13330             mf_info->mf_mode = MULTI_FUNCTION_SI;
13331         } else {
13332             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13333         }
13334 
13335         break;
13336 
13337     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13338     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13339 
13340         /* get outer vlan configuration */
13341         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13342 
13343         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13344             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13345             mf_info->mf_mode = MULTI_FUNCTION_SD;
13346         } else {
13347             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13348         }
13349 
13350         break;
13351 
13352     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13353 
13354         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13355         return (0);
13356 
13357     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13358 
13359         /*
13360          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13361          * and the MAC address is valid.
13362          */
13363         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13364 
13365         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13366             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13367             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13368         } else {
13369             BLOGE(sc, "Invalid config for AFEX mode\n");
13370         }
13371 
13372         break;
13373 
13374     default:
13375 
13376         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13377               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13378 
13379         return (1);
13380     }
13381 
13382     /* set path mf_mode (which could be different than function mf_mode) */
13383     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13384         mf_info->path_has_ovlan = TRUE;
13385     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13386         /*
13387          * Decide on path multi vnics mode. If we're not in MF mode and in
13388          * 4-port mode, this is good enough to check vnic-0 of the other port
13389          * on the same path
13390          */
13391         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13392             uint8_t other_port = !(PORT_ID(sc) & 1);
13393             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13394 
13395             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13396 
13397             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13398         }
13399     }
13400 
13401     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13402         /* invalid MF config */
13403         if (SC_VN(sc) >= 1) {
13404             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13405             return (1);
13406         }
13407 
13408         return (0);
13409     }
13410 
13411     /* get the MF configuration */
13412     mf_info->mf_config[SC_VN(sc)] =
13413         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13414 
13415     switch(mf_info->mf_mode)
13416     {
13417     case MULTI_FUNCTION_SD:
13418 
13419         bxe_get_shmem_mf_cfg_info_sd(sc);
13420         break;
13421 
13422     case MULTI_FUNCTION_SI:
13423 
13424         bxe_get_shmem_mf_cfg_info_si(sc);
13425         break;
13426 
13427     case MULTI_FUNCTION_AFEX:
13428 
13429         bxe_get_shmem_mf_cfg_info_niv(sc);
13430         break;
13431 
13432     default:
13433 
13434         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13435               mf_info->mf_mode);
13436         return (1);
13437     }
13438 
13439     /* get the congestion management parameters */
13440 
13441     vnic = 0;
13442     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13443         /* get min/max bw */
13444         val = MFCFG_RD(sc, func_mf_config[i].config);
13445         mf_info->min_bw[vnic] =
13446             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13447         mf_info->max_bw[vnic] =
13448             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13449         vnic++;
13450     }
13451 
13452     return (bxe_check_valid_mf_cfg(sc));
13453 }
13454 
13455 static int
13456 bxe_get_shmem_info(struct bxe_softc *sc)
13457 {
13458     int port;
13459     uint32_t mac_hi, mac_lo, val;
13460 
13461     port = SC_PORT(sc);
13462     mac_hi = mac_lo = 0;
13463 
13464     sc->link_params.sc   = sc;
13465     sc->link_params.port = port;
13466 
13467     /* get the hardware config info */
13468     sc->devinfo.hw_config =
13469         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13470     sc->devinfo.hw_config2 =
13471         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13472 
13473     sc->link_params.hw_led_mode =
13474         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13475          SHARED_HW_CFG_LED_MODE_SHIFT);
13476 
13477     /* get the port feature config */
13478     sc->port.config =
13479         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13480 
13481     /* get the link params */
13482     sc->link_params.speed_cap_mask[0] =
13483         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13484     sc->link_params.speed_cap_mask[1] =
13485         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13486 
13487     /* get the lane config */
13488     sc->link_params.lane_config =
13489         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13490 
13491     /* get the link config */
13492     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13493     sc->port.link_config[ELINK_INT_PHY] = val;
13494     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13495     sc->port.link_config[ELINK_EXT_PHY1] =
13496         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13497 
13498     /* get the override preemphasis flag and enable it or turn it off */
13499     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13500     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13501         sc->link_params.feature_config_flags |=
13502             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13503     } else {
13504         sc->link_params.feature_config_flags &=
13505             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13506     }
13507 
13508     /* get the initial value of the link params */
13509     sc->link_params.multi_phy_config =
13510         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13511 
13512     /* get external phy info */
13513     sc->port.ext_phy_config =
13514         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13515 
13516     /* get the multifunction configuration */
13517     bxe_get_mf_cfg_info(sc);
13518 
13519     /* get the mac address */
13520     if (IS_MF(sc)) {
13521         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13522         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13523     } else {
13524         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13525         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13526     }
13527 
13528     if ((mac_lo == 0) && (mac_hi == 0)) {
13529         *sc->mac_addr_str = 0;
13530         BLOGE(sc, "No Ethernet address programmed!\n");
13531     } else {
13532         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13533         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13534         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13535         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13536         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13537         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13538         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13539                  "%02x:%02x:%02x:%02x:%02x:%02x",
13540                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13541                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13542                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13543         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13544     }
13545 
13546     return (0);
13547 }
13548 
13549 static void
13550 bxe_get_tunable_params(struct bxe_softc *sc)
13551 {
13552     /* sanity checks */
13553 
13554     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13555         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13556         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13557         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13558         bxe_interrupt_mode = INTR_MODE_MSIX;
13559     }
13560 
13561     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13562         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13563         bxe_queue_count = 0;
13564     }
13565 
13566     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13567         if (bxe_max_rx_bufs == 0) {
13568             bxe_max_rx_bufs = RX_BD_USABLE;
13569         } else {
13570             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13571             bxe_max_rx_bufs = 2048;
13572         }
13573     }
13574 
13575     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13576         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13577         bxe_hc_rx_ticks = 25;
13578     }
13579 
13580     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13581         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13582         bxe_hc_tx_ticks = 50;
13583     }
13584 
13585     if (bxe_max_aggregation_size == 0) {
13586         bxe_max_aggregation_size = TPA_AGG_SIZE;
13587     }
13588 
13589     if (bxe_max_aggregation_size > 0xffff) {
13590         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13591               bxe_max_aggregation_size);
13592         bxe_max_aggregation_size = TPA_AGG_SIZE;
13593     }
13594 
13595     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13596         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13597         bxe_mrrs = -1;
13598     }
13599 
13600     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13601         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13602         bxe_autogreeen = 0;
13603     }
13604 
13605     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13606         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13607         bxe_udp_rss = 0;
13608     }
13609 
13610     /* pull in user settings */
13611 
13612     sc->interrupt_mode       = bxe_interrupt_mode;
13613     sc->max_rx_bufs          = bxe_max_rx_bufs;
13614     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13615     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13616     sc->max_aggregation_size = bxe_max_aggregation_size;
13617     sc->mrrs                 = bxe_mrrs;
13618     sc->autogreeen           = bxe_autogreeen;
13619     sc->udp_rss              = bxe_udp_rss;
13620 
13621     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13622         sc->num_queues = 1;
13623     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13624         sc->num_queues =
13625             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13626                 MAX_RSS_CHAINS);
13627         if (sc->num_queues > mp_ncpus) {
13628             sc->num_queues = mp_ncpus;
13629         }
13630     }
13631 
13632     BLOGD(sc, DBG_LOAD,
13633           "User Config: "
13634           "debug=0x%lx "
13635           "interrupt_mode=%d "
13636           "queue_count=%d "
13637           "hc_rx_ticks=%d "
13638           "hc_tx_ticks=%d "
13639           "rx_budget=%d "
13640           "max_aggregation_size=%d "
13641           "mrrs=%d "
13642           "autogreeen=%d "
13643           "udp_rss=%d\n",
13644           bxe_debug,
13645           sc->interrupt_mode,
13646           sc->num_queues,
13647           sc->hc_rx_ticks,
13648           sc->hc_tx_ticks,
13649           bxe_rx_budget,
13650           sc->max_aggregation_size,
13651           sc->mrrs,
13652           sc->autogreeen,
13653           sc->udp_rss);
13654 }
13655 
13656 static int
13657 bxe_media_detect(struct bxe_softc *sc)
13658 {
13659     int port_type;
13660     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13661 
13662     switch (sc->link_params.phy[phy_idx].media_type) {
13663     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13664     case ELINK_ETH_PHY_XFP_FIBER:
13665         BLOGI(sc, "Found 10Gb Fiber media.\n");
13666         sc->media = IFM_10G_SR;
13667         port_type = PORT_FIBRE;
13668         break;
13669     case ELINK_ETH_PHY_SFP_1G_FIBER:
13670         BLOGI(sc, "Found 1Gb Fiber media.\n");
13671         sc->media = IFM_1000_SX;
13672         port_type = PORT_FIBRE;
13673         break;
13674     case ELINK_ETH_PHY_KR:
13675     case ELINK_ETH_PHY_CX4:
13676         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13677         sc->media = IFM_10G_CX4;
13678         port_type = PORT_FIBRE;
13679         break;
13680     case ELINK_ETH_PHY_DA_TWINAX:
13681         BLOGI(sc, "Found 10Gb Twinax media.\n");
13682         sc->media = IFM_10G_TWINAX;
13683         port_type = PORT_DA;
13684         break;
13685     case ELINK_ETH_PHY_BASE_T:
13686         if (sc->link_params.speed_cap_mask[0] &
13687             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13688             BLOGI(sc, "Found 10GBase-T media.\n");
13689             sc->media = IFM_10G_T;
13690             port_type = PORT_TP;
13691         } else {
13692             BLOGI(sc, "Found 1000Base-T media.\n");
13693             sc->media = IFM_1000_T;
13694             port_type = PORT_TP;
13695         }
13696         break;
13697     case ELINK_ETH_PHY_NOT_PRESENT:
13698         BLOGI(sc, "Media not present.\n");
13699         sc->media = 0;
13700         port_type = PORT_OTHER;
13701         break;
13702     case ELINK_ETH_PHY_UNSPECIFIED:
13703     default:
13704         BLOGI(sc, "Unknown media!\n");
13705         sc->media = 0;
13706         port_type = PORT_OTHER;
13707         break;
13708     }
13709     return port_type;
13710 }
13711 
13712 #define GET_FIELD(value, fname)                     \
13713     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13714 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13715 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13716 
13717 static int
13718 bxe_get_igu_cam_info(struct bxe_softc *sc)
13719 {
13720     int pfid = SC_FUNC(sc);
13721     int igu_sb_id;
13722     uint32_t val;
13723     uint8_t fid, igu_sb_cnt = 0;
13724 
13725     sc->igu_base_sb = 0xff;
13726 
13727     if (CHIP_INT_MODE_IS_BC(sc)) {
13728         int vn = SC_VN(sc);
13729         igu_sb_cnt = sc->igu_sb_cnt;
13730         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13731                            FP_SB_MAX_E1x);
13732         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13733                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13734         return (0);
13735     }
13736 
13737     /* IGU in normal mode - read CAM */
13738     for (igu_sb_id = 0;
13739          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13740          igu_sb_id++) {
13741         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13742         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13743             continue;
13744         }
13745         fid = IGU_FID(val);
13746         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13747             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13748                 continue;
13749             }
13750             if (IGU_VEC(val) == 0) {
13751                 /* default status block */
13752                 sc->igu_dsb_id = igu_sb_id;
13753             } else {
13754                 if (sc->igu_base_sb == 0xff) {
13755                     sc->igu_base_sb = igu_sb_id;
13756                 }
13757                 igu_sb_cnt++;
13758             }
13759         }
13760     }
13761 
13762     /*
13763      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13764      * that number of CAM entries will not be equal to the value advertised in
13765      * PCI. Driver should use the minimal value of both as the actual status
13766      * block count
13767      */
13768     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13769 
13770     if (igu_sb_cnt == 0) {
13771         BLOGE(sc, "CAM configuration error\n");
13772         return (-1);
13773     }
13774 
13775     return (0);
13776 }
13777 
13778 /*
13779  * Gather various information from the device config space, the device itself,
13780  * shmem, and the user input.
13781  */
13782 static int
13783 bxe_get_device_info(struct bxe_softc *sc)
13784 {
13785     uint32_t val;
13786     int rc;
13787 
13788     /* Get the data for the device */
13789     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13790     sc->devinfo.device_id    = pci_get_device(sc->dev);
13791     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13792     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13793 
13794     /* get the chip revision (chip metal comes from pci config space) */
13795     sc->devinfo.chip_id     =
13796     sc->link_params.chip_id =
13797         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13798          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13799          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13800          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13801 
13802     /* force 57811 according to MISC register */
13803     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13804         if (CHIP_IS_57810(sc)) {
13805             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13806                                    (sc->devinfo.chip_id & 0x0000ffff));
13807         } else if (CHIP_IS_57810_MF(sc)) {
13808             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13809                                    (sc->devinfo.chip_id & 0x0000ffff));
13810         }
13811         sc->devinfo.chip_id |= 0x1;
13812     }
13813 
13814     BLOGD(sc, DBG_LOAD,
13815           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13816           sc->devinfo.chip_id,
13817           ((sc->devinfo.chip_id >> 16) & 0xffff),
13818           ((sc->devinfo.chip_id >> 12) & 0xf),
13819           ((sc->devinfo.chip_id >>  4) & 0xff),
13820           ((sc->devinfo.chip_id >>  0) & 0xf));
13821 
13822     val = (REG_RD(sc, 0x2874) & 0x55);
13823     if ((sc->devinfo.chip_id & 0x1) ||
13824         (CHIP_IS_E1(sc) && val) ||
13825         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13826         sc->flags |= BXE_ONE_PORT_FLAG;
13827         BLOGD(sc, DBG_LOAD, "single port device\n");
13828     }
13829 
13830     /* set the doorbell size */
13831     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13832 
13833     /* determine whether the device is in 2 port or 4 port mode */
13834     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13835     if (CHIP_IS_E2E3(sc)) {
13836         /*
13837          * Read port4mode_en_ovwr[0]:
13838          *   If 1, four port mode is in port4mode_en_ovwr[1].
13839          *   If 0, four port mode is in port4mode_en[0].
13840          */
13841         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13842         if (val & 1) {
13843             val = ((val >> 1) & 1);
13844         } else {
13845             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13846         }
13847 
13848         sc->devinfo.chip_port_mode =
13849             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13850 
13851         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13852     }
13853 
13854     /* get the function and path info for the device */
13855     bxe_get_function_num(sc);
13856 
13857     /* get the shared memory base address */
13858     sc->devinfo.shmem_base     =
13859     sc->link_params.shmem_base =
13860         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13861     sc->devinfo.shmem2_base =
13862         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13863                                   MISC_REG_GENERIC_CR_0));
13864 
13865     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13866           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13867 
13868     if (!sc->devinfo.shmem_base) {
13869         /* this should ONLY prevent upcoming shmem reads */
13870         BLOGI(sc, "MCP not active\n");
13871         sc->flags |= BXE_NO_MCP_FLAG;
13872         return (0);
13873     }
13874 
13875     /* make sure the shared memory contents are valid */
13876     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13877     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13878         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13879         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13880         return (0);
13881     }
13882     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13883 
13884     /* get the bootcode version */
13885     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13886     snprintf(sc->devinfo.bc_ver_str,
13887              sizeof(sc->devinfo.bc_ver_str),
13888              "%d.%d.%d",
13889              ((sc->devinfo.bc_ver >> 24) & 0xff),
13890              ((sc->devinfo.bc_ver >> 16) & 0xff),
13891              ((sc->devinfo.bc_ver >>  8) & 0xff));
13892     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13893 
13894     /* get the bootcode shmem address */
13895     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13896     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13897 
13898     /* clean indirect addresses as they're not used */
13899     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13900     if (IS_PF(sc)) {
13901         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13902         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13903         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13904         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13905         if (CHIP_IS_E1x(sc)) {
13906             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13907             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13908             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13909             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13910         }
13911 
13912         /*
13913          * Enable internal target-read (in case we are probed after PF
13914          * FLR). Must be done prior to any BAR read access. Only for
13915          * 57712 and up
13916          */
13917         if (!CHIP_IS_E1x(sc)) {
13918             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13919         }
13920     }
13921 
13922     /* get the nvram size */
13923     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13924     sc->devinfo.flash_size =
13925         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13926     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13927 
13928     /* get PCI capabilites */
13929     bxe_probe_pci_caps(sc);
13930 
13931     bxe_set_power_state(sc, PCI_PM_D0);
13932 
13933     /* get various configuration parameters from shmem */
13934     bxe_get_shmem_info(sc);
13935 
13936     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13937         val = pci_read_config(sc->dev,
13938                               (sc->devinfo.pcie_msix_cap_reg +
13939                                PCIR_MSIX_CTRL),
13940                               2);
13941         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13942     } else {
13943         sc->igu_sb_cnt = 1;
13944     }
13945 
13946     sc->igu_base_addr = BAR_IGU_INTMEM;
13947 
13948     /* initialize IGU parameters */
13949     if (CHIP_IS_E1x(sc)) {
13950         sc->devinfo.int_block = INT_BLOCK_HC;
13951         sc->igu_dsb_id = DEF_SB_IGU_ID;
13952         sc->igu_base_sb = 0;
13953     } else {
13954         sc->devinfo.int_block = INT_BLOCK_IGU;
13955 
13956         /* do not allow device reset during IGU info preocessing */
13957         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13958 
13959         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13960 
13961         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13962             int tout = 5000;
13963 
13964             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13965 
13966             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13967             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13968             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13969 
13970             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13971                 tout--;
13972                 DELAY(1000);
13973             }
13974 
13975             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13976                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13977                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13978                 return (-1);
13979             }
13980         }
13981 
13982         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13983             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13984             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13985         } else {
13986             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13987         }
13988 
13989         rc = bxe_get_igu_cam_info(sc);
13990 
13991         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13992 
13993         if (rc) {
13994             return (rc);
13995         }
13996     }
13997 
13998     /*
13999      * Get base FW non-default (fast path) status block ID. This value is
14000      * used to initialize the fw_sb_id saved on the fp/queue structure to
14001      * determine the id used by the FW.
14002      */
14003     if (CHIP_IS_E1x(sc)) {
14004         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14005     } else {
14006         /*
14007          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14008          * the same queue are indicated on the same IGU SB). So we prefer
14009          * FW and IGU SBs to be the same value.
14010          */
14011         sc->base_fw_ndsb = sc->igu_base_sb;
14012     }
14013 
14014     BLOGD(sc, DBG_LOAD,
14015           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14016           sc->igu_dsb_id, sc->igu_base_sb,
14017           sc->igu_sb_cnt, sc->base_fw_ndsb);
14018 
14019     elink_phy_probe(&sc->link_params);
14020 
14021     return (0);
14022 }
14023 
14024 static void
14025 bxe_link_settings_supported(struct bxe_softc *sc,
14026                             uint32_t         switch_cfg)
14027 {
14028     uint32_t cfg_size = 0;
14029     uint32_t idx;
14030     uint8_t port = SC_PORT(sc);
14031 
14032     /* aggregation of supported attributes of all external phys */
14033     sc->port.supported[0] = 0;
14034     sc->port.supported[1] = 0;
14035 
14036     switch (sc->link_params.num_phys) {
14037     case 1:
14038         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14039         cfg_size = 1;
14040         break;
14041     case 2:
14042         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14043         cfg_size = 1;
14044         break;
14045     case 3:
14046         if (sc->link_params.multi_phy_config &
14047             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14048             sc->port.supported[1] =
14049                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14050             sc->port.supported[0] =
14051                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14052         } else {
14053             sc->port.supported[0] =
14054                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14055             sc->port.supported[1] =
14056                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14057         }
14058         cfg_size = 2;
14059         break;
14060     }
14061 
14062     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14063         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14064               SHMEM_RD(sc,
14065                        dev_info.port_hw_config[port].external_phy_config),
14066               SHMEM_RD(sc,
14067                        dev_info.port_hw_config[port].external_phy_config2));
14068         return;
14069     }
14070 
14071     if (CHIP_IS_E3(sc))
14072         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14073     else {
14074         switch (switch_cfg) {
14075         case ELINK_SWITCH_CFG_1G:
14076             sc->port.phy_addr =
14077                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14078             break;
14079         case ELINK_SWITCH_CFG_10G:
14080             sc->port.phy_addr =
14081                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14082             break;
14083         default:
14084             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14085                   sc->port.link_config[0]);
14086             return;
14087         }
14088     }
14089 
14090     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14091 
14092     /* mask what we support according to speed_cap_mask per configuration */
14093     for (idx = 0; idx < cfg_size; idx++) {
14094         if (!(sc->link_params.speed_cap_mask[idx] &
14095               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14096             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14097         }
14098 
14099         if (!(sc->link_params.speed_cap_mask[idx] &
14100               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14101             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14102         }
14103 
14104         if (!(sc->link_params.speed_cap_mask[idx] &
14105               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14106             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14107         }
14108 
14109         if (!(sc->link_params.speed_cap_mask[idx] &
14110               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14111             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14112         }
14113 
14114         if (!(sc->link_params.speed_cap_mask[idx] &
14115               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14116             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14117         }
14118 
14119         if (!(sc->link_params.speed_cap_mask[idx] &
14120               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14121             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14122         }
14123 
14124         if (!(sc->link_params.speed_cap_mask[idx] &
14125               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14126             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14127         }
14128 
14129         if (!(sc->link_params.speed_cap_mask[idx] &
14130               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14131             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14132         }
14133     }
14134 
14135     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14136           sc->port.supported[0], sc->port.supported[1]);
14137 }
14138 
14139 static void
14140 bxe_link_settings_requested(struct bxe_softc *sc)
14141 {
14142     uint32_t link_config;
14143     uint32_t idx;
14144     uint32_t cfg_size = 0;
14145 
14146     sc->port.advertising[0] = 0;
14147     sc->port.advertising[1] = 0;
14148 
14149     switch (sc->link_params.num_phys) {
14150     case 1:
14151     case 2:
14152         cfg_size = 1;
14153         break;
14154     case 3:
14155         cfg_size = 2;
14156         break;
14157     }
14158 
14159     for (idx = 0; idx < cfg_size; idx++) {
14160         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14161         link_config = sc->port.link_config[idx];
14162 
14163         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14164         case PORT_FEATURE_LINK_SPEED_AUTO:
14165             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14166                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14167                 sc->port.advertising[idx] |= sc->port.supported[idx];
14168                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14169                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14170                     sc->port.advertising[idx] |=
14171                         (ELINK_SUPPORTED_100baseT_Half |
14172                          ELINK_SUPPORTED_100baseT_Full);
14173             } else {
14174                 /* force 10G, no AN */
14175                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14176                 sc->port.advertising[idx] |=
14177                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14178                 continue;
14179             }
14180             break;
14181 
14182         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14183             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14184                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14185                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14186                                               ADVERTISED_TP);
14187             } else {
14188                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14189                           "speed_cap_mask=0x%08x\n",
14190                       link_config, sc->link_params.speed_cap_mask[idx]);
14191                 return;
14192             }
14193             break;
14194 
14195         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14196             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14197                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14198                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14199                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14200                                               ADVERTISED_TP);
14201             } else {
14202                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14203                           "speed_cap_mask=0x%08x\n",
14204                       link_config, sc->link_params.speed_cap_mask[idx]);
14205                 return;
14206             }
14207             break;
14208 
14209         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14210             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14211                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14212                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14213                                               ADVERTISED_TP);
14214             } else {
14215                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14216                           "speed_cap_mask=0x%08x\n",
14217                       link_config, sc->link_params.speed_cap_mask[idx]);
14218                 return;
14219             }
14220             break;
14221 
14222         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14223             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14224                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14225                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14226                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14227                                               ADVERTISED_TP);
14228             } else {
14229                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14230                           "speed_cap_mask=0x%08x\n",
14231                       link_config, sc->link_params.speed_cap_mask[idx]);
14232                 return;
14233             }
14234             break;
14235 
14236         case PORT_FEATURE_LINK_SPEED_1G:
14237             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14238                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14239                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14240                                               ADVERTISED_TP);
14241             } else {
14242                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14243                           "speed_cap_mask=0x%08x\n",
14244                       link_config, sc->link_params.speed_cap_mask[idx]);
14245                 return;
14246             }
14247             break;
14248 
14249         case PORT_FEATURE_LINK_SPEED_2_5G:
14250             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14251                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14252                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14253                                               ADVERTISED_TP);
14254             } else {
14255                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14256                           "speed_cap_mask=0x%08x\n",
14257                       link_config, sc->link_params.speed_cap_mask[idx]);
14258                 return;
14259             }
14260             break;
14261 
14262         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14263             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14264                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14265                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14266                                               ADVERTISED_FIBRE);
14267             } else {
14268                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14269                           "speed_cap_mask=0x%08x\n",
14270                       link_config, sc->link_params.speed_cap_mask[idx]);
14271                 return;
14272             }
14273             break;
14274 
14275         case PORT_FEATURE_LINK_SPEED_20G:
14276             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14277             break;
14278 
14279         default:
14280             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14281                       "speed_cap_mask=0x%08x\n",
14282                   link_config, sc->link_params.speed_cap_mask[idx]);
14283             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14284             sc->port.advertising[idx] = sc->port.supported[idx];
14285             break;
14286         }
14287 
14288         sc->link_params.req_flow_ctrl[idx] =
14289             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14290 
14291         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14292             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14293                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14294             } else {
14295                 bxe_set_requested_fc(sc);
14296             }
14297         }
14298 
14299         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14300                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14301               sc->link_params.req_line_speed[idx],
14302               sc->link_params.req_duplex[idx],
14303               sc->link_params.req_flow_ctrl[idx],
14304               sc->port.advertising[idx]);
14305     }
14306 }
14307 
14308 static void
14309 bxe_get_phy_info(struct bxe_softc *sc)
14310 {
14311     uint8_t port = SC_PORT(sc);
14312     uint32_t config = sc->port.config;
14313     uint32_t eee_mode;
14314 
14315     /* shmem data already read in bxe_get_shmem_info() */
14316 
14317     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14318                         "link_config0=0x%08x\n",
14319                sc->link_params.lane_config,
14320                sc->link_params.speed_cap_mask[0],
14321                sc->port.link_config[0]);
14322 
14323     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14324     bxe_link_settings_requested(sc);
14325 
14326     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14327         sc->link_params.feature_config_flags |=
14328             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14329     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14330         sc->link_params.feature_config_flags &=
14331             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14332     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14333         sc->link_params.feature_config_flags |=
14334             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14335     }
14336 
14337     /* configure link feature according to nvram value */
14338     eee_mode =
14339         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14340           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14341          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14342     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14343         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14344                                     ELINK_EEE_MODE_ENABLE_LPI |
14345                                     ELINK_EEE_MODE_OUTPUT_TIME);
14346     } else {
14347         sc->link_params.eee_mode = 0;
14348     }
14349 
14350     /* get the media type */
14351     bxe_media_detect(sc);
14352 }
14353 
14354 static void
14355 bxe_get_params(struct bxe_softc *sc)
14356 {
14357     /* get user tunable params */
14358     bxe_get_tunable_params(sc);
14359 
14360     /* select the RX and TX ring sizes */
14361     sc->tx_ring_size = TX_BD_USABLE;
14362     sc->rx_ring_size = RX_BD_USABLE;
14363 
14364     /* XXX disable WoL */
14365     sc->wol = 0;
14366 }
14367 
14368 static void
14369 bxe_set_modes_bitmap(struct bxe_softc *sc)
14370 {
14371     uint32_t flags = 0;
14372 
14373     if (CHIP_REV_IS_FPGA(sc)) {
14374         SET_FLAGS(flags, MODE_FPGA);
14375     } else if (CHIP_REV_IS_EMUL(sc)) {
14376         SET_FLAGS(flags, MODE_EMUL);
14377     } else {
14378         SET_FLAGS(flags, MODE_ASIC);
14379     }
14380 
14381     if (CHIP_IS_MODE_4_PORT(sc)) {
14382         SET_FLAGS(flags, MODE_PORT4);
14383     } else {
14384         SET_FLAGS(flags, MODE_PORT2);
14385     }
14386 
14387     if (CHIP_IS_E2(sc)) {
14388         SET_FLAGS(flags, MODE_E2);
14389     } else if (CHIP_IS_E3(sc)) {
14390         SET_FLAGS(flags, MODE_E3);
14391         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14392             SET_FLAGS(flags, MODE_E3_A0);
14393         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14394             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14395         }
14396     }
14397 
14398     if (IS_MF(sc)) {
14399         SET_FLAGS(flags, MODE_MF);
14400         switch (sc->devinfo.mf_info.mf_mode) {
14401         case MULTI_FUNCTION_SD:
14402             SET_FLAGS(flags, MODE_MF_SD);
14403             break;
14404         case MULTI_FUNCTION_SI:
14405             SET_FLAGS(flags, MODE_MF_SI);
14406             break;
14407         case MULTI_FUNCTION_AFEX:
14408             SET_FLAGS(flags, MODE_MF_AFEX);
14409             break;
14410         }
14411     } else {
14412         SET_FLAGS(flags, MODE_SF);
14413     }
14414 
14415 #if defined(__LITTLE_ENDIAN)
14416     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14417 #else /* __BIG_ENDIAN */
14418     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14419 #endif
14420 
14421     INIT_MODE_FLAGS(sc) = flags;
14422 }
14423 
14424 static int
14425 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14426 {
14427     struct bxe_fastpath *fp;
14428     bus_addr_t busaddr;
14429     int max_agg_queues;
14430     int max_segments;
14431     bus_size_t max_size;
14432     bus_size_t max_seg_size;
14433     char buf[32];
14434     int rc;
14435     int i, j;
14436 
14437     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14438 
14439     /* allocate the parent bus DMA tag */
14440     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14441                             1,                        /* alignment */
14442                             0,                        /* boundary limit */
14443                             BUS_SPACE_MAXADDR,        /* restricted low */
14444                             BUS_SPACE_MAXADDR,        /* restricted hi */
14445                             NULL,                     /* addr filter() */
14446                             NULL,                     /* addr filter() arg */
14447                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14448                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14449                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14450                             0,                        /* flags */
14451                             NULL,                     /* lock() */
14452                             NULL,                     /* lock() arg */
14453                             &sc->parent_dma_tag);     /* returned dma tag */
14454     if (rc != 0) {
14455         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14456         return (1);
14457     }
14458 
14459     /************************/
14460     /* DEFAULT STATUS BLOCK */
14461     /************************/
14462 
14463     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14464                       &sc->def_sb_dma, "default status block") != 0) {
14465         /* XXX */
14466         bus_dma_tag_destroy(sc->parent_dma_tag);
14467         return (1);
14468     }
14469 
14470     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14471 
14472     /***************/
14473     /* EVENT QUEUE */
14474     /***************/
14475 
14476     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14477                       &sc->eq_dma, "event queue") != 0) {
14478         /* XXX */
14479         bxe_dma_free(sc, &sc->def_sb_dma);
14480         sc->def_sb = NULL;
14481         bus_dma_tag_destroy(sc->parent_dma_tag);
14482         return (1);
14483     }
14484 
14485     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14486 
14487     /*************/
14488     /* SLOW PATH */
14489     /*************/
14490 
14491     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14492                       &sc->sp_dma, "slow path") != 0) {
14493         /* XXX */
14494         bxe_dma_free(sc, &sc->eq_dma);
14495         sc->eq = NULL;
14496         bxe_dma_free(sc, &sc->def_sb_dma);
14497         sc->def_sb = NULL;
14498         bus_dma_tag_destroy(sc->parent_dma_tag);
14499         return (1);
14500     }
14501 
14502     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14503 
14504     /*******************/
14505     /* SLOW PATH QUEUE */
14506     /*******************/
14507 
14508     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14509                       &sc->spq_dma, "slow path queue") != 0) {
14510         /* XXX */
14511         bxe_dma_free(sc, &sc->sp_dma);
14512         sc->sp = NULL;
14513         bxe_dma_free(sc, &sc->eq_dma);
14514         sc->eq = NULL;
14515         bxe_dma_free(sc, &sc->def_sb_dma);
14516         sc->def_sb = NULL;
14517         bus_dma_tag_destroy(sc->parent_dma_tag);
14518         return (1);
14519     }
14520 
14521     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14522 
14523     /***************************/
14524     /* FW DECOMPRESSION BUFFER */
14525     /***************************/
14526 
14527     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14528                       "fw decompression buffer") != 0) {
14529         /* XXX */
14530         bxe_dma_free(sc, &sc->spq_dma);
14531         sc->spq = NULL;
14532         bxe_dma_free(sc, &sc->sp_dma);
14533         sc->sp = NULL;
14534         bxe_dma_free(sc, &sc->eq_dma);
14535         sc->eq = NULL;
14536         bxe_dma_free(sc, &sc->def_sb_dma);
14537         sc->def_sb = NULL;
14538         bus_dma_tag_destroy(sc->parent_dma_tag);
14539         return (1);
14540     }
14541 
14542     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14543 
14544     if ((sc->gz_strm =
14545          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14546         /* XXX */
14547         bxe_dma_free(sc, &sc->gz_buf_dma);
14548         sc->gz_buf = NULL;
14549         bxe_dma_free(sc, &sc->spq_dma);
14550         sc->spq = NULL;
14551         bxe_dma_free(sc, &sc->sp_dma);
14552         sc->sp = NULL;
14553         bxe_dma_free(sc, &sc->eq_dma);
14554         sc->eq = NULL;
14555         bxe_dma_free(sc, &sc->def_sb_dma);
14556         sc->def_sb = NULL;
14557         bus_dma_tag_destroy(sc->parent_dma_tag);
14558         return (1);
14559     }
14560 
14561     /*************/
14562     /* FASTPATHS */
14563     /*************/
14564 
14565     /* allocate DMA memory for each fastpath structure */
14566     for (i = 0; i < sc->num_queues; i++) {
14567         fp = &sc->fp[i];
14568         fp->sc    = sc;
14569         fp->index = i;
14570 
14571         /*******************/
14572         /* FP STATUS BLOCK */
14573         /*******************/
14574 
14575         snprintf(buf, sizeof(buf), "fp %d status block", i);
14576         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14577                           &fp->sb_dma, buf) != 0) {
14578             /* XXX unwind and free previous fastpath allocations */
14579             BLOGE(sc, "Failed to alloc %s\n", buf);
14580             return (1);
14581         } else {
14582             if (CHIP_IS_E2E3(sc)) {
14583                 fp->status_block.e2_sb =
14584                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14585             } else {
14586                 fp->status_block.e1x_sb =
14587                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14588             }
14589         }
14590 
14591         /******************/
14592         /* FP TX BD CHAIN */
14593         /******************/
14594 
14595         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14596         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14597                           &fp->tx_dma, buf) != 0) {
14598             /* XXX unwind and free previous fastpath allocations */
14599             BLOGE(sc, "Failed to alloc %s\n", buf);
14600             return (1);
14601         } else {
14602             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14603         }
14604 
14605         /* link together the tx bd chain pages */
14606         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14607             /* index into the tx bd chain array to last entry per page */
14608             struct eth_tx_next_bd *tx_next_bd =
14609                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14610             /* point to the next page and wrap from last page */
14611             busaddr = (fp->tx_dma.paddr +
14612                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14613             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14614             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14615         }
14616 
14617         /******************/
14618         /* FP RX BD CHAIN */
14619         /******************/
14620 
14621         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14622         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14623                           &fp->rx_dma, buf) != 0) {
14624             /* XXX unwind and free previous fastpath allocations */
14625             BLOGE(sc, "Failed to alloc %s\n", buf);
14626             return (1);
14627         } else {
14628             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14629         }
14630 
14631         /* link together the rx bd chain pages */
14632         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14633             /* index into the rx bd chain array to last entry per page */
14634             struct eth_rx_bd *rx_bd =
14635                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14636             /* point to the next page and wrap from last page */
14637             busaddr = (fp->rx_dma.paddr +
14638                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14639             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14640             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14641         }
14642 
14643         /*******************/
14644         /* FP RX RCQ CHAIN */
14645         /*******************/
14646 
14647         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14648         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14649                           &fp->rcq_dma, buf) != 0) {
14650             /* XXX unwind and free previous fastpath allocations */
14651             BLOGE(sc, "Failed to alloc %s\n", buf);
14652             return (1);
14653         } else {
14654             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14655         }
14656 
14657         /* link together the rcq chain pages */
14658         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14659             /* index into the rcq chain array to last entry per page */
14660             struct eth_rx_cqe_next_page *rx_cqe_next =
14661                 (struct eth_rx_cqe_next_page *)
14662                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14663             /* point to the next page and wrap from last page */
14664             busaddr = (fp->rcq_dma.paddr +
14665                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14666             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14667             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14668         }
14669 
14670         /*******************/
14671         /* FP RX SGE CHAIN */
14672         /*******************/
14673 
14674         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14675         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14676                           &fp->rx_sge_dma, buf) != 0) {
14677             /* XXX unwind and free previous fastpath allocations */
14678             BLOGE(sc, "Failed to alloc %s\n", buf);
14679             return (1);
14680         } else {
14681             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14682         }
14683 
14684         /* link together the sge chain pages */
14685         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14686             /* index into the rcq chain array to last entry per page */
14687             struct eth_rx_sge *rx_sge =
14688                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14689             /* point to the next page and wrap from last page */
14690             busaddr = (fp->rx_sge_dma.paddr +
14691                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14692             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14693             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14694         }
14695 
14696         /***********************/
14697         /* FP TX MBUF DMA MAPS */
14698         /***********************/
14699 
14700         /* set required sizes before mapping to conserve resources */
14701         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14702             max_size     = BXE_TSO_MAX_SIZE;
14703             max_segments = BXE_TSO_MAX_SEGMENTS;
14704             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14705         } else {
14706             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14707             max_segments = BXE_MAX_SEGMENTS;
14708             max_seg_size = MCLBYTES;
14709         }
14710 
14711         /* create a dma tag for the tx mbufs */
14712         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14713                                 1,                  /* alignment */
14714                                 0,                  /* boundary limit */
14715                                 BUS_SPACE_MAXADDR,  /* restricted low */
14716                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14717                                 NULL,               /* addr filter() */
14718                                 NULL,               /* addr filter() arg */
14719                                 max_size,           /* max map size */
14720                                 max_segments,       /* num discontinuous */
14721                                 max_seg_size,       /* max seg size */
14722                                 0,                  /* flags */
14723                                 NULL,               /* lock() */
14724                                 NULL,               /* lock() arg */
14725                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14726         if (rc != 0) {
14727             /* XXX unwind and free previous fastpath allocations */
14728             BLOGE(sc, "Failed to create dma tag for "
14729                       "'fp %d tx mbufs' (%d)\n", i, rc);
14730             return (1);
14731         }
14732 
14733         /* create dma maps for each of the tx mbuf clusters */
14734         for (j = 0; j < TX_BD_TOTAL; j++) {
14735             if (bus_dmamap_create(fp->tx_mbuf_tag,
14736                                   BUS_DMA_NOWAIT,
14737                                   &fp->tx_mbuf_chain[j].m_map)) {
14738                 /* XXX unwind and free previous fastpath allocations */
14739                 BLOGE(sc, "Failed to create dma map for "
14740                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14741                 return (1);
14742             }
14743         }
14744 
14745         /***********************/
14746         /* FP RX MBUF DMA MAPS */
14747         /***********************/
14748 
14749         /* create a dma tag for the rx mbufs */
14750         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14751                                 1,                  /* alignment */
14752                                 0,                  /* boundary limit */
14753                                 BUS_SPACE_MAXADDR,  /* restricted low */
14754                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14755                                 NULL,               /* addr filter() */
14756                                 NULL,               /* addr filter() arg */
14757                                 MJUM9BYTES,         /* max map size */
14758                                 1,                  /* num discontinuous */
14759                                 MJUM9BYTES,         /* max seg size */
14760                                 0,                  /* flags */
14761                                 NULL,               /* lock() */
14762                                 NULL,               /* lock() arg */
14763                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14764         if (rc != 0) {
14765             /* XXX unwind and free previous fastpath allocations */
14766             BLOGE(sc, "Failed to create dma tag for "
14767                       "'fp %d rx mbufs' (%d)\n", i, rc);
14768             return (1);
14769         }
14770 
14771         /* create dma maps for each of the rx mbuf clusters */
14772         for (j = 0; j < RX_BD_TOTAL; j++) {
14773             if (bus_dmamap_create(fp->rx_mbuf_tag,
14774                                   BUS_DMA_NOWAIT,
14775                                   &fp->rx_mbuf_chain[j].m_map)) {
14776                 /* XXX unwind and free previous fastpath allocations */
14777                 BLOGE(sc, "Failed to create dma map for "
14778                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14779                 return (1);
14780             }
14781         }
14782 
14783         /* create dma map for the spare rx mbuf cluster */
14784         if (bus_dmamap_create(fp->rx_mbuf_tag,
14785                               BUS_DMA_NOWAIT,
14786                               &fp->rx_mbuf_spare_map)) {
14787             /* XXX unwind and free previous fastpath allocations */
14788             BLOGE(sc, "Failed to create dma map for "
14789                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14790             return (1);
14791         }
14792 
14793         /***************************/
14794         /* FP RX SGE MBUF DMA MAPS */
14795         /***************************/
14796 
14797         /* create a dma tag for the rx sge mbufs */
14798         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14799                                 1,                  /* alignment */
14800                                 0,                  /* boundary limit */
14801                                 BUS_SPACE_MAXADDR,  /* restricted low */
14802                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14803                                 NULL,               /* addr filter() */
14804                                 NULL,               /* addr filter() arg */
14805                                 BCM_PAGE_SIZE,      /* max map size */
14806                                 1,                  /* num discontinuous */
14807                                 BCM_PAGE_SIZE,      /* max seg size */
14808                                 0,                  /* flags */
14809                                 NULL,               /* lock() */
14810                                 NULL,               /* lock() arg */
14811                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14812         if (rc != 0) {
14813             /* XXX unwind and free previous fastpath allocations */
14814             BLOGE(sc, "Failed to create dma tag for "
14815                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14816             return (1);
14817         }
14818 
14819         /* create dma maps for the rx sge mbuf clusters */
14820         for (j = 0; j < RX_SGE_TOTAL; j++) {
14821             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14822                                   BUS_DMA_NOWAIT,
14823                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14824                 /* XXX unwind and free previous fastpath allocations */
14825                 BLOGE(sc, "Failed to create dma map for "
14826                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14827                 return (1);
14828             }
14829         }
14830 
14831         /* create dma map for the spare rx sge mbuf cluster */
14832         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14833                               BUS_DMA_NOWAIT,
14834                               &fp->rx_sge_mbuf_spare_map)) {
14835             /* XXX unwind and free previous fastpath allocations */
14836             BLOGE(sc, "Failed to create dma map for "
14837                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14838             return (1);
14839         }
14840 
14841         /***************************/
14842         /* FP RX TPA MBUF DMA MAPS */
14843         /***************************/
14844 
14845         /* create dma maps for the rx tpa mbuf clusters */
14846         max_agg_queues = MAX_AGG_QS(sc);
14847 
14848         for (j = 0; j < max_agg_queues; j++) {
14849             if (bus_dmamap_create(fp->rx_mbuf_tag,
14850                                   BUS_DMA_NOWAIT,
14851                                   &fp->rx_tpa_info[j].bd.m_map)) {
14852                 /* XXX unwind and free previous fastpath allocations */
14853                 BLOGE(sc, "Failed to create dma map for "
14854                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14855                 return (1);
14856             }
14857         }
14858 
14859         /* create dma map for the spare rx tpa mbuf cluster */
14860         if (bus_dmamap_create(fp->rx_mbuf_tag,
14861                               BUS_DMA_NOWAIT,
14862                               &fp->rx_tpa_info_mbuf_spare_map)) {
14863             /* XXX unwind and free previous fastpath allocations */
14864             BLOGE(sc, "Failed to create dma map for "
14865                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14866             return (1);
14867         }
14868 
14869         bxe_init_sge_ring_bit_mask(fp);
14870     }
14871 
14872     return (0);
14873 }
14874 
14875 static void
14876 bxe_free_hsi_mem(struct bxe_softc *sc)
14877 {
14878     struct bxe_fastpath *fp;
14879     int max_agg_queues;
14880     int i, j;
14881 
14882     if (sc->parent_dma_tag == NULL) {
14883         return; /* assume nothing was allocated */
14884     }
14885 
14886     for (i = 0; i < sc->num_queues; i++) {
14887         fp = &sc->fp[i];
14888 
14889         /*******************/
14890         /* FP STATUS BLOCK */
14891         /*******************/
14892 
14893         bxe_dma_free(sc, &fp->sb_dma);
14894         memset(&fp->status_block, 0, sizeof(fp->status_block));
14895 
14896         /******************/
14897         /* FP TX BD CHAIN */
14898         /******************/
14899 
14900         bxe_dma_free(sc, &fp->tx_dma);
14901         fp->tx_chain = NULL;
14902 
14903         /******************/
14904         /* FP RX BD CHAIN */
14905         /******************/
14906 
14907         bxe_dma_free(sc, &fp->rx_dma);
14908         fp->rx_chain = NULL;
14909 
14910         /*******************/
14911         /* FP RX RCQ CHAIN */
14912         /*******************/
14913 
14914         bxe_dma_free(sc, &fp->rcq_dma);
14915         fp->rcq_chain = NULL;
14916 
14917         /*******************/
14918         /* FP RX SGE CHAIN */
14919         /*******************/
14920 
14921         bxe_dma_free(sc, &fp->rx_sge_dma);
14922         fp->rx_sge_chain = NULL;
14923 
14924         /***********************/
14925         /* FP TX MBUF DMA MAPS */
14926         /***********************/
14927 
14928         if (fp->tx_mbuf_tag != NULL) {
14929             for (j = 0; j < TX_BD_TOTAL; j++) {
14930                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14931                     bus_dmamap_unload(fp->tx_mbuf_tag,
14932                                       fp->tx_mbuf_chain[j].m_map);
14933                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14934                                        fp->tx_mbuf_chain[j].m_map);
14935                 }
14936             }
14937 
14938             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14939             fp->tx_mbuf_tag = NULL;
14940         }
14941 
14942         /***********************/
14943         /* FP RX MBUF DMA MAPS */
14944         /***********************/
14945 
14946         if (fp->rx_mbuf_tag != NULL) {
14947             for (j = 0; j < RX_BD_TOTAL; j++) {
14948                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14949                     bus_dmamap_unload(fp->rx_mbuf_tag,
14950                                       fp->rx_mbuf_chain[j].m_map);
14951                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14952                                        fp->rx_mbuf_chain[j].m_map);
14953                 }
14954             }
14955 
14956             if (fp->rx_mbuf_spare_map != NULL) {
14957                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14958                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14959             }
14960 
14961             /***************************/
14962             /* FP RX TPA MBUF DMA MAPS */
14963             /***************************/
14964 
14965             max_agg_queues = MAX_AGG_QS(sc);
14966 
14967             for (j = 0; j < max_agg_queues; j++) {
14968                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14969                     bus_dmamap_unload(fp->rx_mbuf_tag,
14970                                       fp->rx_tpa_info[j].bd.m_map);
14971                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14972                                        fp->rx_tpa_info[j].bd.m_map);
14973                 }
14974             }
14975 
14976             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14977                 bus_dmamap_unload(fp->rx_mbuf_tag,
14978                                   fp->rx_tpa_info_mbuf_spare_map);
14979                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14980                                    fp->rx_tpa_info_mbuf_spare_map);
14981             }
14982 
14983             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14984             fp->rx_mbuf_tag = NULL;
14985         }
14986 
14987         /***************************/
14988         /* FP RX SGE MBUF DMA MAPS */
14989         /***************************/
14990 
14991         if (fp->rx_sge_mbuf_tag != NULL) {
14992             for (j = 0; j < RX_SGE_TOTAL; j++) {
14993                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14994                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14995                                       fp->rx_sge_mbuf_chain[j].m_map);
14996                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14997                                        fp->rx_sge_mbuf_chain[j].m_map);
14998                 }
14999             }
15000 
15001             if (fp->rx_sge_mbuf_spare_map != NULL) {
15002                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15003                                   fp->rx_sge_mbuf_spare_map);
15004                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15005                                    fp->rx_sge_mbuf_spare_map);
15006             }
15007 
15008             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15009             fp->rx_sge_mbuf_tag = NULL;
15010         }
15011     }
15012 
15013     /***************************/
15014     /* FW DECOMPRESSION BUFFER */
15015     /***************************/
15016 
15017     bxe_dma_free(sc, &sc->gz_buf_dma);
15018     sc->gz_buf = NULL;
15019     free(sc->gz_strm, M_DEVBUF);
15020     sc->gz_strm = NULL;
15021 
15022     /*******************/
15023     /* SLOW PATH QUEUE */
15024     /*******************/
15025 
15026     bxe_dma_free(sc, &sc->spq_dma);
15027     sc->spq = NULL;
15028 
15029     /*************/
15030     /* SLOW PATH */
15031     /*************/
15032 
15033     bxe_dma_free(sc, &sc->sp_dma);
15034     sc->sp = NULL;
15035 
15036     /***************/
15037     /* EVENT QUEUE */
15038     /***************/
15039 
15040     bxe_dma_free(sc, &sc->eq_dma);
15041     sc->eq = NULL;
15042 
15043     /************************/
15044     /* DEFAULT STATUS BLOCK */
15045     /************************/
15046 
15047     bxe_dma_free(sc, &sc->def_sb_dma);
15048     sc->def_sb = NULL;
15049 
15050     bus_dma_tag_destroy(sc->parent_dma_tag);
15051     sc->parent_dma_tag = NULL;
15052 }
15053 
15054 /*
15055  * Previous driver DMAE transaction may have occurred when pre-boot stage
15056  * ended and boot began. This would invalidate the addresses of the
15057  * transaction, resulting in was-error bit set in the PCI causing all
15058  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15059  * the interrupt which detected this from the pglueb and the was-done bit
15060  */
15061 static void
15062 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15063 {
15064     uint32_t val;
15065 
15066     if (!CHIP_IS_E1x(sc)) {
15067         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15068         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15069             BLOGD(sc, DBG_LOAD,
15070                   "Clearing 'was-error' bit that was set in pglueb");
15071             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15072         }
15073     }
15074 }
15075 
15076 static int
15077 bxe_prev_mcp_done(struct bxe_softc *sc)
15078 {
15079     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15080                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15081     if (!rc) {
15082         BLOGE(sc, "MCP response failure, aborting\n");
15083         return (-1);
15084     }
15085 
15086     return (0);
15087 }
15088 
15089 static struct bxe_prev_list_node *
15090 bxe_prev_path_get_entry(struct bxe_softc *sc)
15091 {
15092     struct bxe_prev_list_node *tmp;
15093 
15094     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15095         if ((sc->pcie_bus == tmp->bus) &&
15096             (sc->pcie_device == tmp->slot) &&
15097             (SC_PATH(sc) == tmp->path)) {
15098             return (tmp);
15099         }
15100     }
15101 
15102     return (NULL);
15103 }
15104 
15105 static uint8_t
15106 bxe_prev_is_path_marked(struct bxe_softc *sc)
15107 {
15108     struct bxe_prev_list_node *tmp;
15109     int rc = FALSE;
15110 
15111     mtx_lock(&bxe_prev_mtx);
15112 
15113     tmp = bxe_prev_path_get_entry(sc);
15114     if (tmp) {
15115         if (tmp->aer) {
15116             BLOGD(sc, DBG_LOAD,
15117                   "Path %d/%d/%d was marked by AER\n",
15118                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15119         } else {
15120             rc = TRUE;
15121             BLOGD(sc, DBG_LOAD,
15122                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15123                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15124         }
15125     }
15126 
15127     mtx_unlock(&bxe_prev_mtx);
15128 
15129     return (rc);
15130 }
15131 
15132 static int
15133 bxe_prev_mark_path(struct bxe_softc *sc,
15134                    uint8_t          after_undi)
15135 {
15136     struct bxe_prev_list_node *tmp;
15137 
15138     mtx_lock(&bxe_prev_mtx);
15139 
15140     /* Check whether the entry for this path already exists */
15141     tmp = bxe_prev_path_get_entry(sc);
15142     if (tmp) {
15143         if (!tmp->aer) {
15144             BLOGD(sc, DBG_LOAD,
15145                   "Re-marking AER in path %d/%d/%d\n",
15146                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15147         } else {
15148             BLOGD(sc, DBG_LOAD,
15149                   "Removing AER indication from path %d/%d/%d\n",
15150                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15151             tmp->aer = 0;
15152         }
15153 
15154         mtx_unlock(&bxe_prev_mtx);
15155         return (0);
15156     }
15157 
15158     mtx_unlock(&bxe_prev_mtx);
15159 
15160     /* Create an entry for this path and add it */
15161     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15162                  (M_NOWAIT | M_ZERO));
15163     if (!tmp) {
15164         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15165         return (-1);
15166     }
15167 
15168     tmp->bus  = sc->pcie_bus;
15169     tmp->slot = sc->pcie_device;
15170     tmp->path = SC_PATH(sc);
15171     tmp->aer  = 0;
15172     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15173 
15174     mtx_lock(&bxe_prev_mtx);
15175 
15176     BLOGD(sc, DBG_LOAD,
15177           "Marked path %d/%d/%d - finished previous unload\n",
15178           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15179     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15180 
15181     mtx_unlock(&bxe_prev_mtx);
15182 
15183     return (0);
15184 }
15185 
15186 static int
15187 bxe_do_flr(struct bxe_softc *sc)
15188 {
15189     int i;
15190 
15191     /* only E2 and onwards support FLR */
15192     if (CHIP_IS_E1x(sc)) {
15193         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15194         return (-1);
15195     }
15196 
15197     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15198     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15199         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15200               sc->devinfo.bc_ver);
15201         return (-1);
15202     }
15203 
15204     /* Wait for Transaction Pending bit clean */
15205     for (i = 0; i < 4; i++) {
15206         if (i) {
15207             DELAY(((1 << (i - 1)) * 100) * 1000);
15208         }
15209 
15210         if (!bxe_is_pcie_pending(sc)) {
15211             goto clear;
15212         }
15213     }
15214 
15215     BLOGE(sc, "PCIE transaction is not cleared, "
15216               "proceeding with reset anyway\n");
15217 
15218 clear:
15219 
15220     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15221     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15222 
15223     return (0);
15224 }
15225 
15226 struct bxe_mac_vals {
15227     uint32_t xmac_addr;
15228     uint32_t xmac_val;
15229     uint32_t emac_addr;
15230     uint32_t emac_val;
15231     uint32_t umac_addr;
15232     uint32_t umac_val;
15233     uint32_t bmac_addr;
15234     uint32_t bmac_val[2];
15235 };
15236 
15237 static void
15238 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15239                           struct bxe_mac_vals *vals)
15240 {
15241     uint32_t val, base_addr, offset, mask, reset_reg;
15242     uint8_t mac_stopped = FALSE;
15243     uint8_t port = SC_PORT(sc);
15244     uint32_t wb_data[2];
15245 
15246     /* reset addresses as they also mark which values were changed */
15247     vals->bmac_addr = 0;
15248     vals->umac_addr = 0;
15249     vals->xmac_addr = 0;
15250     vals->emac_addr = 0;
15251 
15252     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15253 
15254     if (!CHIP_IS_E3(sc)) {
15255         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15256         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15257         if ((mask & reset_reg) && val) {
15258             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15259             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15260                                     : NIG_REG_INGRESS_BMAC0_MEM;
15261             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15262                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15263 
15264             /*
15265              * use rd/wr since we cannot use dmae. This is safe
15266              * since MCP won't access the bus due to the request
15267              * to unload, and no function on the path can be
15268              * loaded at this time.
15269              */
15270             wb_data[0] = REG_RD(sc, base_addr + offset);
15271             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15272             vals->bmac_addr = base_addr + offset;
15273             vals->bmac_val[0] = wb_data[0];
15274             vals->bmac_val[1] = wb_data[1];
15275             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15276             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15277             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15278         }
15279 
15280         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15281         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15282         vals->emac_val = REG_RD(sc, vals->emac_addr);
15283         REG_WR(sc, vals->emac_addr, 0);
15284         mac_stopped = TRUE;
15285     } else {
15286         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15287             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15288             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15289             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15290             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15291             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15292             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15293             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15294             REG_WR(sc, vals->xmac_addr, 0);
15295             mac_stopped = TRUE;
15296         }
15297 
15298         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15299         if (mask & reset_reg) {
15300             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15301             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15302             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15303             vals->umac_val = REG_RD(sc, vals->umac_addr);
15304             REG_WR(sc, vals->umac_addr, 0);
15305             mac_stopped = TRUE;
15306         }
15307     }
15308 
15309     if (mac_stopped) {
15310         DELAY(20000);
15311     }
15312 }
15313 
15314 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15315 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15316 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15317 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15318 
15319 static void
15320 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15321                          uint8_t          port,
15322                          uint8_t          inc)
15323 {
15324     uint16_t rcq, bd;
15325     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15326 
15327     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15328     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15329 
15330     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15331     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15332 
15333     BLOGD(sc, DBG_LOAD,
15334           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15335           port, bd, rcq);
15336 }
15337 
15338 static int
15339 bxe_prev_unload_common(struct bxe_softc *sc)
15340 {
15341     uint32_t reset_reg, tmp_reg = 0, rc;
15342     uint8_t prev_undi = FALSE;
15343     struct bxe_mac_vals mac_vals;
15344     uint32_t timer_count = 1000;
15345     uint32_t prev_brb;
15346 
15347     /*
15348      * It is possible a previous function received 'common' answer,
15349      * but hasn't loaded yet, therefore creating a scenario of
15350      * multiple functions receiving 'common' on the same path.
15351      */
15352     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15353 
15354     memset(&mac_vals, 0, sizeof(mac_vals));
15355 
15356     if (bxe_prev_is_path_marked(sc)) {
15357         return (bxe_prev_mcp_done(sc));
15358     }
15359 
15360     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15361 
15362     /* Reset should be performed after BRB is emptied */
15363     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15364         /* Close the MAC Rx to prevent BRB from filling up */
15365         bxe_prev_unload_close_mac(sc, &mac_vals);
15366 
15367         /* close LLH filters towards the BRB */
15368         elink_set_rx_filter(&sc->link_params, 0);
15369 
15370         /*
15371          * Check if the UNDI driver was previously loaded.
15372          * UNDI driver initializes CID offset for normal bell to 0x7
15373          */
15374         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15375             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15376             if (tmp_reg == 0x7) {
15377                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15378                 prev_undi = TRUE;
15379                 /* clear the UNDI indication */
15380                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15381                 /* clear possible idle check errors */
15382                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15383             }
15384         }
15385 
15386         /* wait until BRB is empty */
15387         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15388         while (timer_count) {
15389             prev_brb = tmp_reg;
15390 
15391             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15392             if (!tmp_reg) {
15393                 break;
15394             }
15395 
15396             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15397 
15398             /* reset timer as long as BRB actually gets emptied */
15399             if (prev_brb > tmp_reg) {
15400                 timer_count = 1000;
15401             } else {
15402                 timer_count--;
15403             }
15404 
15405             /* If UNDI resides in memory, manually increment it */
15406             if (prev_undi) {
15407                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15408             }
15409 
15410             DELAY(10);
15411         }
15412 
15413         if (!timer_count) {
15414             BLOGE(sc, "Failed to empty BRB\n");
15415         }
15416     }
15417 
15418     /* No packets are in the pipeline, path is ready for reset */
15419     bxe_reset_common(sc);
15420 
15421     if (mac_vals.xmac_addr) {
15422         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15423     }
15424     if (mac_vals.umac_addr) {
15425         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15426     }
15427     if (mac_vals.emac_addr) {
15428         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15429     }
15430     if (mac_vals.bmac_addr) {
15431         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15432         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15433     }
15434 
15435     rc = bxe_prev_mark_path(sc, prev_undi);
15436     if (rc) {
15437         bxe_prev_mcp_done(sc);
15438         return (rc);
15439     }
15440 
15441     return (bxe_prev_mcp_done(sc));
15442 }
15443 
15444 static int
15445 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15446 {
15447     int rc;
15448 
15449     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15450 
15451     /* Test if previous unload process was already finished for this path */
15452     if (bxe_prev_is_path_marked(sc)) {
15453         return (bxe_prev_mcp_done(sc));
15454     }
15455 
15456     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15457 
15458     /*
15459      * If function has FLR capabilities, and existing FW version matches
15460      * the one required, then FLR will be sufficient to clean any residue
15461      * left by previous driver
15462      */
15463     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15464     if (!rc) {
15465         /* fw version is good */
15466         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15467         rc = bxe_do_flr(sc);
15468     }
15469 
15470     if (!rc) {
15471         /* FLR was performed */
15472         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15473         return (0);
15474     }
15475 
15476     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15477 
15478     /* Close the MCP request, return failure*/
15479     rc = bxe_prev_mcp_done(sc);
15480     if (!rc) {
15481         rc = BXE_PREV_WAIT_NEEDED;
15482     }
15483 
15484     return (rc);
15485 }
15486 
15487 static int
15488 bxe_prev_unload(struct bxe_softc *sc)
15489 {
15490     int time_counter = 10;
15491     uint32_t fw, hw_lock_reg, hw_lock_val;
15492     uint32_t rc = 0;
15493 
15494     /*
15495      * Clear HW from errors which may have resulted from an interrupted
15496      * DMAE transaction.
15497      */
15498     bxe_prev_interrupted_dmae(sc);
15499 
15500     /* Release previously held locks */
15501     hw_lock_reg =
15502         (SC_FUNC(sc) <= 5) ?
15503             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15504             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15505 
15506     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15507     if (hw_lock_val) {
15508         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15509             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15510             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15511                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15512         }
15513         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15514         REG_WR(sc, hw_lock_reg, 0xffffffff);
15515     } else {
15516         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15517     }
15518 
15519     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15520         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15521         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15522     }
15523 
15524     do {
15525         /* Lock MCP using an unload request */
15526         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15527         if (!fw) {
15528             BLOGE(sc, "MCP response failure, aborting\n");
15529             rc = -1;
15530             break;
15531         }
15532 
15533         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15534             rc = bxe_prev_unload_common(sc);
15535             break;
15536         }
15537 
15538         /* non-common reply from MCP night require looping */
15539         rc = bxe_prev_unload_uncommon(sc);
15540         if (rc != BXE_PREV_WAIT_NEEDED) {
15541             break;
15542         }
15543 
15544         DELAY(20000);
15545     } while (--time_counter);
15546 
15547     if (!time_counter || rc) {
15548         BLOGE(sc, "Failed to unload previous driver!"
15549             " time_counter %d rc %d\n", time_counter, rc);
15550         rc = -1;
15551     }
15552 
15553     return (rc);
15554 }
15555 
15556 void
15557 bxe_dcbx_set_state(struct bxe_softc *sc,
15558                    uint8_t          dcb_on,
15559                    uint32_t         dcbx_enabled)
15560 {
15561     if (!CHIP_IS_E1x(sc)) {
15562         sc->dcb_state = dcb_on;
15563         sc->dcbx_enabled = dcbx_enabled;
15564     } else {
15565         sc->dcb_state = FALSE;
15566         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15567     }
15568     BLOGD(sc, DBG_LOAD,
15569           "DCB state [%s:%s]\n",
15570           dcb_on ? "ON" : "OFF",
15571           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15572           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15573           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15574           "on-chip with negotiation" : "invalid");
15575 }
15576 
15577 /* must be called after sriov-enable */
15578 static int
15579 bxe_set_qm_cid_count(struct bxe_softc *sc)
15580 {
15581     int cid_count = BXE_L2_MAX_CID(sc);
15582 
15583     if (IS_SRIOV(sc)) {
15584         cid_count += BXE_VF_CIDS;
15585     }
15586 
15587     if (CNIC_SUPPORT(sc)) {
15588         cid_count += CNIC_CID_MAX;
15589     }
15590 
15591     return (roundup(cid_count, QM_CID_ROUND));
15592 }
15593 
15594 static void
15595 bxe_init_multi_cos(struct bxe_softc *sc)
15596 {
15597     int pri, cos;
15598 
15599     uint32_t pri_map = 0; /* XXX change to user config */
15600 
15601     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15602         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15603         if (cos < sc->max_cos) {
15604             sc->prio_to_cos[pri] = cos;
15605         } else {
15606             BLOGW(sc, "Invalid COS %d for priority %d "
15607                       "(max COS is %d), setting to 0\n",
15608                   cos, pri, (sc->max_cos - 1));
15609             sc->prio_to_cos[pri] = 0;
15610         }
15611     }
15612 }
15613 
15614 static int
15615 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15616 {
15617     struct bxe_softc *sc;
15618     int error, result;
15619 
15620     result = 0;
15621     error = sysctl_handle_int(oidp, &result, 0, req);
15622 
15623     if (error || !req->newptr) {
15624         return (error);
15625     }
15626 
15627     if (result == 1) {
15628         uint32_t  temp;
15629         sc = (struct bxe_softc *)arg1;
15630 
15631         BLOGI(sc, "... dumping driver state ...\n");
15632         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15633         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15634     }
15635 
15636     return (error);
15637 }
15638 
15639 static int
15640 bxe_sysctl_trigger_grcdump(SYSCTL_HANDLER_ARGS)
15641 {
15642     struct bxe_softc *sc;
15643     int error, result;
15644 
15645     result = 0;
15646     error = sysctl_handle_int(oidp, &result, 0, req);
15647 
15648     if (error || !req->newptr) {
15649         return (error);
15650     }
15651 
15652     if (result == 1) {
15653         sc = (struct bxe_softc *)arg1;
15654 
15655         BLOGI(sc, "... grcdump start ...\n");
15656         bxe_grc_dump(sc);
15657         BLOGI(sc, "... grcdump done ...\n");
15658     }
15659 
15660     return (error);
15661 }
15662 
15663 static int
15664 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15665 {
15666     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15667     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15668     uint32_t *offset;
15669     uint64_t value = 0;
15670     int index = (int)arg2;
15671 
15672     if (index >= BXE_NUM_ETH_STATS) {
15673         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15674         return (-1);
15675     }
15676 
15677     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15678 
15679     switch (bxe_eth_stats_arr[index].size) {
15680     case 4:
15681         value = (uint64_t)*offset;
15682         break;
15683     case 8:
15684         value = HILO_U64(*offset, *(offset + 1));
15685         break;
15686     default:
15687         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15688               index, bxe_eth_stats_arr[index].size);
15689         return (-1);
15690     }
15691 
15692     return (sysctl_handle_64(oidp, &value, 0, req));
15693 }
15694 
15695 static int
15696 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15697 {
15698     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15699     uint32_t *eth_stats;
15700     uint32_t *offset;
15701     uint64_t value = 0;
15702     uint32_t q_stat = (uint32_t)arg2;
15703     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15704     uint32_t index = (q_stat & 0xffff);
15705 
15706     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15707 
15708     if (index >= BXE_NUM_ETH_Q_STATS) {
15709         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15710         return (-1);
15711     }
15712 
15713     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15714 
15715     switch (bxe_eth_q_stats_arr[index].size) {
15716     case 4:
15717         value = (uint64_t)*offset;
15718         break;
15719     case 8:
15720         value = HILO_U64(*offset, *(offset + 1));
15721         break;
15722     default:
15723         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15724               index, bxe_eth_q_stats_arr[index].size);
15725         return (-1);
15726     }
15727 
15728     return (sysctl_handle_64(oidp, &value, 0, req));
15729 }
15730 
15731 static void
15732 bxe_add_sysctls(struct bxe_softc *sc)
15733 {
15734     struct sysctl_ctx_list *ctx;
15735     struct sysctl_oid_list *children;
15736     struct sysctl_oid *queue_top, *queue;
15737     struct sysctl_oid_list *queue_top_children, *queue_children;
15738     char queue_num_buf[32];
15739     uint32_t q_stat;
15740     int i, j;
15741 
15742     ctx = device_get_sysctl_ctx(sc->dev);
15743     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15744 
15745     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15746                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15747                       "version");
15748 
15749     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15750              BCM_5710_FW_MAJOR_VERSION,
15751              BCM_5710_FW_MINOR_VERSION,
15752              BCM_5710_FW_REVISION_VERSION,
15753              BCM_5710_FW_ENGINEERING_VERSION);
15754 
15755     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15756         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15757          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15758          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15759          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15760                                                                 "Unknown"));
15761     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15762                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15763                     "multifunction vnics per port");
15764 
15765     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15766         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15767          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15768          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15769                                               "???GT/s"),
15770         sc->devinfo.pcie_link_width);
15771 
15772     sc->debug = bxe_debug;
15773 
15774 #if __FreeBSD_version >= 900000
15775     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15776                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15777                       "bootcode version");
15778     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15779                       CTLFLAG_RD, sc->fw_ver_str, 0,
15780                       "firmware version");
15781     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15782                       CTLFLAG_RD, sc->mf_mode_str, 0,
15783                       "multifunction mode");
15784     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15785                       CTLFLAG_RD, sc->mac_addr_str, 0,
15786                       "mac address");
15787     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15788                       CTLFLAG_RD, sc->pci_link_str, 0,
15789                       "pci link status");
15790     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15791                     CTLFLAG_RW, &sc->debug,
15792                     "debug logging mode");
15793 #else
15794     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15795                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15796                       "bootcode version");
15797     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15798                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15799                       "firmware version");
15800     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15801                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15802                       "multifunction mode");
15803     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15804                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15805                       "mac address");
15806     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15807                       CTLFLAG_RD, &sc->pci_link_str, 0,
15808                       "pci link status");
15809     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15810                     CTLFLAG_RW, &sc->debug, 0,
15811                     "debug logging mode");
15812 #endif /* #if __FreeBSD_version >= 900000 */
15813 
15814     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "trigger_grcdump",
15815                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15816                     bxe_sysctl_trigger_grcdump, "IU",
15817                     "set by driver when a grcdump is needed");
15818 
15819     sc->grcdump_done = 0;
15820     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15821                    CTLFLAG_RW, &sc->grcdump_done, 0,
15822                    "set by driver when grcdump is done");
15823 
15824     sc->rx_budget = bxe_rx_budget;
15825     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15826                     CTLFLAG_RW, &sc->rx_budget, 0,
15827                     "rx processing budget");
15828 
15829     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15830                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15831                     bxe_sysctl_state, "IU", "dump driver state");
15832 
15833     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15834         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15835                         bxe_eth_stats_arr[i].string,
15836                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15837                         bxe_sysctl_eth_stat, "LU",
15838                         bxe_eth_stats_arr[i].string);
15839     }
15840 
15841     /* add a new parent node for all queues "dev.bxe.#.queue" */
15842     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15843                                 CTLFLAG_RD, NULL, "queue");
15844     queue_top_children = SYSCTL_CHILDREN(queue_top);
15845 
15846     for (i = 0; i < sc->num_queues; i++) {
15847         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15848         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15849         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15850                                 queue_num_buf, CTLFLAG_RD, NULL,
15851                                 "single queue");
15852         queue_children = SYSCTL_CHILDREN(queue);
15853 
15854         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15855             q_stat = ((i << 16) | j);
15856             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15857                             bxe_eth_q_stats_arr[j].string,
15858                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15859                             bxe_sysctl_eth_q_stat, "LU",
15860                             bxe_eth_q_stats_arr[j].string);
15861         }
15862     }
15863 }
15864 
15865 static int
15866 bxe_alloc_buf_rings(struct bxe_softc *sc)
15867 {
15868 #if __FreeBSD_version >= 800000
15869 
15870     int i;
15871     struct bxe_fastpath *fp;
15872 
15873     for (i = 0; i < sc->num_queues; i++) {
15874 
15875         fp = &sc->fp[i];
15876 
15877         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15878                                    M_NOWAIT, &fp->tx_mtx);
15879         if (fp->tx_br == NULL)
15880             return (-1);
15881     }
15882 #endif
15883     return (0);
15884 }
15885 
15886 static void
15887 bxe_free_buf_rings(struct bxe_softc *sc)
15888 {
15889 #if __FreeBSD_version >= 800000
15890 
15891     int i;
15892     struct bxe_fastpath *fp;
15893 
15894     for (i = 0; i < sc->num_queues; i++) {
15895 
15896         fp = &sc->fp[i];
15897 
15898         if (fp->tx_br) {
15899             buf_ring_free(fp->tx_br, M_DEVBUF);
15900             fp->tx_br = NULL;
15901         }
15902     }
15903 
15904 #endif
15905 }
15906 
15907 static void
15908 bxe_init_fp_mutexs(struct bxe_softc *sc)
15909 {
15910     int i;
15911     struct bxe_fastpath *fp;
15912 
15913     for (i = 0; i < sc->num_queues; i++) {
15914 
15915         fp = &sc->fp[i];
15916 
15917         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15918             "bxe%d_fp%d_tx_lock", sc->unit, i);
15919         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15920 
15921         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15922             "bxe%d_fp%d_rx_lock", sc->unit, i);
15923         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15924     }
15925 }
15926 
15927 static void
15928 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15929 {
15930     int i;
15931     struct bxe_fastpath *fp;
15932 
15933     for (i = 0; i < sc->num_queues; i++) {
15934 
15935         fp = &sc->fp[i];
15936 
15937         if (mtx_initialized(&fp->tx_mtx)) {
15938             mtx_destroy(&fp->tx_mtx);
15939         }
15940 
15941         if (mtx_initialized(&fp->rx_mtx)) {
15942             mtx_destroy(&fp->rx_mtx);
15943         }
15944     }
15945 }
15946 
15947 
15948 /*
15949  * Device attach function.
15950  *
15951  * Allocates device resources, performs secondary chip identification, and
15952  * initializes driver instance variables. This function is called from driver
15953  * load after a successful probe.
15954  *
15955  * Returns:
15956  *   0 = Success, >0 = Failure
15957  */
15958 static int
15959 bxe_attach(device_t dev)
15960 {
15961     struct bxe_softc *sc;
15962 
15963     sc = device_get_softc(dev);
15964 
15965     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15966 
15967     sc->state = BXE_STATE_CLOSED;
15968 
15969     sc->dev  = dev;
15970     sc->unit = device_get_unit(dev);
15971 
15972     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15973 
15974     sc->pcie_bus    = pci_get_bus(dev);
15975     sc->pcie_device = pci_get_slot(dev);
15976     sc->pcie_func   = pci_get_function(dev);
15977 
15978     /* enable bus master capability */
15979     pci_enable_busmaster(dev);
15980 
15981     /* get the BARs */
15982     if (bxe_allocate_bars(sc) != 0) {
15983         return (ENXIO);
15984     }
15985 
15986     /* initialize the mutexes */
15987     bxe_init_mutexes(sc);
15988 
15989     /* prepare the periodic callout */
15990     callout_init(&sc->periodic_callout, 0);
15991 
15992     /* prepare the chip taskqueue */
15993     sc->chip_tq_flags = CHIP_TQ_NONE;
15994     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15995              "bxe%d_chip_tq", sc->unit);
15996     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15997     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15998                                    taskqueue_thread_enqueue,
15999                                    &sc->chip_tq);
16000     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16001                             "%s", sc->chip_tq_name);
16002 
16003     /* get device info and set params */
16004     if (bxe_get_device_info(sc) != 0) {
16005         BLOGE(sc, "getting device info\n");
16006         bxe_deallocate_bars(sc);
16007         pci_disable_busmaster(dev);
16008         return (ENXIO);
16009     }
16010 
16011     /* get final misc params */
16012     bxe_get_params(sc);
16013 
16014     /* set the default MTU (changed via ifconfig) */
16015     sc->mtu = ETHERMTU;
16016 
16017     bxe_set_modes_bitmap(sc);
16018 
16019     /* XXX
16020      * If in AFEX mode and the function is configured for FCoE
16021      * then bail... no L2 allowed.
16022      */
16023 
16024     /* get phy settings from shmem and 'and' against admin settings */
16025     bxe_get_phy_info(sc);
16026 
16027     /* initialize the FreeBSD ifnet interface */
16028     if (bxe_init_ifnet(sc) != 0) {
16029         bxe_release_mutexes(sc);
16030         bxe_deallocate_bars(sc);
16031         pci_disable_busmaster(dev);
16032         return (ENXIO);
16033     }
16034 
16035     if (bxe_add_cdev(sc) != 0) {
16036         if (sc->ifp != NULL) {
16037             ether_ifdetach(sc->ifp);
16038         }
16039         ifmedia_removeall(&sc->ifmedia);
16040         bxe_release_mutexes(sc);
16041         bxe_deallocate_bars(sc);
16042         pci_disable_busmaster(dev);
16043         return (ENXIO);
16044     }
16045 
16046     /* allocate device interrupts */
16047     if (bxe_interrupt_alloc(sc) != 0) {
16048         bxe_del_cdev(sc);
16049         if (sc->ifp != NULL) {
16050             ether_ifdetach(sc->ifp);
16051         }
16052         ifmedia_removeall(&sc->ifmedia);
16053         bxe_release_mutexes(sc);
16054         bxe_deallocate_bars(sc);
16055         pci_disable_busmaster(dev);
16056         return (ENXIO);
16057     }
16058 
16059     bxe_init_fp_mutexs(sc);
16060 
16061     if (bxe_alloc_buf_rings(sc) != 0) {
16062 	bxe_free_buf_rings(sc);
16063         bxe_interrupt_free(sc);
16064         bxe_del_cdev(sc);
16065         if (sc->ifp != NULL) {
16066             ether_ifdetach(sc->ifp);
16067         }
16068         ifmedia_removeall(&sc->ifmedia);
16069         bxe_release_mutexes(sc);
16070         bxe_deallocate_bars(sc);
16071         pci_disable_busmaster(dev);
16072         return (ENXIO);
16073     }
16074 
16075     /* allocate ilt */
16076     if (bxe_alloc_ilt_mem(sc) != 0) {
16077 	bxe_free_buf_rings(sc);
16078         bxe_interrupt_free(sc);
16079         bxe_del_cdev(sc);
16080         if (sc->ifp != NULL) {
16081             ether_ifdetach(sc->ifp);
16082         }
16083         ifmedia_removeall(&sc->ifmedia);
16084         bxe_release_mutexes(sc);
16085         bxe_deallocate_bars(sc);
16086         pci_disable_busmaster(dev);
16087         return (ENXIO);
16088     }
16089 
16090     /* allocate the host hardware/software hsi structures */
16091     if (bxe_alloc_hsi_mem(sc) != 0) {
16092         bxe_free_ilt_mem(sc);
16093 	bxe_free_buf_rings(sc);
16094         bxe_interrupt_free(sc);
16095         bxe_del_cdev(sc);
16096         if (sc->ifp != NULL) {
16097             ether_ifdetach(sc->ifp);
16098         }
16099         ifmedia_removeall(&sc->ifmedia);
16100         bxe_release_mutexes(sc);
16101         bxe_deallocate_bars(sc);
16102         pci_disable_busmaster(dev);
16103         return (ENXIO);
16104     }
16105 
16106     /* need to reset chip if UNDI was active */
16107     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16108         /* init fw_seq */
16109         sc->fw_seq =
16110             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16111              DRV_MSG_SEQ_NUMBER_MASK);
16112         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16113         bxe_prev_unload(sc);
16114     }
16115 
16116 #if 1
16117     /* XXX */
16118     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16119 #else
16120     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16121         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16122         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16123         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16124         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16125         bxe_dcbx_init_params(sc);
16126     } else {
16127         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16128     }
16129 #endif
16130 
16131     /* calculate qm_cid_count */
16132     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16133     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16134 
16135     sc->max_cos = 1;
16136     bxe_init_multi_cos(sc);
16137 
16138     bxe_add_sysctls(sc);
16139 
16140     return (0);
16141 }
16142 
16143 /*
16144  * Device detach function.
16145  *
16146  * Stops the controller, resets the controller, and releases resources.
16147  *
16148  * Returns:
16149  *   0 = Success, >0 = Failure
16150  */
16151 static int
16152 bxe_detach(device_t dev)
16153 {
16154     struct bxe_softc *sc;
16155     if_t ifp;
16156 
16157     sc = device_get_softc(dev);
16158 
16159     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16160 
16161     ifp = sc->ifp;
16162     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16163         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16164         return(EBUSY);
16165     }
16166 
16167     bxe_del_cdev(sc);
16168 
16169     /* stop the periodic callout */
16170     bxe_periodic_stop(sc);
16171 
16172     /* stop the chip taskqueue */
16173     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16174     if (sc->chip_tq) {
16175         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16176         taskqueue_free(sc->chip_tq);
16177         sc->chip_tq = NULL;
16178     }
16179 
16180     /* stop and reset the controller if it was open */
16181     if (sc->state != BXE_STATE_CLOSED) {
16182         BXE_CORE_LOCK(sc);
16183         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16184         sc->state = BXE_STATE_DISABLED;
16185         BXE_CORE_UNLOCK(sc);
16186     }
16187 
16188     /* release the network interface */
16189     if (ifp != NULL) {
16190         ether_ifdetach(ifp);
16191     }
16192     ifmedia_removeall(&sc->ifmedia);
16193 
16194     /* XXX do the following based on driver state... */
16195 
16196     /* free the host hardware/software hsi structures */
16197     bxe_free_hsi_mem(sc);
16198 
16199     /* free ilt */
16200     bxe_free_ilt_mem(sc);
16201 
16202     bxe_free_buf_rings(sc);
16203 
16204     /* release the interrupts */
16205     bxe_interrupt_free(sc);
16206 
16207     /* Release the mutexes*/
16208     bxe_destroy_fp_mutexs(sc);
16209     bxe_release_mutexes(sc);
16210 
16211 
16212     /* Release the PCIe BAR mapped memory */
16213     bxe_deallocate_bars(sc);
16214 
16215     /* Release the FreeBSD interface. */
16216     if (sc->ifp != NULL) {
16217         if_free(sc->ifp);
16218     }
16219 
16220     pci_disable_busmaster(dev);
16221 
16222     return (0);
16223 }
16224 
16225 /*
16226  * Device shutdown function.
16227  *
16228  * Stops and resets the controller.
16229  *
16230  * Returns:
16231  *   Nothing
16232  */
16233 static int
16234 bxe_shutdown(device_t dev)
16235 {
16236     struct bxe_softc *sc;
16237 
16238     sc = device_get_softc(dev);
16239 
16240     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16241 
16242     /* stop the periodic callout */
16243     bxe_periodic_stop(sc);
16244 
16245     BXE_CORE_LOCK(sc);
16246     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16247     BXE_CORE_UNLOCK(sc);
16248 
16249     return (0);
16250 }
16251 
16252 void
16253 bxe_igu_ack_sb(struct bxe_softc *sc,
16254                uint8_t          igu_sb_id,
16255                uint8_t          segment,
16256                uint16_t         index,
16257                uint8_t          op,
16258                uint8_t          update)
16259 {
16260     uint32_t igu_addr = sc->igu_base_addr;
16261     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16262     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16263 }
16264 
16265 static void
16266 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16267                      uint8_t          func,
16268                      uint8_t          idu_sb_id,
16269                      uint8_t          is_pf)
16270 {
16271     uint32_t data, ctl, cnt = 100;
16272     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16273     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16274     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16275     uint32_t sb_bit =  1 << (idu_sb_id%32);
16276     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16277     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16278 
16279     /* Not supported in BC mode */
16280     if (CHIP_INT_MODE_IS_BC(sc)) {
16281         return;
16282     }
16283 
16284     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16285              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16286             IGU_REGULAR_CLEANUP_SET |
16287             IGU_REGULAR_BCLEANUP);
16288 
16289     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16290            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16291            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16292 
16293     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16294             data, igu_addr_data);
16295     REG_WR(sc, igu_addr_data, data);
16296 
16297     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16298                       BUS_SPACE_BARRIER_WRITE);
16299     mb();
16300 
16301     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16302             ctl, igu_addr_ctl);
16303     REG_WR(sc, igu_addr_ctl, ctl);
16304 
16305     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16306                       BUS_SPACE_BARRIER_WRITE);
16307     mb();
16308 
16309     /* wait for clean up to finish */
16310     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16311         DELAY(20000);
16312     }
16313 
16314     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16315         BLOGD(sc, DBG_LOAD,
16316               "Unable to finish IGU cleanup: "
16317               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16318               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16319     }
16320 }
16321 
16322 static void
16323 bxe_igu_clear_sb(struct bxe_softc *sc,
16324                  uint8_t          idu_sb_id)
16325 {
16326     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16327 }
16328 
16329 
16330 
16331 
16332 
16333 
16334 
16335 /*******************/
16336 /* ECORE CALLBACKS */
16337 /*******************/
16338 
16339 static void
16340 bxe_reset_common(struct bxe_softc *sc)
16341 {
16342     uint32_t val = 0x1400;
16343 
16344     /* reset_common */
16345     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16346 
16347     if (CHIP_IS_E3(sc)) {
16348         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16349         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16350     }
16351 
16352     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16353 }
16354 
16355 static void
16356 bxe_common_init_phy(struct bxe_softc *sc)
16357 {
16358     uint32_t shmem_base[2];
16359     uint32_t shmem2_base[2];
16360 
16361     /* Avoid common init in case MFW supports LFA */
16362     if (SHMEM2_RD(sc, size) >
16363         (uint32_t)offsetof(struct shmem2_region,
16364                            lfa_host_addr[SC_PORT(sc)])) {
16365         return;
16366     }
16367 
16368     shmem_base[0]  = sc->devinfo.shmem_base;
16369     shmem2_base[0] = sc->devinfo.shmem2_base;
16370 
16371     if (!CHIP_IS_E1x(sc)) {
16372         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16373         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16374     }
16375 
16376     bxe_acquire_phy_lock(sc);
16377     elink_common_init_phy(sc, shmem_base, shmem2_base,
16378                           sc->devinfo.chip_id, 0);
16379     bxe_release_phy_lock(sc);
16380 }
16381 
16382 static void
16383 bxe_pf_disable(struct bxe_softc *sc)
16384 {
16385     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16386 
16387     val &= ~IGU_PF_CONF_FUNC_EN;
16388 
16389     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16390     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16391     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16392 }
16393 
16394 static void
16395 bxe_init_pxp(struct bxe_softc *sc)
16396 {
16397     uint16_t devctl;
16398     int r_order, w_order;
16399 
16400     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16401 
16402     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16403 
16404     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16405 
16406     if (sc->mrrs == -1) {
16407         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16408     } else {
16409         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16410         r_order = sc->mrrs;
16411     }
16412 
16413     ecore_init_pxp_arb(sc, r_order, w_order);
16414 }
16415 
16416 static uint32_t
16417 bxe_get_pretend_reg(struct bxe_softc *sc)
16418 {
16419     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16420     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16421     return (base + (SC_ABS_FUNC(sc)) * stride);
16422 }
16423 
16424 /*
16425  * Called only on E1H or E2.
16426  * When pretending to be PF, the pretend value is the function number 0..7.
16427  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16428  * combination.
16429  */
16430 static int
16431 bxe_pretend_func(struct bxe_softc *sc,
16432                  uint16_t         pretend_func_val)
16433 {
16434     uint32_t pretend_reg;
16435 
16436     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16437         return (-1);
16438     }
16439 
16440     /* get my own pretend register */
16441     pretend_reg = bxe_get_pretend_reg(sc);
16442     REG_WR(sc, pretend_reg, pretend_func_val);
16443     REG_RD(sc, pretend_reg);
16444     return (0);
16445 }
16446 
16447 static void
16448 bxe_iov_init_dmae(struct bxe_softc *sc)
16449 {
16450     return;
16451 }
16452 
16453 static void
16454 bxe_iov_init_dq(struct bxe_softc *sc)
16455 {
16456     return;
16457 }
16458 
16459 /* send a NIG loopback debug packet */
16460 static void
16461 bxe_lb_pckt(struct bxe_softc *sc)
16462 {
16463     uint32_t wb_write[3];
16464 
16465     /* Ethernet source and destination addresses */
16466     wb_write[0] = 0x55555555;
16467     wb_write[1] = 0x55555555;
16468     wb_write[2] = 0x20;     /* SOP */
16469     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16470 
16471     /* NON-IP protocol */
16472     wb_write[0] = 0x09000000;
16473     wb_write[1] = 0x55555555;
16474     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16475     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16476 }
16477 
16478 /*
16479  * Some of the internal memories are not directly readable from the driver.
16480  * To test them we send debug packets.
16481  */
16482 static int
16483 bxe_int_mem_test(struct bxe_softc *sc)
16484 {
16485     int factor;
16486     int count, i;
16487     uint32_t val = 0;
16488 
16489     if (CHIP_REV_IS_FPGA(sc)) {
16490         factor = 120;
16491     } else if (CHIP_REV_IS_EMUL(sc)) {
16492         factor = 200;
16493     } else {
16494         factor = 1;
16495     }
16496 
16497     /* disable inputs of parser neighbor blocks */
16498     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16499     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16500     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16501     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16502 
16503     /*  write 0 to parser credits for CFC search request */
16504     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16505 
16506     /* send Ethernet packet */
16507     bxe_lb_pckt(sc);
16508 
16509     /* TODO do i reset NIG statistic? */
16510     /* Wait until NIG register shows 1 packet of size 0x10 */
16511     count = 1000 * factor;
16512     while (count) {
16513         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16514         val = *BXE_SP(sc, wb_data[0]);
16515         if (val == 0x10) {
16516             break;
16517         }
16518 
16519         DELAY(10000);
16520         count--;
16521     }
16522 
16523     if (val != 0x10) {
16524         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16525         return (-1);
16526     }
16527 
16528     /* wait until PRS register shows 1 packet */
16529     count = (1000 * factor);
16530     while (count) {
16531         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16532         if (val == 1) {
16533             break;
16534         }
16535 
16536         DELAY(10000);
16537         count--;
16538     }
16539 
16540     if (val != 0x1) {
16541         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16542         return (-2);
16543     }
16544 
16545     /* Reset and init BRB, PRS */
16546     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16547     DELAY(50000);
16548     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16549     DELAY(50000);
16550     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16551     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16552 
16553     /* Disable inputs of parser neighbor blocks */
16554     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16555     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16556     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16557     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16558 
16559     /* Write 0 to parser credits for CFC search request */
16560     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16561 
16562     /* send 10 Ethernet packets */
16563     for (i = 0; i < 10; i++) {
16564         bxe_lb_pckt(sc);
16565     }
16566 
16567     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16568     count = (1000 * factor);
16569     while (count) {
16570         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16571         val = *BXE_SP(sc, wb_data[0]);
16572         if (val == 0xb0) {
16573             break;
16574         }
16575 
16576         DELAY(10000);
16577         count--;
16578     }
16579 
16580     if (val != 0xb0) {
16581         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16582         return (-3);
16583     }
16584 
16585     /* Wait until PRS register shows 2 packets */
16586     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16587     if (val != 2) {
16588         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16589     }
16590 
16591     /* Write 1 to parser credits for CFC search request */
16592     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16593 
16594     /* Wait until PRS register shows 3 packets */
16595     DELAY(10000 * factor);
16596 
16597     /* Wait until NIG register shows 1 packet of size 0x10 */
16598     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16599     if (val != 3) {
16600         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16601     }
16602 
16603     /* clear NIG EOP FIFO */
16604     for (i = 0; i < 11; i++) {
16605         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16606     }
16607 
16608     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16609     if (val != 1) {
16610         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16611         return (-4);
16612     }
16613 
16614     /* Reset and init BRB, PRS, NIG */
16615     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16616     DELAY(50000);
16617     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16618     DELAY(50000);
16619     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16620     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16621     if (!CNIC_SUPPORT(sc)) {
16622         /* set NIC mode */
16623         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16624     }
16625 
16626     /* Enable inputs of parser neighbor blocks */
16627     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16628     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16629     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16630     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16631 
16632     return (0);
16633 }
16634 
16635 static void
16636 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16637 {
16638     int is_required;
16639     uint32_t val;
16640     int port;
16641 
16642     is_required = 0;
16643     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16644            SHARED_HW_CFG_FAN_FAILURE_MASK);
16645 
16646     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16647         is_required = 1;
16648     }
16649     /*
16650      * The fan failure mechanism is usually related to the PHY type since
16651      * the power consumption of the board is affected by the PHY. Currently,
16652      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16653      */
16654     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16655         for (port = PORT_0; port < PORT_MAX; port++) {
16656             is_required |= elink_fan_failure_det_req(sc,
16657                                                      sc->devinfo.shmem_base,
16658                                                      sc->devinfo.shmem2_base,
16659                                                      port);
16660         }
16661     }
16662 
16663     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16664 
16665     if (is_required == 0) {
16666         return;
16667     }
16668 
16669     /* Fan failure is indicated by SPIO 5 */
16670     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16671 
16672     /* set to active low mode */
16673     val = REG_RD(sc, MISC_REG_SPIO_INT);
16674     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16675     REG_WR(sc, MISC_REG_SPIO_INT, val);
16676 
16677     /* enable interrupt to signal the IGU */
16678     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16679     val |= MISC_SPIO_SPIO5;
16680     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16681 }
16682 
16683 static void
16684 bxe_enable_blocks_attention(struct bxe_softc *sc)
16685 {
16686     uint32_t val;
16687 
16688     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16689     if (!CHIP_IS_E1x(sc)) {
16690         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16691     } else {
16692         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16693     }
16694     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16695     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16696     /*
16697      * mask read length error interrupts in brb for parser
16698      * (parsing unit and 'checksum and crc' unit)
16699      * these errors are legal (PU reads fixed length and CAC can cause
16700      * read length error on truncated packets)
16701      */
16702     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16703     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16704     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16705     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16706     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16707     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16708 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16709 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16710     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16711     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16712     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16713 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16714 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16715     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16716     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16717     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16718     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16719 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16720 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16721 
16722     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16723            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16724            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16725     if (!CHIP_IS_E1x(sc)) {
16726         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16727                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16728     }
16729     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16730 
16731     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16732     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16733     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16734 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16735 
16736     if (!CHIP_IS_E1x(sc)) {
16737         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16738         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16739     }
16740 
16741     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16742     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16743 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16744     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16745 }
16746 
16747 /**
16748  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16749  *
16750  * @sc:     driver handle
16751  */
16752 static int
16753 bxe_init_hw_common(struct bxe_softc *sc)
16754 {
16755     uint8_t abs_func_id;
16756     uint32_t val;
16757 
16758     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16759           SC_ABS_FUNC(sc));
16760 
16761     /*
16762      * take the RESET lock to protect undi_unload flow from accessing
16763      * registers while we are resetting the chip
16764      */
16765     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16766 
16767     bxe_reset_common(sc);
16768 
16769     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16770 
16771     val = 0xfffc;
16772     if (CHIP_IS_E3(sc)) {
16773         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16774         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16775     }
16776 
16777     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16778 
16779     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16780 
16781     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16782     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16783 
16784     if (!CHIP_IS_E1x(sc)) {
16785         /*
16786          * 4-port mode or 2-port mode we need to turn off master-enable for
16787          * everyone. After that we turn it back on for self. So, we disregard
16788          * multi-function, and always disable all functions on the given path,
16789          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16790          */
16791         for (abs_func_id = SC_PATH(sc);
16792              abs_func_id < (E2_FUNC_MAX * 2);
16793              abs_func_id += 2) {
16794             if (abs_func_id == SC_ABS_FUNC(sc)) {
16795                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16796                 continue;
16797             }
16798 
16799             bxe_pretend_func(sc, abs_func_id);
16800 
16801             /* clear pf enable */
16802             bxe_pf_disable(sc);
16803 
16804             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16805         }
16806     }
16807 
16808     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16809 
16810     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16811 
16812     if (CHIP_IS_E1(sc)) {
16813         /*
16814          * enable HW interrupt from PXP on USDM overflow
16815          * bit 16 on INT_MASK_0
16816          */
16817         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16818     }
16819 
16820     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16821     bxe_init_pxp(sc);
16822 
16823 #ifdef __BIG_ENDIAN
16824     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16825     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16826     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16827     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16828     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16829     /* make sure this value is 0 */
16830     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16831 
16832     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16833     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16834     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16835     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16836     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16837 #endif
16838 
16839     ecore_ilt_init_page_size(sc, INITOP_SET);
16840 
16841     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16842         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16843     }
16844 
16845     /* let the HW do it's magic... */
16846     DELAY(100000);
16847 
16848     /* finish PXP init */
16849     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16850     if (val != 1) {
16851         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16852             val);
16853         return (-1);
16854     }
16855     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16856     if (val != 1) {
16857         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16858         return (-1);
16859     }
16860 
16861     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16862 
16863     /*
16864      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16865      * entries with value "0" and valid bit on. This needs to be done by the
16866      * first PF that is loaded in a path (i.e. common phase)
16867      */
16868     if (!CHIP_IS_E1x(sc)) {
16869 /*
16870  * In E2 there is a bug in the timers block that can cause function 6 / 7
16871  * (i.e. vnic3) to start even if it is marked as "scan-off".
16872  * This occurs when a different function (func2,3) is being marked
16873  * as "scan-off". Real-life scenario for example: if a driver is being
16874  * load-unloaded while func6,7 are down. This will cause the timer to access
16875  * the ilt, translate to a logical address and send a request to read/write.
16876  * Since the ilt for the function that is down is not valid, this will cause
16877  * a translation error which is unrecoverable.
16878  * The Workaround is intended to make sure that when this happens nothing
16879  * fatal will occur. The workaround:
16880  *  1.  First PF driver which loads on a path will:
16881  *      a.  After taking the chip out of reset, by using pretend,
16882  *          it will write "0" to the following registers of
16883  *          the other vnics.
16884  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16885  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16886  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16887  *          And for itself it will write '1' to
16888  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16889  *          dmae-operations (writing to pram for example.)
16890  *          note: can be done for only function 6,7 but cleaner this
16891  *            way.
16892  *      b.  Write zero+valid to the entire ILT.
16893  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16894  *          VNIC3 (of that port). The range allocated will be the
16895  *          entire ILT. This is needed to prevent  ILT range error.
16896  *  2.  Any PF driver load flow:
16897  *      a.  ILT update with the physical addresses of the allocated
16898  *          logical pages.
16899  *      b.  Wait 20msec. - note that this timeout is needed to make
16900  *          sure there are no requests in one of the PXP internal
16901  *          queues with "old" ILT addresses.
16902  *      c.  PF enable in the PGLC.
16903  *      d.  Clear the was_error of the PF in the PGLC. (could have
16904  *          occurred while driver was down)
16905  *      e.  PF enable in the CFC (WEAK + STRONG)
16906  *      f.  Timers scan enable
16907  *  3.  PF driver unload flow:
16908  *      a.  Clear the Timers scan_en.
16909  *      b.  Polling for scan_on=0 for that PF.
16910  *      c.  Clear the PF enable bit in the PXP.
16911  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16912  *      e.  Write zero+valid to all ILT entries (The valid bit must
16913  *          stay set)
16914  *      f.  If this is VNIC 3 of a port then also init
16915  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16916  *          to the last enrty in the ILT.
16917  *
16918  *      Notes:
16919  *      Currently the PF error in the PGLC is non recoverable.
16920  *      In the future the there will be a recovery routine for this error.
16921  *      Currently attention is masked.
16922  *      Having an MCP lock on the load/unload process does not guarantee that
16923  *      there is no Timer disable during Func6/7 enable. This is because the
16924  *      Timers scan is currently being cleared by the MCP on FLR.
16925  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16926  *      there is error before clearing it. But the flow above is simpler and
16927  *      more general.
16928  *      All ILT entries are written by zero+valid and not just PF6/7
16929  *      ILT entries since in the future the ILT entries allocation for
16930  *      PF-s might be dynamic.
16931  */
16932         struct ilt_client_info ilt_cli;
16933         struct ecore_ilt ilt;
16934 
16935         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16936         memset(&ilt, 0, sizeof(struct ecore_ilt));
16937 
16938         /* initialize dummy TM client */
16939         ilt_cli.start      = 0;
16940         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16941         ilt_cli.client_num = ILT_CLIENT_TM;
16942 
16943         /*
16944          * Step 1: set zeroes to all ilt page entries with valid bit on
16945          * Step 2: set the timers first/last ilt entry to point
16946          * to the entire range to prevent ILT range error for 3rd/4th
16947          * vnic (this code assumes existence of the vnic)
16948          *
16949          * both steps performed by call to ecore_ilt_client_init_op()
16950          * with dummy TM client
16951          *
16952          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16953          * and his brother are split registers
16954          */
16955 
16956         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16957         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16958         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16959 
16960         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16961         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16962         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16963     }
16964 
16965     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16966     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16967 
16968     if (!CHIP_IS_E1x(sc)) {
16969         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16970                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16971 
16972         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16973         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16974 
16975         /* let the HW do it's magic... */
16976         do {
16977             DELAY(200000);
16978             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16979         } while (factor-- && (val != 1));
16980 
16981         if (val != 1) {
16982             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16983             return (-1);
16984         }
16985     }
16986 
16987     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16988 
16989     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16990 
16991     bxe_iov_init_dmae(sc);
16992 
16993     /* clean the DMAE memory */
16994     sc->dmae_ready = 1;
16995     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16996 
16997     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16998 
16999     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17000 
17001     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17002 
17003     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17004 
17005     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17006     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17007     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17008     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17009 
17010     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17011 
17012     /* QM queues pointers table */
17013     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17014 
17015     /* soft reset pulse */
17016     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17017     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17018 
17019     if (CNIC_SUPPORT(sc))
17020         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17021 
17022     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17023     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17024     if (!CHIP_REV_IS_SLOW(sc)) {
17025         /* enable hw interrupt from doorbell Q */
17026         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17027     }
17028 
17029     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17030 
17031     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17032     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17033 
17034     if (!CHIP_IS_E1(sc)) {
17035         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17036     }
17037 
17038     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17039         if (IS_MF_AFEX(sc)) {
17040             /*
17041              * configure that AFEX and VLAN headers must be
17042              * received in AFEX mode
17043              */
17044             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17045             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17046             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17047             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17048             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17049         } else {
17050             /*
17051              * Bit-map indicating which L2 hdrs may appear
17052              * after the basic Ethernet header
17053              */
17054             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17055                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17056         }
17057     }
17058 
17059     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17060     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17061     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17062     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17063 
17064     if (!CHIP_IS_E1x(sc)) {
17065         /* reset VFC memories */
17066         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17067                VFC_MEMORIES_RST_REG_CAM_RST |
17068                VFC_MEMORIES_RST_REG_RAM_RST);
17069         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17070                VFC_MEMORIES_RST_REG_CAM_RST |
17071                VFC_MEMORIES_RST_REG_RAM_RST);
17072 
17073         DELAY(20000);
17074     }
17075 
17076     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17077     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17078     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17079     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17080 
17081     /* sync semi rtc */
17082     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17083            0x80000000);
17084     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17085            0x80000000);
17086 
17087     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17088     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17089     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17090 
17091     if (!CHIP_IS_E1x(sc)) {
17092         if (IS_MF_AFEX(sc)) {
17093             /*
17094              * configure that AFEX and VLAN headers must be
17095              * sent in AFEX mode
17096              */
17097             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17098             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17099             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17100             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17101             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17102         } else {
17103             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17104                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17105         }
17106     }
17107 
17108     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17109 
17110     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17111 
17112     if (CNIC_SUPPORT(sc)) {
17113         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17114         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17115         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17116         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17117         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17118         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17119         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17120         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17121         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17122         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17123     }
17124     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17125 
17126     if (sizeof(union cdu_context) != 1024) {
17127         /* we currently assume that a context is 1024 bytes */
17128         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17129               (long)sizeof(union cdu_context));
17130     }
17131 
17132     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17133     val = (4 << 24) + (0 << 12) + 1024;
17134     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17135 
17136     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17137 
17138     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17139     /* enable context validation interrupt from CFC */
17140     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17141 
17142     /* set the thresholds to prevent CFC/CDU race */
17143     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17144     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17145 
17146     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17147         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17148     }
17149 
17150     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17151     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17152 
17153     /* Reset PCIE errors for debug */
17154     REG_WR(sc, 0x2814, 0xffffffff);
17155     REG_WR(sc, 0x3820, 0xffffffff);
17156 
17157     if (!CHIP_IS_E1x(sc)) {
17158         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17159                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17160                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17161         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17162                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17163                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17164                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17165         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17166                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17167                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17168                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17169     }
17170 
17171     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17172 
17173     if (!CHIP_IS_E1(sc)) {
17174         /* in E3 this done in per-port section */
17175         if (!CHIP_IS_E3(sc))
17176             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17177     }
17178 
17179     if (CHIP_IS_E1H(sc)) {
17180         /* not applicable for E2 (and above ...) */
17181         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17182     }
17183 
17184     if (CHIP_REV_IS_SLOW(sc)) {
17185         DELAY(200000);
17186     }
17187 
17188     /* finish CFC init */
17189     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17190     if (val != 1) {
17191         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17192         return (-1);
17193     }
17194     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17195     if (val != 1) {
17196         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17197         return (-1);
17198     }
17199     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17200     if (val != 1) {
17201         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17202         return (-1);
17203     }
17204     REG_WR(sc, CFC_REG_DEBUG0, 0);
17205 
17206     if (CHIP_IS_E1(sc)) {
17207         /* read NIG statistic to see if this is our first up since powerup */
17208         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17209         val = *BXE_SP(sc, wb_data[0]);
17210 
17211         /* do internal memory self test */
17212         if ((val == 0) && bxe_int_mem_test(sc)) {
17213             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17214             return (-1);
17215         }
17216     }
17217 
17218     bxe_setup_fan_failure_detection(sc);
17219 
17220     /* clear PXP2 attentions */
17221     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17222 
17223     bxe_enable_blocks_attention(sc);
17224 
17225     if (!CHIP_REV_IS_SLOW(sc)) {
17226         ecore_enable_blocks_parity(sc);
17227     }
17228 
17229     if (!BXE_NOMCP(sc)) {
17230         if (CHIP_IS_E1x(sc)) {
17231             bxe_common_init_phy(sc);
17232         }
17233     }
17234 
17235     return (0);
17236 }
17237 
17238 /**
17239  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17240  *
17241  * @sc:     driver handle
17242  */
17243 static int
17244 bxe_init_hw_common_chip(struct bxe_softc *sc)
17245 {
17246     int rc = bxe_init_hw_common(sc);
17247 
17248     if (rc) {
17249         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17250         return (rc);
17251     }
17252 
17253     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17254     if (!BXE_NOMCP(sc)) {
17255         bxe_common_init_phy(sc);
17256     }
17257 
17258     return (0);
17259 }
17260 
17261 static int
17262 bxe_init_hw_port(struct bxe_softc *sc)
17263 {
17264     int port = SC_PORT(sc);
17265     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17266     uint32_t low, high;
17267     uint32_t val;
17268 
17269     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17270 
17271     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17272 
17273     ecore_init_block(sc, BLOCK_MISC, init_phase);
17274     ecore_init_block(sc, BLOCK_PXP, init_phase);
17275     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17276 
17277     /*
17278      * Timers bug workaround: disables the pf_master bit in pglue at
17279      * common phase, we need to enable it here before any dmae access are
17280      * attempted. Therefore we manually added the enable-master to the
17281      * port phase (it also happens in the function phase)
17282      */
17283     if (!CHIP_IS_E1x(sc)) {
17284         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17285     }
17286 
17287     ecore_init_block(sc, BLOCK_ATC, init_phase);
17288     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17289     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17290     ecore_init_block(sc, BLOCK_QM, init_phase);
17291 
17292     ecore_init_block(sc, BLOCK_TCM, init_phase);
17293     ecore_init_block(sc, BLOCK_UCM, init_phase);
17294     ecore_init_block(sc, BLOCK_CCM, init_phase);
17295     ecore_init_block(sc, BLOCK_XCM, init_phase);
17296 
17297     /* QM cid (connection) count */
17298     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17299 
17300     if (CNIC_SUPPORT(sc)) {
17301         ecore_init_block(sc, BLOCK_TM, init_phase);
17302         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17303         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17304     }
17305 
17306     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17307 
17308     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17309 
17310     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17311         if (IS_MF(sc)) {
17312             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17313         } else if (sc->mtu > 4096) {
17314             if (BXE_ONE_PORT(sc)) {
17315                 low = 160;
17316             } else {
17317                 val = sc->mtu;
17318                 /* (24*1024 + val*4)/256 */
17319                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17320             }
17321         } else {
17322             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17323         }
17324         high = (low + 56); /* 14*1024/256 */
17325         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17326         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17327     }
17328 
17329     if (CHIP_IS_MODE_4_PORT(sc)) {
17330         REG_WR(sc, SC_PORT(sc) ?
17331                BRB1_REG_MAC_GUARANTIED_1 :
17332                BRB1_REG_MAC_GUARANTIED_0, 40);
17333     }
17334 
17335     ecore_init_block(sc, BLOCK_PRS, init_phase);
17336     if (CHIP_IS_E3B0(sc)) {
17337         if (IS_MF_AFEX(sc)) {
17338             /* configure headers for AFEX mode */
17339             REG_WR(sc, SC_PORT(sc) ?
17340                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17341                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17342             REG_WR(sc, SC_PORT(sc) ?
17343                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17344                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17345             REG_WR(sc, SC_PORT(sc) ?
17346                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17347                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17348         } else {
17349             /* Ovlan exists only if we are in multi-function +
17350              * switch-dependent mode, in switch-independent there
17351              * is no ovlan headers
17352              */
17353             REG_WR(sc, SC_PORT(sc) ?
17354                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17355                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17356                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17357         }
17358     }
17359 
17360     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17361     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17362     ecore_init_block(sc, BLOCK_USDM, init_phase);
17363     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17364 
17365     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17366     ecore_init_block(sc, BLOCK_USEM, init_phase);
17367     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17368     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17369 
17370     ecore_init_block(sc, BLOCK_UPB, init_phase);
17371     ecore_init_block(sc, BLOCK_XPB, init_phase);
17372 
17373     ecore_init_block(sc, BLOCK_PBF, init_phase);
17374 
17375     if (CHIP_IS_E1x(sc)) {
17376         /* configure PBF to work without PAUSE mtu 9000 */
17377         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17378 
17379         /* update threshold */
17380         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17381         /* update init credit */
17382         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17383 
17384         /* probe changes */
17385         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17386         DELAY(50);
17387         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17388     }
17389 
17390     if (CNIC_SUPPORT(sc)) {
17391         ecore_init_block(sc, BLOCK_SRC, init_phase);
17392     }
17393 
17394     ecore_init_block(sc, BLOCK_CDU, init_phase);
17395     ecore_init_block(sc, BLOCK_CFC, init_phase);
17396 
17397     if (CHIP_IS_E1(sc)) {
17398         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17399         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17400     }
17401     ecore_init_block(sc, BLOCK_HC, init_phase);
17402 
17403     ecore_init_block(sc, BLOCK_IGU, init_phase);
17404 
17405     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17406     /* init aeu_mask_attn_func_0/1:
17407      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17408      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17409      *             bits 4-7 are used for "per vn group attention" */
17410     val = IS_MF(sc) ? 0xF7 : 0x7;
17411     /* Enable DCBX attention for all but E1 */
17412     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17413     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17414 
17415     ecore_init_block(sc, BLOCK_NIG, init_phase);
17416 
17417     if (!CHIP_IS_E1x(sc)) {
17418         /* Bit-map indicating which L2 hdrs may appear after the
17419          * basic Ethernet header
17420          */
17421         if (IS_MF_AFEX(sc)) {
17422             REG_WR(sc, SC_PORT(sc) ?
17423                    NIG_REG_P1_HDRS_AFTER_BASIC :
17424                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17425         } else {
17426             REG_WR(sc, SC_PORT(sc) ?
17427                    NIG_REG_P1_HDRS_AFTER_BASIC :
17428                    NIG_REG_P0_HDRS_AFTER_BASIC,
17429                    IS_MF_SD(sc) ? 7 : 6);
17430         }
17431 
17432         if (CHIP_IS_E3(sc)) {
17433             REG_WR(sc, SC_PORT(sc) ?
17434                    NIG_REG_LLH1_MF_MODE :
17435                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17436         }
17437     }
17438     if (!CHIP_IS_E3(sc)) {
17439         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17440     }
17441 
17442     if (!CHIP_IS_E1(sc)) {
17443         /* 0x2 disable mf_ov, 0x1 enable */
17444         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17445                (IS_MF_SD(sc) ? 0x1 : 0x2));
17446 
17447         if (!CHIP_IS_E1x(sc)) {
17448             val = 0;
17449             switch (sc->devinfo.mf_info.mf_mode) {
17450             case MULTI_FUNCTION_SD:
17451                 val = 1;
17452                 break;
17453             case MULTI_FUNCTION_SI:
17454             case MULTI_FUNCTION_AFEX:
17455                 val = 2;
17456                 break;
17457             }
17458 
17459             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17460                         NIG_REG_LLH0_CLS_TYPE), val);
17461         }
17462         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17463         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17464         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17465     }
17466 
17467     /* If SPIO5 is set to generate interrupts, enable it for this port */
17468     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17469     if (val & MISC_SPIO_SPIO5) {
17470         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17471                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17472         val = REG_RD(sc, reg_addr);
17473         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17474         REG_WR(sc, reg_addr, val);
17475     }
17476 
17477     return (0);
17478 }
17479 
17480 static uint32_t
17481 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17482                        uint32_t         reg,
17483                        uint32_t         expected,
17484                        uint32_t         poll_count)
17485 {
17486     uint32_t cur_cnt = poll_count;
17487     uint32_t val;
17488 
17489     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17490         DELAY(FLR_WAIT_INTERVAL);
17491     }
17492 
17493     return (val);
17494 }
17495 
17496 static int
17497 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17498                               uint32_t         reg,
17499                               char             *msg,
17500                               uint32_t         poll_cnt)
17501 {
17502     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17503 
17504     if (val != 0) {
17505         BLOGE(sc, "%s usage count=%d\n", msg, val);
17506         return (1);
17507     }
17508 
17509     return (0);
17510 }
17511 
17512 /* Common routines with VF FLR cleanup */
17513 static uint32_t
17514 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17515 {
17516     /* adjust polling timeout */
17517     if (CHIP_REV_IS_EMUL(sc)) {
17518         return (FLR_POLL_CNT * 2000);
17519     }
17520 
17521     if (CHIP_REV_IS_FPGA(sc)) {
17522         return (FLR_POLL_CNT * 120);
17523     }
17524 
17525     return (FLR_POLL_CNT);
17526 }
17527 
17528 static int
17529 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17530                            uint32_t         poll_cnt)
17531 {
17532     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17533     if (bxe_flr_clnup_poll_hw_counter(sc,
17534                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17535                                       "CFC PF usage counter timed out",
17536                                       poll_cnt)) {
17537         return (1);
17538     }
17539 
17540     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17541     if (bxe_flr_clnup_poll_hw_counter(sc,
17542                                       DORQ_REG_PF_USAGE_CNT,
17543                                       "DQ PF usage counter timed out",
17544                                       poll_cnt)) {
17545         return (1);
17546     }
17547 
17548     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17549     if (bxe_flr_clnup_poll_hw_counter(sc,
17550                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17551                                       "QM PF usage counter timed out",
17552                                       poll_cnt)) {
17553         return (1);
17554     }
17555 
17556     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17557     if (bxe_flr_clnup_poll_hw_counter(sc,
17558                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17559                                       "Timers VNIC usage counter timed out",
17560                                       poll_cnt)) {
17561         return (1);
17562     }
17563 
17564     if (bxe_flr_clnup_poll_hw_counter(sc,
17565                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17566                                       "Timers NUM_SCANS usage counter timed out",
17567                                       poll_cnt)) {
17568         return (1);
17569     }
17570 
17571     /* Wait DMAE PF usage counter to zero */
17572     if (bxe_flr_clnup_poll_hw_counter(sc,
17573                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17574                                       "DMAE dommand register timed out",
17575                                       poll_cnt)) {
17576         return (1);
17577     }
17578 
17579     return (0);
17580 }
17581 
17582 #define OP_GEN_PARAM(param)                                            \
17583     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17584 #define OP_GEN_TYPE(type)                                           \
17585     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17586 #define OP_GEN_AGG_VECT(index)                                             \
17587     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17588 
17589 static int
17590 bxe_send_final_clnup(struct bxe_softc *sc,
17591                      uint8_t          clnup_func,
17592                      uint32_t         poll_cnt)
17593 {
17594     uint32_t op_gen_command = 0;
17595     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17596                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17597     int ret = 0;
17598 
17599     if (REG_RD(sc, comp_addr)) {
17600         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17601         return (1);
17602     }
17603 
17604     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17605     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17606     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17607     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17608 
17609     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17610     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17611 
17612     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17613         BLOGE(sc, "FW final cleanup did not succeed\n");
17614         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17615               (REG_RD(sc, comp_addr)));
17616         bxe_panic(sc, ("FLR cleanup failed\n"));
17617         return (1);
17618     }
17619 
17620     /* Zero completion for nxt FLR */
17621     REG_WR(sc, comp_addr, 0);
17622 
17623     return (ret);
17624 }
17625 
17626 static void
17627 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17628                        struct pbf_pN_buf_regs *regs,
17629                        uint32_t               poll_count)
17630 {
17631     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17632     uint32_t cur_cnt = poll_count;
17633 
17634     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17635     crd = crd_start = REG_RD(sc, regs->crd);
17636     init_crd = REG_RD(sc, regs->init_crd);
17637 
17638     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17639     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17640     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17641 
17642     while ((crd != init_crd) &&
17643            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17644             (init_crd - crd_start))) {
17645         if (cur_cnt--) {
17646             DELAY(FLR_WAIT_INTERVAL);
17647             crd = REG_RD(sc, regs->crd);
17648             crd_freed = REG_RD(sc, regs->crd_freed);
17649         } else {
17650             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17651             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17652             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17653             break;
17654         }
17655     }
17656 
17657     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17658           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17659 }
17660 
17661 static void
17662 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17663                        struct pbf_pN_cmd_regs *regs,
17664                        uint32_t               poll_count)
17665 {
17666     uint32_t occup, to_free, freed, freed_start;
17667     uint32_t cur_cnt = poll_count;
17668 
17669     occup = to_free = REG_RD(sc, regs->lines_occup);
17670     freed = freed_start = REG_RD(sc, regs->lines_freed);
17671 
17672     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17673     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17674 
17675     while (occup &&
17676            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17677         if (cur_cnt--) {
17678             DELAY(FLR_WAIT_INTERVAL);
17679             occup = REG_RD(sc, regs->lines_occup);
17680             freed = REG_RD(sc, regs->lines_freed);
17681         } else {
17682             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17683             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17684             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17685             break;
17686         }
17687     }
17688 
17689     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17690           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17691 }
17692 
17693 static void
17694 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17695 {
17696     struct pbf_pN_cmd_regs cmd_regs[] = {
17697         {0, (CHIP_IS_E3B0(sc)) ?
17698             PBF_REG_TQ_OCCUPANCY_Q0 :
17699             PBF_REG_P0_TQ_OCCUPANCY,
17700             (CHIP_IS_E3B0(sc)) ?
17701             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17702             PBF_REG_P0_TQ_LINES_FREED_CNT},
17703         {1, (CHIP_IS_E3B0(sc)) ?
17704             PBF_REG_TQ_OCCUPANCY_Q1 :
17705             PBF_REG_P1_TQ_OCCUPANCY,
17706             (CHIP_IS_E3B0(sc)) ?
17707             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17708             PBF_REG_P1_TQ_LINES_FREED_CNT},
17709         {4, (CHIP_IS_E3B0(sc)) ?
17710             PBF_REG_TQ_OCCUPANCY_LB_Q :
17711             PBF_REG_P4_TQ_OCCUPANCY,
17712             (CHIP_IS_E3B0(sc)) ?
17713             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17714             PBF_REG_P4_TQ_LINES_FREED_CNT}
17715     };
17716 
17717     struct pbf_pN_buf_regs buf_regs[] = {
17718         {0, (CHIP_IS_E3B0(sc)) ?
17719             PBF_REG_INIT_CRD_Q0 :
17720             PBF_REG_P0_INIT_CRD ,
17721             (CHIP_IS_E3B0(sc)) ?
17722             PBF_REG_CREDIT_Q0 :
17723             PBF_REG_P0_CREDIT,
17724             (CHIP_IS_E3B0(sc)) ?
17725             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17726             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17727         {1, (CHIP_IS_E3B0(sc)) ?
17728             PBF_REG_INIT_CRD_Q1 :
17729             PBF_REG_P1_INIT_CRD,
17730             (CHIP_IS_E3B0(sc)) ?
17731             PBF_REG_CREDIT_Q1 :
17732             PBF_REG_P1_CREDIT,
17733             (CHIP_IS_E3B0(sc)) ?
17734             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17735             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17736         {4, (CHIP_IS_E3B0(sc)) ?
17737             PBF_REG_INIT_CRD_LB_Q :
17738             PBF_REG_P4_INIT_CRD,
17739             (CHIP_IS_E3B0(sc)) ?
17740             PBF_REG_CREDIT_LB_Q :
17741             PBF_REG_P4_CREDIT,
17742             (CHIP_IS_E3B0(sc)) ?
17743             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17744             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17745     };
17746 
17747     int i;
17748 
17749     /* Verify the command queues are flushed P0, P1, P4 */
17750     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17751         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17752     }
17753 
17754     /* Verify the transmission buffers are flushed P0, P1, P4 */
17755     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17756         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17757     }
17758 }
17759 
17760 static void
17761 bxe_hw_enable_status(struct bxe_softc *sc)
17762 {
17763     uint32_t val;
17764 
17765     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17766     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17767 
17768     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17769     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17770 
17771     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17772     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17773 
17774     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17775     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17776 
17777     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17778     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17779 
17780     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17781     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17782 
17783     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17784     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17785 
17786     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17787     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17788 }
17789 
17790 static int
17791 bxe_pf_flr_clnup(struct bxe_softc *sc)
17792 {
17793     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17794 
17795     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17796 
17797     /* Re-enable PF target read access */
17798     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17799 
17800     /* Poll HW usage counters */
17801     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17802     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17803         return (-1);
17804     }
17805 
17806     /* Zero the igu 'trailing edge' and 'leading edge' */
17807 
17808     /* Send the FW cleanup command */
17809     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17810         return (-1);
17811     }
17812 
17813     /* ATC cleanup */
17814 
17815     /* Verify TX hw is flushed */
17816     bxe_tx_hw_flushed(sc, poll_cnt);
17817 
17818     /* Wait 100ms (not adjusted according to platform) */
17819     DELAY(100000);
17820 
17821     /* Verify no pending pci transactions */
17822     if (bxe_is_pcie_pending(sc)) {
17823         BLOGE(sc, "PCIE Transactions still pending\n");
17824     }
17825 
17826     /* Debug */
17827     bxe_hw_enable_status(sc);
17828 
17829     /*
17830      * Master enable - Due to WB DMAE writes performed before this
17831      * register is re-initialized as part of the regular function init
17832      */
17833     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17834 
17835     return (0);
17836 }
17837 
17838 static int
17839 bxe_init_hw_func(struct bxe_softc *sc)
17840 {
17841     int port = SC_PORT(sc);
17842     int func = SC_FUNC(sc);
17843     int init_phase = PHASE_PF0 + func;
17844     struct ecore_ilt *ilt = sc->ilt;
17845     uint16_t cdu_ilt_start;
17846     uint32_t addr, val;
17847     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17848     int i, main_mem_width, rc;
17849 
17850     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17851 
17852     /* FLR cleanup */
17853     if (!CHIP_IS_E1x(sc)) {
17854         rc = bxe_pf_flr_clnup(sc);
17855         if (rc) {
17856             BLOGE(sc, "FLR cleanup failed!\n");
17857             // XXX bxe_fw_dump(sc);
17858             // XXX bxe_idle_chk(sc);
17859             return (rc);
17860         }
17861     }
17862 
17863     /* set MSI reconfigure capability */
17864     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17865         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17866         val = REG_RD(sc, addr);
17867         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17868         REG_WR(sc, addr, val);
17869     }
17870 
17871     ecore_init_block(sc, BLOCK_PXP, init_phase);
17872     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17873 
17874     ilt = sc->ilt;
17875     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17876 
17877     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17878         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17879         ilt->lines[cdu_ilt_start + i].page_mapping =
17880             sc->context[i].vcxt_dma.paddr;
17881         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17882     }
17883     ecore_ilt_init_op(sc, INITOP_SET);
17884 
17885     /* Set NIC mode */
17886     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17887     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17888 
17889     if (!CHIP_IS_E1x(sc)) {
17890         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17891 
17892         /* Turn on a single ISR mode in IGU if driver is going to use
17893          * INT#x or MSI
17894          */
17895         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17896             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17897         }
17898 
17899         /*
17900          * Timers workaround bug: function init part.
17901          * Need to wait 20msec after initializing ILT,
17902          * needed to make sure there are no requests in
17903          * one of the PXP internal queues with "old" ILT addresses
17904          */
17905         DELAY(20000);
17906 
17907         /*
17908          * Master enable - Due to WB DMAE writes performed before this
17909          * register is re-initialized as part of the regular function
17910          * init
17911          */
17912         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17913         /* Enable the function in IGU */
17914         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17915     }
17916 
17917     sc->dmae_ready = 1;
17918 
17919     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17920 
17921     if (!CHIP_IS_E1x(sc))
17922         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17923 
17924     ecore_init_block(sc, BLOCK_ATC, init_phase);
17925     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17926     ecore_init_block(sc, BLOCK_NIG, init_phase);
17927     ecore_init_block(sc, BLOCK_SRC, init_phase);
17928     ecore_init_block(sc, BLOCK_MISC, init_phase);
17929     ecore_init_block(sc, BLOCK_TCM, init_phase);
17930     ecore_init_block(sc, BLOCK_UCM, init_phase);
17931     ecore_init_block(sc, BLOCK_CCM, init_phase);
17932     ecore_init_block(sc, BLOCK_XCM, init_phase);
17933     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17934     ecore_init_block(sc, BLOCK_USEM, init_phase);
17935     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17936     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17937 
17938     if (!CHIP_IS_E1x(sc))
17939         REG_WR(sc, QM_REG_PF_EN, 1);
17940 
17941     if (!CHIP_IS_E1x(sc)) {
17942         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17943         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17944         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17945         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17946     }
17947     ecore_init_block(sc, BLOCK_QM, init_phase);
17948 
17949     ecore_init_block(sc, BLOCK_TM, init_phase);
17950     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17951 
17952     bxe_iov_init_dq(sc);
17953 
17954     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17955     ecore_init_block(sc, BLOCK_PRS, init_phase);
17956     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17957     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17958     ecore_init_block(sc, BLOCK_USDM, init_phase);
17959     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17960     ecore_init_block(sc, BLOCK_UPB, init_phase);
17961     ecore_init_block(sc, BLOCK_XPB, init_phase);
17962     ecore_init_block(sc, BLOCK_PBF, init_phase);
17963     if (!CHIP_IS_E1x(sc))
17964         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17965 
17966     ecore_init_block(sc, BLOCK_CDU, init_phase);
17967 
17968     ecore_init_block(sc, BLOCK_CFC, init_phase);
17969 
17970     if (!CHIP_IS_E1x(sc))
17971         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17972 
17973     if (IS_MF(sc)) {
17974         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17975         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17976     }
17977 
17978     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17979 
17980     /* HC init per function */
17981     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17982         if (CHIP_IS_E1H(sc)) {
17983             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17984 
17985             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17986             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17987         }
17988         ecore_init_block(sc, BLOCK_HC, init_phase);
17989 
17990     } else {
17991         int num_segs, sb_idx, prod_offset;
17992 
17993         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17994 
17995         if (!CHIP_IS_E1x(sc)) {
17996             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17997             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17998         }
17999 
18000         ecore_init_block(sc, BLOCK_IGU, init_phase);
18001 
18002         if (!CHIP_IS_E1x(sc)) {
18003             int dsb_idx = 0;
18004             /**
18005              * Producer memory:
18006              * E2 mode: address 0-135 match to the mapping memory;
18007              * 136 - PF0 default prod; 137 - PF1 default prod;
18008              * 138 - PF2 default prod; 139 - PF3 default prod;
18009              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18010              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18011              * 144-147 reserved.
18012              *
18013              * E1.5 mode - In backward compatible mode;
18014              * for non default SB; each even line in the memory
18015              * holds the U producer and each odd line hold
18016              * the C producer. The first 128 producers are for
18017              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18018              * producers are for the DSB for each PF.
18019              * Each PF has five segments: (the order inside each
18020              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18021              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18022              * 144-147 attn prods;
18023              */
18024             /* non-default-status-blocks */
18025             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18026                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18027             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18028                 prod_offset = (sc->igu_base_sb + sb_idx) *
18029                     num_segs;
18030 
18031                 for (i = 0; i < num_segs; i++) {
18032                     addr = IGU_REG_PROD_CONS_MEMORY +
18033                             (prod_offset + i) * 4;
18034                     REG_WR(sc, addr, 0);
18035                 }
18036                 /* send consumer update with value 0 */
18037                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18038                            USTORM_ID, 0, IGU_INT_NOP, 1);
18039                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18040             }
18041 
18042             /* default-status-blocks */
18043             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18044                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18045 
18046             if (CHIP_IS_MODE_4_PORT(sc))
18047                 dsb_idx = SC_FUNC(sc);
18048             else
18049                 dsb_idx = SC_VN(sc);
18050 
18051             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18052                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18053                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18054 
18055             /*
18056              * igu prods come in chunks of E1HVN_MAX (4) -
18057              * does not matters what is the current chip mode
18058              */
18059             for (i = 0; i < (num_segs * E1HVN_MAX);
18060                  i += E1HVN_MAX) {
18061                 addr = IGU_REG_PROD_CONS_MEMORY +
18062                             (prod_offset + i)*4;
18063                 REG_WR(sc, addr, 0);
18064             }
18065             /* send consumer update with 0 */
18066             if (CHIP_INT_MODE_IS_BC(sc)) {
18067                 bxe_ack_sb(sc, sc->igu_dsb_id,
18068                            USTORM_ID, 0, IGU_INT_NOP, 1);
18069                 bxe_ack_sb(sc, sc->igu_dsb_id,
18070                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18071                 bxe_ack_sb(sc, sc->igu_dsb_id,
18072                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18073                 bxe_ack_sb(sc, sc->igu_dsb_id,
18074                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18075                 bxe_ack_sb(sc, sc->igu_dsb_id,
18076                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18077             } else {
18078                 bxe_ack_sb(sc, sc->igu_dsb_id,
18079                            USTORM_ID, 0, IGU_INT_NOP, 1);
18080                 bxe_ack_sb(sc, sc->igu_dsb_id,
18081                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18082             }
18083             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18084 
18085             /* !!! these should become driver const once
18086                rf-tool supports split-68 const */
18087             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18088             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18089             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18090             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18091             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18092             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18093         }
18094     }
18095 
18096     /* Reset PCIE errors for debug */
18097     REG_WR(sc, 0x2114, 0xffffffff);
18098     REG_WR(sc, 0x2120, 0xffffffff);
18099 
18100     if (CHIP_IS_E1x(sc)) {
18101         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18102         main_mem_base = HC_REG_MAIN_MEMORY +
18103                 SC_PORT(sc) * (main_mem_size * 4);
18104         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18105         main_mem_width = 8;
18106 
18107         val = REG_RD(sc, main_mem_prty_clr);
18108         if (val) {
18109             BLOGD(sc, DBG_LOAD,
18110                   "Parity errors in HC block during function init (0x%x)!\n",
18111                   val);
18112         }
18113 
18114         /* Clear "false" parity errors in MSI-X table */
18115         for (i = main_mem_base;
18116              i < main_mem_base + main_mem_size * 4;
18117              i += main_mem_width) {
18118             bxe_read_dmae(sc, i, main_mem_width / 4);
18119             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18120                            i, main_mem_width / 4);
18121         }
18122         /* Clear HC parity attention */
18123         REG_RD(sc, main_mem_prty_clr);
18124     }
18125 
18126 #if 1
18127     /* Enable STORMs SP logging */
18128     REG_WR8(sc, BAR_USTRORM_INTMEM +
18129            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18130     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18131            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18132     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18133            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18134     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18135            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18136 #endif
18137 
18138     elink_phy_probe(&sc->link_params);
18139 
18140     return (0);
18141 }
18142 
18143 static void
18144 bxe_link_reset(struct bxe_softc *sc)
18145 {
18146     if (!BXE_NOMCP(sc)) {
18147 	bxe_acquire_phy_lock(sc);
18148         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18149 	bxe_release_phy_lock(sc);
18150     } else {
18151         if (!CHIP_REV_IS_SLOW(sc)) {
18152             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18153         }
18154     }
18155 }
18156 
18157 static void
18158 bxe_reset_port(struct bxe_softc *sc)
18159 {
18160     int port = SC_PORT(sc);
18161     uint32_t val;
18162 
18163     /* reset physical Link */
18164     bxe_link_reset(sc);
18165 
18166     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18167 
18168     /* Do not rcv packets to BRB */
18169     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18170     /* Do not direct rcv packets that are not for MCP to the BRB */
18171     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18172                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18173 
18174     /* Configure AEU */
18175     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18176 
18177     DELAY(100000);
18178 
18179     /* Check for BRB port occupancy */
18180     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18181     if (val) {
18182         BLOGD(sc, DBG_LOAD,
18183               "BRB1 is not empty, %d blocks are occupied\n", val);
18184     }
18185 
18186     /* TODO: Close Doorbell port? */
18187 }
18188 
18189 static void
18190 bxe_ilt_wr(struct bxe_softc *sc,
18191            uint32_t         index,
18192            bus_addr_t       addr)
18193 {
18194     int reg;
18195     uint32_t wb_write[2];
18196 
18197     if (CHIP_IS_E1(sc)) {
18198         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18199     } else {
18200         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18201     }
18202 
18203     wb_write[0] = ONCHIP_ADDR1(addr);
18204     wb_write[1] = ONCHIP_ADDR2(addr);
18205     REG_WR_DMAE(sc, reg, wb_write, 2);
18206 }
18207 
18208 static void
18209 bxe_clear_func_ilt(struct bxe_softc *sc,
18210                    uint32_t         func)
18211 {
18212     uint32_t i, base = FUNC_ILT_BASE(func);
18213     for (i = base; i < base + ILT_PER_FUNC; i++) {
18214         bxe_ilt_wr(sc, i, 0);
18215     }
18216 }
18217 
18218 static void
18219 bxe_reset_func(struct bxe_softc *sc)
18220 {
18221     struct bxe_fastpath *fp;
18222     int port = SC_PORT(sc);
18223     int func = SC_FUNC(sc);
18224     int i;
18225 
18226     /* Disable the function in the FW */
18227     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18228     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18229     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18230     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18231 
18232     /* FP SBs */
18233     FOR_EACH_ETH_QUEUE(sc, i) {
18234         fp = &sc->fp[i];
18235         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18236                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18237                 SB_DISABLED);
18238     }
18239 
18240     /* SP SB */
18241     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18242             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18243             SB_DISABLED);
18244 
18245     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18246         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18247     }
18248 
18249     /* Configure IGU */
18250     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18251         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18252         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18253     } else {
18254         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18255         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18256     }
18257 
18258     if (CNIC_LOADED(sc)) {
18259         /* Disable Timer scan */
18260         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18261         /*
18262          * Wait for at least 10ms and up to 2 second for the timers
18263          * scan to complete
18264          */
18265         for (i = 0; i < 200; i++) {
18266             DELAY(10000);
18267             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18268                 break;
18269         }
18270     }
18271 
18272     /* Clear ILT */
18273     bxe_clear_func_ilt(sc, func);
18274 
18275     /*
18276      * Timers workaround bug for E2: if this is vnic-3,
18277      * we need to set the entire ilt range for this timers.
18278      */
18279     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18280         struct ilt_client_info ilt_cli;
18281         /* use dummy TM client */
18282         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18283         ilt_cli.start = 0;
18284         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18285         ilt_cli.client_num = ILT_CLIENT_TM;
18286 
18287         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18288     }
18289 
18290     /* this assumes that reset_port() called before reset_func()*/
18291     if (!CHIP_IS_E1x(sc)) {
18292         bxe_pf_disable(sc);
18293     }
18294 
18295     sc->dmae_ready = 0;
18296 }
18297 
18298 static int
18299 bxe_gunzip_init(struct bxe_softc *sc)
18300 {
18301     return (0);
18302 }
18303 
18304 static void
18305 bxe_gunzip_end(struct bxe_softc *sc)
18306 {
18307     return;
18308 }
18309 
18310 static int
18311 bxe_init_firmware(struct bxe_softc *sc)
18312 {
18313     if (CHIP_IS_E1(sc)) {
18314         ecore_init_e1_firmware(sc);
18315         sc->iro_array = e1_iro_arr;
18316     } else if (CHIP_IS_E1H(sc)) {
18317         ecore_init_e1h_firmware(sc);
18318         sc->iro_array = e1h_iro_arr;
18319     } else if (!CHIP_IS_E1x(sc)) {
18320         ecore_init_e2_firmware(sc);
18321         sc->iro_array = e2_iro_arr;
18322     } else {
18323         BLOGE(sc, "Unsupported chip revision\n");
18324         return (-1);
18325     }
18326 
18327     return (0);
18328 }
18329 
18330 static void
18331 bxe_release_firmware(struct bxe_softc *sc)
18332 {
18333     /* Do nothing */
18334     return;
18335 }
18336 
18337 static int
18338 ecore_gunzip(struct bxe_softc *sc,
18339              const uint8_t    *zbuf,
18340              int              len)
18341 {
18342     /* XXX : Implement... */
18343     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18344     return (FALSE);
18345 }
18346 
18347 static void
18348 ecore_reg_wr_ind(struct bxe_softc *sc,
18349                  uint32_t         addr,
18350                  uint32_t         val)
18351 {
18352     bxe_reg_wr_ind(sc, addr, val);
18353 }
18354 
18355 static void
18356 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18357                           bus_addr_t       phys_addr,
18358                           uint32_t         addr,
18359                           uint32_t         len)
18360 {
18361     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18362 }
18363 
18364 void
18365 ecore_storm_memset_struct(struct bxe_softc *sc,
18366                           uint32_t         addr,
18367                           size_t           size,
18368                           uint32_t         *data)
18369 {
18370     uint8_t i;
18371     for (i = 0; i < size/4; i++) {
18372         REG_WR(sc, addr + (i * 4), data[i]);
18373     }
18374 }
18375 
18376 
18377 /*
18378  * character device - ioctl interface definitions
18379  */
18380 
18381 
18382 #include "bxe_dump.h"
18383 #include "bxe_ioctl.h"
18384 #include <sys/conf.h>
18385 
18386 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18387                 struct thread *td);
18388 
18389 static struct cdevsw bxe_cdevsw = {
18390     .d_version = D_VERSION,
18391     .d_ioctl = bxe_eioctl,
18392     .d_name = "bxecnic",
18393 };
18394 
18395 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18396 
18397 
18398 #define DUMP_ALL_PRESETS        0x1FFF
18399 #define DUMP_MAX_PRESETS        13
18400 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18401 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18402 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18403 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18404 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18405 
18406 #define IS_REG_IN_PRESET(presets, idx)  \
18407                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18408 
18409 
18410 static int
18411 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18412 {
18413     if (CHIP_IS_E1(sc))
18414         return dump_num_registers[0][preset-1];
18415     else if (CHIP_IS_E1H(sc))
18416         return dump_num_registers[1][preset-1];
18417     else if (CHIP_IS_E2(sc))
18418         return dump_num_registers[2][preset-1];
18419     else if (CHIP_IS_E3A0(sc))
18420         return dump_num_registers[3][preset-1];
18421     else if (CHIP_IS_E3B0(sc))
18422         return dump_num_registers[4][preset-1];
18423     else
18424         return 0;
18425 }
18426 
18427 static int
18428 bxe_get_total_regs_len32(struct bxe_softc *sc)
18429 {
18430     uint32_t preset_idx;
18431     int regdump_len32 = 0;
18432 
18433 
18434     /* Calculate the total preset regs length */
18435     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18436         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18437     }
18438 
18439     return regdump_len32;
18440 }
18441 
18442 static const uint32_t *
18443 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18444 {
18445     if (CHIP_IS_E2(sc))
18446         return page_vals_e2;
18447     else if (CHIP_IS_E3(sc))
18448         return page_vals_e3;
18449     else
18450         return NULL;
18451 }
18452 
18453 static uint32_t
18454 __bxe_get_page_reg_num(struct bxe_softc *sc)
18455 {
18456     if (CHIP_IS_E2(sc))
18457         return PAGE_MODE_VALUES_E2;
18458     else if (CHIP_IS_E3(sc))
18459         return PAGE_MODE_VALUES_E3;
18460     else
18461         return 0;
18462 }
18463 
18464 static const uint32_t *
18465 __bxe_get_page_write_ar(struct bxe_softc *sc)
18466 {
18467     if (CHIP_IS_E2(sc))
18468         return page_write_regs_e2;
18469     else if (CHIP_IS_E3(sc))
18470         return page_write_regs_e3;
18471     else
18472         return NULL;
18473 }
18474 
18475 static uint32_t
18476 __bxe_get_page_write_num(struct bxe_softc *sc)
18477 {
18478     if (CHIP_IS_E2(sc))
18479         return PAGE_WRITE_REGS_E2;
18480     else if (CHIP_IS_E3(sc))
18481         return PAGE_WRITE_REGS_E3;
18482     else
18483         return 0;
18484 }
18485 
18486 static const struct reg_addr *
18487 __bxe_get_page_read_ar(struct bxe_softc *sc)
18488 {
18489     if (CHIP_IS_E2(sc))
18490         return page_read_regs_e2;
18491     else if (CHIP_IS_E3(sc))
18492         return page_read_regs_e3;
18493     else
18494         return NULL;
18495 }
18496 
18497 static uint32_t
18498 __bxe_get_page_read_num(struct bxe_softc *sc)
18499 {
18500     if (CHIP_IS_E2(sc))
18501         return PAGE_READ_REGS_E2;
18502     else if (CHIP_IS_E3(sc))
18503         return PAGE_READ_REGS_E3;
18504     else
18505         return 0;
18506 }
18507 
18508 static bool
18509 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18510 {
18511     if (CHIP_IS_E1(sc))
18512         return IS_E1_REG(reg_info->chips);
18513     else if (CHIP_IS_E1H(sc))
18514         return IS_E1H_REG(reg_info->chips);
18515     else if (CHIP_IS_E2(sc))
18516         return IS_E2_REG(reg_info->chips);
18517     else if (CHIP_IS_E3A0(sc))
18518         return IS_E3A0_REG(reg_info->chips);
18519     else if (CHIP_IS_E3B0(sc))
18520         return IS_E3B0_REG(reg_info->chips);
18521     else
18522         return 0;
18523 }
18524 
18525 static bool
18526 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18527 {
18528     if (CHIP_IS_E1(sc))
18529         return IS_E1_REG(wreg_info->chips);
18530     else if (CHIP_IS_E1H(sc))
18531         return IS_E1H_REG(wreg_info->chips);
18532     else if (CHIP_IS_E2(sc))
18533         return IS_E2_REG(wreg_info->chips);
18534     else if (CHIP_IS_E3A0(sc))
18535         return IS_E3A0_REG(wreg_info->chips);
18536     else if (CHIP_IS_E3B0(sc))
18537         return IS_E3B0_REG(wreg_info->chips);
18538     else
18539         return 0;
18540 }
18541 
18542 /**
18543  * bxe_read_pages_regs - read "paged" registers
18544  *
18545  * @bp          device handle
18546  * @p           output buffer
18547  *
18548  * Reads "paged" memories: memories that may only be read by first writing to a
18549  * specific address ("write address") and then reading from a specific address
18550  * ("read address"). There may be more than one write address per "page" and
18551  * more than one read address per write address.
18552  */
18553 static void
18554 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18555 {
18556     uint32_t i, j, k, n;
18557 
18558     /* addresses of the paged registers */
18559     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18560     /* number of paged registers */
18561     int num_pages = __bxe_get_page_reg_num(sc);
18562     /* write addresses */
18563     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18564     /* number of write addresses */
18565     int write_num = __bxe_get_page_write_num(sc);
18566     /* read addresses info */
18567     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18568     /* number of read addresses */
18569     int read_num = __bxe_get_page_read_num(sc);
18570     uint32_t addr, size;
18571 
18572     for (i = 0; i < num_pages; i++) {
18573         for (j = 0; j < write_num; j++) {
18574             REG_WR(sc, write_addr[j], page_addr[i]);
18575 
18576             for (k = 0; k < read_num; k++) {
18577                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18578                     size = read_addr[k].size;
18579                     for (n = 0; n < size; n++) {
18580                         addr = read_addr[k].addr + n*4;
18581                         *p++ = REG_RD(sc, addr);
18582                     }
18583                 }
18584             }
18585         }
18586     }
18587     return;
18588 }
18589 
18590 
18591 static int
18592 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18593 {
18594     uint32_t i, j, addr;
18595     const struct wreg_addr *wreg_addr_p = NULL;
18596 
18597     if (CHIP_IS_E1(sc))
18598         wreg_addr_p = &wreg_addr_e1;
18599     else if (CHIP_IS_E1H(sc))
18600         wreg_addr_p = &wreg_addr_e1h;
18601     else if (CHIP_IS_E2(sc))
18602         wreg_addr_p = &wreg_addr_e2;
18603     else if (CHIP_IS_E3A0(sc))
18604         wreg_addr_p = &wreg_addr_e3;
18605     else if (CHIP_IS_E3B0(sc))
18606         wreg_addr_p = &wreg_addr_e3b0;
18607     else
18608         return (-1);
18609 
18610     /* Read the idle_chk registers */
18611     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18612         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18613             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18614             for (j = 0; j < idle_reg_addrs[i].size; j++)
18615                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18616         }
18617     }
18618 
18619     /* Read the regular registers */
18620     for (i = 0; i < REGS_COUNT; i++) {
18621         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18622             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18623             for (j = 0; j < reg_addrs[i].size; j++)
18624                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18625         }
18626     }
18627 
18628     /* Read the CAM registers */
18629     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18630         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18631         for (i = 0; i < wreg_addr_p->size; i++) {
18632             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18633 
18634             /* In case of wreg_addr register, read additional
18635                registers from read_regs array
18636              */
18637             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18638                 addr = *(wreg_addr_p->read_regs);
18639                 *p++ = REG_RD(sc, addr + j*4);
18640             }
18641         }
18642     }
18643 
18644     /* Paged registers are supported in E2 & E3 only */
18645     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18646         /* Read "paged" registers */
18647         bxe_read_pages_regs(sc, p, preset);
18648     }
18649 
18650     return 0;
18651 }
18652 
18653 static int
18654 bxe_grc_dump(struct bxe_softc *sc)
18655 {
18656     int rval = 0;
18657     uint32_t preset_idx;
18658     uint8_t *buf;
18659     uint32_t size;
18660     struct  dump_header *d_hdr;
18661 
18662     if (sc->grcdump_done)
18663 	return (rval);
18664 
18665     ecore_disable_blocks_parity(sc);
18666 
18667     buf = sc->grc_dump;
18668     d_hdr = sc->grc_dump;
18669 
18670     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18671     d_hdr->version = BNX2X_DUMP_VERSION;
18672     d_hdr->preset = DUMP_ALL_PRESETS;
18673 
18674     if (CHIP_IS_E1(sc)) {
18675         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18676     } else if (CHIP_IS_E1H(sc)) {
18677         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18678     } else if (CHIP_IS_E2(sc)) {
18679         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18680                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18681     } else if (CHIP_IS_E3A0(sc)) {
18682         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18683                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18684     } else if (CHIP_IS_E3B0(sc)) {
18685         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18686                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18687     }
18688 
18689     buf += sizeof(struct  dump_header);
18690 
18691     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18692 
18693         /* Skip presets with IOR */
18694         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18695             (preset_idx == 11))
18696             continue;
18697 
18698         rval = bxe_get_preset_regs(sc, sc->grc_dump, preset_idx);
18699 
18700 	if (rval)
18701             break;
18702 
18703         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18704 
18705         buf += size;
18706     }
18707 
18708     ecore_clear_blocks_parity(sc);
18709     ecore_enable_blocks_parity(sc);
18710 
18711     sc->grcdump_done = 1;
18712     return(rval);
18713 }
18714 
18715 static int
18716 bxe_add_cdev(struct bxe_softc *sc)
18717 {
18718     int grc_dump_size;
18719 
18720     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18721 				sizeof(struct  dump_header);
18722 
18723     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18724 
18725     if (sc->grc_dump == NULL)
18726         return (-1);
18727 
18728     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18729 
18730     if (sc->eeprom == NULL) {
18731         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18732         free(sc->grc_dump, M_DEVBUF); sc->grc_dump = NULL;
18733         return (-1);
18734     }
18735 
18736     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18737                             sc->ifp->if_dunit,
18738                             UID_ROOT,
18739                             GID_WHEEL,
18740                             0600,
18741                             "%s",
18742                             if_name(sc->ifp));
18743 
18744     if (sc->ioctl_dev == NULL) {
18745 
18746         free(sc->grc_dump, M_DEVBUF);
18747         free(sc->eeprom, M_DEVBUF);
18748         sc->eeprom = NULL;
18749 
18750         return (-1);
18751     }
18752 
18753     sc->ioctl_dev->si_drv1 = sc;
18754 
18755     return (0);
18756 }
18757 
18758 static void
18759 bxe_del_cdev(struct bxe_softc *sc)
18760 {
18761     if (sc->ioctl_dev != NULL)
18762         destroy_dev(sc->ioctl_dev);
18763 
18764     if (sc->grc_dump != NULL)
18765         free(sc->grc_dump, M_DEVBUF);
18766 
18767     if (sc->eeprom != NULL) {
18768         free(sc->eeprom, M_DEVBUF);
18769         sc->eeprom = NULL;
18770     }
18771 
18772     return;
18773 }
18774 
18775 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18776 {
18777 
18778     if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
18779         return FALSE;
18780 
18781     return TRUE;
18782 }
18783 
18784 
18785 static int
18786 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18787 {
18788     int rval = 0;
18789 
18790     if(!bxe_is_nvram_accessible(sc)) {
18791         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18792         return (-EAGAIN);
18793     }
18794     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18795 
18796 
18797    return (rval);
18798 }
18799 
18800 static int
18801 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18802 {
18803     int rval = 0;
18804 
18805     if(!bxe_is_nvram_accessible(sc)) {
18806         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18807         return (-EAGAIN);
18808     }
18809     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18810 
18811    return (rval);
18812 }
18813 
18814 static int
18815 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18816 {
18817     int rval = 0;
18818 
18819     switch (eeprom->eeprom_cmd) {
18820 
18821     case BXE_EEPROM_CMD_SET_EEPROM:
18822 
18823         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18824                        eeprom->eeprom_data_len);
18825 
18826         if (rval)
18827             break;
18828 
18829         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18830                        eeprom->eeprom_data_len);
18831         break;
18832 
18833     case BXE_EEPROM_CMD_GET_EEPROM:
18834 
18835         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18836                        eeprom->eeprom_data_len);
18837 
18838         if (rval) {
18839             break;
18840         }
18841 
18842         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18843                        eeprom->eeprom_data_len);
18844         break;
18845 
18846     default:
18847             rval = EINVAL;
18848             break;
18849     }
18850 
18851     if (rval) {
18852         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18853     }
18854 
18855     return (rval);
18856 }
18857 
18858 static int
18859 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18860 {
18861     uint32_t ext_phy_config;
18862     int port = SC_PORT(sc);
18863     int cfg_idx = bxe_get_link_cfg_idx(sc);
18864 
18865     dev_p->supported = sc->port.supported[cfg_idx] |
18866             (sc->port.supported[cfg_idx ^ 1] &
18867             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18868     dev_p->advertising = sc->port.advertising[cfg_idx];
18869     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18870         ELINK_ETH_PHY_SFP_1G_FIBER) {
18871         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18872         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18873     }
18874     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18875         !(sc->flags & BXE_MF_FUNC_DIS)) {
18876         dev_p->duplex = sc->link_vars.duplex;
18877         if (IS_MF(sc) && !BXE_NOMCP(sc))
18878             dev_p->speed = bxe_get_mf_speed(sc);
18879         else
18880             dev_p->speed = sc->link_vars.line_speed;
18881     } else {
18882         dev_p->duplex = DUPLEX_UNKNOWN;
18883         dev_p->speed = SPEED_UNKNOWN;
18884     }
18885 
18886     dev_p->port = bxe_media_detect(sc);
18887 
18888     ext_phy_config = SHMEM_RD(sc,
18889                          dev_info.port_hw_config[port].external_phy_config);
18890     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
18891         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
18892         dev_p->phy_address =  sc->port.phy_addr;
18893     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18894             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
18895         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18896             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
18897         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
18898     else
18899         dev_p->phy_address = 0;
18900 
18901     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
18902         dev_p->autoneg = AUTONEG_ENABLE;
18903     else
18904        dev_p->autoneg = AUTONEG_DISABLE;
18905 
18906 
18907     return 0;
18908 }
18909 
18910 static int
18911 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18912         struct thread *td)
18913 {
18914     struct bxe_softc    *sc;
18915     int                 rval = 0;
18916     device_t            pci_dev;
18917     bxe_grcdump_t       *dump = NULL;
18918     int grc_dump_size;
18919     bxe_drvinfo_t   *drv_infop = NULL;
18920     bxe_dev_setting_t  *dev_p;
18921     bxe_dev_setting_t  dev_set;
18922     bxe_get_regs_t  *reg_p;
18923     bxe_reg_rdw_t *reg_rdw_p;
18924     bxe_pcicfg_rdw_t *cfg_rdw_p;
18925     bxe_perm_mac_addr_t *mac_addr_p;
18926 
18927 
18928     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18929         return ENXIO;
18930 
18931     pci_dev= sc->dev;
18932 
18933     dump = (bxe_grcdump_t *)data;
18934 
18935     switch(cmd) {
18936 
18937         case BXE_GRC_DUMP_SIZE:
18938             dump->pci_func = sc->pcie_func;
18939             dump->grcdump_size =
18940                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18941                      sizeof(struct  dump_header);
18942             break;
18943 
18944         case BXE_GRC_DUMP:
18945 
18946             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18947                                 sizeof(struct  dump_header);
18948 
18949             if ((sc->grc_dump == NULL) || (dump->grcdump == NULL) ||
18950                 (dump->grcdump_size < grc_dump_size) || (!sc->grcdump_done)) {
18951                 rval = EINVAL;
18952                 break;
18953             }
18954 	    dump->grcdump_dwords = grc_dump_size >> 2;
18955             rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18956             sc->grcdump_done = 0;
18957 
18958             break;
18959 
18960         case BXE_DRV_INFO:
18961             drv_infop = (bxe_drvinfo_t *)data;
18962             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
18963             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
18964                 BXE_DRIVER_VERSION);
18965             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
18966                 sc->devinfo.bc_ver_str);
18967             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
18968                 "%s", sc->fw_ver_str);
18969             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
18970             drv_infop->reg_dump_len =
18971                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
18972                     + sizeof(struct  dump_header);
18973             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
18974                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
18975             break;
18976         case BXE_DEV_SETTING:
18977             dev_p = (bxe_dev_setting_t *)data;
18978             bxe_get_settings(sc, &dev_set);
18979             dev_p->supported = dev_set.supported;
18980             dev_p->advertising = dev_set.advertising;
18981             dev_p->speed = dev_set.speed;
18982             dev_p->duplex = dev_set.duplex;
18983             dev_p->port = dev_set.port;
18984             dev_p->phy_address = dev_set.phy_address;
18985             dev_p->autoneg = dev_set.autoneg;
18986 
18987             break;
18988 
18989         case BXE_GET_REGS:
18990 
18991             reg_p = (bxe_get_regs_t *)data;
18992             grc_dump_size = reg_p->reg_buf_len;
18993 
18994             if (sc->grc_dump == NULL) {
18995                 rval = EINVAL;
18996                 break;
18997             }
18998 
18999             if(!sc->grcdump_done) {
19000                 bxe_grc_dump(sc);
19001             }
19002             if(sc->grcdump_done) {
19003                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19004                 sc->grcdump_done = 0;
19005             }
19006 
19007             break;
19008         case BXE_RDW_REG:
19009             reg_rdw_p = (bxe_reg_rdw_t *)data;
19010             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19011                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19012                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19013 
19014             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19015                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19016                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19017 
19018             break;
19019 
19020         case BXE_RDW_PCICFG:
19021             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19022             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19023 
19024                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19025                                          cfg_rdw_p->cfg_width);
19026 
19027             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19028                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19029                             cfg_rdw_p->cfg_width);
19030             } else {
19031                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19032             }
19033             break;
19034 
19035         case BXE_MAC_ADDR:
19036             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19037             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19038                 sc->mac_addr_str);
19039             break;
19040 
19041         case BXE_EEPROM:
19042             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19043             break;
19044 
19045 
19046         default:
19047             break;
19048     }
19049 
19050     return (rval);
19051 }
19052